text
stringlengths
184
4.48M
import React, { createContext, useCallback, useState, useContext } from "react"; import api from '../services/api' interface ISignInCredentials { email: string; password: string; }; interface IUser { name: string; email: string; id: string; avatar_url: string; } interface IAuthState { token: string; user: IUser; }; interface IAuthContent { user: IUser; signIn(credentials: ISignInCredentials): Promise<void>; signOut(): void; updateUser(user: IUser): void; }; const AuthContent = createContext<IAuthContent>({} as IAuthContent); export const AuthProvider: React.FC = ({ children }) => { const [data, setData] = useState<IAuthState>(() => { const token = localStorage.getItem('@GoBarber:token'); const user = localStorage.getItem('@GoBarber:user'); if (token && user) { api.defaults.headers.common['Authorization'] = `Bearer ${token}`; return { token, user: JSON.parse(user) }; } return {} as IAuthState; }); const signIn = useCallback(async ({ email, password }: ISignInCredentials) => { const response = await api.post('sessions', { email, password }); const { token, user } = response.data; localStorage.setItem('@GoBarber:token', token); localStorage.setItem('@GoBarber:user', JSON.stringify(user)); api.defaults.headers.common['Authorization'] = `Bearer ${token}`; console.log(api.defaults.headers.common['authorization']) setData({ token, user }); }, []); const updateUser = useCallback(async (user: IUser) => { localStorage.setItem('@GoBarber:user', JSON.stringify(user)); setData({ token: data.token, user }) }, [setData, data.token]); const signOut = useCallback(() => { localStorage.removeItem('@GoBarber:token'); localStorage.removeItem('@GoBarber:user'); setData({} as IAuthState); }, []); return ( <AuthContent.Provider value={{ user: data.user, signIn, signOut, updateUser }}> {children} </AuthContent.Provider> ); }; export default function useAuth(): IAuthContent { const context = useContext(AuthContent); if (!context) throw new Error('useAuth must be used within an AutheProvider'); return context; };
/* * Copyright (c) 2017 Stuart Boston * * This file is part of the Board Game Geek API Wrapper. * * This API wrapper is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * The API wrapper is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with the API Wrapper. If not, see <http://www.gnu.org/licenses/>. * */ package com.omertron.bgg.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import java.util.List; @JacksonXmlRootElement(localName = "items") @JsonIgnoreProperties({"termsofuse", "script"}) public class CollectionItemWrapper extends AbstractXmlMapping { @JacksonXmlElementWrapper(useWrapping = false) @JacksonXmlProperty(localName = "item") private List<CollectionItem> items; @JacksonXmlProperty(localName = "totalitems", isAttribute = true) private int totalItems; @JacksonXmlProperty(localName = "pubdate", isAttribute = true) private String publishDate; public List<CollectionItem> getItems() { return items; } public void setItems(List<CollectionItem> items) { this.items = items; } public int getTotalItems() { return totalItems; } public void setTotalItems(int totalItems) { this.totalItems = totalItems; } public String getPublishDate() { return publishDate; } public void setPublishDate(String publishDate) { this.publishDate = publishDate; } }
<?php class Alunno implements JsonSerializable { protected $nome; protected $cognome; protected $eta; public function __construct($nome, $cognome, $eta) { $this->nome = $nome; $this->cognome = $cognome; $this->eta = $eta; } public function jsonSerialize(){ $a = [ "nome" => $this->nome, "cognome" => $this->cognome, "eta" => $this->eta ]; return $a; } function setNome($nome) { $this->nome = $nome; } function getNome() { return $this->nome; } function setCognome($cognome) { $this->cognome = $cognome; } function getCognome() { return $this->cognome; } function setEta($eta) { $this->eta = $eta; } function getEta() { return $this->eta; } function __toString() { return "<ul><li>" . $this->nome . "</li><li>" . $this->cognome . "</li><li>" . $this->eta . "</li></ul>"; } }
//*Swiper // *Import base import styles from './slider.module.scss'; import './slider.scss'; //*Import images import specialist1 from './../../assets/image/specialist1.png'; import specialist2 from './../../assets/image/specialist2.png'; import specialist3 from './../../assets/image/specialist3.png'; import specialist4 from './../../assets/image/specialist4.png'; import specialist5 from './../../assets/image/specialist5.png'; import specialist6 from './../../assets/image/specialist6.png'; import specialist7 from './../../assets/image/specialist7.png'; import specialist8 from './../../assets/image/specialist8.png'; //*Import swiper import { Swiper, SwiperSlide } from 'swiper/react'; import { Keyboard, Mousewheel, Navigation } from 'swiper'; //*Import styles for swiper import 'swiper/scss/mousewheel'; import 'swiper/css/navigation'; import 'swiper/scss/keyboard'; import 'swiper/scss'; const Slider = () => { return ( <> {/* Initialization of the Swiper */} <Swiper modules={[Keyboard, Mousewheel, Navigation]} navigation={{ nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }} spaceBetween={10} slidesPerView={5} keyboard={{ enablet: true }} mousewheel={{ sensitivity: 5 }} onSwiper={(swiper) => console.log(swiper)} onSlideChange={() => console.log('slide change')} loop={true} //*Responsive breakpoints breakpoints={{ 320: { slidesPerView: 2, }, 480: { slidesPerView: 3, }, 768: { slidesPerView: 4, }, 1024: { slidesPerView: 5, }, }} > {/* Button next */} <button className='swiper-button-next next'> <span> <svg className='icon'> <use xlinkHref='#icon-next'></use> </svg> </span> </button> <div className={styles.imageSlider}> {/* Slide 1 */} <SwiperSlide className={styles.imageSliderImage}> <img src={specialist1} alt={'specialist1'} /> </SwiperSlide> {/* Slide 2 */} <SwiperSlide className={styles.imageSliderImage}> <img src={specialist2} alt={'specialist2'} /> </SwiperSlide> {/* Slide 3 */} <SwiperSlide className={styles.imageSliderImage}> <img src={specialist3} alt={'specialist3'} /> </SwiperSlide> {/* Slide 4 */} <SwiperSlide className={styles.imageSliderImage}> <img src={specialist4} alt={'specialist4'} /> </SwiperSlide> {/* Slide 5 */} <SwiperSlide className={styles.imageSliderImage}> <img src={specialist5} alt={'specialist5'} /> </SwiperSlide> {/* Slide 6 */} <SwiperSlide className={styles.imageSliderImage}> <img src={specialist6} alt={'specialist6'} /> </SwiperSlide> {/* Slide 7 */} <SwiperSlide className={styles.imageSliderImage}> <img src={specialist7} alt={'specialist7'} /> </SwiperSlide> {/* Slide 8 */} <SwiperSlide className={styles.imageSliderImage}> <img src={specialist8} alt={'specialist8'} /> </SwiperSlide> </div> {/* Button prev */} <button className='swiper-button-prev prev'> <span> <svg className='icon'> <use xlinkHref='#icon-prev'></use> </svg> </span> </button> </Swiper> </> ); }; export default Slider;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>gen4 - Doom</title> <!-- put your name here --> <meta name="author" content="Enrico Di Pietro"> <!-- put page info here --> <meta name="date" content="1993-12-10"> <!-- the date the product was launched --> <meta name="generation" content="gen4"> <meta name="product" content="Doom"> <meta name="description" content="Times change. Doom is eternal."> <!-- a short description of the product --> <meta name="picture" content="media/doom.gif"> <!-- a square gif representing the product (if you are not able to edit the gif, ask someone in your group or the CSS Leaders to edit it for you) --> <!-- this is the base style, necessary in every product page --> <link rel="stylesheet" href="../../styles/base/style.css"> <!-- this is the generation style, must be set to the appropriate generation --> <link rel="stylesheet" id="generation-style" href="../../styles/gen4/style.css"> <!-- this is the user style, here you shoud set variables and add your css (optional) --> <style id="user-style"> :root{ /* these are the background images (left and right) */ --background-image-left: url( "media/doom_left.jpg" ); --background-image-right: url( "media/doom_right.jpg" ); /* this is the fading color between the images */ --background-fade-color: #ff0000; /* this is the color behind the image (visible only if the image has transparence) */ --banner-color: #000000; /* the audio file that will be played */ --audio-file: url( "media/doom.mp3" ); /* the container parameters */ --container-background-color: #000000; --container-text-color: #e8e4c9; --container-border-color: #ff0000; /* the index parameters */ --index-background-color: #000000; --index-text-color: #e8e4c9; --index-border-color: #ff0000; /* text styles parameters */ --link-color-hover: #f00; /* content scrollbar */ --scrollbar-thumb: #8B0000; } /* your style here */ </style> <!-- this is the script file for all the onload operations --> <script src="../../script/onload.js"></script> </head> <body onload="onload();"> <!-- the backgrounds --> <div class="bg" id="bg-left"></div> <div class="bg" id="bg-right"></div> <!-- the back and the music button --> <div class="button" id="back-button"></div> <div class="button" id="sound-button"></div> <!-- the index of the page, with all the link to the sections --> <div id="index"> <ol> <li><a href="#s1">The game</a> <ol> <li><a href="#s1.1">Doom</a></li> <li><a href="#s1.2">Description</a></li> <li><a href="#s1.3">Why is Doom so well known?</a></li> </ol> </li> <li><a href="#s2">Innovations</a> <ol> <li><a href="#s2.1">Introduction</a></li> <li><a href="#s2.2">Multiplayer</a></li> <li><a href="#s2.3">Graphic</a></li> <li><a href="#s2.4">Mods</a></li> </ol> <li><a href="#s3">Play the game!</a> </li> </ol> </div> <div id="container"> <div id="banner"> <img alt="Banner Image" src="media/doom_banner.jpg"> </div> <div id="content"> <h2 id="s1">The game</h2> </br> <h3 id="s1.1">Doom</h3> <p> Doom is a <i>first-person shooter</i> game developed by id Software for MS-DOS in 1993. The player takes the role of an unnamed space marine that fight hordes of demons from Hell, in a science fiction and horror scenario. </p> </br> <h3 id="s1.2">Description</h3> <p> The player has to go through a series of levels set in military bases on the moons of Mars and in Hell. To finish a level the player must explore the area to find a marked exit room while walking a map is filled with the location you went through. The levels are grouped into episodes and the last level features a <i>boss fight</i> where the player has to face an enemy stronger than the others encountered before. </br> The enemies are demons and possessed undead humans that the player fights using different weapons. During the game, the player must manage ammunition, health and armour. There are 5 difficulty levels: those manage the amount of damage done by enemies, the speed of their movements and if they respawn. </p> </br> </br> <img src="media/screen_0.jpg" alt="Doom game screen" class="center"> <blockquote cite="https://apkpure.com/it/pro-doom-1-1993-guide/com.doma.modaa"></blockquote> </br> <h3 id="s1.3">Why is Doom so well known?</h3> <p> It was one of the first videogames rated M for Mature due to his violence and explicit content. It was also criticized by groups for the content of satanic imagery. Doom introduced the fear that the new technology used in videogames led to more realistic simulations that could influence people making them more confident using violence. </br> It's a challenging game that requires the player to be concentrate to complete a level but is also nice to play just for having fun, so a lot of people loved it. It was also one of the first FPS genre games. </p> </br> </br> <h2 id="s2">Innovations</h2> </br> <h3 id="s2.1">Introduction</h3> <p> The fact that Doom was played by millions of people promoted the emerging FPS genre. However, the term FPS was lately introduced and the firsts videogames that followed this structure were called "Doom clones". This game pioneered online distribution, 3D graphics, networked multiplayer gaming and custom modifications via packaged files (WADs). </p> </br> <h3 id="s2.2">Multiplayer</h3> <p> Deathmatching between players became attractive due to the large distribution of PC systems and the violence of this game, so players started playing one against the other in different ways: over phone line using a modem or by linking two PCs with a null-modem cable. </p> </br> </br> <img src="media/multiplayer.png" alt="Doom multiplayer" class="center"> <blockquote cite="https://piecebypixel.wordpress.com/2016/04/01/a-doomed-classic/"></blockquote> </br> <h3 id="s2.3">Graphic</h3> <p> The levels are presented in 3D perspective but the enemies and the objects are 2D sprites presented from several angles. This technique is called 2.5D graphics. For this generation, this kind of new graphic was a huge innovation and had a big impact on the games that were afterwards developed. </p> </br> </br> <img src="media/sprites.png" alt="Doom sprites" class="center"> <blockquote cite="https://forum.zdoom.org/viewtopic.php?f=45&t=30879&start=255"></blockquote> </br> </br> <h3 id="s2.4">Mods</h3> <p> It is possible to modify the game creating custom levels using WAD files. This feature generated a large community that started making mods. The mod files also allow to create and modify creatures, weapons and even the sounds. </p> </br> </br> <img src="media/mods.jpg" alt="Doom mods" class="center"> <blockquote cite="https://www.gamepressure.com/download.asp?ID=64210"></blockquote> <h3 id="s3">Play the game</h3> <p> Now you have two choices, you can watch the gameplay below or click this <a href="https://playclassic.games/games/first-person-shooter-dos-games-online/play-doom-online/play/">link</a> and play the game :) </p> </br> </br> <iframe width=100% height=500px src="https://www.youtube.com/embed/MnqLJpgq7jc" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </br> </br> <div class="footer"> <p>@ Enrico Di Pietro</p> </div> </div> </div> </body> </html>
import React, { useState } from 'react'; import MoviesList from './components/MoviesList'; import './App.css'; function App() { const [movies, setMovies] = useState([]); function fetchMoviesHandler() { fetch('https://swapi.dev/api/films/') .then((response) => response.json()) //.json() bta3mul translate lal json la javscript object // response.json() hye promise reje3et //array of object [{},{},{}] //()=>{} //arrow function .then((data) => { const transformedMovies = data.results.map(movieData => ( //return la array of objects , li2an hye bta3mul retun la 6 object btheton bi array //nehna ken fina nheta 3ade setMovies(data.results) //bas li2an mabadna ngayer shi bel Movies.js text , fa 3melna i3adet tasmye men hon degre { id: movieData.episode_id, title: movieData.title, openingText: movieData.opening_crawl, releaseDate: movieData.release_date } )); // console.log(transformedMovies); (6)[{… }, {… }, {… }, {… }, {… }, {… }] setMovies(transformedMovies); }); } return ( <React.Fragment> <section> <button onClick={fetchMoviesHandler}>Fetch Movies</button> </section> <section> <MoviesList movies={movies} /> </section> </React.Fragment> ); } export default App;
:tower_url: https://your-control-node-ip-address :license_url: http://ansible-workshop-bos.redhatgov.io/wslic.txt :image_links: https://s3.amazonaws.com/ansible-workshop-bos.redhatgov.io/_images = Exercise 1.5 - Creating and Running a Job Template --- A job template is a definition and set of parameters for running an Ansible job. Job templates are useful to execute the same job many times. [.lead] Creating a Job Template ==== *Step 1:* Select JOB TEMPLATES + *Step 2:* Click on ADD <insert image:at_add.png[Add,35,25] + *Step 3:* Complete the form using the following values + |=== |NAME |Apache Basic Job Template |DESCRIPTION|Template for the apache-basic-playbook |JOB TYPE|Run |INVENTORY|Ansible Workshop Inventory |PROJECT|Ansible Workshop Project |PLAYBOOK|examples/apache-basic-playbook/site.yml |MACHINE CREDENTIAL|Ansible Workshop Credential |LIMIT|web |OPTIONS a| - [*] Enable Privilege Escalation |=== --- image::at_jt_detail.png[caption="Figure 11: ",title="Job Template Form",link="{image_links}/at_jt_detail.png"] --- *Step 4:* Select ADD SURVEY image:at_addsurvey.png[Add,35,25] + *Step 5:* Complete the survey form with following values + |=== |PROMPT|Please enter a test message for your new website |DESCRIPTION|Website test message prompt |ANSWER VARIABLE NAME|apache_test_message |ANSWER TYPE|Text |MINIMUM/MAXIMUM LENGTH| Use the defaults |DEFAULT ANSWER| Be creative, keep it clean, we're all professionals here |=== --- image::at_survey_detail.png[caption="Figure 12: ",title="Survey Form",link="{image_links}/at_survey_detail.png"] --- *Step 6:* Select ADD image:at_add.png[Add,35,25] + *Step 7:* Select SAVE image:at_save.png[Add,35,25] + ==== [.lead] Running a Job Template Now that you've sucessfully creating your Job Template, you are ready to launch it. Once you do, you will be redirected to a job screen which is refreshing in realtime showing you the status of the job. ==== *Step 1:* Select JOB TEMPLATES [NOTE] Alternatively, if you haven't navigated away from the job templates creation page, you can scroll down to see all existing job templates *Step 2:* Click on the rocketship icon image:at_launch_icon.png[Add,35,25] for the *Apache Basic Job Template* + *Step 3:* When prompted, enter your desired test message + --- image::at_survey_prompt.png[caption="Figure 13: ",title="Survey Prompt"] --- *Step 4:* Select LAUNCH image:at_survey_launch.png[SurveyL,35,25] + *Step 5:* Sit back, watch the magic happen + One of the first things you will notice is the summary section. This gives you details about your job such as who launched it, what playbook it's running, what the status is, i.e. pending, running, or complete. + --- image::at_job_status.png[caption="Figure 14: ",title="Job Summary",link="{image_links}/at_job_status.png"] --- Scrolling down, you will be able to see details on the play and each task in the playbook. + --- image::at_job_tasklist.png[caption="Figure 15: ",title="Play and Task Details",link="{image_links}/at_job_tasklist.png"] --- To the right, you can view standard output; the same way you could if you were running Ansible Core from the command line. + --- image::at_job_stdout.png[caption="Figure 16: ",title="Job Standard Output",link="{image_links}/at_job_stdout.png"] --- *Step 6:* Once your job is sucessful, navigate to your new website + ---- http://<IP_of_node-1_or_node-2> ---- If all went well, you should see something like this, but with your own custom message of course. + --- image::at_web_tm.png[caption="Figure 17: ",title="New Website with Personalized Test Message"] --- ==== == End Result At this point in the workshop, you've experienced the core functionality of Ansible Tower. But wait... there's more! You've just begun to explore the possibilities of Ansible Core and Tower. Take a look at the resources page in this guide to explore some more features.
import { Link } from "react-router-dom"; const Phone = ({phone}) => { const {id, phone_name, brand_name, rating, price, image} = phone || {} return ( <div> <div className="relative flex w-96 flex-col rounded-xl bg-white bg-clip-border text-gray-700 shadow-md"> <div className="relative mx-4 mt-4 h-96 overflow-hidden rounded-xl bg-white bg-clip-border text-gray-700"> <img src={image} className="h-full w-full object-cover"/> </div> <div className="p-6"> <div className="mb-2 flex items-center justify-between"> <p className="block font-sans text-base font-medium leading-relaxed text-blue-gray-900 antialiased"> {phone_name} </p> <p className="block font-sans text-base font-medium leading-relaxed text-blue-gray-900 antialiased"> {price} </p> </div> <p className="block font-sans text-sm font-normal leading-normal text-gray-700 antialiased opacity-75"> {rating} </p> </div> <div className="p-6 pt-0"> <Link to={`/phones/${id}`}> <button className="block w-full select-none bg-gray-300 rounded-lg bg-blue-gray-900/10 py-3 px-6 text-center align-middle font-sans text-xs font-bold uppercase text-blue-gray-900 transition-all hover:scale-105 focus:scale-105 focus:opacity-[0.85] active:scale-100 active:opacity-[0.85] disabled:pointer-events-none disabled:opacity-50 disabled:shadow-none" type="button"> See Details </button> </Link> </div> </div> </div> ); }; export default Phone;
/* * Copyright (c) 2020-2022 Mauro Trevisan * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package io.github.mtrevisan.boxon.core.helpers.configurations; import freemarker.core.Environment; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; import io.github.mtrevisan.boxon.annotations.configurations.CompositeConfigurationField; import io.github.mtrevisan.boxon.annotations.configurations.CompositeSubField; import io.github.mtrevisan.boxon.annotations.configurations.NullEnum; import io.github.mtrevisan.boxon.exceptions.CodecException; import io.github.mtrevisan.boxon.exceptions.ConfigurationException; import io.github.mtrevisan.boxon.exceptions.EncodeException; import io.github.mtrevisan.boxon.io.ParserDataType; import io.github.mtrevisan.boxon.core.keys.ConfigurationKey; import io.github.mtrevisan.boxon.semanticversioning.Version; import io.github.mtrevisan.boxon.helpers.StringHelper; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; final class CompositeManager implements ConfigurationManagerInterface{ private static final String NOTIFICATION_TEMPLATE = "compositeTemplate"; private static final Configuration FREEMARKER_CONFIGURATION = new Configuration(Configuration.VERSION_2_3_31); static{ FREEMARKER_CONFIGURATION.setDefaultEncoding(StandardCharsets.UTF_8.name()); FREEMARKER_CONFIGURATION.setLocale(Locale.US); FREEMARKER_CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } private final CompositeConfigurationField annotation; CompositeManager(final CompositeConfigurationField annotation){ this.annotation = annotation; } @Override public String getShortDescription(){ return annotation.shortDescription(); } @Override public Object getDefaultValue(final Field field, final Version protocol) throws EncodeException{ //compose field value final String composition = annotation.composition(); final CompositeSubField[] fields = annotation.value(); final Map<String, Object> dataValue = new HashMap<>(fields.length); for(int i = 0; i < fields.length; i ++) dataValue.put(fields[i].shortDescription(), fields[i].defaultValue()); return replace(composition, dataValue, fields); } @Override public void addProtocolVersionBoundaries(final Collection<String> boundaries){ boundaries.add(annotation.minProtocol()); boundaries.add(annotation.maxProtocol()); } @Override public Annotation annotationToBeProcessed(final Version protocol){ final boolean shouldBeExtracted = ConfigurationHelper.shouldBeExtracted(protocol, annotation.minProtocol(), annotation.maxProtocol()); return (shouldBeExtracted? annotation: PlainManager.EMPTY_ANNOTATION); } //at least one field is mandatory @Override public boolean isMandatory(final Annotation annotation){ boolean mandatory = false; final CompositeSubField[] compositeFields = this.annotation.value(); for(int j = 0; !mandatory && j < compositeFields.length; j ++) mandatory = StringHelper.isBlank(compositeFields[j].defaultValue()); return mandatory; } @Override public Map<String, Object> extractConfigurationMap(final Class<?> fieldType, final Version protocol) throws ConfigurationException, CodecException{ if(!ConfigurationHelper.shouldBeExtracted(protocol, annotation.minProtocol(), annotation.maxProtocol())) return Collections.emptyMap(); final Map<String, Object> compositeMap = extractMap(); final CompositeSubField[] bindings = annotation.value(); final Map<String, Object> compositeFieldsMap = new HashMap<>(bindings.length); for(int j = 0; j < bindings.length; j ++){ final Map<String, Object> fieldMap = extractMap(bindings[j], fieldType); compositeFieldsMap.put(bindings[j].shortDescription(), fieldMap); } ConfigurationHelper.putIfNotEmpty(ConfigurationKey.CONFIGURATION_COMPOSITE_FIELDS, compositeFieldsMap, compositeMap); if(protocol.isEmpty()) ConfigurationHelper.extractMinMaxProtocol(annotation.minProtocol(), annotation.maxProtocol(), compositeMap); return Collections.unmodifiableMap(compositeMap); } private Map<String, Object> extractMap() throws ConfigurationException{ final Map<String, Object> map = new HashMap<>(6); ConfigurationHelper.putIfNotEmpty(ConfigurationKey.LONG_DESCRIPTION, annotation.longDescription(), map); ConfigurationHelper.putIfNotEmpty(ConfigurationKey.PATTERN, annotation.pattern(), map); ConfigurationHelper.putIfNotEmpty(ConfigurationKey.CHARSET, annotation.charset(), map); return map; } private static Map<String, Object> extractMap(final CompositeSubField binding, final Class<?> fieldType) throws ConfigurationException, CodecException{ final Map<String, Object> map = new HashMap<>(10); ConfigurationHelper.putIfNotEmpty(ConfigurationKey.LONG_DESCRIPTION, binding.longDescription(), map); ConfigurationHelper.putIfNotEmpty(ConfigurationKey.UNIT_OF_MEASURE, binding.unitOfMeasure(), map); ConfigurationHelper.putIfNotEmpty(ConfigurationKey.PATTERN, binding.pattern(), map); if(!fieldType.isEnum() && !fieldType.isArray()) ConfigurationHelper.putIfNotEmpty(ConfigurationKey.FIELD_TYPE, ParserDataType.toPrimitiveTypeOrSelf(fieldType).getSimpleName(), map); final Object defaultValue = ConfigurationHelper.convertValue(binding.defaultValue(), fieldType, NullEnum.class); ConfigurationHelper.putIfNotEmpty(ConfigurationKey.DEFAULT_VALUE, defaultValue, map); return map; } @Override public void validateValue(final Field field, final String dataKey, final Object dataValue) throws EncodeException{ //check pattern final String pattern = annotation.pattern(); if(!pattern.isEmpty()){ final Pattern formatPattern = Pattern.compile(pattern); //compose outer field value final String composition = annotation.composition(); final CompositeSubField[] fields = annotation.value(); @SuppressWarnings("unchecked") final String outerValue = replace(composition, (Map<String, Object>)dataValue, fields); //value compatible with data type and format if(!formatPattern.matcher(outerValue).matches()) throw EncodeException.create("Data value not compatible with `pattern` for data key {}; found {}, expected {}", dataKey, outerValue, pattern); } } @Override @SuppressWarnings("unchecked") public Object convertValue(final Field field, final String dataKey, Object dataValue, final Version protocol) throws EncodeException{ //compose field value final String composition = annotation.composition(); final CompositeSubField[] fields = annotation.value(); if(dataValue instanceof Map) dataValue = replace(composition, (Map<String, Object>)dataValue, fields); return dataValue; } private static String replace(final String text, final Map<String, Object> replacements, final CompositeSubField[] fields) throws EncodeException{ final Map<String, Object> trueReplacements = new HashMap<>(fields.length); for(int i = 0; i < fields.length; i ++){ final String key = fields[i].shortDescription(); trueReplacements.put(key, replacements.get(key)); } return substitutePlaceholders(text, trueReplacements); } private static String substitutePlaceholders(final String text, final Map<String, Object> dataModel) throws EncodeException{ if(dataModel != null){ try{ final Writer writer = new StringWriter(); final Template template = new Template(NOTIFICATION_TEMPLATE, new StringReader(text), FREEMARKER_CONFIGURATION); //create a processing environment final Environment mainTemplateEnvironment = template.createProcessingEnvironment(dataModel, writer); //process everything mainTemplateEnvironment.process(); return writer.toString(); } catch(final IOException | TemplateException e){ throw EncodeException.create(e); } } return text; } }
package com.budgettracking.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.budgettracking.model.HardwareCost; import com.budgettracking.service.HardwareCostService; @RestController @RequestMapping("/api") public class HardwareCostController { @Autowired private HardwareCostService hwService; /* * ADD NEW RESOURCE DATA SAVE DATA */ @PostMapping("/saveHW") public HardwareCost saveHardwareCost(@RequestBody HardwareCost hw) { return hwService.saveHardwareCost(hw); } /* * GET ALL RESOURCE DATA UI LIST */ @GetMapping("/getAllHW") public List<HardwareCost> getAllHardwareCost() { return hwService.getAllHardwareCost(); } /* * GET PARTICULAR RESOURCE DATA */ @GetMapping("/getHWById/{hw_id}") public HardwareCost getHardwareCostById( @PathVariable("hw_id")int hw_id) { return hwService.getHardwareCostById(hw_id); } /* * DELETE EXIST RESOURCE DATA */ @DeleteMapping("/deleteHWById/{hw_id}") public String deleteHardwareCost( @PathVariable("hw_id")int hw_id) { hwService.deleteHardwareCost(hw_id); return "HARDWARE COST DATA DELETE SUCCESSFULLY"; } /* * UPDATE EXIST RESOURCE DATA SAVE DATA */ @PutMapping("/updateHWById/{hw_id}") public HardwareCost updateHardwareCost(@RequestBody HardwareCost hw,@PathVariable("hw_id")int hw_id) { return hwService.updateHardwareCost(hw, hw_id); } }
"use client"; import React, { useEffect, useState } from "react"; import { useFormState, useFormStatus } from "react-dom"; import { AlertDialog, AlertDialogContent, AlertDialogDescription, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger, } from "@/components/ui/alert-dialog"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Input } from "../ui/input"; import { DatePicker } from "../ui/date-picker"; import { Button } from "../ui/button"; import addNewBlog from "@/actions/add-form"; import Multiselect from "../ui/select-create"; import { addCategory } from "@/lib/prisma/category"; import { addTag } from "@/lib/prisma/tags"; import { toast } from "sonner" interface Tag { id: string; value: string; label: string; } interface AddBlogProps { tags: Tag[]; categories: Tag[]; } interface Option { id?: string; value: string; label: string; } export default function AddBlog({ tags, categories }: AddBlogProps) { // const [thumbnail, setThumbnail] = useState() const [date, setDate] = useState<Date>(new Date()); const { pending } = useFormStatus(); const [formState, formAction] = useFormState(addNewBlog, { success: undefined, errors: undefined, fieldValues: { title: "", slug: "", description: "", url: "", date: date, category: "", language: "", platform: "", tags: [], thumbnail: "", }, }); useEffect(() => { if(formState.success) { toast.success("A new blog has been added successfully.") } else toast.error(formState.error) }, [formState]) return ( <AlertDialog> <AlertDialogTrigger>Add Blog</AlertDialogTrigger> <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>Add a new blog</AlertDialogTitle> <AlertDialogDescription> Writing blogs made you who you are today. Never stop writing! </AlertDialogDescription> </AlertDialogHeader> {formState.success && <p>Blog added to db</p>} <form action={formAction} className="flex flex-col gap-3 my-4"> <div> <Input placeholder="Title" type="text" name="title" className={`${ formState?.errors?.title ? "border-red-500 focus-visible:ring-red-500 " : "" }`} /> <p className="text-red-400 text-xs font-semibold pt-1"> {" "} {formState?.errors?.title}{" "} </p> </div> <Input placeholder="Slug" type="text" name="slug" /> <Input placeholder="Description" type="textarea" name="description" aria-rowcount={4} /> <Input placeholder="Published URL" type="text" name="url" /> {/* <DatePicker name="date" date={date} setDate={setDate} /> */} <label htmlFor="date">date</label> <input type="date" name="date" onChange={e => console.log(e)} id="date" /> <Select name="platform" defaultValue={PLATFORMS[0].value}> <SelectTrigger> <SelectValue placeholder="Platform" /> </SelectTrigger> <SelectContent> {PLATFORMS.map((platform) => ( <SelectItem value={platform.value} key={platform.value}> {platform.label} </SelectItem> ))} </SelectContent> </Select> {/* defaultValue={formData.language} onValueChange={(e) => handleSelectFields("language", e)} */} <Select name="language" defaultValue="English"> <SelectTrigger> <SelectValue placeholder="Language" /> </SelectTrigger> <SelectContent> <SelectItem value="English">English</SelectItem> <SelectItem value="Marathi">Marathi</SelectItem> <SelectItem value="Hindi">Hindi</SelectItem> </SelectContent> </Select> {/* Category */} <Multiselect placeholder="Select category" options={categories} onCreateOption={addCategory} name="category" /> {/* Tags */} <Multiselect placeholder="Select or create tags" options={tags} isMulti onCreateOption={addTag} name="tags" /> <Input type="file" name="thumbnail" /> <Button type="submit" disabled={pending}> {pending ? "Adding...": "Add a new blog"} </Button> </form> </AlertDialogContent> </AlertDialog> ); } const PLATFORMS = [ { value: "personal", label: "Personal blog" }, { value: "freecodecamp", label: "FreeCodeCamp" }, { value: "dev.to", label: "Dev.to" }, { value: "hackernoon", label: "Hackernoon" }, { value: "showwcase", label: "Showwcase" }, { value: "reactplay", label: "ReactPlay" }, { value: "thedapplist", label: "The Dapp List" }, { value: "nextbillion", label: "Nextbillion" }, { value: "flycode", label: "FlyCode" }, ]; const validateBlogForm = async (blog: FormData) => { // const thumbnailURL = await uploadImage(blog.get("thumbnail")) const thumbnailURL = "await uploadImage(blog.get())"; // TODO: Change this back to normal console.log(blog.get("photos")); const newBlog = { title: blog.get("title"), slug: blog.get("slug"), description: blog.get("description"), url: blog.get("url"), // date: date, category: blog.get("category"), platform: blog.get("platform"), language: blog.get("language"), tags: blog.getAll("tags"), thumbnail: thumbnailURL, }; // const result = BlogSchema.safeParse(newBlog) // if (!result.success) { // let errorMessage = "" // result.error.issues.forEach((issue: any) => { // errorMessage += `${issue.path} : ${issue.message} . ` // }) // alert(errorMessage) // return; // } // const response = await addNewBlog(JSON.stringify(result.data)) // if (response?.result?.title === newBlog.title) { // alert("New blog added successfully") // return // } };
// // HomeGoalHeader.swift // Fitness Tracker // // Created by Ben Gavan on 25/08/2017. // Copyright © 2017 Ben Gavan. All rights reserved. // import Foundation //import LBTAComponents class GoalsHeader: DatasourceCell { override func setupViews() { super.setupViews() self.backgroundColor = .white separatorLineView.isHidden = false separatorLineView.backgroundColor = UIColor(r: 230, g: 230, b: 230) // Initialize let items = ["Bike", "Run", "Swim"] let customSC = UISegmentedControl(items: items) customSC.selectedSegmentIndex = 0 // Set up Frame and SegmentedControl // let frame = UIScreen.main.bounds // customSC.frame = CGRect(x: 0, y: 0, width: frame.width - 20, height: frame.height*0.1) // Style the Segmented Control customSC.layer.cornerRadius = 5.0 // Don't let background bleed customSC.backgroundColor = UIColor(r: 160, g: 160, b: 160) customSC.tintColor = .black // Add target action method customSC.addTarget(self, action: #selector(self.changeColor), for: .valueChanged) // Add this custom Segmented Control to our view addSubview(customSC) customSC.anchor(self.topAnchor, left: self.leftAnchor, bottom: self.bottomAnchor, right: self.rightAnchor, topConstant: 5, leftConstant: 5, bottomConstant: 5, rightConstant: 5, widthConstant: 0, heightConstant: 0) } /** Handler for when custom Segmented Control changes and will change the background color of the view depending on the selection. */ public func changeColor(sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 1: print("Run") case 2: print("Swim") default: print("Bike") } // collectionView?.reloadItems(at: [IndexPath.init(item: 0, section: 0)]) } }
import React from "react"; import { View, Dimensions, TouchableOpacity, StyleSheet, Text } from "react-native"; import { Avatar } from "react-native-elements"; import Feather from 'react-native-vector-icons/Feather'; const styles = StyleSheet.create({ container: { width: '100%', flex: 1, alignSelf: 'center', height: Dimensions.get('window').height / 10, backgroundColor: '#fff', borderRadius: 10, shadowColor: '#000', shadowOpacity: .1, shadowOffset: { width: 10, height: 10, }, flexDirection: 'row', marginBottom: 15, alignItems: 'center', padding: 15, }, userName: { marginLeft: 15, fontWeight: '500', fontSize: 18, }, choiceContainer: { position: 'absolute', marginLeft: 30, height: '100%', width: '40%', right: '5%', alignItems: 'center', justifyContent: 'space-around', flexDirection: 'row' } }); const FriendRequestCard = (props) => { const { theme } = props; return ( <View style={{...styles.container, backgroundColor: theme.colors.cardBackground}}> <Avatar size={Dimensions.get('window').width / 7} rounded source={require('../assets/images/farmer_pp.png')} containerStyle={{ alignSelf: 'center' }} /> <Text style={{...styles.userName, color: theme.colors.text}}>{props.name}</Text> <View style={styles.choiceContainer}> <TouchableOpacity onPress={props.handleAccept}> <Feather size={30} name={"check-circle"} color={"#26931e"} /> </TouchableOpacity> <TouchableOpacity onPress={props.handleReject}> <Feather size={30} name={"slash"} color={"#a70000"} /> </TouchableOpacity> </View> </View> ) } export default FriendRequestCard;
const {promisify}=require('util'); const jwt=require('jsonwebtoken'); const User=require('../models/userModel'); const catchAsync=require("../utils/catchAsync"); const AppError=require("../utils/appError"); const sendEmail=require("../utils/email"); const crypto=require('crypto'); const signToken=id=>{ return jwt.sign({id},process.env.JWT_SECRET,{ expiresIn:process.env.JWT_EXPIRES_IN }) } const createSendToken=(user,statusCode,res)=>{ const token=signToken(user._id); const cookieOptions={ expires:new Date(Date.now()+process.env.JWT_COOKIE_EXPIRES_IN*24*60*60*1000), httpOnly:true } if(process.env.NODE_ENV==='production') cookieOptions.secure=true; res.cookie('jwt',token,cookieOptions); user.password=undefined; res.status(statusCode).json({ status: 'success', token, data:{ user } }); } exports.signup=catchAsync(async(req,res,next)=>{ const newUser=await User.create({ name:req.body.name, email:req.body.email, password:req.body.password, passwordConfirm:req.body.passwordConfirm }); createSendToken(newUser,201,res); }); exports.login=catchAsync(async(req,res,next)=>{ const {email,password}=req.body; if(!email ||!password){ return next(new AppError('Please provide email and password!',400)); } const user=await User.findOne({email:email}).select('+password'); if(!user||!(await user.correctPassword(password,user.password))){ return next(new AppError('Incorrect email or password',401)); } createSendToken(user,200,res); }) exports.protect=catchAsync(async(req,res,next)=>{ let token; if(req.headers.authorization && req.headers.authorization.startsWith('Bearer')){ token=req.headers.authorization.split(" ")[1]; } if(!token){ return next(new AppError("you are not logged in! Please log in to get access",401)); } console.log(token); //verification token const decoded=await promisify(jwt.verify)(token,process.env.JWT_SECRET); //check if user still exists const currentUser=await User.findById(decoded.id); if(!currentUser) return next(new AppError("the user belonging to the token does no longer exists")); //check if user changed password after the token was issued if(currentUser.changedPasswordAfter(decoded.iat)) return next(new AppError("User recently changed password! please log in again",401)); //grant access to protected route req.user=currentUser; next(); }) exports.restrictTo=(...roles)=>{ return (req,res,next)=>{ if(!roles.includes(req.user.role)){ return next(new AppError("you do not have permission to perform this action",403)); } next(); } } exports.forgotPassword=catchAsync(async(req,res,next)=>{ const user =await User.findOne({email:req.body.email}); if(!user){ return next(new AppError("there is no user with email address",401)); } const resetToken=user.createPasswordResetToken(); await user.save({validateBeforeSave:false}); const resetURL=`${req.protocol}://${req.get('host')}/api/v1/users/resetPassword/${resetToken}`; const message=`Forgot your password? Submit a PATCH request with your new password and passwordCofirm to:${resetURL}.\nIf you didn't forget your password,please ignore this eamil!`; // try{ await sendEmail({ email:user.email, subject:'Your password rest token(valid for 10 min)', message }); // }catch(err){ // user.passwordResetToken=undefined; // user.passwordResetExpires=undefined; // await user.save({validateBeforeSave:false}); // return next(new AppError("there was an error sending the email.try again later"),500) // } res.status(200).json({ status:"success", message:"Token sent to email" }); }) exports.resetPassword=catchAsync(async(req,res,next)=>{ console.log(req.body); const hashedToken=crypto.createHash('sha256').update(req.params.token).digest('hex'); const user=await User.findOne({passwordResetToken:hashedToken,passwordResetExpires:{$gt:Date.now()}}); if(!user){ return next(new AppError("Token is invalid or expired"),400); } user.password=req.body.password; user.passwordConfirm=req.body.passwordConfirm; user.passwordResetToken=undefined; user.passwordResetExpires=undefined; await user.save(); createSendToken(user,201,res); }) exports.updatePassword=catchAsync(async(req,res,next)=>{ const user=await User.findById(req.user.id).select('+password'); if(!(await user.correctPassword(req.body.passwordCurrent,user.password))){ return next(new AppError("Your current password is wrong"),401) } user.password=req.body.password; user.passwordConfirm=req.body.passwordConfirm; await user.save(); createSendToken(user,200,res); })
The Date Time Javascript Library Author(copyright): Edward Macnaghten <eddy@edlsystems.com> Version 2.0 - 17-March-2019 License: GPL-V3.0 INTRODUCTION This is maninly a wrapper around the Javascript "Date" object to make it easier to incorporate. Dates are complex. If you do not think so, then imagine the difference between adding months and adding days to a date, then adding months plus some day, etc. That is inconsistent depending on when in the year you do so. That is before you think of fractions of months. That is before you consider leap years. As for hours, minutes and seconds, you have a nightmare with time zones. Now put in the equation daylight saving. If you mention "Leap Seconds" to a developer involved in time and dates then the developer will totally ignore you (which is whart most of us do with leap seconds, they are ignored here). This sets of objects tries to make things easier for an application developer. It assumes: 1 - Time zones are irrelevant. Most instances of applications in the real world are localised, so only a single time zone is relevant. 2 - Daylight Savings errors we can live with, so long as number of days between dates is OK and differences in time can ignore them. There are three (user) objects MDate - A date class, deals with years, months and days only. No time. MTime - A time class, deals with Hours, minutes, seconds and milliseconds only. Dates are irrelevant. This doubles as an interval class, so number of ays can be incorporated here too. MDateTime - A DateTime class, handles dates and times. The "MDate" and "MDateTime" are wrappers arround a "Date" object. The "MTime" class stores it's information as a series of integers. They also support a concept of "null" value, where a blank or null value is supplied. Dependencies ~~~~~~~~~~~~ The following MUutilities files are required to be included: mdecimal.js - To provice the MDecimal object mutilbase.js - To provice the the base MUtilBase class Methods and Functions ~~~~~~~~~~~~~~~~~~~~~ A Summary copied from the source file: Following are summary of methods and functions, not all apply to all the above classes, they do not where irrevelant Where an MDate, MTime or MDateTime object is required, and the appropriate one is not provided, the system will try and create the appropriate object using the supplied argument as the creation one. i.e: setMDate("2019-03-02") is same as setMDate(new MDate("2019-03-02")) All numbers passed can be floats, integers, strings(with numbers in it) or MDecimal objects All three classes derive from a MDateTimeBase class An "MDateTimeMagic(arg)" function is supplied, this will return null (on error) or an instance of one of the three classes, which one depends on the argument supplied. The Class method/function overview: Creation: ~~~~~~~~~ new CLASS("NOW") - Create object as of "now" new CLASS() - Create object of NULL new CLASS(null) - Same new CLASS("") - Same new CLASS(object) - Cast from MDate, MDateTime, MTime and Date objects new CLASS(string) - Set from ISO string (No time zones) new CLASS(number) - Set from JS milliseconds new CLASS(all_else) - Does it's best from "string" Setting: ~~~~~~~~ setMDate(MDate_obj) - Sets date portion of object setMTime(MDate_obj) - Sets time portion of object setMDateTime(MDate_obj) - Sets relevant parts of object assemble(integers) - Assembles from integers Only supply integers relevant to object YYYY, MM, DD for MDate HH, MM, SS, MMMM for MTime All 7 for MDateTime setDate(day) - Sets the Date (day) portion of Date setMonth(month) - Sets the Month portion of Date Months start at 1 (Jan), and ends at 12 (Dec) setYear(year) - Sets the (full) year setHours(hour) - Sets the hour part of time (0 - 23) setMinutes(minutes) - Sets the minutes part of time (0 - 59) setSecconds(seconds) - Sets the seconds part of time (0 - 59) setMillisecconds(mils) - Sets the milliseconds part of time (0 - 999) setTime(milliseconds) - Sets the time based on milliseconds, (0 - 86400000) setDays(days) - Only applciable to MTime as an interval sets the number of days zero() - Only applicable to MTime - sets to midnight Getting: ~~~~~~~~ toString() - Returns an ISO string representation of the object toShortString() - MTime objects ony - retutns string HH:MM getDays() - MTime intervals only - get number of days as integer getYYYY() - YYYY can be Year, Month, Date (day of month), Hours, Minutes, Seconds, Milliseconds, Day (day of week) or Time (number of milliseconds since midnight) Manipulating: ~~~~~~~~~~~~~ addXXXX(amoubnt) - Adds units to object, XXXX can be: Miliseconds, Seconds, Minutes, Hours, Days, Months, Years addMTime(MTime_obj) - Can also be MTime for adding an mtime interval floor() - Truncates the time portion - MDateTime only Extracting ~~~~~~~~~~ plusXXXXX(amnt) - Like add.... except it returns new object rather than manipulates current diffXXXX(object) - Difference between this and object (of same type) return a number (Float) copy() - Creates and returns a deep copy of the object Testing ~~~~~~~ isNull() - Returns true if null isValid() - Returns false if not valid All comparisons change "other" to "this" object type cmp(other) - Returns 0 if equal to other 1 if greater than other -1 if less than other lt(other) - Returns true if this less than other gt(other) - Returns true if this greater than other le(other) - Returns true if less than or equal to other ge(other) - Returns true if greater than or equal to other
import React, { useEffect } from 'react'; import { Routes, Route, useLocation } from 'react-router-dom'; import { HomePage } from './pages/HomePage/HomePage' import { NotFoundPage } from './pages/NotFoundPage/NotFoundPage' import { LoginPage } from './pages/LoginPage/LoginPage' import appStyles from './app.module.css'; import { SignUpPage } from './pages/SignUpPage/SignUpPage'; import { ForgotPasswordPage } from './pages/ForgotPasswordPage/ForgotPasswordPage'; import { ResetPasswordPage } from './pages/ResetPasswordPage/ResetPasswordPage'; import { ProfilePage } from './pages/ProfilePage/ProfilePage'; import { OnlyAfterForgotPage, OnlyAuth, OnlyUnAuth } from './pages/ProtectedElement'; import { useDispatch, useSelector } from 'react-redux'; import { INGREDIENTS_URL } from './utils/constants'; import CardModal from './components/BurgerIngredients/CardModal'; import AppHeader from './components/AppHeader'; import { fetchDataAction } from './services/actions/fetchData'; import { IngPage } from './pages/IngPage/IngPage'; import { openCardModal } from './services/actions/modalngredients'; function App() { const location = useLocation(); let state = location.state; const dispatch = useDispatch(); const isIngredientCardModalOpen = JSON.parse((localStorage.getItem('modalIngredientCard')) || '[]'); useEffect(() => { //@ts-ignore dispatch(fetchDataAction(INGREDIENTS_URL)); if (isIngredientCardModalOpen) dispatch(openCardModal(isIngredientCardModalOpen)) }, []) //@ts-ignore const isOpen = useSelector(state => state.modalIngredients.isOpen); return ( <div className={appStyles.app}> <AppHeader /> <Routes location={state?.background || location}> <Route path="/" element={<HomePage />} /> <Route path="/login" element={<OnlyUnAuth component={<LoginPage />} />} /> <Route path="/register" element={<OnlyUnAuth component={<SignUpPage />} />} /> <Route path="/forgot-password" element={<OnlyUnAuth component={<ForgotPasswordPage />} />} /> <Route path="/reset-password" element={<OnlyAfterForgotPage component={<ResetPasswordPage />} />} /> {/* @ts-ignore */} <Route path="/profile" element={<OnlyAuth component={<ProfilePage />} />} /> {!state?.background && (<Route path="/ingredients/:id" element={<IngPage />} />)} <Route path="*" element={<NotFoundPage />} /> </Routes> {(state?.background && isOpen) && ( <Routes> <Route path="/ingredients/:id" element={<CardModal />} /> </Routes> )} </div> ) } export default App;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <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.11.3/font/bootstrap-icons.min.css"> <title>My Robot-contact</title> <title>Document</title> </head> <body> <nav class="navbar navbar-expand-lg bg-light"> <div class="container-fluid"> <a class="navbar-brand" href="index.html"><i class="bi bi-robot mx-2"></i>My Robot</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="index.html">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="page2.html">Our Inventions</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Contact</a> </li> </ul> </div> </div> </nav> <section id="ContactUs"> <h3 class="mx-auto text-center"> Contact Us <i class="bi bi-telephone"></i> </h3> <form id="formulario" class=" row g-3 needs-validation col-6 mx-auto" action="recieved.html" method="get" novalidate> <div class="col-md-6 position-relative mb-1"> <label for="inputName" class="form-label">Name:</label> <input type="text" class="form-control" id="inputName" aria-describedby="namelHelp" name="campoName" required /> <div class="valid-tooltip">Ok</div> </div> <div class="col-md-6 position-relative mb-1"> <label for="inputName" class="form-label">Last Name:</label> <input type="text" class="form-control" id="inputLastName" aria-describedby="lastnamelHelp" name="campolastName" required /> <div class="valid-tooltip">Ok</div> </div> <div class="col-md-6 position-relative mb-1"> <label for="inputPhone" class="form-label">Phone Number</label> <input type="tel" class="form-control" id="inputPhone" aria-describedby="phoneHelp" name="campoPhone" required /> </div> <div class="col-md-6 position-relative mb-1"> <label for="inputEmail" class="form-label">Email Address</label> <input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" name="campoEmail" required /> <div class="form-text" id="emailHelp"> No compartiremos su correo electrónico. </div> </div> <div class="input-group"> <span class="input-group-text">With textarea</span> <textarea class="form-control" aria-label="With textarea"></textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </section> <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> </body> </html>
import React, { useContext, useState } from "react"; import axios from "axios"; import { useEffect } from "react"; import { useRef } from "react"; // import { usernameContext, passwordContext } from "../../../App"; const Community = () => { // const [array, setArray] = useState([{ username: "Krish", message: "Hi" }]); // const { username, setusername } = useContext(usernameContext); const [username, setusername] = useState(); const [message, setmessage] = useState(); const [groupname, setgroupname] = useState("Group1"); const [array, setArray] = useState([ { username: "Ishaan", message: "Great" }, { username: "Shreyan", message: "I'm good, how are you?" }, ]); const inputRef = useRef(); useEffect(() => { if (message) { axios .post(`http://localhost:5000/community?chat=${groupname}`, { username: username, message: message, }) .catch((error) => { console.log(error); }); } }, [message]); useEffect(() => { axios .get(`http://localhost:5000/community?chat=${groupname}`) .then(function (response) { setArray(response.data); console.log(response.data); }) .catch(function (error) { console.log(error); }); }, []); useEffect(() => { setTimeout(() => { axios .get(`http://localhost:5000/community?chat=${groupname}`) .then(function (response) { // alert("done"); setArray(response.data); console.log(response.data); }) .catch(function (error) { console.log(error); }); }, 4000); }); return ( <> <div className="flex flex-row p-5 min-h-[90vh]"> <div className="w-2/6 border-4 rounded-l-xl"> <div className="text-3xl font-semibold mb-4 p-4 pb-0">Groups</div> <hr /> <div className="bg-gray-100 p-4 h-[88%]"> <div className=""> {/* <div onClick={() => setgroupname("TSEC students")} className={`border ${ groupname == "TSEC students" ? "bg-[#67ff6a]" : "bg-green-200" } cursor-pointer border-green-500 rounded-lg my-2 p-2 font-semibold text-xl`} > <div>TSEC students</div> </div> <div onClick={() => setgroupname("TSEC people")} className={`border ${ groupname == "TSEC people" ? "bg-[#67ff6a]" : "bg-green-200" } cursor-pointer border-green-500 rounded-lg my-2 p-2 font-semibold text-xl`} > <div>TSEC people</div> </div> */} <div onClick={() => setgroupname("ConvoCare")} className={`border ${ groupname == "ConvoCare" ? "bg-[#67ff6a]" : "bg-green-200" } cursor-pointer border-green-500 rounded-lg my-2 p-2 font-semibold text-xl`} > <div>ConvoCare</div> </div> <div onClick={() => setgroupname("Healing Together")} className={`border ${ groupname == "Healing Together" ? "bg-[#67ff6a]" : "bg-green-200" } cursor-pointer border-green-500 rounded-lg my-2 p-2 font-semibold text-xl`} > <div>Healing Together</div> </div> <div onClick={() => setgroupname("Mending Mindsets")} className={`border ${ groupname == "Mending Mindsets" ? "bg-[#67ff6a]" : "bg-green-200" } cursor-pointer border-green-500 rounded-lg my-2 p-2 font-semibold text-xl`} > <div>Mending Mindsets</div> </div> <div onClick={() => setgroupname("Mental Health Awareness")} className={`border ${ groupname == "Mental Health Awareness" ? "bg-[#67ff6a]" : "bg-green-200" } cursor-pointer border-green-500 rounded-lg my-2 p-2 font-semibold text-xl`} > <div>Mental Health Awareness</div> </div> </div> </div> </div> <div className="w-4/6 border-4 rounded-r-xl"> <div className="text-3xl font-semibold mb-4 px-4 pt-4"> {groupname} </div> <hr /> <div className="bg-gray-100 p-4"> <div className="flex justify-start pt-8"> <div> <div className="bg-gray-300 p-3 my-2 rounded-b-xl rounded-tr-xl"> <div className="text-md font-semibold text-blue-600"> Shreyan </div> <div className="text-lg">hey</div> </div> </div> </div> <div className="flex justify-end"> <div> <div className="bg-green-300 p-3 my-2 rounded-b-xl rounded-tl-xl"> how are you guys? </div> </div> </div> {array && array.map((item) => { return ( <div> {item.username == username ? ( <div className="flex justify-end"> <div className="bg-green-300 p-3 my-2 w-fit rounded-b-xl rounded-tl-xl"> {item.message} </div> </div> ) : ( <div className="bg-gray-300 p-3 my-2 w-fit rounded-b-xl rounded-tr-xl"> <div className="text-md font-semibold text-blue-600"> {item.username} </div> <div className="text-lg">{item.message}</div> </div> )} </div> ); })} </div> <div className="flex flex-row justify-end py-5 border p-2"> <input ref={inputRef} id="message" name="message" placeholder="Enter Message" className="border border-green-500 text-green-600 w-full rounded-lg px-3" type="text" /> <button onClick={() => { setmessage(inputRef.current.value); }} className="ml-5 bg-green-500 hover:bg-green-600 transition ease-in rounded-lg px-3 py-2 font-semibold text-white" > Send </button> </div> </div> </div> </> ); }; export default Community;
<?php namespace CrazyFactory\SpapiClient; class Authentication { /** * ## Signature Version 4 signing process * * Signature Version 4 is the process to add authentication information to AWS requests sent by HTTP. * For security, most requests to AWS must be signed with an access key, * which consists of an access key ID and secret access key. * These two keys are commonly referred to as your security credentials. * For details on how to obtain credentials for your account * * REF : https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html * * PS : Guzzle Request instance doesn't allow us to update headers after instantiation * So, we need to sign the header separately and return Authentication header back as a result. * * @param $signOptions * @return array * @throws \Exception */ public static function calculateSignature($signOptions): array { //required $service = $signOptions['service'] ?? null; $accessKey = $signOptions['accessKey'] ?? null; $secretKey = $signOptions['secretKey'] ?? null; $region = $signOptions['region'] ?? null; $host = $signOptions['host'] ?? null; $method = $signOptions['method'] ?? null; //optional $accessToken = $signOptions['accessToken'] ?? null; $securityToken = $signOptions['securityToken'] ?? null; $queryString = $signOptions['queryString'] ?? ''; $data = $signOptions['payload'] ?? []; $uri = $signOptions['uri'] ?? ''; $userAgent = $signOptions['userAgent'] ?? 'crazy_factory_client'; if (is_null($service)) { throw new \Exception("Service is required"); } if (is_null($accessKey)) { throw new \Exception("Access key is required"); } if (is_null($secretKey)) { throw new \Exception("Secret key is required"); } if (is_null($region)) { throw new \Exception("Region key is required"); } if (is_null($host)) { throw new \Exception("Host key is required"); } if (is_null($method)) { throw new \Exception("Method key is required"); } $terminationString = 'aws4_request'; $algorithm = 'AWS4-HMAC-SHA256'; $amzdate = gmdate('Ymd\THis\Z'); $date = substr($amzdate, 0, 8); // Prepare payload if (is_array($data)) { $param = json_encode($data); if ($param == "[]") { $requestPayload = ""; } else { $requestPayload = $param; } } else { $requestPayload = $data; } // Hashed payload $hashedPayload = hash('sha256', $requestPayload); //Compute Canonical Headers $canonicalHeaders = [ 'host' => $host, 'user-agent' => $userAgent, ]; // Check and attach access token to request header. if (!is_null($accessToken)) { $canonicalHeaders['x-amz-access-token'] = $accessToken; } $canonicalHeaders['x-amz-date'] = $amzdate; // Check and attach STS token to request header. if (!is_null($securityToken)) { $canonicalHeaders['x-amz-security-token'] = $securityToken; } $canonicalHeadersStr = ''; foreach ($canonicalHeaders as $h => $v) { $canonicalHeadersStr .= $h . ':' . $v . "\n"; } $signedHeadersStr = join(';', array_keys($canonicalHeaders)); //Prepare credentials scope $credentialScope = $date . '/' . $region . '/' . $service . '/' . $terminationString; //prepare canonical request $canonicalRequest = $method . "\n" . $uri . "\n" . $queryString . "\n" . $canonicalHeadersStr . "\n" . $signedHeadersStr . "\n" . $hashedPayload; //Prepare the string to sign $stringToSign = $algorithm . "\n" . $amzdate . "\n" . $credentialScope . "\n" . hash('sha256', $canonicalRequest); //Start signing locker process //Reference : https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html $kSecret = "AWS4" . $secretKey; $kDate = hash_hmac('sha256', $date, $kSecret, true); $kRegion = hash_hmac('sha256', $region, $kDate, true); $kService = hash_hmac('sha256', $service, $kRegion, true); $kSigning = hash_hmac('sha256', $terminationString, $kService, true); //Compute the signature $signature = trim(hash_hmac('sha256', $stringToSign, $kSigning)); //Finalize the authorization structure $authorizationHeader = $algorithm . " Credential={$accessKey}/{$credentialScope}, SignedHeaders={$signedHeadersStr}, Signature={$signature}"; $amazonHeader = array_merge($canonicalHeaders, [ "Authorization" => $authorizationHeader, ]); return $amazonHeader; } }
[discrete] [[esql-to_integer]] === `TO_INTEGER` Converts an input value to an integer value. The input can be a single- or multi-valued field or an expression. The input type must be of a boolean, date, string or numeric type. Example: [source.merge.styled,esql] ---- include::{esql-specs}/ints.csv-spec[tag=to_int-long] ---- [%header.monospaced.styled,format=dsv,separator=|] |=== include::{esql-specs}/ints.csv-spec[tag=to_int-long-result] |=== Note that in this example, the last value of the multi-valued field cannot be converted as an integer. When this happens, the result is a *null* value. In this case a _Warning_ header is added to the response. The header will provide information on the source of the failure: `"Line 1:61: evaluation of [TO_INTEGER(long)] failed, treating result as null. Only first 20 failures recorded."` A following header will contain the failure reason and the offending value: `"org.elasticsearch.xpack.ql.QlIllegalArgumentException: [501379200000] out of [integer] range"` If the input parameter is of a date type, its value will be interpreted as milliseconds since the https://en.wikipedia.org/wiki/Unix_time[Unix epoch], converted to integer. Boolean *true* will be converted to integer *1*, *false* to *0*. Alias: TO_INT
/* eslint-disable @typescript-eslint/no-this-alias */ import mongoose from "mongoose"; import User, { IUser } from "./user"; export interface ITransaction { patientId: mongoose.PopulatedDoc<IUser>; doctorId: mongoose.PopulatedDoc<IUser>; amount: number; transactionId: string; status: string; dateTime: string; } const transactionSchema = new mongoose.Schema( { patientId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "User", }, doctorId: { type: mongoose.Schema.Types.ObjectId, required: true, ref: "User", }, amount: { type: Number, required: true, min: 0, }, transactionId: { type: String, required: true, minlength: 2, maxlength: 50, }, status: { type: String, required: true, minlength: 2, maxlength: 50, }, dateTime: { type: Date, required: true, }, }, { timestamps: true, } ); transactionSchema.pre("save", async function (next) { if (this.isModified("Status")) { this.dateTime = new Date(); } if (this.doctorId.toString() === this.patientId.toString()) { return next(new Error("Doctor cannot be patient")); } const doctorExists = await User.exists({ _id: this.doctorId }); if (!doctorExists) { return next(new Error("Doctor does not exist")); } const patientExists = await User.exists({ _id: this.patientId }); if (!patientExists) { return next(new Error("Patient does not exist")); } next(); }); const Transaction = mongoose.model("transaction", transactionSchema); export default Transaction;
import { ApiProperty } from "@nestjs/swagger"; import { IsDate, IsNumber, IsOptional, IsString, Min, MinDate, } from "class-validator"; export class UpdateCleaningSubscriptionBookingDto { @ApiProperty({ required: false, description: "Date of the cleaning", }) @IsOptional() @IsDate({ message: "Cleaning date must be a valid date" }) @MinDate(new Date(), { message: "Cleaning date must be in the future" }) cleaningDate?: Date; @ApiProperty({ required: false, description: "Additional charges for the cleaning", }) @IsOptional() @IsNumber({}, { message: "Additional charges must be a number" }) @Min(0, { message: "Additional charges cannot be negative" }) additionalCharges?: number; @ApiProperty({ required: false, description: "Remarks or notes for the cleaning booking", }) @IsOptional() @IsString({ message: "Remarks must be a string" }) remarks?: string; }
import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model from sklearn.neighbors import KNeighborsClassifier def nearest_neighbour_curse_of_dimensionality() -> None: """ Classification with 3 different types of irises (Setosa, Versicolour, and Virginica) from their petal and sepal length and width """ iris_X, iris_y = datasets.load_iris(return_X_y=True) print(np.unique(iris_y)) # array([0, 1, 2]) # KNN Example (K Nearest Neighbours) # Split iris data in train and test data # A random permutation, to split the data randomly np.random.seed(0) indices = np.random.permutation(len(iris_X)) iris_X_train = iris_X[indices[:-10]] iris_y_train = iris_y[indices[:-10]] iris_X_test = iris_X[indices[-10:]] iris_y_test = iris_y[indices[-10:]] # Create and fit a nearest-neighbor classifier knn = KNeighborsClassifier() knn.fit(iris_X_train, iris_y_train) # KNeighborsClassifier() print(knn.predict(iris_X_test)) # array([1, 2, 1, 0, 0, 0, 2, 1, 2, 0]) print(iris_y_test) # array([1, 1, 1, 0, 0, 0, 2, 1, 2, 0]) """ For an estimator to be effective, you need the distance between neighboring points to be less than some value. In one dimension, this requires on average 1/d points. If the number of features is p, you now require 1/(d^p) points. As p becomes large, the number of training points required for a good estimator grows exponentially. This is called the curse of dimensionality and is a core problem that machine learning addresses. """ def linear_model_regression_to_sparsity() -> None: """ The diabetes dataset consists of 10 physiological variables (age, sex, weight, blood pressure) measured on 442 patients, and an indication of disease progression after one year: The task at hand is to predict disease progression from physiological variables. """ diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True) diabetes_X_train = diabetes_X[:-20] diabetes_X_test = diabetes_X[-20:] diabetes_y_train = diabetes_y[:-20] diabetes_y_test = diabetes_y[-20:] # Linear Regression regr = linear_model.LinearRegression() print(regr.fit(diabetes_X_train, diabetes_y_train)) # LinearRegression() print(regr.coef_) # [0.30349955 -237.63931533 510.53060544 327.73698041 -814.13170937 # 492.81458798 102.84845219 184.60648906 743.51961675 76.09517222] # The mean square error print(np.mean((regr.predict(diabetes_X_test) - diabetes_y_test) ** 2)) # 2004.5... # Explained variance score: 1 is perfect prediction # and 0 means that there is no linear relationship # between X and y. print(regr.score(diabetes_X_test, diabetes_y_test)) # 0.585... def shrinkage() -> None: """ If there are few data points per dimension, noise in the observations induces high variance: A solution in high-dimensional statistical learning is to shrink the regression coefficients to zero: any two randomly chosen set of observations are likely to be uncorrelated. This is called Ridge regression: """ X = np.c_[0.5, 1].T y = [0.5, 1] test = np.c_[0, 2].T regr = linear_model.LinearRegression() plt.figure() np.random.seed(0) for _ in range(6): this_X = 0.1 * np.random.normal(size=(2, 1)) + X regr.fit(this_X, y) plt.plot(test, regr.predict(test)) plt.scatter(this_X, y, s=3) # LinearRegression... plt.savefig("./Images/2_output_plot.png") regr = linear_model.Ridge(alpha=0.1) plt.figure() np.random.seed(0) for _ in range(6): this_X = 0.1 * np.random.normal(size=(2, 1)) + X regr.fit(this_X, y) plt.plot(test, regr.predict(test)) plt.scatter(this_X, y, s=3) plt.savefig("./Images/2B_output_plot.png") # This is an example of bias/variance tradeoff: the larger # the ridge alpha parameter, the higher the bias and the # lower the variance. # We can choose alpha to minimize left out error, this time # using the diabetes dataset rather than our synthetic data: diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True) diabetes_X_train = diabetes_X[:-20] diabetes_X_test = diabetes_X[-20:] diabetes_y_train = diabetes_y[:-20] diabetes_y_test = diabetes_y[-20:] alphas = np.logspace(-4, -1, 6) print( [ regr.set_params(alpha=alpha) .fit(diabetes_X_train, diabetes_y_train) .score(diabetes_X_test, diabetes_y_test) for alpha in alphas ] ) # [0.585..., 0.585..., 0.5854..., 0.5855..., 0.583..., 0.570...] if __name__ == "__main__": nearest_neighbour_curse_of_dimensionality() linear_model_regression_to_sparsity() shrinkage()
import React from 'react'; // 컨텍스트 가져오기 import {ViewProductContext} from '../../context/ViewProductContext'; export default function Section4SlideWrapSlide({상품}) { // 컨텍스트 사용 등록 const {setViewProductFn} = React.useContext(ViewProductContext); const [state, setState] = React.useState({ H:0, //시 M:0, //분 S:0 //초 }); React.useEffect(()=>{ let setId = setInterval(function(){ // 타이머카운트 : 타임세일 24시간 // 시작시간 = 현재시간(타임세일시작시간) // 종료시간 = 현재시간(타임세일시작시간)+24시간 // 현재시간 // 남은시간 = 종료시간 - 현재시간 let timeSale = '2023-05-28 09:00:00'; let start = new Date(timeSale); // 타임세일시작시간 start.setHours(start.getHours()+24); // 24시간 타임세일(종료시간) let now = new Date(); // 현재시간 let countTime = start - now; // 남은시간(카운트타임) = 타임세일종료시간-현재시간 let h=0, m=0, s=0; if( now >= start ){ clearInterval(setId); h=0; m=0; s=0; } else{ h = Math.floor(countTime/(60*60*1000)) % 24 ; // 1일은 24시(남은시간 계산) 소수미만 버림 m = Math.floor(countTime/(60*1000)) % 60 ; // 1시간은 60분 s = Math.floor(countTime/(1000)) % 60 ; // 1분은 60초 } setState({ ...state, H: h<10 ? `0${h}`: h, M: m<10 ? `0${m}`: m, S: s<10 ? `0${s}`: s }); }, 1000); },[]); const onClickViewProduct=(e, item, imgPath)=>{ e.preventDefault(); setViewProductFn(item, imgPath); // 현재 클릭한 상품정보가 최상위 컴포넌트에게 전달된다. } return ( <ul className="slide-wrap"> <li className="slide slide1"> <div className="slide-gap"> <ul> <li><h2>일일특가</h2></li> <li><h3>24시간 한정 특가</h3></li> <li> <div className="timer"> <img src="./img/intro/timer.svg" alt="" /> </div> <div className="timer-counter"> <span className='hours'>{state.H}</span> <i>:</i> <span className='minutes'>{state.M}</span> <i>:</i> <span className='seconds'>{state.S}</span> </div> </li> <li> <p>망설이면 늦어요!</p> </li> </ul> </div> </li> { 상품.map((item, idx)=>{ return( <li className="slide" key={item.번호}> <div className="slide-gap" onClick={(e)=>onClickViewProduct(e, item, `./img/intro/${item.이미지}`)}> <div className="img-box"> <img src={`./img/intro/${item.이미지}`} alt="" /> <span><img src="./img/intro/icon_cart_purple.svg" alt="" /></span> </div> <div className="txt-box"> <ul> <li>{item.상품소개}</li> <li>{item.상품이름}</li> <li> { item.할인율 > 0 ? ( <> <strong>{Math.round(item.할인율*100)}%</strong> <span>{(Math.round(item.정가*(1-item.할인율))).toLocaleString('ko-KR')}원</span> <em>{item.정가.toLocaleString('ko-KR')}원</em> </> ) : ( item.정가.toLocaleString('ko-KR') ) } </li> <li> <img src={`./img/intro/icon_review.svg`} alt="" /> <span>{`후기`}</span> <span>{item.후기카운트}</span> </li> </ul> </div> </div> </li> ) }) } </ul> ); };
import streamlit as st from pytube import YouTube from dotenv import load_dotenv load_dotenv() import os import google.generativeai as genai from youtube_transcript_api import YouTubeTranscriptApi genai.configure(api_key=os.getenv("GOOGLE_API_KEY")) prompt="""You are Yotube video summarizer. You will be taking the transcript text and summarizing the entire video and providing the important summary in points within 250 words. Please provide the summary of the text given here: """ def extract_transcipt_details(youtube_video_url): try: video_id = youtube_video_url.split("=")[1] transcript_text = YouTubeTranscriptApi.get_transcript(video_id) transcript = " ".join([i['text'] for i in transcript_text]) video_title = YouTube(youtube_video_url).title return transcript, video_title except Exception as e: raise e def generate_gemini_content(transcript_text,prompt,video_title): model=genai.GenerativeModel("gemini-pro") response=model.generate_content(prompt+transcript_text) output = f"Video Title: {video_title}\n\n{response.text}" return output st.title("YouTube Video Summarizer") YouTube_link = st.text_input("Enter YouTube Video Link:") if YouTube_link: video_id = YouTube_link.split("=")[1] st.image(f"http://img.youtube.com/vi/{video_id}/0.jpg", use_column_width=True) if st.button("Summarize Video"): transcript_text, video_title= extract_transcipt_details(YouTube_link) if transcript_text: summary = generate_gemini_content(transcript_text, prompt, video_title) st.markdown("## Summarize Video:") st.write(summary)
// // Copyright (C) 2012-2023 Jack Araz, Eric Conte & Benjamin Fuks // The MadAnalysis development team, email: <ma5team@iphc.cnrs.fr> // // This file is part of MadAnalysis 5. // Official website: <https://github.com/MadAnalysis/madanalysis5> // // MadAnalysis 5 is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // MadAnalysis 5 is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with MadAnalysis 5. If not, see <http://www.gnu.org/licenses/> // #ifndef READER_TEXT_BASE_h #define READER_TEXT_BASE_h // STL headers #include <fstream> #include <iostream> #include <sstream> // SampleAnalyzer headers #include "SampleAnalyzer/Commons/Base/PortableDatatypes.h" #include "SampleAnalyzer/Commons/Base/ReaderBase.h" class gz_istream; namespace MA5 { class ReaderTextBase : public ReaderBase { // ------------------------------------------------------------- // data members // ------------------------------------------------------------- protected: /// Streaming in GZ format gz_istream * gzinput_; /// Streaming for reading input std::istream* input_; std::streampos oldpos_; /// Streaming for fifo std::ifstream* input_fifo_; /// Name of the file (without prefix such as file: or rfio:) std::string filename_; // ------------------------------------------------------------- // method members // ------------------------------------------------------------- public: /// Constructor without argument ReaderTextBase() { input_ = 0; input_fifo_ = 0; } /// Destructor virtual ~ReaderTextBase() { if (input_ !=0) delete input_; if (input_fifo_!=0) delete input_fifo_; } /// Initialize virtual MAbool Initialize(const std::string& rawfilename, const Configuration& cfg); /// Read the sample (virtual pure) virtual MAbool ReadHeader(SampleFormat& mySample) = 0; /// Finalize the header (virtual pure) virtual MAbool FinalizeHeader(SampleFormat& mySample) = 0; /// Read the event (virtual pure) virtual StatusCode::Type ReadEvent(EventFormat& myEvent, SampleFormat& mySample) = 0; /// Finalize the event (virtual pure) virtual MAbool FinalizeEvent(SampleFormat& mySample, EventFormat& myEvent) = 0; /// Finalize virtual MAbool Finalize(); /// Read line text MAbool ReadLine(std::string& line, MAbool removeComment=true); /// Get the file size (in octet) virtual MAint64 GetFileSize(); /// Get the final position in file virtual MAint64 GetFinalPosition(); /// Get the position in file virtual MAint64 GetPosition(); }; } #endif
import 'Cliente.dart'; import 'Tecnico.dart'; import 'ParteTecnico.dart'; import 'ParteTrabajo.dart'; class Trabajo { Cliente cliente; Tecnico tecnico; ParteTrabajo parteTrabajo; ParteTecnico parteTecnico; String descripcion; bool hecho; double presupuesto; Trabajo(String desc, Cliente clienteCreador) { this.descripcion = desc; this.cliente = clienteCreador; } void asignarTecnico(Tecnico nuevoTecnico) { tecnico = nuevoTecnico; nuevoTecnico.asignarTrabajo(this); } void realizado() { if (tecnico != null) { hecho = true; } else { print("El trabajo no tiene asignado un técnico\n"); } } void setPresupuesto(double nuevoPresupuesto) { presupuesto = nuevoPresupuesto; } void darParteTecnico(int amable, int profesional, int eficaz) { if (parteTecnico != null) { parteTecnico.setAmabilidad(amable); parteTecnico.setProfesionalidad(profesional); parteTecnico.setEficacia(eficaz); } else { parteTecnico = new ParteTecnico(amable, profesional, eficaz); } } void darParteTrabajo( int horas, int costoMateriales, int costoDesplazamiento) { if (parteTrabajo != null) { parteTrabajo.setHorasExtra(horas); parteTrabajo.setCosteMaterialesExtra(costoMateriales); parteTrabajo.setCosteDesplazamiento(costoDesplazamiento); } else { parteTrabajo = new ParteTrabajo(horas, costoMateriales, costoDesplazamiento); } } double getPresupuesto() { return presupuesto; } String getDescripcion() { return descripcion; } Tecnico getTecnico() { return tecnico; } ParteTecnico getParteTecnico() { return parteTecnico; } ParteTrabajo getParteTrabajo() { return parteTrabajo; } }
import { TextField } from "@mui/material"; import html2canvas from "html2canvas"; import jsPDF from "jspdf"; import React, { useEffect, useRef, useState } from "react"; import { sendInventory } from "../services/orderService"; import Card from "../UI/Card"; import style from "./AdminInventory.module.css"; import SaveAltIcon from "@mui/icons-material/SaveAlt"; import ReactToPrint from "react-to-print"; import { Button } from "@mui/base"; const AdminInventory = () => { // const ctx = useSelector((state) => state.cartReducer); // const dispatch = useDispatch(); const initialState = { quantity: 0, price: "", comment: "", vendor: "", number: "", location: "", }; const [inputValues, setInputValues] = useState(Array(40).fill(initialState)); const [time, setTime] = useState(); let pdfRef = useRef(); let componentRef = useRef(); const items = [ "1. Chicken Patties", "2. Beef Patties", "3. Thigh Pieces", "4. Shawarma Chicken Pieces", "5. Chicken 9 cut Pieces", "6. Wings", "7. Fries", "8. Paratha", "9. Mushroom", "10. Cholay", "11. Samosa", "12. Buns", "13. Shawarma Bread", "14. Mayo", "15. Mayo Garlic", "16. Shawarma Hot Sauce", "17. Buffalo Sauce", "18. Bechamel Sauce", "19. Masala", "20. Ice Berg", "21. Meda", "22. Pickle", "23. Tomatoes", "24. Onions", "25. Chimichuri", "26. Ketchup packets (Small)", "27. Big ketucp sachet", "28. Garlic sauce sachet", "29. Big Box", "30. Small Box", "31. Aluminium Box", "32. Dip Packets", "33. Butter Paper", "34. Serving plate", "35. Oil", "36. Ghee", "37. Gas", "38. Butter", "39. Milk ", "40. Cleaning supplies", ]; const throttle = (func, delay) => { let lastExecTime = 0; return (...args) => { const now = Date.now(); if (now - lastExecTime >= delay) { lastExecTime = now; func(...args); } }; }; const handleInputChange = throttle((index, key, value) => { setInputValues((prevValues) => { const updatedValues = [...prevValues]; updatedValues[index] = { ...updatedValues[index], [key]: value }; return updatedValues; }); }, 10); const downloadPdf = async (e) => { e.preventDefault(); html2canvas(pdfRef.current, { backgroundColor: "#000000" }).then( (canvas) => { const pdf = new jsPDF("p", "pt", "a4"); const imgData = canvas.toDataURL("image/png"); const imgWidth = 650; const imgHeight = (canvas.height * imgWidth) / canvas.width; // Calculate the center position. const xPos = (pdf.internal.pageSize.width - imgWidth) / 2; let yPos = (pdf.internal.pageSize.height - imgHeight) / 2; pdf.addImage(imgData, "PNG", xPos, yPos, imgWidth, imgHeight); pdf.save(`BabaJanis Inventory.pdf`); } ); const inventory = { time: time, inventory: inputValues.map((input, i) => ({ item: items[i], quantity: input.quantity, price: input.price, comment: input.comment, vendor: input.vendor, number: input.number, location: input.location, })), }; console.log(inventory); sendInventory(inventory) .then((response) => { console.log("Inventory sent successfully:", response); }) .catch((error) => { window.alert("Error while Saving Inventory ☹"); console.log("Error while Saving Inventory:", error); }); }; const handleInputFocus = (event) => { event.target.select(); }; useEffect(() => { const monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ]; const currentTime = new Date(); setTime( `${currentTime.getDate().toString()}-${ monthNames[currentTime.getMonth()] }-${currentTime.getFullYear().toString()}` ); }, []); return ( <div ref={pdfRef}> <h1> <u>Inventory Mode On..!</u> </h1> <Card> <form className={style.form} onSubmit={downloadPdf} ref={(e) => (componentRef = e)} > <span style={{ display: "flex", justifyContent: "flex-end" }}> {time} </span> <table className={style.table}> <thead> <tr style={{ color: "aqua" }}> <th>Item</th> <th>Quantity</th> <th>Comment</th> <th>Price</th> <th>Vendor</th> <th>Number</th> <th>Location</th> </tr> </thead> <tbody> {inputValues.map((row, index) => ( <tr key={index}> <td>{items[index]}</td> <td> {/* <span style={{ color: "aqua" }}>*</span> */} <TextField id="outlined-controlled" type="number" size="small" // placeholder="Quantity" value={row.quantity} onFocus={(e) => handleInputFocus(e)} onChange={(e) => handleInputChange(index, "quantity", e.target.value) } /> </td> <td> <TextField id="outlined-controlled" type="text" size="small" // placeholder="Comment" value={row.comment} onFocus={(e) => handleInputFocus(e)} onChange={(e) => handleInputChange(index, "comment", e.target.value) } /> </td> <td> <TextField id="outlined-controlled" type="number" size="small" // placeholder="Price" value={row.price} onFocus={(e) => handleInputFocus(e)} onChange={(e) => handleInputChange(index, "price", e.target.value) } /> </td> <td> <TextField id="outlined-controlled" type="text" size="small" // placeholder="Vendor" value={row.vendor} onFocus={(e) => handleInputFocus(e)} onChange={(e) => handleInputChange(index, "vendor", e.target.value) } /> </td> <td> <TextField id="outlined-controlled" type="text" size="small" // placeholder="Number" value={row.number} onFocus={(e) => handleInputFocus(e)} onChange={(e) => handleInputChange(index, "number", e.target.value) } /> </td> <td> <TextField id="outlined-controlled" type="text" size="small" // placeholder="Location" value={row.location} onFocus={(e) => handleInputFocus(e)} onChange={(e) => handleInputChange(index, "location", e.target.value) } /> </td> </tr> ))} </tbody> </table> <button className={style.btn} type="submit"> Save as PDF <SaveAltIcon sx={{ marginLeft: "5px", fontSize: "medium" }} /> </button> <ReactToPrint trigger={() => { return ( <Button style={{ display: "flex", justifyContent: "flex-end" }} className={style.btn} > Print </Button> ); }} content={() => componentRef} documentTitle="BABA Jani's " pageStyle="Print" /> </form> </Card> </div> ); }; export default AdminInventory;
#!/usr/bin/env python3 """Compile a summary of latest dictionary data to accompany a release.""" from rich import print from db.get_db_session import get_db_session from db.models import PaliWord, PaliRoot, Sandhi, DerivedData from tools.pali_sort_key import pali_sort_key from tools.tic_toc import tic, toc from tools.configger import config_read, config_update from tools.paths import ProjectPaths from tools.uposatha_day import uposatha_today def main(): tic() print("[bright_yellow]summary") print("[green]reading db tables") pth = ProjectPaths() db_session = get_db_session(pth.dpd_db_path) dpd_db = db_session.query(PaliWord).all() roots_db = db_session.query(PaliRoot).all() sandhi_db = db_session.query(Sandhi).all() derived_db = db_session.query(DerivedData).all() last_count = config_read("uposatha", "count", default_value=74657) print("[green]summarizing data") line1, line5, root_families = dpd_size(dpd_db) line2 = root_size(roots_db, root_families) line3 = sandhi_size(sandhi_db) line4 = inflection_size(derived_db) line6 = root_data(roots_db) new_words_string = new_words(db_session, last_count) print() print(line1) print(line2) print(line3) print(line4) print(line5) print(line6) print("- 100% dictionary recognition up to and including ") print() print(f"new words include: {new_words_string}") if uposatha_today(): print("[green]updating uposatha count") config_update("uposatha", "count", len(dpd_db)) toc() def dpd_size(dpd_db): total_headwords = len(dpd_db) total_complete = 0 total_partially_complete = 0 total_incomplete = 0 root_families: dict = {} total_data = 0 columns = PaliWord.__table__.columns column_names = [c.name for c in columns] exceptions = ["id", "user_id", "created_at", "updated_at"] for i in dpd_db: if i.meaning_1: if i.example_1: total_complete += 1 else: total_partially_complete += 1 else: total_incomplete += 1 if i.root_key: subfamily = f"{i.root_key} {i.family_root}" if subfamily in root_families: root_families[f"{i.root_key} {i.family_root}"] += 1 else: root_families[f"{i.root_key} {i.family_root}"] = 1 for column in column_names: if column not in exceptions: cell_value = getattr(i, column) if cell_value: total_data += 1 line1 = "- " line1 += f"{total_headwords:_} headwords, " line1 += f"{total_complete:_} complete, " line1 += f"{total_partially_complete:_} partially complete, " line1 += f"{total_incomplete:_} incomplete entries" line1 = line1.replace("_", " ") line5 = f"- {total_data:_} cells of Pāḷi word data" line5 = line5.replace("_", " ") return line1, line5, root_families def new_words(db_session, last_count): db = db_session.query(PaliWord).filter(PaliWord.id > last_count).all() new_words = [i.pali_1 for i in db] new_words = sorted(new_words, key=pali_sort_key) new_words_string = "" for nw in new_words: if nw != new_words[-1]: new_words_string += f"{nw}, " else: new_words_string += f"{nw} " new_words_string += f"[{len(new_words)}]" return new_words_string def root_size(roots_db, root_families): total_roots = len(roots_db) total_root_families = len(root_families) total_derived_from_roots = 0 for family in root_families: total_derived_from_roots += root_families[family] line2 = "- " line2 += f"{total_roots:_} roots, " line2 += f"{total_root_families:_} root families, " line2 += f"{total_derived_from_roots:_} words derived from roots" line2 = line2.replace("_", " ") return line2 def sandhi_size(sandhi_db): total_sandhis = len(sandhi_db) line3 = f"- {total_sandhis:_} deconstructed compounds" line3 = line3.replace("_", " ") return line3 def inflection_size(derived_db): total_inflections = 0 all_inflection_set = set() for i in derived_db: inflections = i.inflections_list total_inflections += len(inflections) all_inflection_set.update(inflections) # print(total_inflections) # print(len(all_inflection_set)) line4 = f"- {total_inflections:_} unique inflected forms recognised" line4 = line4.replace("_", " ") return line4 def root_data(roots_db): columns = PaliRoot.__table__.columns column_names = [c.name for c in columns] exceptions = ["root_info", "root_matrix", "created_at", "updated_at"] total_roots_data = 0 for i in roots_db: for column in column_names: if column not in exceptions: cell_value = getattr(i, column) if cell_value: total_roots_data += 1 line6 = f"- {total_roots_data:_} cells of Pāḷi root data" line6 = line6.replace("_", " ") return line6 if __name__ == "__main__": main()
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using Soda.AutoMapper; using Soda.Ice.Domain; using Soda.Ice.Shared.ViewModels; using Soda.Ice.WebApi.Auth; using Soda.Ice.WebApi.Options; using Soda.Ice.WebApi.Services.CurrentUserServices; using Soda.Ice.WebApi.UnitOfWorks; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; namespace Soda.Ice.WebApi.Controllers; /// <summary> /// 注册用户信息 /// </summary> public class AuthorizationController : ApiControllerBase { private readonly Session _session; private readonly IUnitOfWork _unitOfWork; private readonly PermissionRequirement _tokenParameter; public AuthorizationController( Session session, IConfiguration configuration, IUnitOfWork unitOfWork, IOptions<AppSettings> options) { _session = session; _unitOfWork = unitOfWork; _tokenParameter = options.Value.TokenParameter; } /// <summary> /// 登录 /// </summary> /// <param name="request"> </param> /// <returns> </returns> [HttpPost("login")] [AllowAnonymous] public async Task<IActionResult> Login([FromBody] VLogin request) { if (string.IsNullOrEmpty(request.Account) || string.IsNullOrEmpty(request.Password)) return Fail("Invalid Request"); var user = await _unitOfWork.Query<User>().Where(x => x.Account.Equals(request.Account)).FirstOrDefaultAsync(); if (user is null) { return Fail("账号不存在"); } if (user!.Password != request.Password) { return Fail("密码错误"); } //生成Token和RefreshToken var token = GenUserToken(user.Id, request.Account, user.Name); var refreshToken = "123456"; return Success(new VToken { Token = token, RefreshToken = refreshToken, User = user.MapTo<VUser>() }); } /// <summary> /// 注册 /// </summary> /// <param name="dto"> </param> /// <returns> </returns> [HttpPost("register")] [AllowAnonymous] public async Task<IActionResult> Register([FromBody] VRegisterUser dto) { if (dto is null) throw new ArgumentNullException(nameof(dto)); var user = dto.MapTo<User>(); await _unitOfWork.Db.AddAsync<User>(user); var res = await _unitOfWork.CommitAsync(); if (res) Success("注册成功"); return Fail("注册失败"); } [HttpPost("change")] public async Task<IActionResult> ChangePassword([FromBody] VChangePassword vChangePassword) { var user = await _unitOfWork.Query<User>().FirstOrDefaultAsync(x => x.Id == _session.UserId); if (user is null) return Fail("找不到用户"); if (!user.Password.Equals(vChangePassword.OldPassword)) { return Fail("密码错误"); } if (vChangePassword.Verify()) { user.Password = vChangePassword.NewPassword; _unitOfWork.Db.Update(user); if (await _unitOfWork.CommitAsync()) { return Success("修改密码成功"); } } return Fail("修改密码失败"); } /// <summary> /// 生成Token /// </summary> /// <param name="id"> </param> /// <param name="username"> </param> /// <param name="role"> </param> /// <returns> </returns> private string GenUserToken(Guid id, string username, string role) { var claims = new[] { new Claim(ClaimTypes.Sid, id.ToString()), new Claim(ClaimTypes.DateOfBirth,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), new Claim(ClaimTypes.Name, username), new Claim(ClaimTypes.Role, role), }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_tokenParameter.Secret)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var jwtToken = new JwtSecurityToken(_tokenParameter.Issuer, _tokenParameter.Audience, claims, expires: DateTime.UtcNow.AddMinutes(_tokenParameter.AccessExpiration), signingCredentials: credentials); var token = new JwtSecurityTokenHandler().WriteToken(jwtToken); return token; } }
{%- liquid assign default_color = 'rgba(0,0,0,0)' assign items_resp = section.settings.items_resp | default: '3,2,1' assign enable_menu = section.settings.enable_menu assign sectionID = '#section-' | append: section.id assign block_bg_color = section.settings.block_bg_color | default: default_color assign section_style = section.settings.style assign spacing_items = section.settings.spacing_items assign subheading = section.settings.subheading assign isBoxed = section.settings.boxed_layout assign menu_btn = section.settings.menu_btn assign bg_color = section.settings.bg_color | default: default_color | replace: default_color, '' assign heading = section.settings.heading assign show_border_bottom = section.settings.show_border_bottom assign heading_style_block = section.blocks | where: 'type', 'heading-style' | first assign collection_blocks = section.blocks | where: 'type', 'collection' assign show_heading_section = section.settings.show_heading_section assign block_text_center = section.settings.block_text_center -%} {%- capture section_class -%} home-categories {% if show_border_bottom %} has-border {%- endif %} style-{{section_style}} {%- endcapture -%} {%- unless section.settings.bg_full -%} {%- assign bg_class = ' .section_content-wrapper' -%} {%- endunless -%} <div class="{{section_class}}" id="section-{{section.id}}" data-section-type="featured-collections"data-section-id="{{section.id}}"> {%- if isBoxed -%}<div class="container">{%- endif -%} <div class="section_content-wrapper"> {%- if show_heading_section and heading != blank or subheading != blank -%} {%- capture heading_css -%}{%- render 'snippet-heading-css' sectionID: sectionID, section: heading_style_block -%}{%- endcapture -%} <div class="section_content-head"> {%- render 'snippet-heading' config: section.settings -%} </div> {%- endif -%} <div class="section_content-body"> {%- case section_style -%} {%- when '1' -%} {%- liquid assign slider_id = '#slider-' | append: section.id assign controls_id = '#controls-' | append: section.id assign total_item = collection_blocks | size -%} <div class="slider-container js-slider-container"> <div class="slider-wrapper"> <div class="slider-list" id="slider-{{section.id}}"> {%- for block in collection_blocks -%} {%- if block.type != 'collection' -%}{%- continue -%}{%- endif -%} {%- liquid assign _collection = block.settings.collection assign collection = collections[_collection] assign image = block.settings.image assign block_menu = block.settings.menu assign block_title = block.settings.title -%} <div class="card_section-item slider-item" {{block.shopify_attributes}}> {%- if _collection == blank -%} {%- include 'svgset', type: 'empty-category' -%} {%- else -%} <div class="card_section-item-inner {% unless enable_menu %}no-menu{%- endunless -%}"> <div class="card_section-header"> <div class="card_section-figure"> <a href="{{collection.url}}" class="image"> {%- if image != blank -%} {%- render 'image-style', image: image, alt: collection.title -%} {%- else-%} {%- render 'image-style' image: collection.featured_image, alt: collection.title -%} {%- endif -%} </a> </div> </div> <div class="card_section-body"> <div class="card_section-menu"> <ul class="menu-list-content"> <li class="menu-item"> <h3 class="title"><a href="{{collection.url}}">{{block_title | default: collection.title}}</a></h3> </li> {%- if enable_menu -%} {%- for link in linklists[block_menu].links limit: 4 -%} <li class="menu-item"><a href="{{link.url}}">{{link.title}}</a></li> {%- endfor -%} {%- endif -%} </ul> {%- if enable_menu -%} <a href="{{collection.url}}" class="btn-show-all"> <div class=""> <span>{{menu_btn}}</span> <span class="svg_emlement-ui">{%- render 'svg' type: 'angle-right' -%}</span> </div> </a> {%- endif -%} </div> </div> </div> {%- endif -%} </div> {%- else -%} {%- assign total_item = 5 -%} {%- for i in (1..7) -%} <div class="card_section-item slider-item"> {%- include 'svgset', type: 'empty-category' -%} </div> {%- endfor -%} {%- endfor -%} </div> {%- render 'set-tns-config' slider_id : slider_id, controls_id : controls_id, loop : section.settings.loop, autoplay : section.settings.autoplay, autoplay_timeout: section.settings.autoplay_timeout, dots : section.settings.dots, items_resp : items_resp, controls : section.settings.controls, total_item : total_item, padding : spacing_items, classID : sectionID -%} </div> </div> {% comment %} end {% endcomment %} {%- when '2' -%} <div class="{%- render 'grid-class' value: items_resp -%}"> {%- for block in collection_blocks -%} {%- liquid assign _collection = block.settings.collection assign collection = collections[_collection] assign image = block.settings.image assign block_menu = block.settings.menu assign block_title = block.settings.title -%} <div class="card_section-item" {{block.shopify_attributes}}> {%- if _collection == blank -%} {%- include 'svgset', type: 'empty-category' -%} {%- else -%} <div class="card_section-item-inner {% unless enable_menu %}no-menu{%- endunless -%}"> <div class="card_section-header"> <div class="card_section-figure"> <a href="{{collection.url}}" class="image"> {%- if image != blank -%} {%- render 'image-style', image: image, alt: collection.title -%} {%- else-%} {%- render 'image-style' image: collection.featured_image, alt: collection.title -%} {%- endif -%} </a> </div> </div> <div class="card_section-body"> <div class="card_section-menu"> <ul class="menu-list-content"> <li class="menu-item"> <h3 class="title"><a href="{{collection.url}}">{{block_title | default: collection.title}}</a></h3> </li> {%- if enable_menu -%} {%- for link in linklists[block_menu].links limit: 4 -%} <li class="menu-item"><a href="{{link.url}}">{{link.title}}</a></li> {%- endfor -%} {%- endif -%} </ul> {%- if enable_menu -%} <a href="{{collection.url}}" class="btn-show-all"> <div class=""> <span>{{menu_btn}}</span> <span class="svg_emlement-ui">{%- render 'svg' type: 'angle-right' -%}</span> </div> </a> {%- endif -%} </div> </div> </div> {%- endif -%} </div> {%- else -%} {%- for i in (1..5) -%} <div class="card_section-item"> {%- include 'svgset', type: 'empty-category' -%} </div> {%- endfor -%} {%- endfor -%} </div> {% comment %} end {% endcomment %} {%- endcase -%} </div> </div> {%- if isBoxed -%}</div>{%- endif -%} </div> {%- capture sectionCss -%} {%- if block_text_center -%}{{sectionID}} .menu-list-content, {{sectionID}} .menu-list-content a{text-align: center;}{{sectionID}} .btn-show-all>div{justify-content: center}{%- endif -%} {{heading_css}} {%- render 'css-responsive' preClassID: sectionID, classID: bg_class value_1: section.settings.section_padding, property_1: 'padding' value_2: section.settings.section_margin, property_2: 'margin' value_3: bg_color, property_3: 'background-color' -%} {%- if block_bg_color != default_color -%} {{sectionID}} .card_section-item-inner{background-color:{{block_bg_color}};} {%- endif -%} {%- render 'css-responsive', classID: sectionID, nextClassID: '.card_section-header', value_1: section.settings.collection_image_max_w, property_1: 'max-width' -%} {%- if section_style == '2' -%} {%- render 'css-responsive', preClassID: sectionID, classID: '.d-grid', value_1: spacing_items, property_1: 'grid-gap' -%} {%- endif -%} {%- endcapture -%} {%- if sectionCss != blank -%}<style>{{sectionCss | strip_newlines}}</style>{%- endif -%} <script> window.theme = window.theme || {}; if(!!window.theme.sectionRegister){ !window.theme.sectionRegister.includes("featured-collections") && (window.theme.sectionRegister = [...window.theme.sectionRegister, "featured-collections"]); }else{ window.theme.sectionRegister = ["featured-collections"]; } </script> {% comment %} compress {% endcomment %} {% schema %} { "name": { "en": "Categories" }, "tag": "section", "settings": [ { "type": "paragraph", "content": { "en": "Please see [instruction](https://support.arenacommerce.com/a/solutions/articles/6000248061) before use." } }, { "type": "paragraph", "content": { "en": "Created by 'Categories' section" } }, { "type": "text", "id": "title", "label": { "en": "Section Label" }, "default": "Categories" }, { "type": "header", "content": { "en": "General settings" } }, { "type": "checkbox", "id": "boxed_layout", "label": { "en": "Boxed layout" }, "default": true }, { "type": "text", "id": "section_margin", "label": "Section margin", "placeholder": { "en": "E.g: 20px 0px 20px 0px" }, "default": "20px 0px 20px 0px", "info": { "en": "Order: Top Right Bottom Left" } }, { "type": "text", "id": "section_padding", "label": "Section padding", "placeholder": { "en": "E.g: 20px 0px 20px 0px" }, "default": "20px 0px 20px 0px", "info": { "en": "Order: Top Right Bottom Left" } }, { "type": "select", "id": "style", "label": { "en": "Style" }, "options": [ { "value": "1", "label": { "en": "Slider" } }, { "value": "2", "label": { "en": "Grid" } } ] }, { "type": "header", "content": { "en": "Heading section" } }, { "type": "paragraph", "content": { "en": "To custom style. Please add block 'Heading Style'" } }, { "type": "checkbox", "id": "show_heading_section", "label": { "en": "Show" }, "default": true }, { "type": "text", "id": "heading", "label": { "en": "Heading" }, "default": "Lorem ipsum dolor sit." }, { "type": "text", "id": "subheading", "label": { "en": "Subheading" }, "default": "Lorem ipsum dolor sit amet consectetur." }, { "type": "header", "content": { "en": "Background" } }, { "type": "checkbox", "id": "bg_full", "label": { "en": "Full section background" } }, { "type": "color", "id": "bg_color", "label": { "en": "Background color" } }, { "type": "header", "content": { "en": "Block item settings" } }, { "type" : "checkbox", "id" : "block_text_center", "label" : { "en": "Text center" }, "default": false }, { "type": "color", "id": "block_bg_color", "label": { "en": "Background color" } }, { "type": "checkbox", "id": "enable_menu", "label": { "en": "Enable Menu" }, "default": true }, { "type": "text", "id": "menu_btn", "label": { "en": "Button label" }, "default": "Show all" }, { "type": "header", "content": { "en": "Layout content" } }, { "type": "text", "id": "items_resp", "label": { "en": "Max number of items per row" }, "default": "5,3,2", "placeholder": { "en": "E.g: 4,3,2" } }, { "type": "text", "id": "spacing_items", "label": { "en": "Spacing between items" }, "placeholder": { "en": "E.g: 10px" }, "info": { "en": "Order: top right bottom left" }, "default": "10px" }, { "type": "header", "content": { "en": "Slider settings" } }, { "type": "checkbox", "id": "loop", "label": { "en": "Loop" }, "default": false }, { "type": "checkbox", "id": "controls", "label": { "en": "Controls" }, "default": true }, { "type": "checkbox", "id": "dots", "label": { "en": "Dots" }, "default": true }, { "type": "checkbox", "id": "autoplay", "label": { "en": "Autoplay" }, "default": true }, { "type": "range", "id": "autoplay_timeout", "label": { "en": "Change slide every(s)" }, "step": 0.5, "min": 2, "max": 10, "unit": "s", "default": 4 } ], "blocks": [ { "type": "collection", "name": { "en": "Collection" }, "settings": [ { "type": "text", "id": "title", "label": { "en": "Title" }, "info": { "en": "If empty,will take title of collection." } }, { "type": "collection", "id": "collection", "label": { "en": "Collection" } }, { "type": "image_picker", "id": "image", "label": { "en": "Image" }, "info": { "en": "Use of image collection if blank" } }, { "type": "link_list", "id": "menu", "label": { "en": "Menu" } } ] }, { "type": "heading-style", "limit": 1, "name": { "en": "Heading style" }, "settings": [ { "type": "text", "id": "section_heading_margin", "label": { "en": "Margin" }, "placeholder": { "en": "E.g: 20px 0px 20px 0px " }, "info": { "en": "Order: Top Right Bottom Left" }, "default": "0 0 30px 0" }, { "type": "select", "id": "section_heading_align", "label": { "en": "Alignment" }, "options": [ { "value": "left", "label": { "en": "Left" } }, { "value": "center", "label": { "en": "Center" } }, { "value": "right", "label": { "en": "Right" } } ], "default": "center" }, { "type": "header", "content": { "en": "Heading settings" } }, { "type": "color", "id": "section_heading_cl", "label": { "en": "Text color" }, "default": "#103178" }, { "type": "text", "id": "section_heading_fs", "label": { "en": "Font size" }, "default": "40px", "placeholder": { "en": "E.g: 40px" } }, { "type": "range", "id": "section_heading_fw", "label": { "en": "Font weight" }, "min": 100, "max": 900, "step": 100, "default": 600 }, { "type": "text", "id": "section_heading_lh", "label": { "en": "Line height" }, "default": "60px", "placeholder": { "en": "E.g: 60px" } }, { "type": "header", "content": { "en": "Subheading settings" } }, { "type": "color", "id": "section_subheading_cl", "label": { "en": "Text color" }, "default": "#5B6C8F" }, { "type": "text", "id": "section_subheading_fs", "label": { "en": "Font size" }, "default": "24px", "placeholder": { "en": "E.g: 24px" } }, { "type": "range", "id": "section_subheading_fw", "label": { "en": "Font weight" }, "min": 100, "max": 900, "step": 100, "default": 400 }, { "type": "text", "id": "section_subheading_lh", "label": { "en": "Line height" }, "default": "35px", "placeholder": { "en": "E.g: 35px" } } ] } ], "presets": [ { "name": { "en": "Categories" }, "category": "Collection" } ] } {% endschema %}
import { useState } from "react"; import { StyleSheet, View, FlatList, Button } from "react-native"; import { StatusBar } from "expo-status-bar"; import GoalItem from "./components/GoalItem"; import GoalInput from "./components/GoalInput"; export default function App() { const [courceGoal, setCourceGoal] = useState([]); const [modelIsVisible, setModelIsVisible] = useState(false); function startAddGoalHandler() { setModelIsVisible(true); } function endAddGoalHandler() { setModelIsVisible(false); } const addGoalHandeler = (enteredGoalText) => { setCourceGoal((currentCourceGoal) => [ ...currentCourceGoal, { text: enteredGoalText, id: Math.random().toString() }, ]); endAddGoalHandler(); }; const deleteGoalHandeler = (id) => { setCourceGoal((currentCourceGoal) => { return currentCourceGoal.filter((goal) => goal.id !== id); }); }; return ( <> <StatusBar style="light"/> <View style={styles.appContainer}> <Button title="Add New Goal" color="#5e0acc" onPress={startAddGoalHandler} /> <GoalInput visible={modelIsVisible} onAddGoal={addGoalHandeler} onCancel={endAddGoalHandler} /> <View style={styles.goalsContainer}> <FlatList data={courceGoal} renderItem={(itemData) => { return ( <GoalItem text={itemData.item.text} id={itemData.item.id} onDeleteItem={deleteGoalHandeler} /> ); }} keyExtractor={(item, index) => { return item.id; }} alwaysBounceVertical={false} /> </View> </View> </> ); } const styles = StyleSheet.create({ appContainer: { flex: 1, paddingTop: 70, paddingHorizontal: 16, backgroundColor:'#1e085a' }, goalsContainer: { flex: 5, }, });
import { SanityDocument } from 'next-sanity'; import { PortableTextBlock } from 'sanity'; export interface ImageType { caption?: string; asset: { _ref: string; _type: string; }; _type: string; alt?: string; } export type ShoppingCartProviderProps = { children: any; }; export interface ShoppingCartContext { getItemQuantity: (id: number) => number; increaseItemQuantity: (id: number) => void; decreaseQuantity: (id: number) => void; removeFromCart: (id: number) => void; addToCart: (item: ProductType) => void; totalCartPrice: () => number; cartQuantity: number; cartItems: ProductType[]; toggleCart: () => void; isCartOpen: boolean; } export interface PaginationProps { currentPage: number; totalCount: number; pageSize: number; onPageChange: (selectedPage: number) => void; } export interface NavItem { title?: string; _key: string; route?: { accessibleSlug: { current: string; }; }; } export interface SiteConfig extends SanityDocument { footerText?: string; primaryNavigation?: NavItem[]; logo?: ImageType; } export type ProductType = { _id: number; _createdAt: Date; name: string; slug: string; price: number; image: string; details: string; category: string; featured: boolean; quantity: number; }; export interface Route { slug: Slug; } export interface Slug { current: string | undefined; } export interface Page extends SanityDocument { title?: string; description?: string; slug?: string; content?: PortableTextBlock[]; openGraphImage?: ImageType; }
<!DOCTYPE html> <html lang="PT-BR"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Calcule seu Índice de Massa Corporal (IMC) e descubra os benefícios de estar dentro do IMC adequado. Melhore sua saúde, fortaleça o sistema imunológico e reduza o risco de doenças crônicas. Nossa calculadora online é a ferramenta perfeita para monitorar sua saúde e alcançar uma vida saudável. Consulte um profissional de saúde para avaliação personalizada."> <title>Calculadora de IMC</title> <style> @font-face { font-family: 'Roboto'; src: url(Roboto-Regular.ttf); } body{ font-family: 'Roboto', sans-serif; height: auto; } main{ -webkit-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); -moz-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); border-radius: 8px; display: grid; margin: auto; justify-items: center; align-content: center; } footer { display:grid; text-align: center; justify-content: center; font-weight: 700; letter-spacing: 1px; font-size: 18px; color: rgb(46, 46, 46); } section{ margin: auto; } section p{ text-align: justify; } h2{ color: rgba(0, 0, 0, 0.884); text-align: center; margin-bottom: 50px; margin: auto; } a:link{ text-decoration: none; color:tomato; } a:visited{ text-decoration: none; color:rgb(145, 37, 17); } a:hover{ color: rgb(109, 18, 18); } @media only screen and (min-width:300px) and (max-width:767px){ body{ font-family: 'Roboto'; justify-content: center; align-content: center; background: rgb(205,205,205); background: linear-gradient(127deg, rgb(136, 135, 135) 05%, rgb(192, 191, 191) 25%, rgba(219,219,219,1) 50%, rgba(238,238,238,1) 75%, rgba(255,255,255,1) 100%);display: grid; } main{ margin-top: 165px; margin-bottom: 165px; width:90vw; height: 60vh; } h1{ color: rgba(0, 0, 0, 0.884); font-weight:900; text-align: center; width: 75vw; line-height:40px; font-size:50px; } h2{ font-size: 26px; margin-bottom: 40px; } article{ width: 90vw; } p{ font-size: 20px; } .Container{ height: 5vh; border-radius: 5px; width: 70vw; background-color: rgb(46, 45, 45); color: aliceblue; align-items: center; display: flex; padding-left:10px ; margin-top: 0; } button{ background-color: rgb(46, 45, 45); -webkit-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); -moz-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); box-shadow: 0px 9px 15px -4px rgba(0,0,0,1); border: none; border-radius: 5px; height: 7vh; width: 50vw; margin-top: 10px; font-size: 24px; font-weight: 600; letter-spacing: 1.5px; color: rgb(228, 223, 223); } input#altura, input#peso{ height: 4.5vh; border-radius: 5px; width: 50vw; background-color: rgb(46, 45, 45); color: aliceblue; align-items: center; display: flex; padding-left:10px ; margin-bottom: 10px; margin-top: 0; font-size: 18px; text-align: center; } } @media only screen and (min-width:768px) and (max-width:1023px){ body{ font-family: 'Roboto'; justify-content: center; align-content: center; background: rgb(205,205,205); background: linear-gradient(127deg, rgb(136, 135, 135) 05%, rgb(192, 191, 191) 25%, rgba(219,219,219,1) 50%, rgba(238,238,238,1) 75%, rgba(255,255,255,1) 100%);display: grid; } main{ margin-top: 270px; margin-bottom: 230px; width:90vw; height: 50vh; } h1{ color: rgba(0, 0, 0, 0.884); font-weight:900; text-align: center; width: 75vw; line-height:65px; font-size:70px; } h2{ font-size: 30px; width: 90vw; margin-bottom: 50px; } section p{ width: 90vw; font-size: 24px; } .Container{ height: 5vh; border-radius: 5px; width: 70vw; background-color: rgb(46, 45, 45); color: aliceblue; align-items: center; display: flex; padding-left:10px ; margin-top: 5px; } button{ background-color: rgb(46, 45, 45); -webkit-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); -moz-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); box-shadow: 0px 9px 15px -4px rgba(0,0,0,1); border: none; border-radius: 5px; height: 8vh; width: 35vw; margin-top: 30px; font-size: 28px; font-weight: 600; letter-spacing: 1.5px; color: rgb(228, 223, 223); } input#altura, input#peso{ height: 4.5vh; border-radius: 5px; width: 35vw; background-color: rgb(46, 45, 45); color: aliceblue; align-items: center; display: flex; padding-left:10px ; margin-bottom: 10px; margin-top: 0; font-size: 18px; text-align: center; } } @media only screen and (min-width:1024px){ body{ font-family: 'Roboto'; background: rgb(205,205,205); background: linear-gradient(90deg, rgba(205,205,205,1) 0%, rgba(213,213,213,1) 25%, rgba(219,219,219,1) 50%, rgba(238,238,238,1) 75%, rgba(255,255,255,1) 100%);display: grid; justify-content: center; align-content: center; } main{ margin-top: 160px; margin-bottom: 160px; width: 50vw; height: 60vh; -webkit-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); -moz-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); border-radius: 8px; display: grid; justify-items: center; align-content: center; } button{ background-color: transparent; -webkit-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); -moz-box-shadow: 0px 15px 25px -6px rgba(0,0,0,1); box-shadow: 0px 9px 15px -4px rgba(0,0,0,1); border: none; border-radius: 5px; height: 8vh; width: 15vw; margin-top: 60px; font-size: 30px; font-weight: 600; letter-spacing: 1.5px; color: rgba(0, 0, 0, 0.884); } button:hover{ cursor: pointer; -webkit-box-shadow: 0px 6px 9px -4px rgba(0,0,0,0.75); -moz-box-shadow: 0px 6px 9px -4px rgba(0,0,0,0.75); box-shadow: 0px 6px 9px -4px rgba(0,0,0,0.75); background-color: rgb(46, 45, 45); color: rgb(228, 223, 223); transition: .6s; } button:active{ background-color:rgb(139, 100, 130); transition: .3s; color: rgba(240, 248, 255, 0.815); } button:hover{ cursor: pointer; -webkit-box-shadow: 0px 6px 9px -4px rgba(0,0,0,0.75); -moz-box-shadow: 0px 6px 9px -4px rgba(0,0,0,0.75); box-shadow: 0px 6px 9px -4px rgba(0,0,0,0.75); background-color: rgb(46, 45, 45); color: rgb(228, 223, 223); transition: .6s; } h1{ line-height:70px; font-weight:900; font-size: 70px; text-align: center; margin-top: 0px; color: rgba(0, 0, 0, 0.884); } .Container{ height: 6.5vh; border-radius: 5px; width: 35vw; background-color: rgb(46, 45, 45); color: aliceblue; align-items: center; display: flex; padding-left:10px ; margin-top: 5px; margin-bottom: 15px; } input#altura, input#peso{ height: 4.5vh; border-radius: 5px; width: 10vw; background-color: rgb(46, 45, 45); color: aliceblue; align-items: center; display: flex; padding-left:10px ; margin: 5px; font-size: 18px; text-align: center; } section{ width: 70vw; } section p{ text-align: justify; font-size: 24px; } h2{ font-size: 38px; width: 55vw; } } </style> </head> <body> <main> <h1>Calcule seu IMC</h1> <input type="number" name="altura" id="altura" placeholder="Digite sua altura"> <input type="number" name="peso" id="peso" placeholder="Digite seu peso"> <div class="Container" id="resultadoImc" name="generate"></div> <button type="button" value="imc" onclick="somar()">Calcular</button> </main> <section> <article> <h2>Descubra o segredo para uma vida saudável com a nossa Calculadora de IMC!</h2> <p>Você já ouviu falar sobre o IMC? O Índice de Massa Corporal é uma ferramenta simples, mas poderosa, que nos ajuda a entender se estamos no caminho certo para alcançar uma saúde ideal. Agora, você pode calcular o seu IMC facilmente com a nossa calculadora online e desvendar os benefícios de estar dentro dessa faixa. </p> <p>Mas o que é o IMC? O IMC é uma medida que relaciona o seu peso com a sua altura, revelando se você está abaixo do peso, dentro do peso ideal, com sobrepeso ou obeso. É uma maneira confiável de avaliar o seu estado nutricional e identificar possíveis riscos à sua saúde. </p> <p>Estar dentro do IMC adequado traz inúmeros benefícios. Quando você mantém um peso saudável, melhora a sua qualidade de vida de várias maneiras. Primeiro, seu sistema imunológico fica mais forte, tornando-o menos suscetível a doenças. Além disso, você terá mais energia para aproveitar as atividades diárias, melhorando o seu desempenho físico e mental. </p> <p>Outra vantagem de estar dentro do IMC é a redução do risco de desenvolver doenças crônicas, como diabetes, doenças cardíacas e hipertensão arterial. Ao cuidar do seu corpo, você também cuida do seu coração e diminui as chances de problemas relacionados a essas condições. </p> <p>Alcançar e manter o IMC ideal também pode melhorar sua autoestima e confiança. Quando você se sente bem consigo mesmo, isso reflete em todas as áreas da sua vida, seja no trabalho, nos relacionamentos ou nas suas atividades sociais. </p> <p>Nossa calculadora de IMC é a sua ferramenta poderosa para monitorar sua saúde. Basta inserir sua altura e peso, e em questão de segundos, você terá seu resultado. Com base nesse valor, você pode adotar medidas para melhorar sua saúde e bem-estar. </p> <p>Aproveite essa oportunidade de transformar a sua vida! Calcule seu IMC agora e descubra como alcançar uma vida mais saudável e feliz. Lembre-se, cuidar do seu corpo é um investimento valioso para o seu futuro. </p> </article> </section> <footer> <p>Todos os direitos reservados <br> <a href="https://github.com/Ester-Farias">&copy; Ester Farias</a> </p> </footer> <script> function somar(){ var boxaltura = window.document.getElementById('altura') var boxpeso = window.document.getElementById('peso') var convAltura = Number(boxaltura.value) var convPeso = Number(boxpeso.value) var calcImc = convPeso / (convAltura * convAltura) var calcImc = calcImc.toFixed(1) var resultadoImc = window.document.getElementById('resultadoImc') if (calcImc <= 18.5) { resultadoImc.innerHTML = `Seu IMC é de ${calcImc}. <br> E você possui Magreza!` } else if (calcImc >= 18.5 && calcImc <= 24.9) { resultadoImc.innerHTML = `Seu IMC é de ${calcImc}. <br> E você está com peso normal.` } else if (calcImc >= 25 && calcImc <= 29.9) { resultadoImc.innerHTML = `Seu IMC é de ${calcImc}. <br> E você está com sobrepeso.` } else if (calcImc >= 30 && calcImc <= 34.9) { resultadoImc.innerHTML = `Seu IMC é de ${calcImc}. <br> E você está com obesidade grau I.` } else if (calcImc >= 35 && calcImc <= 40) { resultadoImc.innerHTML = `Seu IMC é de ${calcImc}. <br> E você está com obesidade grau II.` } else { resultadoImc.innerHTML = `Seu IMC é de ${calcImc}. <br> E você está com obesidade grau III.` } } </script> </body> </html>
############ Function #################### [T, V, U, H, S] = Super_Water_Table(label, value, P) ############ Description ################# Super_Water_Table is a function that searches the Superheated Water Pressure Tables and outputs the values associated with an input value. The function automatically interpolates between rows in the table for values not in the table itself. The input value, however, must lie between certain bounds which are outlined below. The function also interpolates between tables for pressures found between the available pressure tables. This interpolation creates an entire table of values for the specified pressure and then outputs the values associated with the input values. The function Super_Water_Table utilizes the companion table SuperWaterTable.mat as well as the functions Row_Interp.m and Sat_Water_Table.m and its companion table SatWaterTable.mat SuperWaterTable.mat is the superheated water pressure table from "Thermodynamics: An Engineering Approach, 8th Ed." in English units. SatWaterTable.mat is the saturated water pressure table from "Thermodynamics: An Engineering Approach, 8th Ed." in English units. ########### Outputs ###################### Super_Water_Table outputs 5 variables [T, V, U, H, S] which correspond to the following: T = Temperature (degrees F) V = Specific Volume (ft^3/lbm) U = Internal Energy (Btu/lbm) H = Enthalpy (Btu/lbm) S = Enthalpy (Btu/lbm*R) ########### Inputs ####################### ------------------------------------------------------- $$$$$$$$$ Input values must be in English Units $$$$$$$ ------------------------------------------------------- Super_Water_Table relies on 3 inputs (label, value, P) The variable "value" is the input number to be referenced and should be type double. The variable "label" denotes what the number in "value" represents (i.e. temperature, enthalpy, etc) Acceptable inputs for "label" are as follows: 'Temperature', 'Volume', 'Energy', 'Enthalpy', 'Entropy' where 'Volume' refers to specific volume and 'Energy' refers to internal energy. The variable "P" denotes the pressure at that state. The pressure value determines the table of values that "value" is compared against. ############ Value Bounds ################ Bounds for pressure is as follows: P = [1, 6000] (psi) Exact Value Tables for P are: P = [1, 5, 10, 15, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 225, ... 250, 275, 300, 350, 400, 450, 500, 600, 700, 800, 1000, 1250, ... 1500, 1750, 2000, 2500, 3000, 3500, 4000, 5000, 6000] Pressures that do not match exact values will generate tables by interpolating between the tables that the value lies between. These generated tables have a certain degree of accuracy that is mostly untested. Some tested values were found to deviate by 1%. Use with caution. Bounds for other values are based on the value for pressure. If value specified falls outside the determined bounds an error message will appear with the bound that has been exceeded. ############ Example 1 ################### label = 'Temperature'; value = 700; P = 15; [T, V, U, H, S] = Super_Water_Table(label, value, P) Returns: T = 700 V = 45.981 U = 1256.3 H = 1383.9 S = 2.0156 ############ Example 2 ################### label = 'Temperature'; value = 100; P = 15; [T, V, U, H, S] = Super_Water_Table(label, value, P) Returns: Error using Super_Water_Table (line 82) Temperature cannot be less than 212.99 degrees F for specified pressure ############ Example 3 ################### To return only desired values use ~ to block off undesired values during output. For example, if the input is temperature and desired outputs are H and S. label = 'Temperature'; value = 1000; P = 15; [~, ~, ~, H, S] = Super_Water_Table(label, value, P) Returns: H = 1534.8 S = 2.1312 ############ Example 4 ################### To return only a single value, one does not need to use ~ on the values following it in the list. For example, if the input is temperature and the desired output is only internal energy. label = 'Temperature'; value = 1000; P = 15; [~, ~, U] = Super_Water_Table(label, value, P) Returns: U = 1374
<?php use App\Models\Enums\OrderStatusEnum; use Illuminate\Database\Eloquent\Concerns\HasUuids; use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { use HasUuids; /** * Run the migrations. */ public function up(): void { Schema::create('orders', function (Blueprint $table) { $table->uuid('id')->primary(); $table->foreignId('user_id')->references('id')->on('users')->onDelete('restrict'); $table->enum('status', OrderStatusEnum::values())->default(OrderStatusEnum::UNPAID); $table->unsignedDecimal('amount', 10, 2); $table->text('shipment')->max(255)->nullable()->default(null); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('orders'); } };
import { HardhatRuntimeEnvironment } from "hardhat/types" import { DeployFunction } from "hardhat-deploy/types" // Deployment names const META_POOL_NAME = "SaddleSUSDMetaPoolV3" const META_POOL_LP_TOKEN_NAME = `${META_POOL_NAME}LPToken` const META_POOL_DEPOSIT_NAME = `${META_POOL_NAME}Deposit` const TARGET_META_SWAP_DEPOSIT_NAME = `MetaSwapDeposit` const BASE_POOL_NAME = `SaddleUSDPoolV2` const func: DeployFunction = async function (hre: HardhatRuntimeEnvironment) { const { deployments, getNamedAccounts } = hre const { execute, get, getOrNull, log, save } = deployments const { deployer } = await getNamedAccounts() // Manually check if the pool is already deployed const metaPoolDeposit = await getOrNull(META_POOL_DEPOSIT_NAME) if (metaPoolDeposit) { log(`reusing ${META_POOL_DEPOSIT_NAME} at ${metaPoolDeposit.address}`) } else { const receipt = await execute( "SwapDeployer", { from: deployer, log: true, }, "clone", ( await get(TARGET_META_SWAP_DEPOSIT_NAME) ).address, ) const newPoolEvent = receipt?.events?.find( (e: any) => e["event"] === "NewClone", ) const deployedAddress = newPoolEvent["args"]["cloneAddress"] log( `deployed ${META_POOL_DEPOSIT_NAME} (targeting ${TARGET_META_SWAP_DEPOSIT_NAME}) at ${deployedAddress}`, ) await save(META_POOL_DEPOSIT_NAME, { abi: (await get(TARGET_META_SWAP_DEPOSIT_NAME)).abi, address: deployedAddress, }) await execute( META_POOL_DEPOSIT_NAME, { from: deployer, log: true, gasLimit: 1_000_000 }, "initialize", ( await get(BASE_POOL_NAME) ).address, ( await get(META_POOL_NAME) ).address, ( await get(META_POOL_LP_TOKEN_NAME) ).address, ) } } export default func func.tags = [META_POOL_DEPOSIT_NAME] func.dependencies = ["SUSDMetaPoolTokens", META_POOL_NAME]
package org.example; import lombok.Getter; import lombok.Setter; import java.util.Scanner; @Setter @Getter public class MazeGame { private static final char STOP = 'B'; private static final char EMPTY = '.'; private static final char OBSTACLE = 'X'; private char[][] board; private int rows; private int cols; private int startRow; private int startCol; private int stopRow; private int stopCol; private int playerRow; private int playerCol; public MazeGame(int rows, int cols) { this.rows = rows; this.cols = cols; this.board = new char[rows][cols]; initializeBoard(); this.playerRow = startRow; this.playerCol = startCol; } private void initializeBoard() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { board[i][j] = EMPTY; } } } public void generateMaze() { stopRow = 4; stopCol = 4; board[stopRow][stopCol] = STOP; board[1][2] = OBSTACLE; board[0][0] = OBSTACLE; board[4][3] = OBSTACLE; board[3][3] = OBSTACLE; board[2][1] = OBSTACLE; } public void displayMazeWithPlayer() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (i == playerRow && j == playerCol) { System.out.print("P "); } else { System.out.print(board[i][j] + " "); } } System.out.println(); } } public void moveLeft() { if (playerCol - 1 >= 0 && board[playerRow][playerCol - 1] != OBSTACLE) { board[playerRow][playerCol] = EMPTY; playerCol--; } else { System.out.println("Wrong direction, choose another way!"); } } public void moveRight() { if (playerCol + 1 < cols && board[playerRow][playerCol + 1] != OBSTACLE) { board[playerRow][playerCol] = EMPTY; playerCol++; } else { System.out.println("Wrong direction, choose another way!"); } } public void moveUp() { if (playerRow - 1 >= 0 && board[playerRow - 1][playerCol] != OBSTACLE) { board[playerRow][playerCol] = EMPTY; playerRow--; } else { System.out.println("Wrong direction, choose another way!"); } } public void moveDown() { if (playerRow + 1 < rows && board[playerRow + 1][playerCol] != OBSTACLE) { board[playerRow][playerCol] = EMPTY; playerRow++; } else { System.out.println("Wrong direction, choose another way!"); } } public void playGame() { Scanner scanner = new Scanner(System.in); char direction; do { displayMazeWithPlayer(); System.out.print("Enter direction (L - left, R - right, U - up, D - down, Q - quit): "); direction = scanner.next().toUpperCase().charAt(0); switch (direction) { case 'L': moveLeft(); break; case 'R': moveRight(); break; case 'U': moveUp(); break; case 'D': moveDown(); break; case 'Q': System.out.println("Game Over. Quitting..."); break; default: System.out.println("Invalid direction. Try again."); } } while (direction != 'Q' && (playerRow != stopRow || playerCol != stopCol)); if (playerRow == stopRow && playerCol == stopCol) { System.out.println("Congratulations! You reached the destination!"); } } public static void main(String[] args) { MazeGame mazeGame = new MazeGame(5, 5); mazeGame.generateMaze(); mazeGame.playGame(); } }
package pers.sg.kms.daos; import java.util.List; import org.hibernate.LockOptions; import org.hibernate.Query; import org.hibernate.criterion.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import pers.sg.kms.model.Leaveschool; /** * A data access object (DAO) providing persistence and search support for * Leaveschool entities. Transaction control of the save(), update() and * delete() operations can directly support Spring container-managed * transactions or they can be augmented to handle user-managed Spring * transactions. Each of these methods provides additional information for how * to configure it for the desired type of transaction control. * * @see pers.sg.kms.model.Leaveschool * @author MyEclipse Persistence Tools */ @Repository public class LeaveschoolDAO extends BaseHibernateDAO { private static final Logger log = LoggerFactory.getLogger(LeaveschoolDAO.class); // property constants public static final String LEAVE_CONTENT = "leaveContent"; public void save(Leaveschool transientInstance) { log.debug("saving Leaveschool instance"); try { getSession().save(transientInstance); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } } public void delete(Leaveschool persistentInstance) { log.debug("deleting Leaveschool instance"); try { getSession().delete(persistentInstance); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } } public Leaveschool findById(Long id) { log.debug("getting Leaveschool instance with id: " + id); try { Leaveschool instance = (Leaveschool) getSession().get("pers.sg.kms.model.Leaveschool", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public List findByExample(Leaveschool instance) { log.debug("finding Leaveschool instance by example"); try { List results = getSession().createCriteria("pers.sg.kms.model.Leaveschool").add(Example.create(instance)) .list(); log.debug("find by example successful, result size: " + results.size()); return results; } catch (RuntimeException re) { log.error("find by example failed", re); throw re; } } public List findByProperty(String propertyName, Object value) { log.debug("finding Leaveschool instance with property: " + propertyName + ", value: " + value); try { String queryString = "from Leaveschool as model where model." + propertyName + "= ?"; Query queryObject = getSession().createQuery(queryString); queryObject.setParameter(0, value); List results = queryObject.list(); getSession().close(); return results; } catch (RuntimeException re) { log.error("find by property name failed", re); throw re; } } public List findByLeaveContent(Object leaveContent) { return findByProperty(LEAVE_CONTENT, leaveContent); } public List findAll() { log.debug("finding all Leaveschool instances"); try { String queryString = "from Leaveschool"; Query queryObject = getSession().createQuery(queryString); return queryObject.list(); } catch (RuntimeException re) { log.error("find all failed", re); throw re; } } public Leaveschool merge(Leaveschool detachedInstance) { log.debug("merging Leaveschool instance"); try { Leaveschool result = (Leaveschool) getSession().merge(detachedInstance); log.debug("merge successful"); return result; } catch (RuntimeException re) { log.error("merge failed", re); throw re; } } public void attachDirty(Leaveschool instance) { log.debug("attaching dirty Leaveschool instance"); try { getSession().saveOrUpdate(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } public void attachClean(Leaveschool instance) { log.debug("attaching clean Leaveschool instance"); try { getSession().buildLockRequest(LockOptions.NONE).lock(instance); log.debug("attach successful"); } catch (RuntimeException re) { log.error("attach failed", re); throw re; } } }
import React, { useContext, useEffect, useState } from 'react' import Axios from 'axios' import Container from '@mui/material/Container' import Paper from '@mui/material/Paper' import Box from '@mui/material/Box' import Card from '@mui/material/Card' import CardContent from '@mui/material/CardContent' import TextField from '@mui/material/TextField' import Button from '@mui/material/Button' import CardHeader from '@mui/material/CardHeader' // import bg from '../assets/bg_login.jpg' import bg from '../assets/blog_bg_new.jpg' import { createUser, loginUser } from '../services/userServices' import { useNavigate } from 'react-router-dom' import AppContext from '../context/appContext' // const bg = "https://source.unsplash.com/random/1280x720?purple" const defaultUser = { id: '', name: '', summary: '', password: '' } const Signup = () => { const context = useContext(AppContext) const { handleSnackbarOpen } = context const [user, setUser] = useState(defaultUser) const navigate = useNavigate() const handleUserId = (e) => { setUser({ ...user, id: e.target.value }) } const handlePassword = (e) => { setUser({ ...user, password: e.target.value }) } const handleName = (e) => { setUser({ ...user, name: e.target.value }) } const handleSummary = (e) => { setUser({ ...user, summary: e.target.value }) } const handleSubmit = async (e) => { e.preventDefault() console.log(user) const res = await createUser(user) if (res.status === 200) { handleSnackbarOpen('User created successfully. You will be redirected to login page now') setTimeout(() => navigate('/login'), 2000) } else { handleSnackbarOpen(res.data) } } useEffect(() => { document.title = 'Home - Blog App' }, []) return ( <Box sx={{ display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', height: '100vh' }}> <Container maxWidth='xs'> <Card sx={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '1rem', borderRadius: '20px' }}> <CardContent> <CardHeader title="Signup" subheader="to post and view blogs" sx={{ textAlign: 'center' }} /> <TextField onChange={handleUserId} value={user.id} label="User ID" variant='outlined' type='text' margin='normal' color='secondary' fullWidth /> <TextField onChange={handleName} value={user.name} label="Full Name" variant='outlined' type='text' margin='normal' color='secondary' fullWidth /> <TextField onChange={handleSummary} value={user.summary} label="Bio" variant='outlined' type='text' margin='normal' color='secondary' rows={3} multiline fullWidth /> <TextField onChange={handlePassword} value={user.password} label="Password" variant='outlined' type='password' margin='normal' color='secondary' fullWidth > </TextField> <Button onClick={handleSubmit} disableElevation fullWidth variant='contained' sx={{ borderRadius: '20px', marginTop: '2rem' }}> Create Account </Button> </CardContent> </Card> </Container> <Box component='img' src={bg} sx={{ position: 'absolute', width: '100%', height: '120vh', overflow: 'hidden', top: '0', objectFit: 'cover', zIndex: '-20' }} /> </Box > ) } export default Signup
#include <iostream> using namespace std; void argumentByValue(int n) { n++; cout << "Im Funktionsaufruf von argumentByValue hat das Argument " << "nach dem Inkrementieren den Wert " << n << endl; } void argumentByReference1(int* p) { (*p)++; // int-Wert an der Speicherstelle p wird um 1 erhöht cout << "Im Funktionsaufruf von argumentByReference1 hat das Argument " << "nach dem Inkrementieren den Wert " << *p << endl; } void argumentByReference2(int &n) { n++; cout << "Im Funktionsaufruf von argumentByReference2 hat das Argument " << "nach dem Inkrementieren den Wert " << n << endl; } int main(){ int x = 3; cout << "Wert von x im Hauptprogramm nach der Initialisierung: " << x << endl; argumentByValue(x); cout << "Wert von x im Hauptprogramm nach dem Aufruf von " << "argumentByValue: " << x << endl; argumentByReference1(&x); cout << "Wert von x im Hauptprogramm nach dem Aufruf von " << "argumentByReference1: " << x << endl; argumentByReference2(x); cout << "Wert von x im Hauptprogramm nach dem Aufruf von " << "argumentByReference2: " << x << endl; return 0; }
import { assert, describe, it, beforeAll } from 'vitest' import { fireEvent, getByTestId, render } from '@testing-library/preact' import { App } from '../src/App' describe('App', () => { let container beforeAll(() => { const render_result = render(<App />) container = render_result.container }) it('contains a form', () => { assert.isTrue(container.innerHTML.includes('form')) }) it('contains a submit button', () => { const submit_button = getByTestId(container, 'submit-button') assert.isNotNull(submit_button) }) it('contains a input for the URL to audit', () => { const input = getByTestId(container, 'url-to-audit') const url = 'https://www.example.com' assert.notEqual(input.value, url) fireEvent.change(input, { target: { value: url } }) assert.equal(input.value, url) }) })
<?php include 'functions.php'; $rawMessage = 'LEVKHWDKOXAESDXKHOHLHYLVEBIKXOWIHVIDKXOVHDKHOEKDWVDY OJDEOJIYDRIVDBDOJDXKDKODSIKLIKIWWHOIKLVHWIHLEQDOHSDCHG EVDCJCJDHEOOXGHLHSHDVXYYDGEOESEGEWDKDCDESIWWDKRHYD EKISXIHKKDBHKIWWIXWLDQIEVIDKBHLLDWDQGDHKLEYLHLEHLLHOOH LESHSDRIVYDSVEKDXKESIDMXHWDDKGHVLDOEWHVIJHDQGHLLHLEW HYLVXLLXVHSDOEKLIKDQIKLESIWVIHLLEVIKXQIVEYIKCHGIVBEVLXKHO HXYHVISHKKDOVDLDOD'; ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Assignement 1 - Esercizio 1</title> <link href="css/main.css" rel="stylesheet"/> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"/> </head> <body> <header> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="#">Assignement 1</a> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto mb-2 mb-md-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="#">Esercizio 1</a> </li> <li class="nav-item"> <a class="nav-link" href="esercizio2.php">Esercizio 2</a> </li> </ul> </div> </div> </nav> </header> <main class="flex-shrink-0"> <section class="container"> <h1 class="mt-5">Assignement 1 - Esercizio 1</h1> <p class="lead">Testo da cifrare</p> <p class="monospace"><?php echo $rawMessage ?></p> </section> <section class="container"> <h2>Step 1: rimuovere punteggiatura e spazi</h2> <p class="monospace text-break"> <?php $message = preProcessing($rawMessage); echo $message; ?> </p> </section> <section class="container"> <h2>Step 2: analisi delle frequenze</h2> <div class="mt-2 mb-2">Tabella con l'analisi delle frequenze delle lettere del testo cifrato, in ordine decrescente</div> <table> <tr> <th>Lettera</th> <th>Totale occorrenze</th> <th>Percentuale</th> </tr> <?php $letters = frequencyAnalysis($message); ?> <script>var cypherGraphDataUnordered = <?php echo json_encode($letters); ?>;</script> <?php arsort($letters); foreach($letters as $letter => $value) { echo '<tr>'; echo '<td>'.$letter.'</td>'; echo '<td>'.$value['count'].'</td>'; echo '<td>'.$value['percent'].'%</td>'; echo '</tr>'; } ?> </table> <div class="row align-items-start mt-2 mb-2"> <div class="col"> <p class="mb-2">Grafico a barre delle frequenze delle lettere del testo cifrato, in ordine descresente.</p> <script>var cypherGraphData = <?php echo json_encode($letters); ?>;</script> <div id="cypher_graph"></div> </div> <div class="col"> <p class="mb-2">Grafico a barre delle frequenze delle lettere della lingua Italiana, in ordine decrescente.</p> <script> var italianGraphDataUnordered = <?php echo json_encode($italianFrequency); ?>; var italianGraphData = <?php arsort($italianFrequency); echo json_encode($italianFrequency); ?>; </script> <div id="italian_graph"></div> </div> </div> </section> <section class="container"> <h2>Step 3: verifica se cifrario di cesare</h2> <div class="row align-items-start mt-2 mb-2"> <div class="col"> <p class="mb-2">Grafico a barre delle frequenze delle lettere del testo cifrato</p> <script>var cypherGraphData = <?php echo json_encode($letters); ?>;</script> <div id="cypher_graph_unordered"></div> </div> <div class="col"> <p class="mb-2">Grafico a barre delle frequenze delle lettere della lingua Italiana</p> <div id="italian_graph_unordered"></div> </div> </div> </section> <section class="container"> <h2>Step 3: analisi delle doppie</h2> <p>Di seguito vengono individuate ed evidenziate tutte le lettere doppie (in arancione) e le lettere direttamente precedenti o successive (in giallo).</p> <p class="monospace text-break"> <?php $doppie = hihglighter($message); ?> </p> <div class="row align-items-start mt-2 mb-2"> <div class="col"> <table> <tr> <th>Doppie testo cifrato</th> <th>Totale occorrenze</th> </tr> <?php arsort($doppie); foreach($doppie as $doppia => $value) { echo '<tr>'; echo '<td>'.$doppia.'</td>'; echo '<td>'.$value.'</td>'; echo '</tr>'; } ?> </table> </div> <div class="col"> <table> <tr> <th>Doppie lingua italiana</th> <th>Frequenze</th> </tr> <?php arsort($italianDoppieFrequency); foreach($italianDoppieFrequency as $doppia => $value) { echo '<tr>'; echo '<td>'.$doppia.'</td>'; echo '<td>'.$value.'%</td>'; echo '</tr>'; } ?> </table> </div> </div> </section> <section class="container"> <h2>Step 4: sostituzione delle lettere</h2> <div> <?php $a = array( 'H' => 'a', 'K' => 'n', 'X' => 'u', 'E' => 'o', 'L' => 't', 'V' => 'r', 'Y' => 's', 'B' => 'f', 'O' => 'c', 'W' => 'l', 'I' => 'e', 'G' => 'p', 'S' => 'd', 'D' => 'i', 'A' => 'b', 'J' => 'h', 'R' => 'v', 'Q' => 'm', 'C' => 'z', 'M' => 'q', ); ?> <p><?php print_r($a); ?></p> <p class="monospace text-break decode"> <?php echo decode($message, $a); ?> </p> </div> </section> <section class="container"> <h2>Step 5: testo in chiaro (con spazi e punteggiatura)</h2> <p class="monospace text-break">Torna l'incubo di una catastrofe nucleare in Ucraina con il rischio che si verifichi un incidente nella centrale atomica di Zaporizhzhia occupata dai russi poco dopo l'inizio dell' invasione due anni fa.</p> <p class="monospace text-break">Nelle ultime ore, infatti, l'impianto è stato attaccato da diversi droni uno dei quali in particolare ha impattato la struttura di contenimento del reattore numero senza per fortuna causare danni critici.</p> </section> </main> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> <script src="https://cdn.plot.ly/plotly-2.31.1.min.js" charset="utf-8"></script> <script src="js/esercizio1.js"></script> </body> </html>
import { IconProp } from "@fortawesome/fontawesome-svg-core"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { FunctionComponent } from "react"; import { useRouter } from 'next/navigation'; type SidebarLinkProps = { icon: IconProp, redirectUrl: string } const SidebarLink: FunctionComponent<SidebarLinkProps> = ({ icon, redirectUrl }) => { const { push } = useRouter(); return ( <span className="sm:px-6 py-2 flex gap-2 items-center justify-center sm:rounded-md sm:hover:bg-slate-700 sm:hover:text-white cursor-pointer" onClick={() => push(redirectUrl)} > <FontAwesomeIcon icon={icon} className="text-xl"/> </span> ); }; export default SidebarLink;
import { useState } from "react"; import { daysOfWeek } from "../helpers/date"; import { IModal, IHabit } from "../helpers/types"; import { CloseSVG } from "../assets/SVG/CloseSVG"; interface ModalProps { modal: IModal; setModal: React.Dispatch<React.SetStateAction<IModal>>; habits: IHabit[]; updateHabits: React.Dispatch<React.SetStateAction<IHabit[]>>; } const Modal = ({ modal, setModal, habits, updateHabits }: ModalProps) => { const [deleteModal, setDeleteModal] = useState(null); // update habit schedule function toggleScheduleDate(e: React.MouseEvent<HTMLButtonElement>) { e.preventDefault(); let element = e.target as HTMLButtonElement; const dayNum = parseInt(element.value); let newSchedule = modal.schedule; newSchedule = newSchedule.includes(dayNum) ? newSchedule.filter((a: number) => a != dayNum) : [...newSchedule, dayNum]; setModal({ ...modal, schedule: newSchedule }); } return ( <> <div className={`modal ${modal.color}`}> <button className="closeBtn" onClick={() => setModal(null)}> <CloseSVG /> </button> <form onSubmit={(e) => { e.preventDefault(); let updatedArr = [...habits]; updatedArr[modal.habitIndex].name = modal.name; updatedArr[modal.habitIndex].schedule = modal.schedule; updatedArr[modal.habitIndex].color = modal.color; updateHabits(updatedArr); setModal(null); }} > <div className="form-container"> <input aria-label="Edit habit name" onChange={(e) => setModal({ ...modal, name: e.target.value })} value={modal.name} placeholder={modal.name} /> <p> Longest Streak: {modal.longestStreak}{" "} {modal.longestStreak !== 0 && modal.streak == modal.longestStreak ? "🔥" : null} </p> <p>Current Streak: {modal.streak}</p> <label htmlFor="colors">Color:</label> <select id="colors" value={modal.color} onChange={(e) => setModal({ ...modal, color: e.target.value })} > <option value="purple">Purple</option> <option value="sky">Sky</option> <option value="pink">Pink</option> <option value="blue">Blue</option> <option value="red">Red</option> <option value="green">Green</option> <option value="orange">Orange</option> </select> <div className="history flex"> {[...new Array(120).fill(false), ...modal.days] .slice(-120) .map((day: boolean) => { return ( <div className={day ? `complete ${modal.color}` : null} ></div> ); })} </div> <div className="schedule flex"> {Object.keys(daysOfWeek).map((day) => { return ( <button className={ modal.schedule.includes(parseInt(day)) ? `selected ${modal.color}` : "" } value={day} onClick={toggleScheduleDate} > {day == "4" ? "Th" : daysOfWeek[day][0]} </button> ); })} </div> <button className="link-button" value={modal.habitIndex} onClick={(e: React.MouseEvent<HTMLButtonElement>): void => { let element = e.target as HTMLButtonElement; e.preventDefault(); setDeleteModal(parseInt(element.value)); }} > Delete </button> </div> <button type="submit">Save</button> </form> </div> {deleteModal !== null ? ( <div className="deleteModal"> Are you sure you want to delete{" "} <span>{habits[deleteModal].name}</span>? <div className="flex"> <button onClick={() => { setDeleteModal(null); }} > Cancel </button> <button onClick={() => { // delete habit let updatedArr = [...habits]; updatedArr.splice(deleteModal, 1); updateHabits(updatedArr); setDeleteModal(null); setModal(null); }} > Delete </button> </div> </div> ) : null} </> ); }; export default Modal;
import ReactPlayer from "react-player"; import { Modal } from "antd"; import { useCurrentBreakpoint } from "../hooks"; /** * VideoModal * * Modal for ReactPlayer compenent */ export const VideoModal: React.FC<{ url: string; visible: boolean; onCancel: () => void; }> = ({ url, visible, onCancel }): JSX.Element => { // Hooks const { breakpoint } = useCurrentBreakpoint(); // Widths for divider at the top of the Pages type Dimensions = { [key: string]: { height: string; width: number; }; }; const dimensions: Dimensions = { xs: { width: 360, height: "203px" }, sm: { width: 570, height: "321px" }, md: { width: 700, height: "394px" }, lg: { width: 850, height: "478px" }, xl: { width: 900, height: "506px" }, xxl: { width: 900, height: "506px" }, }; return ( <div className="modal-container"> <Modal centered footer={null} destroyOnClose closable={false} visible={visible} onCancel={onCancel} width={dimensions[breakpoint]?.width} bodyStyle={{ padding: "0px", height: dimensions[breakpoint]?.height, }} > <ReactPlayer controls url={url} stopOnUnmount width={dimensions[breakpoint]?.width || "100%"} height={dimensions[breakpoint]?.height || "100%"} /> </Modal> </div> ); };
package com.test.poi.extract; import java.io.IOException; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.beans.factory.annotation.Autowired; import com.test.poi.model.User; public class UserExcelExporter { //@Autowired private XSSFWorkbook workbook; private XSSFSheet sheet; private List<User> user; public UserExcelExporter(List<User> user) { super(); this.user = user; workbook = new XSSFWorkbook(); } private void writeHeaderLine() { sheet = workbook.createSheet("Users"); Row row = sheet.createRow(0); CellStyle style = workbook.createCellStyle(); XSSFFont font = workbook.createFont(); font.setBold(true); font.setFontHeight(16); style.setFont(font); createCell(row, 0, "User ID", style); createCell(row, 1, "Name", style); createCell(row, 2, "E-mail", style); } private void createCell(Row row, int columnCount, Object value, CellStyle style) { sheet.autoSizeColumn(columnCount); Cell cell = row.createCell(columnCount); if (value instanceof Integer) { cell.setCellValue((Integer) value); } else if (value instanceof Boolean) { cell.setCellValue((Boolean) value); }else { cell.setCellValue((String) value); } cell.setCellStyle(style); } private void writeDataLines() { int rowCount = 1; CellStyle style = workbook.createCellStyle(); XSSFFont font = workbook.createFont(); font.setFontHeight(14); style.setFont(font); for (User user : user) { Row row = sheet.createRow(rowCount++); int columnCount = 0; createCell(row, columnCount++, user.getId(), style); createCell(row, columnCount++, user.getName(), style); createCell(row, columnCount++, user.getEmail(), style); /* * createCell(row, columnCount++, user.getRoles().toString(), style); * createCell(row, columnCount++, user.isEnabled(), style); */ } } public void export(HttpServletResponse httpResponse) throws IOException { writeHeaderLine(); writeDataLines(); ServletOutputStream outputStream = httpResponse.getOutputStream(); workbook.write(outputStream); workbook.close(); outputStream.close(); } }
import { DEFAULT_CONFIG } from "@goauthentik/common/api/config"; import { EVENT_FLOW_ADVANCE, EVENT_FLOW_INSPECTOR_TOGGLE } from "@goauthentik/common/constants"; import { AKElement } from "@goauthentik/elements/Base"; import "@goauthentik/elements/Expand"; import { msg } from "@lit/localize"; import { CSSResult, TemplateResult, css, html } from "lit"; import { customElement, property } from "lit/decorators.js"; import PFButton from "@patternfly/patternfly/components/Button/button.css"; import PFCard from "@patternfly/patternfly/components/Card/card.css"; import PFDescriptionList from "@patternfly/patternfly/components/DescriptionList/description-list.css"; import PFNotificationDrawer from "@patternfly/patternfly/components/NotificationDrawer/notification-drawer.css"; import PFProgressStepper from "@patternfly/patternfly/components/ProgressStepper/progress-stepper.css"; import PFStack from "@patternfly/patternfly/layouts/Stack/stack.css"; import PFBase from "@patternfly/patternfly/patternfly-base.css"; import { FlowInspection, FlowsApi, Stage } from "@goauthentik/api"; @customElement("ak-flow-inspector") export class FlowInspector extends AKElement { flowSlug: string; @property({ attribute: false }) state?: FlowInspection; @property({ attribute: false }) error?: Response; static get styles(): CSSResult[] { return [ PFBase, PFButton, PFStack, PFCard, PFNotificationDrawer, PFDescriptionList, PFProgressStepper, css` .pf-c-drawer__body { min-height: 100vh; max-height: 100vh; } code.break { word-break: break-all; } pre { word-break: break-all; overflow-x: hidden; white-space: break-spaces; } `, ]; } constructor() { super(); this.flowSlug = window.location.pathname.split("/")[3]; window.addEventListener(EVENT_FLOW_ADVANCE, this.advanceHandler as EventListener); } disconnectedCallback(): void { super.disconnectedCallback(); window.removeEventListener(EVENT_FLOW_ADVANCE, this.advanceHandler as EventListener); } advanceHandler = (): void => { new FlowsApi(DEFAULT_CONFIG) .flowsInspectorGet({ flowSlug: this.flowSlug, }) .then((state) => { this.state = state; }) .catch((exc) => { this.error = exc; }); }; // getStage return a stage without flowSet, for brevity getStage(stage?: Stage): unknown { if (!stage) { return stage; } delete stage.flowSet; return stage; } renderAccessDenied(): TemplateResult { return html`<div class="pf-c-drawer__body pf-m-no-padding"> <div class="pf-c-notification-drawer"> <div class="pf-c-notification-drawer__header"> <div class="text"> <h1 class="pf-c-notification-drawer__header-title"> ${msg("Flow inspector")} </h1> </div> </div> <div class="pf-c-notification-drawer__body"> <div class="pf-l-stack pf-m-gutter"> <div class="pf-l-stack__item"> <div class="pf-c-card"> <div class="pf-c-card__body">${this.error?.statusText}</div> </div> </div> </div> </div> </div> </div>`; } render(): TemplateResult { if (this.error) { return this.renderAccessDenied(); } if (!this.state) { this.advanceHandler(); return html`<ak-empty-state ?loading="${true}" header=${msg("Loading")}> </ak-empty-state>`; } return html`<div class="pf-c-drawer__body pf-m-no-padding"> <div class="pf-c-notification-drawer"> <div class="pf-c-notification-drawer__header"> <div class="text"> <h1 class="pf-c-notification-drawer__header-title"> ${msg("Flow inspector")} </h1> </div> <div class="pf-c-notification-drawer__header-action"> <div class="pf-c-notification-drawer__header-action-close"> <button @click=${() => { this.dispatchEvent( new CustomEvent(EVENT_FLOW_INSPECTOR_TOGGLE, { bubbles: true, composed: true, }), ); }} class="pf-c-button pf-m-plain" type="button" aria-label=${msg("Close")} > <i class="fas fa-times" aria-hidden="true"></i> </button> </div> </div> </div> <div class="pf-c-notification-drawer__body"> <div class="pf-l-stack pf-m-gutter"> <div class="pf-l-stack__item"> <div class="pf-c-card"> <div class="pf-c-card__header"> <div class="pf-c-card__title">${msg("Next stage")}</div> </div> <div class="pf-c-card__body"> <dl class="pf-c-description-list"> <div class="pf-c-description-list__group"> <dt class="pf-c-description-list__term"> <span class="pf-c-description-list__text" >${msg("Stage name")}</span > </dt> <dd class="pf-c-description-list__description"> <div class="pf-c-description-list__text"> ${this.state.currentPlan?.nextPlannedStage ?.stageObj?.name || "-"} </div> </dd> </div> <div class="pf-c-description-list__group"> <dt class="pf-c-description-list__term"> <span class="pf-c-description-list__text" >${msg("Stage kind")}</span > </dt> <dd class="pf-c-description-list__description"> <div class="pf-c-description-list__text"> ${this.state.currentPlan?.nextPlannedStage ?.stageObj?.verboseName || "-"} </div> </dd> </div> <div class="pf-c-description-list__group"> <dt class="pf-c-description-list__term"> <span class="pf-c-description-list__text" >${msg("Stage object")}</span > </dt> <dd class="pf-c-description-list__description"> ${this.state.isCompleted ? html` <div class="pf-c-description-list__text" > ${msg("This flow is completed.")} </div>` : html`<ak-expand> <pre class="pf-c-description-list__text"> ${JSON.stringify(this.getStage(this.state.currentPlan?.nextPlannedStage?.stageObj), null, 4)}</pre > </ak-expand>`} </dd> </div> </dl> </div> </div> </div> <div class="pf-l-stack__item"> <div class="pf-c-card"> <div class="pf-c-card__header"> <div class="pf-c-card__title">${msg("Plan history")}</div> </div> <div class="pf-c-card__body"> <ol class="pf-c-progress-stepper pf-m-vertical"> ${this.state.plans.map((plan) => { return html`<li class="pf-c-progress-stepper__step pf-m-success" > <div class="pf-c-progress-stepper__step-connector"> <span class="pf-c-progress-stepper__step-icon"> <i class="fas fa-check-circle" aria-hidden="true" ></i> </span> </div> <div class="pf-c-progress-stepper__step-main"> <div class="pf-c-progress-stepper__step-title"> ${plan.currentStage.stageObj?.name} </div> <div class="pf-c-progress-stepper__step-description" > ${plan.currentStage.stageObj?.verboseName} </div> </div> </li> `; })} ${this.state.currentPlan?.currentStage && !this.state.isCompleted ? html` <li class="pf-c-progress-stepper__step pf-m-current pf-m-info" > <div class="pf-c-progress-stepper__step-connector" > <span class="pf-c-progress-stepper__step-icon" > <i class="pficon pf-icon-resources-full" aria-hidden="true" ></i> </span> </div> <div class="pf-c-progress-stepper__step-main"> <div class="pf-c-progress-stepper__step-title" > ${this.state.currentPlan?.currentStage ?.stageObj?.name} </div> <div class="pf-c-progress-stepper__step-description" > ${this.state.currentPlan?.currentStage ?.stageObj?.verboseName} </div> </div> </li>` : html``} ${this.state.currentPlan?.nextPlannedStage && !this.state.isCompleted ? html`<li class="pf-c-progress-stepper__step pf-m-pending" > <div class="pf-c-progress-stepper__step-connector" > <span class="pf-c-progress-stepper__step-icon" ></span> </div> <div class="pf-c-progress-stepper__step-main"> <div class="pf-c-progress-stepper__step-title" > ${this.state.currentPlan.nextPlannedStage .stageObj?.name} </div> <div class="pf-c-progress-stepper__step-description" > ${this.state.currentPlan?.nextPlannedStage ?.stageObj?.verboseName} </div> </div> </li>` : html``} </ol> </div> </div> </div> <div class="pf-l-stack__item"> <div class="pf-c-card"> <div class="pf-c-card__header"> <div class="pf-c-card__title"> ${msg("Current plan context")} </div> </div> <div class="pf-c-card__body"> <pre> ${JSON.stringify(this.state.currentPlan?.planContext, null, 4)}</pre > </div> </div> </div> <div class="pf-l-stack__item"> <div class="pf-c-card"> <div class="pf-c-card__header"> <div class="pf-c-card__title">${msg("Session ID")}</div> </div> <div class="pf-c-card__body"> <code class="break">${this.state.currentPlan?.sessionId}</code> </div> </div> </div> </div> </div> </div> </div>`; } }
# # (C) Tenable Network Security, Inc. # # The descriptive text and package checks in this plugin were # extracted from Red Hat Security Advisory RHSA-2008:0038 and # CentOS Errata and Security Advisory 2008:0038 respectively. # if (NASL_LEVEL < 3000) exit(0); include("compat.inc"); if (description) { script_id(29933); script_version("$Revision: 1.13 $"); script_cvs_date("$Date: 2016/11/17 20:59:08 $"); script_cve_id("CVE-2007-3278", "CVE-2007-4769", "CVE-2007-4772", "CVE-2007-6067", "CVE-2007-6600", "CVE-2007-6601"); script_bugtraq_id(27163); script_osvdb_id(40899); script_xref(name:"RHSA", value:"2008:0038"); script_name(english:"CentOS 4 / 5 : postgresql (CESA-2008:0038)"); script_summary(english:"Checks rpm output for the updated packages"); script_set_attribute( attribute:"synopsis", value:"The remote CentOS host is missing one or more security updates." ); script_set_attribute( attribute:"description", value: "Updated postgresql packages that fix several security issues are now available for Red Hat Enterprise Linux 4 and 5. This update has been rated as having moderate security impact by the Red Hat Security Response Team. PostgreSQL is an advanced Object-Relational database management system (DBMS). The postgresql packages include the client programs and libraries needed to access a PostgreSQL DBMS server. Will Drewry discovered multiple flaws in PostgreSQL's regular expression engine. An authenticated attacker could use these flaws to cause a denial of service by causing the PostgreSQL server to crash, enter an infinite loop, or use extensive CPU and memory resources while processing queries containing specially crafted regular expressions. Applications that accept regular expressions from untrusted sources may expose this problem to unauthorized attackers. (CVE-2007-4769, CVE-2007-4772, CVE-2007-6067) A privilege escalation flaw was discovered in PostgreSQL. An authenticated attacker could create an index function that would be executed with administrator privileges during database maintenance tasks, such as database vacuuming. (CVE-2007-6600) A privilege escalation flaw was discovered in PostgreSQL's Database Link library (dblink). An authenticated attacker could use dblink to possibly escalate privileges on systems with 'trust' or 'ident' authentication configured. Please note that dblink functionality is not enabled by default, and can only by enabled by a database administrator on systems with the postgresql-contrib package installed. (CVE-2007-3278, CVE-2007-6601) All postgresql users should upgrade to these updated packages, which include PostgreSQL 7.4.19 and 8.1.11, and resolve these issues." ); # http://lists.centos.org/pipermail/centos-announce/2008-January/014576.html script_set_attribute( attribute:"see_also", value:"http://www.nessus.org/u?53ef809a" ); # http://lists.centos.org/pipermail/centos-announce/2008-January/014593.html script_set_attribute( attribute:"see_also", value:"http://www.nessus.org/u?6f0547a1" ); # http://lists.centos.org/pipermail/centos-announce/2008-January/014594.html script_set_attribute( attribute:"see_also", value:"http://www.nessus.org/u?ea083562" ); # http://lists.centos.org/pipermail/centos-announce/2008-January/014603.html script_set_attribute( attribute:"see_also", value:"http://www.nessus.org/u?719ae469" ); # http://lists.centos.org/pipermail/centos-announce/2008-January/014604.html script_set_attribute( attribute:"see_also", value:"http://www.nessus.org/u?94f6bced" ); script_set_attribute( attribute:"solution", value:"Update the affected postgresql packages." ); script_set_cvss_base_vector("CVSS2#AV:L/AC:L/Au:N/C:C/I:C/A:C"); script_set_cvss_temporal_vector("CVSS2#E:ND/RL:OF/RC:C"); script_set_attribute(attribute:"exploitability_ease", value:"Exploits are available"); script_set_attribute(attribute:"exploit_available", value:"true"); script_cwe_id(189, 264, 287, 399); script_set_attribute(attribute:"plugin_type", value:"local"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-contrib"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-devel"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-docs"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-jdbc"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-libs"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-pl"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-python"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-server"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-tcl"); script_set_attribute(attribute:"cpe", value:"p-cpe:/a:centos:centos:postgresql-test"); script_set_attribute(attribute:"cpe", value:"cpe:/o:centos:centos:4"); script_set_attribute(attribute:"cpe", value:"cpe:/o:centos:centos:5"); script_set_attribute(attribute:"patch_publication_date", value:"2008/01/12"); script_set_attribute(attribute:"plugin_publication_date", value:"2008/01/14"); script_end_attributes(); script_category(ACT_GATHER_INFO); script_copyright(english:"This script is Copyright (C) 2008-2016 Tenable Network Security, Inc."); script_family(english:"CentOS Local Security Checks"); script_dependencies("ssh_get_info.nasl"); script_require_keys("Host/local_checks_enabled", "Host/CentOS/release", "Host/CentOS/rpm-list"); exit(0); } include("audit.inc"); include("global_settings.inc"); include("rpm.inc"); if (!get_kb_item("Host/local_checks_enabled")) audit(AUDIT_LOCAL_CHECKS_NOT_ENABLED); if (!get_kb_item("Host/CentOS/release")) audit(AUDIT_OS_NOT, "CentOS"); if (!get_kb_item("Host/CentOS/rpm-list")) audit(AUDIT_PACKAGE_LIST_MISSING); cpu = get_kb_item("Host/cpu"); if (isnull(cpu)) audit(AUDIT_UNKNOWN_ARCH); if ("x86_64" >!< cpu && "ia64" >!< cpu && cpu !~ "^i[3-6]86$") audit(AUDIT_LOCAL_CHECKS_NOT_IMPLEMENTED, "CentOS", cpu); flag = 0; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-contrib-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-contrib-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-contrib-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-devel-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-devel-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-devel-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-docs-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-docs-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-docs-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-jdbc-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-jdbc-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-jdbc-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-libs-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-libs-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-libs-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-pl-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-pl-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-pl-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-python-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-python-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-python-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-server-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-server-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-server-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-tcl-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-tcl-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-tcl-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"i386", reference:"postgresql-test-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"ia64", reference:"postgresql-test-7.4.19-1.c4.1")) flag++; if (rpm_check(release:"CentOS-4", cpu:"x86_64", reference:"postgresql-test-7.4.19-1.el4_6.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-8.1.11-1.el5_1.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-contrib-8.1.11-1.el5_1.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-devel-8.1.11-1.el5_1.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-docs-8.1.11-1.el5_1.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-libs-8.1.11-1.el5_1.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-pl-8.1.11-1.el5_1.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-python-8.1.11-1.el5_1.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-server-8.1.11-1.el5_1.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-tcl-8.1.11-1.el5_1.1")) flag++; if (rpm_check(release:"CentOS-5", reference:"postgresql-test-8.1.11-1.el5_1.1")) flag++; if (flag) { if (report_verbosity > 0) security_hole(port:0, extra:rpm_report_get()); else security_hole(0); exit(0); } else audit(AUDIT_HOST_NOT, "affected");
import asyncio import random from enum import Enum from typing import Optional from dataclasses import dataclass from datetime import datetime, timedelta class Response(Enum): Success = 1 RetryAfter = 2 Failure = 3 class ApplicationStatusResponse(Enum): Success = 1 Failure = 2 @dataclass class ApplicationResponse: application_id: str status: ApplicationStatusResponse description: str last_request_time: datetime retriesCount: Optional[int] = None async def get_application_status1(identifier: str) -> Response: # Имитация задержки await asyncio.sleep(random.uniform(0.1, 0.5)) # Случайный выбор результата return random.choice([Response.Success, Response.RetryAfter, Response.Failure]) async def get_application_status2(identifier: str) -> Response: # Имитация задержки await asyncio.sleep(random.uniform(0.1, 0.5)) # Случайный выбор результата return random.choice([Response.Success, Response.RetryAfter, Response.Failure]) async def perform_operation(identifier: str) -> ApplicationResponse: start_time = datetime.now() tasks = [get_application_status1(identifier), get_application_status2(identifier)] done, _ = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) for task in done: response = task.result() if response == Response.Success: return ApplicationResponse( application_id=identifier, status=ApplicationStatusResponse.Success, description="Operation succeeded", last_request_time=datetime.now() ) # Если все задачи завершились неудачей return ApplicationResponse( application_id=identifier, status=ApplicationStatusResponse.Failure, description="Operation failed", last_request_time=datetime.now(), retriesCount=len(done) # Пример, как можно использовать retriesCount ) async def main(): identifier = "12345" result = await perform_operation(identifier) print(result) if __name__ == "__main__": asyncio.run(main())
// * Hooks import { useState, useEffect } from 'react' // * Cmps import Home from '@/components/Home' import Footer from '@/components/Footer' import Collections from '@/components/Collections' import ContactUs from '@/components/ContactUs' import Portfolio from '@/components/Portfolio' import MainHeader from '@/components/MainHeader' // * Types import { SelectedPage } from '@/shared/types' import Policy from './components/Policy' export default function App() { const [isTopOfPage, setIsTopOfPage] = useState<boolean>(true) const [isMainNavOpen, setIsMainNavOpen] = useState<boolean>(false) const [selectedPage, setSelectedPage] = useState<SelectedPage>(SelectedPage.Home) useEffect(() => { const handleScroll = () => { if (window.scrollY === 0) { setIsTopOfPage(true) setSelectedPage(SelectedPage.Home) } else setIsTopOfPage(false) } window.addEventListener('scroll', handleScroll) return () => window.removeEventListener('scroll', handleScroll) }, []) return <div className="app h-fit"> <MainHeader isTopOfPage={isTopOfPage} selectedPage={selectedPage} isMainNavOpen={isMainNavOpen} setSelectedPage={setSelectedPage} setIsMainNavOpen={setIsMainNavOpen} /> <Home selectedPage={selectedPage} setSelectedPage={setSelectedPage} /> <Collections setSelectedPage={setSelectedPage} /> <Portfolio setSelectedPage={setSelectedPage} /> <Policy setSelectedPage={setSelectedPage} /> <ContactUs setSelectedPage={setSelectedPage} /> <Footer /> </div> }
<template> <div class="item"> <input type="checkbox" name="" id="" @change="updateCheck()" v-model="item.completed" /> <span :class="[item.completed ? 'completed' : '', 'itemText']">{{ item.name }}</span> <button @click="removeItem()" class="trashCan"> <font-awesome-icon icon="trash" /> </button> </div> </template> <script> export default { props: ["item"], methods: { updateCheck() { axios .put("api/item/" + this.item.id, { item: this.item }) .then(result => { if (result.status == 200) { this.$emit("itemChanged"); } }) .catch(err => { console.log(err); }); }, removeItem() { axios .delete("api/item/" + this.item.id) .then(result => { if (result.status == 200) { this.$emit("itemChanged"); } }) .catch(err => { console.log(err); }); } } }; </script> <style scoped> .completed { text-decoration: line-through; color: #999; } .itemText { width: 100%; margin-left: 20px; } .item { display: flex; justify-content: center; align-items: center; } .trashCan { background-color: #e6e6e6; border: none; color: #ff0000; outline: none; } </style>
<template> <APanel :isOpen="isOpen" contentClass="menu-mob__content" class="menu-mob" :class="{ [active]: true }" @close="close" > <transition :name="transitionName"> <MenuMobMain v-if="active === 'main'" v-model="active" /> <MenuMobCategories v-if="active === 'categories'" @back="onBack" /> </transition> </APanel> </template> <script lang="ts"> import { computed, defineComponent, ref, useRoute, useRouter, watch, } from '@nuxtjs/composition-api' import useMobileMenu from '@/utils/compositions/useMobileMenu' export default defineComponent({ setup() { const { isOpen, open, close } = useMobileMenu() const active = ref('main') const onBack = () => { active.value = 'main' } const transitionName = computed(() => { return active.value === 'main' ? 't-switch' : 't-switch-back' }) return { transitionName, onBack, active, isOpen, close, } }, }) </script> <style lang="postcss"> .menu-mob { @apply fixed top-0 left-0 right-0 bottom-0 lg:block hidden; z-index: 300!important; &.main &__content { @apply max-w-[300px] sm:max-w-[250px]; } &__content { @apply w-full max-w-[350px] transition h-full bg-white z-20 relative overflow-y-auto; } } .t-switch-leave-to, .t-switch-back-enter { transform: translateX(-100%); /* opacity: 0; */ } .t-switch-enter, .t-switch-back-leave-to { transform: translateX(100%); } .t-switch-leave-active, .t-switch-enter-active, .t-switch-back-leave-active, .t-switch-back-enter-active { position: absolute; width: 100%; transition: 0.3s; } </style>
package the_bloater.large_class; public class ExtractSubClass { // todo: extract subclass PartsItem & LaborItem from JobItem abstract class JobItem { private int quantity; public JobItem(int quantity) { this.quantity = quantity; } public int getTotalPrice() { return quantity * getUnitPrice(); } public int getQuantity() { return quantity; } abstract int getUnitPrice(); } class PartsItem extends JobItem { private int unitPrice; public PartsItem(int quantity, int unitPrice) { super(quantity); this.unitPrice = unitPrice; } public int getUnitPrice() { return unitPrice; } } class LaborItem extends JobItem { private Employee employee; public LaborItem(int quantity, Employee employee) { super(quantity); this.employee = employee; } public int getUnitPrice() { return employee.getRate(); } public Employee getEmployee() { return employee; } } class LaborAndPartsItem extends JobItem { private Employee employee; private int unitPrice; public LaborAndPartsItem(int quantity, int unitPrice, Employee employee) { super(quantity); this.unitPrice = unitPrice; this.employee = employee; } public int getUnitPrice() { return employee.getRate() + unitPrice; } public Employee getEmployee() { return employee; } } class Employee { private int rate; public Employee(int rate) { this.rate = rate; } public int getRate() { return rate; } } void test() { Employee kent = new Employee(50); JobItem j1 = new LaborItem(5, kent); JobItem j2 = new PartsItem(15, 10); int total = j1.getTotalPrice() + j2.getTotalPrice(); JobItem j3 = new LaborAndPartsItem(5, 10, kent); System.out.println(total); System.out.println(j3.getTotalPrice()); } public static void main(String[] args) { new ExtractSubClass().test(); } }
#!/usr/bin/python3 """Defining a locked class""" class LockedClass: """This class is used to create a dynamic creation of attributes. only those mentioned in list can be created""" __slots__ = ['first_name'] def __init__(self, name=None): """This function is used to initialize the class Args: name (str): the value of first name""" self.first_name = name
# source("app_server.R") # Li-followings are variables needed for maps tab: # ---------------------------------------------------------------------------- # read in the Jasper's table(subject to change) map_df <- read.csv("OurData.csv", stringsAsFactors = FALSE) # only use the county data, ignore city data(they are not in right form) map_df <- map_df[map_df$geo_type == "county", ] # replace NA with standard value = 100 map_df[is.na(map_df)] <- 100 # clean col names colnames(map_df)[7:ncol(map_df)] <- as.character(as.Date(colnames(map_df)[7:ncol(map_df)], "X%m.%d.%y")) # ---------------------------------------------------------------------------- # global var prepare code end here ui <- fluidPage( tags$head( tags$style(HTML(" @import url('https://fonts.googleapis.com/css2?family=Readex+Pro:wght@300&display=swap'); body { background-color: #ffffe6; color: black; }")) ), navbarPage("Transportation in Covid Times", tabPanel("Introduction", h1("Introduction"), p("This project mainly explores how the pandemic influenced people's choice of transportation. This dataset was collected from Apple’s Maps app which was collected through users' devices. The dataset provides visualization of changes in transportation usage patterns of people during the COVID-19 pandemic. Such visualizations help us understand the behavioral changes of people in the United States maneuvered by the devastating global pandemic. Our analysis filtered down all data which only happened in the United States city and county, which was how the transportation trends had changed because of the COVID-19. It also revealed the relationship between region, subregion, and change of the transportation type.In addition, Our dataset provides information on transportation types, occurring dates, and mobility changes."), br(), img(src = "Tendencias_Movilidad_ENG.png", height = 600, width = 450, style="display: block; margin-left: auto; margin-right: auto;") ), tabPanel("Chart 1", sidebarLayout( sidebarPanel( radioButtons(inputId = "TypeW", "Transportation type:", choices = list("By walking" = 1, "By public transit" = 2, "By driving" = 3), selected = 1 ), dateRangeInput("DatesW", "Date range:", start = "2020-01-13", end = "2021-10-26", min = "2020-01-13", max = "2021-10-26", format = "yyyy-mm-dd", separator = " - ", ) ), mainPanel(h1("Change of transportation Usage in the USA by time"), p("This chart demonstrates the relationship among different transportation choice in certain period of time chosen by user. By using scatterplot, user can obeserve how transportation usage has shifted througout this pendemic."), plotOutput(outputId = "scatter") ) )), tabPanel("Chart 2", sidebarLayout( sidebarPanel( radioButtons( inputId = "sType", label = "Select a Region:", choices = list("Washington"= '1', "New York"= '2', "California"= '3'), ) ), mainPanel( h1("Methods of Transportation"), p("This is a pie chart that compares the methods of transportation used in Washington, New York and California. As these three regions have", strong("very different methods of transportation.")), br(), plotlyOutput(outputId = "piechart") ) )), # Li- UI part for map tab # --------------------------------------------------------- tabPanel("Chart 3", h1("Mobility Fluctuation during Covid-19"), p("These maps reflects mobility and covid cases respectively: "), p(strong("Mobility Fluctuation Map:"), "Represent the fluctuation of people's mobility pattern with a baseline set to pre-Covid period (darker means larger fluctuation)"), p(strong("New Cases Map:"), " Represent the amount of new cases in each state during the same period (darker means more cases)"), p(strong("Quick insights of this part:"), "In general, The comparison of two maps shows that states where people have changed there mobility pattern the most (compared to pre-Covid period) tend to be states with less cases. On the other hand, states where people remains doing what they did before Covid has larger number of new cases"), br(), sidebarLayout( sidebarPanel( sliderInput(inputId = "timeRange", label = "Choose a Date Interval\n (click play button to get animated map)", min = as.Date("2020-01-30"), max = as.Date(colnames(map_df)[651]), value = c(as.Date("2020-01-30"),as.Date(colnames(map_df)[651])), animate = animationOptions(200) #local PC performance limit ), verbatimTextOutput("range") ), mainPanel( br(), tabsetPanel( id = "graphs", tabPanel("Maps", plotlyOutput(outputId = "mapPlot"), plotlyOutput(outputId = "casesPlot")), tabPanel("Data Table", tableOutput(outputId = "check")) ) ) )), # ----------------------------------------------------------- # Li- map UI ends here tabPanel("Conclusion", h1("Conclusion"), p("First, through the analysis of the dataset, we found that mobility trends has a strong positive relationship with new cases of COVID-19. If people changed their transportation , the states? new cases would be less than unchanged states. In addition, some states constantly increasing new cases but will suddenly change when the mobility trends are changed. Therefore, we found that transportation mobility trends are related to the pandemic new cases."), p("Second, from the analysis we learned that the COVID-19 cases is not only related to population, city area, and weekend effects, but after taking those elements out of analysis, we still could pursue that trend of transportation way has direct relationship with pandemic cases. "), p("Third, we found that even though the COVID-19 triggered the change of the transportation choosing, driving is the most popular way for people to choose for their transportation. Moreover, we found that there are still some people need transit for their transportation, even it might cause increase of probability of getting Covid-19. "), p("Overall, transit has the largest change during pandemic mobility trends, but there are still people need to choose different transportation, and the pandemic total cases has a strong relationship with mobility trends."), img(src = "map.png", height = 320, width = 500, style="display: block; margin-left: auto; margin-right: auto;"), img(src = "pie chart.png", height = 320, width = 510, style="display: block; margin-left: auto; margin-right: auto;"), img(src = "Scatterplot.png", height = 320, width = 500, style="display: block; margin-left: auto; margin-right: auto;"), ), ))
////给定一个 N 叉树,返回其节点值的 前序遍历 。 //// //// N 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。 //// //// //// //// //// //// 进阶: //// //// 递归法很简单,你可以使用迭代法完成此题吗? //// //// //// //// 示例 1: //// //// //// //// ////输入:root = [1,null,3,2,4,null,5,6] ////输出:[1,3,5,6,2,4] //// ////示例 2: //// //// //// //// ////输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,1 //2, ////null,13,null,null,14] ////输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10] //// //// //// //// //// 提示: //// //// //// N 叉树的高度小于或等于 1000 //// 节点总数在范围 [0, 10^4] 内 //// //// //// //// Related Topics 栈 树 深度优先搜索 👍 178 👎 0 // package com.rj.leetcode_solution.leetcode.editor.cn; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.LinkedList; import java.util.List; //java:N 叉树的前序遍历 class P589NAryTreePreorderTraversal { public static void main(String[] args) { Solution solution = new P589NAryTreePreorderTraversal().new Solution(); } //leetcode submit region begin(Prohibit modification and deletion) /* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val) { val = _val; } public Node(int _val, List<Node> _children) { val = _val; children = _children; } }; */ class Solution { public List<Integer> preorder(Node root) { //方法1.递归 return preorder1(root); //方法2. 迭代 // return preorder2(root); } private List<Integer> preorder2(Node root) { LinkedList<Integer> res = new LinkedList<>(); if (root == null) { return res; } Deque<Node> stack = new ArrayDeque<>(); stack.push(root); while (!stack.isEmpty()) { Node node = stack.pop(); res.add(node.val); //后进先出 Collections.reverse(node.children); for (Node child : node.children) { stack.push(child); } } return res; } private List<Integer> preorder1(Node root) { List<Integer> res = new ArrayList<>(); preNodeOrder(root, res); return res; } private void preNodeOrder(Node root, List<Integer> res) { if (root == null) { return; } res.add(root.val); for (Node child : root.children) { if (child != null) { preNodeOrder(child, res); } } } } //leetcode submit region end(Prohibit modification and deletion) }
import React, {useState, useEffect} from 'react' // ES6 import './NavbarComp.css' import {Navbar, Container, Nav, NavDropdown} from 'react-bootstrap' import {Link} from 'react-router-dom' import { BrowserRouter as Router, Routes, Route } from 'react-router-dom' import Home from './Home' import Contact from './Contact' import Cart from './Cart' import Music from './inventories/music' import Sports from './inventories/sports' import Arduino from './inventories/tech/arduino' import BroadBand from './inventories/tech/broad-band' import MicroControl from './inventories/tech/microcontrolers' import Sensor from './inventories/tech/sensors' import useCart from './inventories/useCart'; function NavbarComp(){ const {list, totalCost, updateCart} = useCart(); // the custom HOOK return ( <Router> <div classsName="App"> <Navbar bg="dark" variant="dark" expand="lg"> <Container> <Navbar.Brand className="host" as={Link} to={"/"}>Learners <span>Space</span></Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="ms-auto"> <Nav.Link className="bar-item" as={Link} to={"/"}>Home</Nav.Link> <Nav.Link className="bar-item" as={Link} to={"/inventories/Music"}>Music</Nav.Link> <Nav.Link className="bar-item" as={Link} to={"/inventories/Sports"}>Sports</Nav.Link> <NavDropdown className="bar-item" bg="dark" variant="dark" title="Tech" id="basic-nav-dropdown"> <NavDropdown.Item as={Link} to={"/inventories/tech/arduino"}>Arduino</NavDropdown.Item> <NavDropdown.Item as={Link} to={"/inventories/tech/broad-band"}> Broad Band </NavDropdown.Item> <NavDropdown.Item as={Link} to={"/inventories/tech/microcontroler"}>Micro Controllers</NavDropdown.Item> <NavDropdown.Item as={Link} to={"/inventories/tech/sensors"}> Sensors </NavDropdown.Item> </NavDropdown> <Nav.Link className="bar-item" as={Link} to={"/Contact"}>Contact</Nav.Link> <Nav.Link className="bar-item" as={Link} to={"/Cart"}>Cart</Nav.Link> </Nav> </Navbar.Collapse> </Container> </Navbar> </div> <div> <Routes> <Route path="/" element={<Home />}/> <Route path="/Cart" element={<Cart list={list} total={totalCost} />}/> <Route path="/Contact" element={<Contact />}/> <Route path="/inventories/music" element={<Music updateCart = {updateCart}/>}/> <Route path="/inventories/sports" element={<Sports updateCart = {updateCart}/>}/> <Route path="/inventories/tech/arduino" element={<Arduino updateCart = {updateCart}/>}/> <Route path="/inventories/tech/broad-band" element={<BroadBand updateCart = {updateCart}/>}/> <Route path="/inventories/tech/microcontroler" element={<MicroControl updateCart = {updateCart}/>}/> <Route path="/inventories/tech/sensors" element={<Sensor updateCart = {updateCart}/>}/> </Routes> </div> </Router> ); } export default NavbarComp
import { Table } from "docs-ui" import ApiKeyEvents from "../commerce-modules/api-key/events/_events-table/page.mdx" import AuthEvents from "../commerce-modules/auth/events/_events-table/page.mdx" import CartEvents from "../commerce-modules/cart/events/_events-table/page.mdx" import CurrencyEvents from "../commerce-modules/currency/events/_events-table/page.mdx" import CustomerEvents from "../commerce-modules/customer/events/_events-table/page.mdx" import FulfillmentEvents from "../commerce-modules/fulfillment/events/_events-table/page.mdx" import InventoryEvents from "../commerce-modules/inventory/events/_events-table/page.mdx" import OrderEvents from "../commerce-modules/order/events/_events-table/page.mdx" import PaymentEvents from "../commerce-modules/payment/events/_events-table/page.mdx" import PricingEvents from "../commerce-modules/pricing/events/_events-table/page.mdx" import ProductEvents from "../commerce-modules/product/events/_events-table/page.mdx" import PromotionEvents from "../commerce-modules/promotion/events/_events-table/page.mdx" import RegionEvents from "../commerce-modules/region/events/_events-table/page.mdx" import SalesChannelEvents from "../commerce-modules/sales-channel/events/_events-table/page.mdx" import StockLocationEvents from "../commerce-modules/stock-location/events/_events-table/page.mdx" import StoreEvents from "../commerce-modules/store/events/_events-table/page.mdx" import TaxEvents from "../commerce-modules/tax/events/_events-table/page.mdx" import UserEvents from "../commerce-modules/user/events/_events-table/page.mdx" export const metadata = { title: `Events Reference`, } # {metadata.title} This documentation page includes the list of all events triggered by Medusa's commerce modules. ## API Key Module Events <ApiKeyEvents /> ## Auth Module Events <AuthEvents /> ## Cart Module Events <CartEvents /> ## Currency Module Events <CurrencyEvents /> ## Customer Module Events <CustomerEvents /> ## Fulfillment Module Events <FulfillmentEvents /> ## Inventory Module Events <InventoryEvents /> ## Order Module Events <OrderEvents /> ## Payment Module Events <PaymentEvents /> ## Pricing Module Events <PricingEvents /> ## Product Module Events <ProductEvents /> ## Promotion Module Events <PromotionEvents /> ## Region Module Events <RegionEvents /> ## Sales Channel Module Events <SalesChannelEvents /> ## Stock Location Module Events <StockLocationEvents /> ## Store Module Events <StoreEvents /> ## Tax Module Events <TaxEvents /> ## User Module Events <UserEvents />
package main import ( "fmt" "log" "net/http" "time" "github.com/ArtyomHov/go-booking/pkg/config" "github.com/ArtyomHov/go-booking/pkg/handlers" "github.com/ArtyomHov/go-booking/pkg/render" "github.com/alexedwards/scs/v2" ) const portNumber = ":8080" var app config.AppConfig var session *scs.SessionManager func main() { // Set to true when in production app.InProduction = false session = scs.New() session.Lifetime = 24 * time.Hour session.Cookie.Persist = true session.Cookie.SameSite = http.SameSiteLaxMode session.Cookie.Secure = app.InProduction app.Session = session tc, err := render.CreateTemplateCache() if err != nil { log.Println("Cannot create template cache.") } app.TemplateCache = tc app.UseCache = false repo := handlers.NewRepo(&app) handlers.NewHandlers(repo) render.NewTemplates(&app) // http.HandleFunc("/", handlers.Repo.Home) // http.HandleFunc("/about", handlers.Repo.About) fmt.Println(fmt.Sprintf("Starting application on port %s", portNumber)) // _ = http.ListenAndServe(portNumber, nil) srv := &http.Server{ Addr: portNumber, Handler: routes(&app), } err = srv.ListenAndServe() log.Fatal(err) }
from ..config import * from ..handler.timerConverter import TimeConverter TC = TimeConverter(DB) Animations = { "Enemies":{}, "Friendly":{ "Chicken":{ 'Walk':{ 'left':[(96,145,16,16),(112,145,16,16),(128,145,16,16)], 'right':[(96,162,16,16),(112,162,16,16),(128,162,16,16)], 'up':[(96,128,16,16),(112,128,16,16),(128,128,16,16)], 'down':[(96,176,16,16),(112,176,16,16),(128,176,16,16)], }, 'Idle':{ 'left':[(112,145,16,16),], 'right':[(112,162,16,16),], 'up':[(112,128,16,16),], 'down':[(112,176,16,16),], }, } } } """ ENEMIES """ class Enemy(pyg.sprite.Sprite): _layer = 3 _attack_delay = TC.getTime(1) _move_delay = TC.getTime(2) # Stats _damage = 5 _speed = 5 _defense = 5 _level = 1 _baseExp = 10 health = 100 maxhealth = 100 _locked = False _type = 'enemy' _name = "Enemy Base" def __init__(self, XY,*groups) -> None: super().__init__(*groups) self.rect = Rect(XY[0],XY[1],32,32) self.image = pyg.Surface((32,32)) self.image.fill((200,0,0)) self.camera = self.groups()[0] self.repeat = 0 self.path = pyg.math.Vector2(0,0) def getRange(self): return self._damage * random.choice([0.8,0.9,1,1.1,1.2]) def attack(self,player): if self.health > 0: if self._attack_delay <= 0 and not (player._dead): player.takeDamage(self.getRange()) self._attack_delay = TC.getTime(1) def collision(self, player): if self.rect.colliderect(player.rect): self.attack(player) self._locked = True else: self._locked = False def takeDamage(self, damage:float or int): if self.health > 0: d = self._defense / 3 self.health -= (damage - d) def Reward(self): try: plr = self.camera.player if self.health <= 0 and plr.health >= 1: exp = int(self._baseExp* (1+(self._level * (plr.luck/3)))) gold = int(25*(self._level*(plr.luck/3))) plr.Experience += exp plr.money += gold print(f'[Enemy] Player Killed {self._name} and won {Fore.LIGHTBLUE_EX}{exp}{Fore.RESET} of exp and {Fore.YELLOW}${gold}{Fore.RESET} of money') except Exception as err: print(f'{Fore.RED}[Enemy - Reward] {err}{Fore.RESET}') def IsDead(self): if self.health<=0: self.Reward() self.kill() def movement(self): if self._move_delay <= 0: if not self._locked: if self.repeat >= random.randint(2,4): self.path.x = random.choice([-1.2,-1,0,1,1.2]) self.path.y = random.choice([-1.2,-1,0,1,1.2]) self._move_delay = TC.getTime(2) self.repeat = 0 else: self.repeat += 1 self._move_delay = TC.getTime(random.choice([0.1,0.2,0.3])) self.rect.x += self.path.x * self._speed self.rect.y += self.path.y * self._speed def draw_info(self): convert_offset = self.camera.convert_offset((self.rect.centerx,self.rect.bottom)) if self.health < self.maxhealth: pme.draw_bar((convert_offset[0]-16,convert_offset[1]+18),(32,15),self.health,self.maxhealth,text=f'{round(self.health)}/{round(self.maxhealth)}', textfont=5, screen=self.camera.internal_surf) pme.draw_text([convert_offset[0]-16,convert_offset[1]+6],str(self._name[12:]),5,(255,255,255),screen=self.camera.internal_surf) def update(self, player): if self.health <= 0: self._locked = True self.collision(player) self.movement() self.IsDead() if self._attack_delay > 0: self._attack_delay -= 1 if self._move_delay > 0: self._move_delay -= 1 """ FRIENDLY """ class Friendly(pyg.sprite.Sprite): _layer = 3 _move_delay = TC.getTime(1) _damage = 5 _speed = 5 _locked = False _type = 'enemy' _name = "Friendly Base" health = 100 maxhealth = 100 size = (32,32) def __init__(self, XY,*groups) -> None: super().__init__(*groups) self.camera = self.groups()[0] self.repeat = 0 self.path = pyg.math.Vector2(0,0) self.animations = {'Walk':{'up':[],'down':[],'left':[],'right':[]},'Idle':{'up':[],'down':[],'left':[],'right':[]}} self.setupAnimations() self.anim_frame = 0 self.state = 'Idle' self.lastSide = 'left' self.rect = Rect(XY[0],XY[1],32,32) self.image = self.animations[self.state][self.lastSide][self.anim_frame] or pyg.Surface((32,32)) def animPlay(self): track = self.animations[self.state][self.lastSide] self.anim_frame += .15 if self.anim_frame > len(track): self.anim_frame = 0 self.image = track[int(self.anim_frame)] def setupAnimations(self): try: myStyle = Animations['Friendly'] myStyle = myStyle[self._name] for state in myStyle.keys(): for side in myStyle[state].keys(): for i,anim in enumerate(myStyle[state][side]): s = spritesheet('.'+PLAYERS_SPRITESHEET) self.animations[state][side].insert(i,pyg.transform.scale(s.image_at(anim,-1),self.size)) except Exception as err: print(err) def collision(self, player): if self.rect.colliderect(player.rect): self._locked = True else: self._locked = False def movement(self): if self._move_delay <= 0: if not self._locked: if self.repeat >= random.randint(2,4): self.path.x = random.choice([-1.2,-1,0,1,1.2]) self.path.y = random.choice([-1.2,-1,0,1,1.2]) self._move_delay = TC.getTime(0.5) self.repeat = 0 else: self.CheckSideAndState() self.repeat += 1 self._move_delay = TC.getTime(random.choice([0.1,0.2,0.3])) self.rect.x += self.path.x * self._speed self.rect.y += self.path.y * self._speed if self.path.x != 0 or self.path.y != 0: self.animPlay() def draw_info(self): surface = self.camera.internal_surf convert_offset = self.camera.convert_offset((self.rect.centerx,self.rect.bottom)) if self.health < self.maxhealth: pme.draw_bar((convert_offset[0]-16,convert_offset[1]+18),(32,15),self.health,self.maxhealth,text=f'{round(self.health)}/{round(self.maxhealth)}', textfont=5, screen=surface) pme.draw_text([convert_offset[0]-16,convert_offset[1]+6],str(self._name[12:]),5,(255,255,255),screen=surface) def CheckSideAndState(self): if not self._locked: if self.path.y != 0 or self.path.x != 0: self.state = 'Walk' if self.path.x > 0: self.lastSide = 'right' elif self.path.x < 0: self.lastSide = 'left' elif self.path.y > 0: self.lastSide = 'down' elif self.path.y < 0: self.lastSide = 'up' else: self.state = 'Idle' else: self.state = 'Idle' if self.health <= 0: self.state = 'Dead' def update(self, player): self.collision(player) self.movement() if self._move_delay > 0: self._move_delay -= 1 class Chicken(Friendly): _name = "Chicken" health = 25 maxhealth = 25 _speed = 2.5
#include "variadic_functions.h" /** * sum_them_all - function that sums up arguments * @n: size of array * * Return: Always 0 (Success) */ int sum_them_all(const unsigned int n, ...) { va_list ap; int sum = 0; unsigned int i; if (n == 0) { return (0); } va_start(ap, n); for (i = 0; i < n; i++) { sum += va_arg(ap, int); } va_end(ap); return (sum); }
<div class="container-fluid"> <div class="row no-gutter"> <div class="col-md-6 d-none d-md-flex bg-image"></div> <div class="col-md-6 bg-light"> <div class="login d-flex align-items-center py-5"> <div class="container"> <div class="row"> <div class="col-lg-10 col-xl-7 mx-auto"> <div *ngIf="!register"> <h3 class="display-4">Login</h3> <form class="w-75" [formGroup]="loginForm" (ngSubmit)="onSubmitLogin()"> <div class="form-group mb-3 "> <input id="inputEmail" type="email" formControlName="email" [ngClass]="{ 'is-invalid': logSubmitted && log.email.errors }" placeholder="Email address" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4"> <div *ngIf="logSubmitted && log.email.errors" class="invalid-feedback"> <div *ngIf="log.email.errors.required">Email is required</div> <div *ngIf="log.email.errors.email">Email must be a valid email address </div> </div> </div> <div class="form-group mb-3"> <input id="inputPassword" type="password" formControlName="password" [ngClass]="{ 'is-invalid': logSubmitted && log.password.errors }" placeholder="Password" required="" class="form-control rounded-pill border-0 shadow-sm px-4 text-primary"> <div *ngIf="logSubmitted && log.password.errors" class="invalid-feedback"> <div *ngIf="log.password.errors.required">Password is required</div> </div> </div> <div class="text-center"> <button type="submit" class="w-75 btn btn-primary btn-block text-uppercase mb-2 rounded-pill shadow-sm "> ingresar </button> </div> </form> <div> <span (click)="formRegister()">no tengo cuenta</span> </div> </div> <div *ngIf="register"> <h3 class="display-4">register</h3> <form class="w-100" [formGroup]="registerForm" (ngSubmit)="onSubmitRegister()"> <div class="form-group mb-3 d-flex"> <div class="col-6 px-2"> <input id="inputName" type="text" formControlName="name" [ngClass]="{ 'is-invalid': regSubmitted && reg.name.errors }" placeholder="Nombre" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4"> <div *ngIf="regSubmitted && reg.name.errors" class="invalid-feedback"> <div *ngIf="reg.name.errors.required">name is required</div> </div> </div> <div class="col-6 px-2"> <input id="inputSurname" type="text" formControlName="surname" [ngClass]="{ 'is-invalid': regSubmitted && reg.surname.errors }" placeholder="Apellidos" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4"> <div *ngIf="regSubmitted && reg.surname.errors" class="invalid-feedback"> <div *ngIf="reg.surname.errors.required">surname is required</div> </div> </div> </div> <div class="form-group mb-3 d-flex"> <div class="col-6 px-2"> <input id="inputDate" type="date" formControlName="datebirth" [ngClass]="{ 'is-invalid': regSubmitted && reg.datebirth.errors }" placeholder="Nombres" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4"> <div *ngIf="regSubmitted && reg.datebirth.errors" class="invalid-feedback"> <div *ngIf="reg.datebirth.errors.required">datebirth is required</div> </div> </div> <div class="col-6 px-2"> <input id="inputEmail" type="email" formControlName="emailregister" [ngClass]="{ 'is-invalid': regSubmitted && reg.emailregister.errors }" placeholder="Email address" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4"> <div *ngIf="regSubmitted && reg.emailregister.errors" class="invalid-feedback"> <div *ngIf="reg.emailregister.errors.required">Email is required</div> <div *ngIf="reg.emailregister.errors.email">Email must be a valid email address </div> </div> </div> </div> <div class="form-group mb-3 d-flex"> <div class="col-6 px-2"> <input id="docNumber" type="text" formControlName="docnumber" [ngClass]="{ 'is-invalid': regSubmitted && reg.docnumber.errors }" placeholder="Numero de documento" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4"> <div *ngIf="regSubmitted && reg.docnumber.errors" class="invalid-feedback"> <div *ngIf="reg.docnumber.errors.required">docnumber is required</div> </div> </div> <div class="col-6 px-2"> <input id="inputArea" type="email" formControlName="area" [ngClass]="{ 'is-invalid': regSubmitted && reg.area.errors }" placeholder="Area" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4"> <div *ngIf="regSubmitted && reg.area.errors" class="invalid-feedback"> <div *ngIf="reg.area.errors.required">area is required</div> </div> </div> </div> <div class="form-group mb-3 d-flex"> <div class="col-6 px-2"> <input id="inputName" type="password" formControlName="pass" [ngClass]="{ 'is-invalid': regSubmitted && reg.pass.errors }" placeholder="Contraseña" required="" autofocus="" class="form-control rounded-pill border-0 shadow-sm px-4"> <div *ngIf="regSubmitted && reg.pass.errors" class="invalid-feedback"> <div *ngIf="reg.pass.errors.required">name is required</div> </div> </div> </div> <div class="text-center"> <button type="submit" class="w-75 btn btn-primary btn-block text-uppercase mb-2 rounded-pill shadow-sm "> Registrar </button> </div> </form> <div> <span (click)="formRegister()">ya tengo cuenta</span> </div> </div> </div> </div> </div> </div> </div> </div> </div>
from subinterpreter_parallelism import parallel from pure_cpp_parallelism import c_factorial from random import randint import isolated_benchmark from multiprocessing import Process from threading import Thread import logging import time logging.basicConfig( format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S') # Number of task runs to spawn. NUM_TASKS = 10 # Increase MIN & MAX to increase time taken by each task (should be < 1000000000) MIN = 90000000 MAX = 90000100 # Benchmark Python function against multiple Python processes. logging.warning(f"Multi-processing mode started for {NUM_TASKS} regular Python tasks") start = time.time() processes = [Process(target=isolated_benchmark.py_factorial, args=(randint(MIN, MAX),)) for _ in range(NUM_TASKS)] for p in processes: p.start() for p in processes: p.join() end = time.time() logging.warning(f"Multi-processing mode ended for {NUM_TASKS} regular Python tasks in {end-start} seconds") # Benchmark Python function against the custom handwritten sub-interpreter parallelism module. logging.warning(f"Sub-interpreter parallelism mode started for {NUM_TASKS} regular Python tasks") start = time.time() result = parallel(*[['isolated_benchmark', 'py_factorial', (randint(MIN,MAX),)] for _ in range(NUM_TASKS)]) end = time.time() logging.warning(f"Sub-interpreter parallelism mode ended with {result=} in {end-start} seconds") # Benchmark similar C++ extension function. logging.warning(f"Multi-threaded C++ code execution from Python function started for {NUM_TASKS} tasks") start = time.time() threads = [Thread(target=c_factorial, args=(randint(MIN,MAX),)) for _ in range(NUM_TASKS)] for thread in threads: thread.start() for thread in threads: thread.join() end = time.time() logging.warning(f"Multi-threaded C++ code execution from Python function in {end-start} seconds") # Benchmark Python function against a single thread. start = time.time() logging.warning("Single threaded mode for 1 regular Python task begins") result = isolated_benchmark.py_factorial(randint(MIN, MAX)) end = time.time() logging.warning(f"Single threaded mode ended for 1 regular Python task with {result=} in {end-start} seconds") # Benchmark Python function against multiple threads. logging.warning(f"Multi-threaded mode for {NUM_TASKS} regular Python functions begins") start = time.time() threads = [Thread(target=isolated_benchmark.py_factorial, args=(randint(MIN,MAX),)) for _ in range(NUM_TASKS)] for thread in threads: thread.start() for thread in threads: thread.join() end = time.time() logging.warning(f"Multi-threaded mode ended for {NUM_TASKS} regular Python functions in {end-start} seconds")
#%% import numpy as np from scipy.optimize import curve_fit from scipy.special import assoc_laguerre import math #%% ------------------ Rabi Frequencies & Distributions ------------------ def rabi_freq(nStart, nDelta, LD_param): """ Calculates Rabi Frequency for nStart -> nStart + nDelta Args: nStart (int): Initial phonon state nDelta (int): Change in phonon number LD_param (float): Lamb-Dicke Parameter Returns: float: Rabi frequency normalised to carrier Rabi frequency value """ nEnd = nStart + nDelta if nEnd > 0: nSmall = min([nStart, nEnd]) nBig = max([nStart, nEnd]) factor2 = np.exp(-0.5 * LD_param**2) * LD_param**(np.absolute(nDelta)) factor3 = np.sqrt(np.math.factorial(nSmall)/np.math.factorial(nBig)) factor4 = assoc_laguerre(LD_param**2, nSmall, np.absolute(nDelta)) return factor2 * factor3 * factor4 else: return 0 def coherent_distribution(nBar, max_n_fit): return [nBar**n * np.exp(-nBar) / np.math.factorial(n) for n in range(max_n_fit)] def thermal_distribution(nBar, max_n_fit): return [nBar**n / ((nBar + 1)**(n+1)) for n in range(max_n_fit)] #%% ------------------ Fourier Transform Fit Equations ------------------ def sinsquare_func(t, p): a, b, Tpi, phase = p return a + b * np.sin((np.pi * t / (2 * Tpi)) + phase)**2 def sinsquare_fit(x, y, y_err, p, lower_bound = None, upper_bound = None): a, b, Tpi, phase = p if lower_bound == None: lower_bound = [0, 0, Tpi/2, 0] if upper_bound == None: upper_bound = [1, 1, Tpi*2, np.pi*2] func_fit = lambda x, *p: sinsquare_func(x, p) popt, pcov = curve_fit(func_fit, x, y, p0 = p, sigma = y_err, absolute_sigma = True, bounds = (lower_bound, upper_bound)) return popt, pcov def sinsquare_decay_func(t, a, b, d, Tpi, phase): return a + b * np.exp(-d * t) * np.sin((np.pi * t / (2 * Tpi)) + phase)**2 def sinsquare_decay_inverted_func(t, a, b, d, Tpi, phase): return 1 - (a + b * np.exp(-d * t) * np.sin((np.pi * t / (2 * Tpi)) + phase)**2) def multi_sin_largeLD_func(t, p): res = np.zeros_like(t) # Store calculated excited state population max_n_fit = int(np.size(p) - 5) # Highest Fock state considered a = list(p[:max_n_fit]) # List of population for each Fock state a[-1] = 1 - np.sum(a[:len(a)]) # Ensure sum of population is 1 Omega_0 = p[max_n_fit] LD_param = p[max_n_fit + 1] gamma = p[max_n_fit + 2] # Decoherence Rate amp = p[max_n_fit + 3] # Amplitude factor offset = p[max_n_fit + 4] # Offset Omega = [Omega_0 * rabi_freq(i, 1, LD_param) for i in range(max_n_fit)] for i in range(max_n_fit): res = res + a[i] * np.cos(Omega[i] * t) * np.exp(-gamma * (i + 2)**(0.7) * t) # Calculate excited state population res = amp * (1.0 / 2 - res / 2.0) + offset return res def multi_sin_largeLD_fit(x, y, y_err, pop_guess, variables, lower_bound = None, upper_bound = None): max_n_fit = len(pop_guess) Omega_0, LD_param, gamma, amp, offset = variables if lower_bound == None: lower_bound = [0 for i in range(max_n_fit)] lower_bound.append(Omega_0 * 0.9) lower_bound.append(LD_param * 0.95) lower_bound.append(0.0) lower_bound.append(0.8) lower_bound.append(0.0) if upper_bound == None: upper_bound = [1 for i in range(max_n_fit)] upper_bound.append(Omega_0 * 1.1) upper_bound.append(LD_param * 1.05) upper_bound.append(1.0) upper_bound.append(0.98) upper_bound.append(0.1) p = list(pop_guess) + list(variables) func_fit = lambda x, *p: multi_sin_largeLD_func(x, p) popt, pcov = curve_fit(func_fit, x, y, p0 = p, sigma = y_err, absolute_sigma= True, bounds = (lower_bound, upper_bound)) if np.sum(popt[:max_n_fit]) > 1.0: #print("Sum of Fock State Population exceeds 1. Force highest Fock State to 0 population") popt[max_n_fit - 2] = 0 return popt, pcov def try_fit(x, y, y_err, max_n_fit, variables): Omega_0, LD_param, gamma, amp, offset = variables random_pop_guess = np.random.rand(max_n_fit) random_pop_guess = random_pop_guess/sum(random_pop_guess) popt, pcov = multi_sin_largeLD_fit(x, y, y_err, random_pop_guess, variables) new_pop_guess = popt[:11] lower_bound = [0 for i in range(max_n_fit)] lower_bound.append(Omega_0 * 0.9) lower_bound.append(LD_param * 0.95) lower_bound.append(0.0) lower_bound.append(0.0) lower_bound.append(0.0) upper_bound = [1 for i in range(max_n_fit)] upper_bound.append(Omega_0 * 1.1) upper_bound.append(LD_param * 1.05) upper_bound.append(1.0) upper_bound.append(1.0) upper_bound.append(1.0) popt, pcov = multi_sin_largeLD_fit(x, y, y_err, new_pop_guess, variables, lower_bound, upper_bound) return popt, pcov
from permutations import permutations from itertools import accumulate def iter2set(fn): def wrapper(*args): return set(fn(*args)) return wrapper def is_matched(expr): """ Credit to Alain T.: https://stackoverflow.com/questions/38833819/python-program-to-check-matching-of-simple-parentheses """ levels = list(accumulate((c == "(") - (c == ")") for c in expr)) return all(level >= 0 for level in levels) and levels[-1] == 0 @iter2set def balanced(n): ''' Given a positive number n, compute the set of all strings of length n, in any order, that only contain balanced brackets. For example: >>> balanced(6) {'((()))', '(()())', '(())()', '()(())', '()()()'} Note that, by definition, the only string of length 0 containing balanced brackets is the empty string. Params: n (int): The length of string we want Returns: (set of str): Each string in this set contains balanced brackets. In the event n is odd, this set is empty. Raises: ValueError: If n is negative ''' if n < 0: raise ValueError if n % 2 != 0: return string = "()" * int(n / 2) for perm in permutations(string[1:]): for i in range(len(string)): result = string[0:1] + perm[:i] + perm[i:] if is_matched(result): yield result
<?php namespace App\Services\Polls; use App\Models\Poll; class PollVotesService { public $poll; public function __construct($poll) { $this->poll = $poll; } /** * Add a vote to the poll. * * @param string $name The name of the voter. * @param array $selectedPollAnswers The selected poll answers. */ public function addVote(string $name, array $selectedPollAnswers): void { foreach ($selectedPollAnswers as $item) { $pollAnswer = Poll::find($this->poll->id)->pollAnswers()->find($item['poll_answer_id']); if (!$pollAnswer->max_votes > $pollAnswer->votes && !$pollAnswer->unlimited_votes) { return; } $pollAnswer->update([ 'votes' => $pollAnswer->votes + 1, ]); } $this->poll->pollVotes()->create([ 'name' => $name, 'votes' => json_encode($selectedPollAnswers), ]); } /** * Deletes a vote from the poll. * * @param int $voteId The ID of the vote to be deleted. */ public function deleteVote(int $voteId): void { $vote = $this->poll->pollVotes()->find($voteId); $selectedPollAnswers = json_decode($vote->votes, true); foreach ($selectedPollAnswers as $item) { $pollAnswer = Poll::find($this->poll->id)->pollAnswers()->find($item['poll_answer_id']); $pollAnswer->update([ 'votes' => $pollAnswer->votes - 1, ]); } $vote->delete(); } /** * Formats the votes for a given array of poll answers. * * @param mixed $array The array of poll answers. * @param string $formattedString The initial string to format the votes. * @param bool $useHTML Whether to use HTML formatting (default is true). * @return string The formatted votes. */ public function getFormattedVotes(mixed $array, string $formattedString, bool $useHTML = true): string { foreach ($array as $item) { $pollAnswer = $this->poll->pollAnswers()->find($item['poll_answer_id']); if ($pollAnswer->unlimited_votes) { $name = $pollAnswer->title; } else { $name = $pollAnswer->title.' ('.$pollAnswer->votes.'/'.$pollAnswer->max_votes.' '.__('sites/poll.votes').')'; } if ($item['custom_input'] == null) { $formattedString .= $name.($useHTML ? ' <br>' : '; '); continue; } $formattedString .= $name.' => '.$item['custom_input'].($useHTML ? ' <br>' : '; '); } return $formattedString; } }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>BookFreak</title> <!-- goole fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@100;400;900&family=Ubuntu&display=swap" rel="stylesheet"> <!-- css stylesheets from bootstrap --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <!-- css created stylesheet --> <link rel="stylesheet" href="css/styles.css"> <!-- font awesome linker --> <script defer src="https://use.fontawesome.com/releases/v5.0.7/js/all.js"></script> <!-- javascript-in bootstrap link --> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script> </head> <body> <section id="title"> <div class="container-fluid"> <nav class="navbar navbar-expand-lg navbar-dark "> <a class="navbar-brand" href="">BookFreak</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="#footer">Contact</a> </li> <li class="nav-item"> <a class="nav-link" href="#pricing">Pricing</a> </li> <li class="nav-item"> <a class="nav-link" href="#cta">Download</a> </li> </ul> </div> </nav> <div class="row"> <div class="col-lg-6"> <h1 class="big-heading">Find Books That You'll Like and start reading</h1> <button type="button" class="btn btn-dark btn-lg download-buttons"><span class="fab fa-apple"></span> Download</button> <button type="button" class="btn btn-outline-light btn-lg download-buttons"><span class="fab fa-google-play"></span> Download</button> </div> <div class="col-lg-6"> <img class="title-image" src="images/My project.png" alt="app-home-page"> </div> </div> </div> </section> <!-- Features --> <section id="features"> <div class="container-fluid"> <div class="row features-row "> <div class="col-lg-4 feature-text"> <i class="fas fa-check-circle fa-4x feature-i"></i> <h3 class="feature-title">Easy to use.</h3> <p class="features-p">Easy to find books that you will love in all formats.</p> </div> <div class="col-lg-4 feature-text"> <i class="fas fa-solid fa-bullseye fa-4x feature-i"></i> <h3 class="feature-title">Elite Clientele</h3> <p class="features-p">We have every edition of any given book you are looking for.</p> </div> <div class="col-lg-4 feature-text"> <i class="fas fa-solid fa-heart fa-4x feature-i"></i> <h3 class="feature-title">Fast & Flexible</h3> <p class="features-p">Fastest delivery.Read and return anytime during your subscription</p> </div> </div> </div> </section> <!-- Testimonials --> <section id="testimonials"> <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active container-fluid"> <h2 class="testimonial-text">No time to waste let's start reading.Finding books was never that easy before. </h2> <img class="testimonial-image" src="https://image.freepik.com/free-photo/handsome-man-reading-book_23-2147860525.jpg" alt="john-reading"> <em>John,New York</em> </div> <div class="carousel-item container-fluid"> <h2 class="testimonial-text">I always spent hours on finding books at reasonable price but now I have no worries.</h2> <img class="testimonial-image" src="images/lady-img.jpg" alt="lady-profile"> <em>Beverly, Illinois</em> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </section> <!-- Press --> <section id="press"> <img class="press-logo" src="images/tnw.png" alt="tnw-logo"> <img class="press-logo" src="images/bizinsider.png" alt="biz-insider-logo"> <img class="press-logo" src="images/mashable.png" alt="mashable-logo"> <img class="press-logo" src="images/techcrunch.png" alt="tc-logo"> </section> <!-- Pricing --> <section id="pricing"> <h2 class="testimonial-text">Plans for getting a subscription</h2> <p>Simple and affordable subscription plans for you</p> <div class="row"> <div class=" pricing-col col-lg-4 col-md-6"> <div class="card"> <div class="card-header"> <h3 class="feature-title">Silver</h3> </div> <div class="card-body"> <h2 class="price-text">$10/year</h2> <p>Get any 10 books</p> <p>Preview 10 books daily</p> <p>Unlimited App Usage</p> <button type="button" class="btn btn-block btn-lg btn-outline-dark">Sign Up</button> </div> </div> </div> <div class=" pricing-col col-lg-4 col-md-6"> <div class="card"> <div class="card-header"> <h3 class="feature-title">Gold</h3> </div> <div class="card-body"> <h2 class="price-text">$20/year</h2> <p>Get 30 books</p> <p>preview upto 50 books daily</p> <p>Unlimited App Usage</p> <button type="button" class="btn btn-lg btn-block btn-dark">Sign Up</button> </div> </div> </div> <div class="pricing-col col-lg-4 col-md-12"> <div class="card"> <div class="card-header"> <h3 class="feature-title">Platinum</h3> </div> <div class="card-body"> <h2 class="price-text">$30/year</h2> <p>Pirority Listing</p> <p>Get fastest delivery and upto 60 books</p> <p>Unlimited App Usage & preview unlimited books</p> <button type="button" class="btn btn-dark btn-block btn-lg">Sign Up</button> </div> </div> </div> </div> </section> <!-- Call to Action --> <section id="cta"> <div class="container-fluid"> <h2 class="last">Find the books that you love & join us today!</h2> <button type="button" class="btn btn-dark btn-lg download-buttons"><span class="fab fa-apple"></span> Download</button> <button type="button" class="btn btn-outline-light btn-lg download-buttons"><span class="fab fa-google-play"></span> Download</button> </div> </section> <!-- Footer --> <footer id="footer"> <div class="container-fluid"> <i class="fab fa-twitter i-sep"></i> <i class="fab fa-facebook-f i-sep"></i> <i class="fab fa-instagram i-sep"></i> <i class="fas fa-solid fa-envelope i-sep"></i> <p>© Copyright 2023 BookFreak</p> </div> </footer> </body> </html>
import discord from discord.ext import tasks from discord import app_commands from mcstatus import JavaServer import time from constants import discord_bot_token intents = discord.Intents.default() client = discord.Client(intents=intents) tree = app_commands.CommandTree(client) last_update_players = [] server_address = "numbereater.com" status_channel = 1179990041494294648 log_channel = 1179991971234848860 debug_channel = 1180938049480310804 async def send_error_message(error): await client.get_channel(debug_channel).send(f"Error: {str(error)} at time: {time.strftime('%H:%M:%S %d/%m/%Y')}") async def get_server_info(): while True: try: server = JavaServer.lookup(server_address) query = server.query() status = server.status() online_players = status.players.online # check to make sure the objects are the correct types check = (online_players, query.players.names) try: assert isinstance(check, tuple) assert isinstance(check[0], int) assert isinstance(check[1], list) except AssertionError as e: await send_error_message(e) continue return online_players, query.players.names except Exception as e: await send_error_message(e) return 0, [] # Function to update the client's status message async def update_client_status(): online_players, specific_players = await get_server_info() await client.change_presence( activity=discord.Game(name=f"{online_players} players online") ) async def player_log_logs(): global last_update_players _, specific_players = await get_server_info() # Find the strings in list1 that are not in list2 difference1 = [item for item in specific_players if item not in last_update_players] for player in difference1: await client.get_channel(log_channel).send( f"{player} has logged into the server!" ) # Find the strings in list2 that are not in list1 difference2 = [item for item in last_update_players if item not in specific_players] for player in difference2: await client.get_channel(log_channel).send( f"{player} has logged out of the server" ) last_update_players = specific_players async def update_online_message(): channel = client.get_channel(status_channel) online_players, specific_players = await get_server_info() specific_players = ", ".join(specific_players) message_content = f"The server has {online_players} players online\nThe server has the following players online: {specific_players}".strip() # send message to debug channel, uses current time and date await client.get_channel(debug_channel).send( f"Online players updated at {time.strftime('%H:%M:%S %d/%m/%Y')}" ) # Check if a previous message exists existing_message = None async for message in channel.history(limit=None): if message.author == client.user: existing_message = message break # If a previous message exists, update it; otherwise, send a new message if existing_message: # check if the existing message text is the same as the new message text if existing_message.content != message_content: # delete the existing message and send a new one await existing_message.delete() await channel.send(message_content) else: await channel.send(message_content) @tree.command( name="online-players", description="Gets the online players", ) # Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, # but note that it will take some time (up to an hour) to register the command if it's for all guilds. async def online_players(ctx): online_players, specific_players = await get_server_info() specific_players = ", ".join(specific_players) print(f"The server has {online_players} players online") print(f"The server has the following players online: {specific_players}") await ctx.response.send_message( f"The server has {online_players} players online\nThe server has the " f"following players online: {specific_players}" ) # Bot event: When the client is ready @client.event async def on_ready(): await tree.sync() print(f"Logged in as {client.user.name}") # Start a background task to update the status every minute update_client.start() # Schedule the update_client_status function to run every minute @tasks.loop(minutes=0.08) async def update_client(): await update_client_status() await update_online_message() await player_log_logs() # Start the client with your client token client.run(discord_bot_token)
// Global variables float ballX, ballY; float ballSpeedX = 6, ballSpeedY = 6; float paddleX, paddleSpeed = 10, paddleWidth = 100, paddleHeight = 20; boolean moveLeft = false, moveRight = false; boolean isPaused = false; String[] grid = { "OOOOOOOOOOOOOOOOOOOO", "OOOOOOOOOOOOOOOOOOOO", "OOOOOOOOOXXOOOOOOOOO", "OOOOOOOXXXXXXXOOOOOO", "OOOOOXXXXXXXXXXXOOOO", "OOOOXXXXXXXXXXXXXOOO", "OOOXXXXXXXXXXXXXXXOO", "OOXXXXXXXXXXXXXXXXXO", "OXXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXX", "OXXXXXXXXXXXXXXXXXXX", "OOXXXXXXXXXXXXXXXXXO", "OOOXXXXXXXXXXXXXXXOO", "OOOOXXXXXXXXXXXXXOOO", "OOOOOXXXXXXXXXXXOOOO", "OOOOOOOXXXXXXXOOOOOO", "OOOOOOOOOXXOOOOOOOOO", "OOOOOOOOOOOOOOOOOOOO", "OOOOOOOOOOOOOOOOOOOO" }; int rows = 20; // 20 rows int cols = 20; // 20 columns boolean[][] bricks = new boolean[rows][cols]; float brickWidth, brickHeight = 20; int score = 0; int lives = 3; int brickOffsetY = 50; // Offset for bricks to move them down boolean gameOver = false; // Game over state void setup() { size(1600, 1200); initializeGame(); } void draw() { if (!gameOver) { if (!isPaused) { moveBall(); } background(0); displayBall(); displayPaddle(); displayBricks(); displayLivesAndScore(); if (isPaused) { displayPauseScreen(); } } else { displayGameOver(); } } void initializeGame() { ballX = width / 2; ballY = height - paddleHeight - 20; paddleX = width / 2 - paddleWidth / 2; brickWidth = width / cols; ballSpeedX = 6; ballSpeedY = -6; gameOver = false; score = 0; lives = 3; initializeBricks(); } void initializeBricks() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { bricks[i][j] = (grid[i].charAt(j) == 'X'); } } } void moveBall() { ballX += ballSpeedX; ballY += ballSpeedY; // Boundary checking for the ball if (ballX < 0 || ballX > width) { ballSpeedX *= -1; // Bounce off left and right walls } if (ballY < 0) { ballSpeedY *= -1; // Bounce off the top wall } if (ballY > height) { lives--; // Decrement lives when the ball hits the bottom if (lives <= 0) { gameOver = true; // Set game over if no lives left return; // Exit the function to avoid resetting the ball position } // Reset ball position for the next life ballX = width / 2; ballY = height - paddleHeight - 20; ballSpeedY = -abs(ballSpeedY); // Ensure the ball starts moving upwards } // Paddle collision if (ballY + 10 >= height - paddleHeight && ballX >= paddleX && ballX <= paddleX + paddleWidth) { ballSpeedY *= -1; // Bounce off the paddle } // Brick collision for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (bricks[i][j]) { float brickX = j * brickWidth; float brickY = i * brickHeight + brickOffsetY; if (ballX > brickX && ballX < brickX + brickWidth && ballY > brickY && ballY < brickY + brickHeight) { bricks[i][j] = false; // Destroy the brick on collision ballSpeedY *= -1; // Reverse the ball's vertical direction score += 10; // Increase the score for each brick destroyed } } } } } void displayBall() { fill(255); ellipse(ballX, ballY, 20, 20); } void displayPaddle() { // Update paddle position based on key presses if (moveLeft && paddleX > 0) { paddleX -= paddleSpeed; } if (moveRight && paddleX < width - paddleWidth) { paddleX += paddleSpeed; } rect(paddleX, height - paddleHeight, paddleWidth, paddleHeight); } void keyPressed() { if (key == 'p' || key == 'P') { isPaused = !isPaused; // Toggle pause state } if (!isPaused) { // Existing key control code if (key == CODED) { if (keyCode == LEFT) { moveLeft = true; } else if (keyCode == RIGHT) { moveRight = true; } } if (gameOver && key == 'r') { initializeGame(); } } } void keyReleased() { if (key == CODED) { if (keyCode == LEFT) { moveLeft = false; } else if (keyCode == RIGHT) { moveRight = false; } } } void displayBricks() { fill(255, 0, 0); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (bricks[i][j]) { rect(j * brickWidth, i * brickHeight + brickOffsetY, brickWidth, brickHeight); } } } } void displayLivesAndScore() { textSize(20); fill(255); text("Lives: " + lives, 20, 30); text("Score: " + score, width - 120, 30); } void displayGameOver() { background(0); textSize(40); fill(255, 0, 0); text("GAME OVER", width / 2 - 100, height / 2); textSize(20); text("Score: " + score, width / 2 - 50, height / 2 + 40); text("Press 'R' to Restart", width / 2 - 75, height / 2 + 70); } void displayPauseScreen() { textSize(40); fill(255, 255, 255); text("PAUSED", width / 2 - 70, height / 2); }
import { ApiProperty } from '@nestjs/swagger'; export class RegisterRequestDto { @ApiProperty({ required: true, type: String, nullable: false, description: 'fullName', example: 'myfullName', }) fullName: string; @ApiProperty({ required: true, type: String, nullable: false, description: 'username', example: 'myUserName', }) username: string; @ApiProperty({ required: true, type: String, nullable: false, description: 'password', example: 'myPassword', }) password: string; @ApiProperty({ required: true, type: String, nullable: false, description: 'email', example: 'myEmail', }) email: string; @ApiProperty({ required: true, type: String, nullable: false, description: 'mobileNumber', example: 'myMobileNumber', }) mobileNumber: string; } export class LoginRequestDto { @ApiProperty({ required: true, type: String, nullable: false, description: 'username', example: 'myUserName', }) username: string; @ApiProperty({ required: true, type: String, nullable: false, description: 'password', example: 'myPassword', }) password: string; } export class LoginResponseDto { @ApiProperty({ description: 'token', type: String, nullable: true, }) token: string | null; }
import "../styles/App.scss"; import { useEffect, useState, Suspense, lazy } from "react"; import { Route, Switch} from 'react-router-dom'; import axios from "axios"; import Fallback from './Fallback'; import Champions from "./Champions"; import InidividualChampInfo from './IndividualChampInfo'; import About from './About'; import Signup from "./auth/Signup"; import {AuthProvider} from '../contexts/AuthContext' import LogIn from './auth/LogIn'; import Profile from "./Profile"; const MatchHistory = lazy(()=> import ('./MatchHistory')) const SearchBar = lazy(()=> import ('./SearchBar')) const HomePage = lazy(()=> import ('./HomePage')) const App = () => { require('dotenv').config() const [champObj, setChampObj] = useState<object>({}); useEffect(()=>{ axios({ method:'GET', url: 'https://ddragon.leagueoflegends.com/cdn/11.4.1/data/en_US/champion.json', responseType: 'json', }) .then((res)=> { setChampObj(res.data.data); }) },[]) return ( <div className="App"> <div className="flexContainer"> <AuthProvider> <Suspense fallback={<Fallback/>}> <SearchBar/> <Switch> <Route exact path={`/match/:userName`} render={()=> <MatchHistory/> } /> <Route exact path='/' render={()=> <HomePage/>}/> <Route exact path='/about' render={()=><About/>}/> <Route exact path='/champions' render={()=><Champions champObj={champObj}/>}/> <Route path='/champions/:champName' render={()=><InidividualChampInfo/>}/> <Route path='/signup' render={()=><Signup/>}/> <Route path='/login' render={()=><LogIn/>}/> <Route path='/profile' render={()=><Profile/>}/> </Switch> </Suspense> </AuthProvider> </div> </div> ); } export default App;
// SPDX-License-Identifier: MIT // Author: Emmanouil Kalyvas pragma solidity ^0.8.0; import "./Tools.sol"; contract Parameters { Tools _tools; address _owner; uint256 public M; //Minimum minting rate uint256 public B; //Maximum burning rate uint256 public C; //Missing energy recover rate uint256 public H; //Hours to keep consumsion session active uint256 public F; //Storage provider fee (amount of ent for storage provider cut) string[] parameterStrings; constructor( Tools tools){ parameterStrings = ['M','B','C','H','F']; //Default values _tools = tools; _owner = msg.sender; M = 50 * _tools.multiplier() / 100; //0.5 ENT B = 50 * _tools.multiplier() / 100; //0.5 ENT C = 5 * _tools.multiplier() / 100; //5% H = 2 hours; F = 20 * _tools.multiplier() / 100; //20% } function isValidParam(string memory param) view public returns(bool){ uint length = parameterStrings.length; for(uint i = 0; i < length; i++){ if (_tools.equal(parameterStrings[i], param)) return true; } return false; } function setParameter(string memory param,uint256 value) public { require(_owner == msg.sender,"You are not allowed to change contract parameters"); if (_tools.equal(param, parameterStrings[0])){ //Set M setM(value); } else if (_tools.equal(param, parameterStrings[1])){ //Set B setB(value); } else if (_tools.equal(param, parameterStrings[2])){ //Set C setC(value); } else if (_tools.equal(param, parameterStrings[3])){ //Set H setH(value); } else if (_tools.equal(param, parameterStrings[4])){ //Set F setF(value); } } function setM(uint256 m) public { require(_owner == msg.sender,"You are not allowed to change contract parameters"); M = m; } function setB(uint256 b) public { require(_owner == msg.sender,"You are not allowed to change contract parameters"); B = b; } function setC(uint256 c) public { require(_owner == msg.sender,"You are not allowed to change contract parameters"); C = c; } function setH(uint256 h) public{ require(_owner == msg.sender,"You are not allowed to change contract parameters"); H = h * 3600; } function setF(uint256 f) public{ require(_owner == msg.sender,"You are not allowed to change contract parameters"); F = f; } }
import React from 'react'; import { Controller, useForm } from 'react-hook-form'; import { Keyboard } from 'react-native'; import { useMutationLogin } from 'common'; import { Button, Input, Text, View } from 'tamagui'; import * as z from 'zod'; const schema = z.object({ email: z.string().email(), password: z.string().min(6), }); type FormData = z.infer<typeof schema>; const LoginScreen = () => { const {loginMutation: { mutateAsync, isLoading }} = useMutationLogin(); const { control, handleSubmit, formState } = useForm<FormData>({ mode: 'onChange', resolver: async (values) => { try { schema.parse(values); return { values, errors: {} }; } catch (error) { const formErrors = (error as z.ZodError).formErrors.fieldErrors; return { values: {}, errors: formErrors }; } }, }); const onSubmit = ({ email, password }: FormData) => { Keyboard.dismiss() mutateAsync({ email: email.toLowerCase(), password }) }; return ( <View flex={1} justifyContent='center' space={4}> <Controller control={control} name="email" defaultValue="" disabled={isLoading} render={({ field: { onChange, onBlur, value } }) => ( <Input placeholder="Enter your email" onBlur={onBlur} onChangeText={onChange} value={value.toLowerCase()} /> )} /> {formState.errors.email && ( <Text testID='email-error-message' color='red'>{formState.errors.email}</Text> )} <Controller control={control} name="password" defaultValue="" disabled={isLoading} render={({ field: { onChange, onBlur, value } }) => ( <Input placeholder="Enter your password" onBlur={onBlur} onChangeText={onChange} value={value} secureTextEntry /> )} /> {formState.errors.password && ( <Text testID='password-error-message' color='red'>{formState.errors.password}</Text> )} <Button testID='login-button' onPress={() => handleSubmit(onSubmit)} disabled={!formState.isValid} backgroundColor={ formState.isValid ? 'purple' : 'gray'}> Login </Button> </View> ); } export default LoginScreen;
// ****************************************************************************************** // * // * AR MODELING (Burg and Yule-Walker method are implemented) // * // * // * Main features : // * - Prediction : calculate future datas based on past data, past volume and past low/high // * - Spectral analysis : compute sharp and clean spectrum of the data and plot it in Decibels // * - Find up to 10 or more dominant cycles from the data // * // * // * Native AFL for maximum speed without needed external dll // * Many criterions for auto order selection : FPE, AIC, MDL, CAT, CIC ... // * + 2 optionnal VBS Scripts (one for experimentation about rounding, the other for PolyFit detrending) // * // * // * Use and modify it freely. v0.04, tomy_frenchy, tom_borgo@hotmail.com, mich. 11/2006. // * Thanks to Fred for PolyFit function AFL and Gaussian Elimination VBS // * // ****************************************************************************************** // ****************************************************************************************** // * // * DESCRITION // * // * AR_Prediction.afl compute AR (Auto-Regressive) model from the data. // * Burg method is called too Maximum Likelihood, Maximum Entropy Method (MEM), // * Maximum Entropy Spectral Analysis (MESA). All are the same. // * Yule-Walker method is based on the Autocorellation of the data and by minimising // * the Least Square error between model and data. // * // * Purpose of AR modeling are to obtain a simple model to describe data. // * From this model we can for two main application : // * - Calculate future data (make prediction). It is possible because the model is // * described by a mathematical expression. // * - Make spectral analysis to exctract main cycle from the data. Spectral Analysis is // * more powerfull this way than classic FFT for short horizon data and for spectrum wich // * have sharp frequency (cyclic signal) // * // * // * MAIN FUNCTION : // * 1- AR_Burg: to compute AR Burg model // * 2- AR_YuleWalker: to compute AR Yule Walker model // * 3- AR_Predict: to predict future data based on the computed AR model // * 4- AR_Freq: to compute the spectrum from the computed AR model // * 5- AR_Sin: to find main frequency in the computed spectrum (dominant cycles from the data) // * // * // * ALL THE CODE IS COMMENTED SO YOU CAN FIND PARAMETERS FOR THE FUNCTION IN THE DEMO SECTION AT THE END OF THE FILE. // * All the source is commented, so you can learn a lot from it. // * There are many sources paper on the net about the subject. // * // * // ****************************************************************************************** // ****************************************************************************************** // * // * PARAMETERS // * // * // * // * Main parameters for AR modeling : // * // * // * Price field = Data to predict // * AR Model = Burg model or Yule-Yalker model // * Length to look back = Horizon used on the data to compute the model // * Order AR = Order wanted for the AR model // * Number of bar to predict = Length prediction // * Auto AR order = Find automatically the best order // * Auto AR criterion = Criterion to use for Auto AR order // * FPE: Final Prediction Error (classic old one) // * AIC: Akaine Information Criterion (classic less old one) // * MDL: Minimum Description Length // * CAT: Criterion Autoregressive Transfer // * CIC: Combined Information Criterion (good one) // * Mixed: An upper averaging from all those criterion (best, recommended) // * Burg: Hamming Window = If Hamming Window is applyed during model computation (only Burg model) // * Burg: Double Precision = If Double Precision is used to compute the model (only Burg model) // * Y-W: Biased = If Autocorrelation estimator should be biased (Yes) or not-biased (No) (only Yule-Walker model) // * // * // * // * Pre-Processing begore modeling AR model : // * // * // * Intraday EOD GAP Filter = For intraday data, first data of the day is same than last data of yesterday day // * // * // * Periods T3 = Periods for Tillson's T3 filter (high order low pass denoiser) // * Slope T3 = Slope for Tillson's T3 filter (0.7 to 0.83 for usual value) (Higher value mean more dynamic filter) // * // * // * Detrending method = Method to use to detrend the data // * None: no detrending is done // * Log10: log10(data) detrending is done (usefull for trend wich increase with time) // * Derivation: differentiation one by one from the data (prefered method because is sure to kill the linear trend) // * Linear Regression: substract linear regression from the data (good method too if fitting is ok) // * PolyFit: substract n-th order polynomial regression from the data (order 3 can give nice result) // * PolyFit Order = Order for the PolyFit detrending method (usefull just if you choose this method of detrending) // * // * // * Center data = Remove the bias in the data (substract the mean). // * AR modeling NEED NOT BIASED data, so this sould be always left on "Yes". // * // * // * Normalize = Scale data between [-1;1] (usefull for better computation because less rounding error) // * // * // * Volume HL weight on data = Multiply data by a factor computed from volume and high/low information from the data // * !!! This is experimental feature !!! // * Strength Volume = Strength of volume weighting // * Strength Fractal = Strength of High/Low (Fractal) weighting // * Periods Fract (even) = Periods to compute the fractal factor (an even period is needed) // * Scale Final Weights = Final dynamic of the weights (high value increase difference between low weight and high weight) // * Translate Final Weights = Final strength of the weights (high value bring all the weights near their maximum) // * Scale / Translate is based on Inverse Fisher Transform and work like a limiter/compressor of the weights // * // * // * Time weight on data = Apply time windowing on data so more recent data are more weighted than old data to compute the AR model // * Weighting Time Window = Choose the strength of the weights // * Log: natural logarithm, small time weigthing on the data // * Ramp: a ramp, linear time weigthing on the data // * Exp: exponential, strong time weigthing on the data // * // * // * // * Post-Processing before plotting predicted data : // * // * Retrending method = Choose if trend should be added back to predicted data // * Trend is automatically added back for "Log10" and "Derivation" methods, // * so data stay in good scale // * // * Color PolyFit = Color to plot the curve from "PolyFit" detrending method // * Color PolyFit = Color to plot the line from "Linear Regression" detrending method // * // * // ****************************************************************************************** EnableScript("VBScript"); <% ' Called by ARG_Burg AFL funct. to compute Ki in Double Precision function Compute_KI(f, b, W, i, LongBar) n = LongBar - 1 for j = i to n Num = Num + cDBL(W(j))*( cDBL(f(j))*cDBL(b(j-1)) ) Den = Den + cDBL(W(j))*( cDBL(f(j))^2 + cDBL(b(j-1))^2 ) next KI = 2*Num/Den Compute_KI = KI end function function Gaussian_Elimination (GE_Order, GE_N, GE_SumXn, GE_SumYXn) Dim b(10, 10) Dim w(10) Dim Coeff(10) for i = 1 To 10 Coeff(i) = 0 next n = GE_Order + 1 for i = 1 to n for j = 1 to n if i = 1 AND j = 1 then b(i, j) = cDBL(GE_N) else b(i, j) = cDbl(GE_SumXn(i + j - 2)) end if next w(i) = cDbl(GE_SumYXn(i)) next n1 = n - 1 for i = 1 to n1 big = cDbl(abs(b(i, i))) q = i i1 = i + 1 for j = i1 to n ab = cDbl(abs(b(j, i))) if (ab >= big) then big = ab q = j end if next if (big <> 0.0) then if (q <> i) then for j = 1 to n Temp = cDbl(b(q, j)) b(q, j) = b(i, j) b(i, j) = Temp next Temp = w(i) w(i) = w(q) w(q) = Temp end if end if for j = i1 to n t = cDbl(b(j, i) / b(i, i)) for k = i1 to n b(j, k) = b(j, k) - t * b(i, k) next w(j) = w(j) - t * w(i) next next if (b(n, n) <> 0.0) then Coeff(n) = w(n) / b(n, n) i = n - 1 while i > 0 SumY = cDbl(0) i1 = i + 1 for j = i1 to n SumY = SumY + b(i, j) * Coeff(j) next Coeff(i) = (w(i) - SumY) / b(i, i) i = i - 1 wend Gaussian_Elimination = Coeff end if end function %> function PolyFit(GE_Y, GE_BegBar, GE_EndBar, GE_Order, GE_ExtraB, GE_ExtraF) { BI = BarIndex(); GE_N = GE_EndBar - GE_BegBar + 1; GE_XBegin = -(GE_N - 1) / 2; GE_X = IIf(BI < GE_BegBar, 0, IIf(BI > GE_EndBar, 0, (GE_XBegin + BI - GE_BegBar))); GE_X_Max = LastValue(Highest(GE_X)); GE_X = GE_X / GE_X_Max; X1 = GE_X; GE_Y = IIf(BI < GE_BegBar, 0, IIf(BI > GE_EndBar, 0, GE_Y)); GE_SumXn = Cum(0); GE_SumXn[1] = LastValue(Cum(GE_X)); GE_X2 = GE_X * GE_X; GE_SumXn[2] = LastValue(Cum(GE_X2)); GE_X3 = GE_X * GE_X2; GE_SumXn[3] = LastValue(Cum(GE_X3)); GE_X4 = GE_X * GE_X3; GE_SumXn[4] = LastValue(Cum(GE_X4)); GE_X5 = GE_X * GE_X4; GE_SumXn[5] = LastValue(Cum(GE_X5)); GE_X6 = GE_X * GE_X5; GE_SumXn[6] = LastValue(Cum(GE_X6)); GE_X7 = GE_X * GE_X6; GE_SumXn[7] = LastValue(Cum(GE_X7)); GE_X8 = GE_X * GE_X7; GE_SumXn[8] = LastValue(Cum(GE_X8)); GE_X9 = GE_X * GE_X8; GE_SumXn[9] = LastValue(Cum(GE_X9)); GE_X10 = GE_X * GE_X9; GE_SumXn[10] = LastValue(Cum(GE_X10)); GE_X11 = GE_X * GE_X10; GE_SumXn[11] = LastValue(Cum(GE_X11)); GE_X12 = GE_X * GE_X11; GE_SumXn[12] = LastValue(Cum(GE_X12)); GE_X13 = GE_X * GE_X12; GE_SumXn[13] = LastValue(Cum(GE_X13)); GE_X14 = GE_X * GE_X13; GE_SumXn[14] = LastValue(Cum(GE_X14)); GE_X15 = GE_X * GE_X14; GE_SumXn[15] = LastValue(Cum(GE_X15)); GE_X16 = GE_X * GE_X15; GE_SumXn[16] = LastValue(Cum(GE_X16)); GE_SumYXn = Cum(0); GE_SumYXn[1] = LastValue(Cum(GE_Y)); GE_YX = GE_Y * GE_X; GE_SumYXn[2] = LastValue(Cum(GE_YX)); GE_YX2 = GE_YX * GE_X; GE_SumYXn[3] = LastValue(Cum(GE_YX2)); GE_YX3 = GE_YX2 * GE_X; GE_SumYXn[4] = LastValue(Cum(GE_YX3)); GE_YX4 = GE_YX3 * GE_X; GE_SumYXn[5] = LastValue(Cum(GE_YX4)); GE_YX5 = GE_YX4 * GE_X; GE_SumYXn[6] = LastValue(Cum(GE_YX5)); GE_YX6 = GE_YX5 * GE_X; GE_SumYXn[7] = LastValue(Cum(GE_YX6)); GE_YX7 = GE_YX6 * GE_X; GE_SumYXn[8] = LastValue(Cum(GE_YX7)); GE_YX8 = GE_YX7 * GE_X; GE_SumYXn[9] = LastValue(Cum(GE_YX8)); GE_Coeff = Cum(0); GE_VBS = GetScriptObject(); GE_Coeff = GE_VBS.Gaussian_Elimination(GE_Order, GE_N, GE_SumXn, GE_SumYXn); for (i = 1; i <= GE_Order + 1; i++) printf(NumToStr(i, 1.0) + " = " + NumToStr(GE_Coeff[i], 1.9) + "\n"); GE_X = IIf(BI < GE_BegBar - GE_ExtraB - GE_ExtraF, 0, IIf(BI > GE_EndBar, 0, (GE_XBegin + BI - GE_BegBar + GE_ExtraF) / GE_X_Max)); GE_X2 = GE_X * GE_X; GE_X3 = GE_X2 * GE_X; GE_X4 = GE_X3 * GE_X; GE_X5 = GE_X4 * GE_X; GE_X6 = GE_X5 * GE_X; GE_X7 = GE_X6 * GE_X; GE_X8 = GE_X7 * GE_X; GE_X9 = GE_X8 * GE_X; GE_X10 = GE_X9 * GE_X; GE_X11 = GE_X10 * GE_X; GE_X12 = GE_X11 * GE_X; GE_X13 = GE_X12 * GE_X; GE_X14 = GE_X13 * GE_X; GE_X15 = GE_X14 * GE_X; GE_X16 = GE_X15 * GE_X; GE_Yn = IIf(BI < GE_BegBar - GE_ExtraB - GE_ExtraF, -1e10, IIf(BI > GE_EndBar, -1e10, GE_Coeff[1] + GE_Coeff[2] * GE_X + GE_Coeff[3] * GE_X2 + GE_Coeff[4] * GE_X3 + GE_Coeff[5] * GE_X4 + GE_Coeff[6] * GE_X5 + GE_Coeff[7] * GE_X6 + GE_Coeff[8] * GE_X7 + GE_Coeff[9] * GE_X8)); return GE_Yn; } function Time_weighting(data, window, BegBar, EndBar) { BI = BarIndex(); if (window == "Log") alphatime = log(Cum(1)); if (window == "Ramp") alphatime = Cum(1); if (window == "Exp") alphatime = exp(Cum(0.01)); alphatime = Ref(alphatime, -BegBar); alphatime = alphatime - alphatime[BegBar]; alphatime = alphatime / alphatime[EndBar]; alphatime = IIf(BI < BegBar, 0, IIf(BI > EndBar, 0, alphatime)); return alphatime*data; } function Volume_HighLow_weighting(data, coef_vol, coefdim, period, scale, translation) { // Coefficient Volume highvol = V; highvol = HHV(Median(V, 5), 5000); nbr_vol = coef_vol*highvol/(1 - coef_vol) + 1; alpha_vol = V/nbr_vol; alpha_vol = IIf(alpha_vol > 0.99, 0.99, alpha_vol); alpha_vol = IIf(alpha_vol < 0.01, 0.01, alpha_vol); // Coefficient High/Low (Adpated from FRAMA from John Ehlers) coefdim = coefdim * 2 - 0.01; N = 2*floor(period/2); delta1 = HHV(Ref(High, -N/2), N/2) - LLV(Ref(Low, -N/2), N/2); delta2 = HHV(High, N/2) - LLV(Low, N/2); delta = HHV(High, N) - LLV(Low, N); Dimen = log((delta1 + delta2)/delta)/log(2); alphadim = exp(-coefdim*Dimen); alphadimnorm = Min(Max(alphadim, 0.01), 0.99); // Mix Volume and High/Low, and scale them with Inverse Fisher Tansform alpha = alphadimnorm + alpha_vol; data_av = scale*(alpha - translation); alpha = (exp(2*data_av) - 1)/(exp(2*data_av) + 1); alpha = Min(Max(alpha,0.01),0.99); return alpha*data; } function Filter_GAP_EOD(data) { time_frame = Minute() - Ref(Minute(), -1); time_frame = IIf(time_frame < 0, time_frame + 60, time_frame); time_frame = time_frame[1]; day_begin = 152900 + 100*time_frame; day_end = 215900; delta = 0; timequote = TimeNum(); for (i = 1; i < BarCount; i++) { if (timequote[i] == Day_begin) delta = data[i] - data[i-1]; data[i] = data[i] - delta; } return data; } function T3(data, periods, slope) { // High Order Low-Pass filter e1 = EMA(data, periods); e2 = EMA(e1, periods); e3 = EMA(e2, periods); e4 = EMA(e3, periods); e5 = EMA(e4, periods); e6 = EMA(e5, periods); c1 = -slope*slope*slope; c2 = 3*slope*slope + 3*slope*slope*slope; c3 = -6*slope*slope - 3*slope - 3*slope*slope*slope; c4 = 1 + 3*slope+slope*slope*slope + 3*slope*slope; result = c1*e6 + c2*e5 + c3*e4 + c4*e3; return result; } function f_centeredT3(data, periods, slope) { // Centered T3 Moving Average slide = floor(periods/2); centeredT3 = data; centeredT3 = Ref(T3(data,periods,slope),slide); centeredT3 = IIf( IsNan(centeredT3) OR !IsFinite(centeredT3) OR IsNull(centeredT3), data, centeredT3); return centeredT3; } function f_detrend(data, BegBar, EndBar, ExtraF, method_detrend, PF_order) { // Detrend data BI = BarIndex(); LongBar = EndBar - BegBar + 1 ; detrended[0] = 0; if (method_detrend == "Log10") detrended = log10(data); if (method_detrend == "Derivation") detrended = data - Ref(data, -1); if (method_detrend == "Linear Regression") { x = Cum(1); x = Ref(x,-1); x[0] = 0; x = Ref(x, -BegBar); a = LinRegSlope(data, LongBar); a = a[EndBar]; b = LinRegIntercept(data, LongBar); b = b[EndBar]; y = a*x + b; global detrending_parameters; detrending_parameters = y; y = IIf(BI < BegBar, -1e10, IIf(BI > EndBar + ExtraF, -1e10, y)); Plot( y, "Linear Regression", ParamColor( "Color Linear Regression", colorCycle ), ParamStyle("Style") ); detrended = data - y; } if (method_detrend == "PolyFit") { Yn = PolyFit(data, BegBar, EndBar, PF_order, 0, ExtraF); Yn = Ref(Yn, -ExtraF); global detrending_parameters; detrending_parameters = Yn; Yn = IIf(BI < BegBar, -1e10, IIf(BI > EndBar + ExtraF, -1e10, Yn)); Plot( Yn, "PolyFit", ParamColor( "Color PolyFit", colorCycle ), ParamStyle("Style") ); detrended = data - Yn; } return detrended; } function f_retrend(data, Value_BegBar, BegBar, EndBar, method_detrend) { BI = BarIndex(); retrended = -1e10; if (method_detrend == "Log10") { retrended = 10^(data); } if (method_detrend == "Derivation") { retrended[BegBar] = Value_BegBar; for (i = BegBar + 1; i < EndBar + 1; i++) retrended[i] = data[i] + retrended[i-1]; } if (method_detrend == "Linear Regression") { retrended = data + detrending_parameters; } if (method_detrend == "PolyFit") { retrended = data + detrending_parameters; } return retrended; } function durbinlevison(Autocorr, OrderAR, LongBar, AutoOrder, AutoOrder_Criterion) { // for Yule Walker method only // Initialization AR_Coeff = 0; alpha[1] = noise_variance[1] = Autocorr[0]; beta[1] = Autocorr[1]; k[1] = Autocorr[1] / Autocorr[0]; AR_Coeff[1] = k[1]; // Initialize recursive criterion for order AR selection if (AutoOrder == 1) { FPE = AIC = MDL = CAT = CIC = -1e10; CAT_factor = 0; CIC_product = (1 + 1/(LongBar + 1))/(1 - 1/(LongBar + 1)); CIC_add = 1 + 1/(LongBar + 1); } // Main iterative loop for (n = 1; n < OrderAR; n++) { // Compute last coefficient for (i = 1; i < n + 1; i++) AR_Coeff_inv[n+1-i] = AR_Coeff[i]; temp = 0; for (i = 1; i < n + 1; i++) temp = temp + Autocorr[i] * AR_Coeff_inv[i]; beta[n+1] = Autocorr[n+1] - temp; alpha[n+1] = alpha[n] * (1 - k[n]*k[n]); k[n+1] = beta[n+1] / alpha[n+1]; AR_Coeff[n+1] = k[n+1]; // Compute other coefficients by recursion for (i = 1; i < n + 1; i++) New_AR_Coeff[i] = AR_Coeff[i] - k[n+1] * AR_Coeff_inv[i]; New_AR_Coeff[n+1] = AR_Coeff[n+1]; // Update AR_Coeff = New_AR_Coeff; noise_variance[n+1] = alpha[n+1]; if (AutoOrder == 1) { i = n + 1; // Compute criterions for order AR selection FPE[i] = noise_variance[i]*(LongBar + (i + 1))/(LongBar - (i + 1)); // Final Prediction Error AIC[i] = log(noise_variance[i])+2*i/LongBar; // Akaine Information Criterion MDL[i] = log(noise_variance[i]) + i*log(LongBar)/LongBar; // Minimum Description Length CAT_factor = CAT_factor + (LongBar - i)/(LongBar*noise_variance[i]); CAT[i] = CAT_factor/LongBar - (LongBar - i)/(LongBar*noise_variance[i]); // Criterion Autoregressive Transfer CIC_product = CIC_product * (1 + 1/(LongBar + 1 - i))/(1 - 1/(LongBar + 1 - i)); CIC_add = CIC_add + (1 + 1/(LongBar + 1 - i)); CIC[i] = log(noise_variance[i]) + Max(CIC_product - 1,3*CIC_add); // Combined Information Criterion } // End main iterative loop } if (AutoOrder == 1) { // Clean data because of rounding number for very low or very high value, and discard small changes FPE = IIf(abs(LinRegSlope(FPE, 2)/FPE[1]) < 0.005 OR abs(FPE) > 1e7, -1e10, FPE); AIC = IIf(log(abs(LinRegSlope(AIC, 2)/AIC[1])) < 0.005 OR abs(AIC) > 1e7, -1e10, AIC); MDL = IIf(log(abs(LinRegSlope(MDL, 2)/MDL[1])) < 0.005 OR abs(MDL) > 1e7, -1e10, MDL); CAT = IIf(log(abs(LinRegSlope(CAT, 2)/CAT[1])) < 0.005 OR abs(CAT) > 1e7, -1e10, CAT); CIC = IIf(abs(LinRegSlope(CIC, 2)/CIC[1]) < 0.005 OR abs(CIC) > 1e7, -1e10, CIC); // Find lower value Mixed_Order = 0; FPE_Order = Mixed_Order[1] = LastValue(Max(ValueWhen(FPE == Lowest(FPE) AND IsFinite(FPE), Cum(1), 1) - 1, 2)); AIC_Order = Mixed_Order[2] = LastValue(Max(ValueWhen(AIC == Lowest(AIC) AND IsFinite(AIC), Cum(1), 1) - 1, 2)); MDL_Order = Mixed_Order[3] = LastValue(Max(ValueWhen(MDL == Lowest(MDL) AND IsFinite(MDL), Cum(1), 1) - 1, 2)); CAT_Order = Mixed_Order[4] = LastValue(Max(ValueWhen(CAT == Lowest(CAT) AND IsFinite(CAT), Cum(1), 1) - 1, 2)); CIC_Order = Mixed_Order[5] = LastValue(Max(ValueWhen(CIC == Lowest(CIC) AND IsFinite(CIC), Cum(1), 1) - 1, 2)); // Mixed array is an averaging from all criterions taking in consideration order choose by criterions is often too low Mixed_Order_array = Median(Mixed_Order, 5); Mixed_Order = 2*ceil(Mixed_Order_array[5]); // Print informations about best order for each criterion printf("\nFPE Order : "+FPE_Order); printf("\nAIC Order : "+AIC_Order); printf("\nMDL Order : "+MDL_Order); printf("\nCAT Order : "+CAT_Order); printf("\nCIC Order : "+CIC_Order); printf("\n*** Mixed Order *** : "+Mixed_Order); // Mark best order in a[1] wich is returned at the end of the function if (AutoOrder_Criterion == "FPE") AR_Coeff[1] = FPE_Order; if (AutoOrder_Criterion == "AIC") AR_Coeff[1] = AIC_Order; if (AutoOrder_Criterion == "MDL") AR_Coeff[1] = MDL_Order; if (AutoOrder_Criterion == "CAT") AR_Coeff[1] = CAT_Order; if (AutoOrder_Criterion == "CIC (good)") AR_Coeff[1] = CIC_Order; if (AutoOrder_Criterion == "Mixed (best)") AR_Coeff[1] = Mixed_Order; } AR_Coeff[0] = alpha[OrderAR]; // noise variance estimator return AR_Coeff; } function AR_YuleWalker(data, BegBar, EndBar, OrderAR, Biased, AutoOrder, AutoOrder_Criterion) { BI = BarIndex(); Data_all = data; Data = IIf(BI < BegBar, 0, IIf(BI > EndBar, 0, Data)); LongBar = EndBar - BegBar + 1; // Window Hamming to make it more stable for non-biased estimator if (Biased == 0) { pi = atan(1) * 4; x = Cum(1); x = Ref(x,-1); x[0] = 0; W = 0.54 - 0.46*cos(2*pi*x/(LongBar-1)); Wi = Ref(W,-BegBar); data = Wi*data; } // Compute Autocorrelation function for (i = 0; i < OrderAR + 1; i++) { temp = 0; for (j = BegBar; j < EndBar + 1 - i; j++) { temp = temp + data[j]*data[j+i]; } if (Biased == 1) Autocorr[i]=(1/(LongBar))*temp; // biased estomator (best, model is always stable), small variance but less power if (Biased == 0) Autocorr[i]=(1/(LongBar-i))*temp; // non-biased estimator (model can be unstable), large variance } Autocorr=Autocorr/Autocorr[0]; // normalization (don't change result, to be less exposed to bad rounding) // Compute AR parameters with Durbin-Levison recursive algorithm for symmetric Toeplitz matrix (Hermitian matrix) AR_Coeff = durbinlevison(Autocorr, OrderAR, LongBar, AutoOrder, AutoOrder_Criterion); // End AR_Coeff = IIf(BI > OrderAR, -1e10, AR_Coeff); // usefull for AR_Pred and AR_Freq return AR_Coeff; // AR_Coeff[0] is noise variance estimator } function AR_Burg(data, BegBar, EndBar, OrderAR, Window, AutoOrder, AutoOrder_Criterion, DoublePrecision) { BI = BarIndex(); LongBar = EndBar - BegBar + 1; // LongBar = the number of data // Initialize recursive criterion for order AR selection if (AutoOrder == 1) { FPE = AIC = MDL = CAT = CIC = -1e10; CAT_factor = 0; CIC_product = (1 + 1/(LongBar + 1))/(1 - 1/(LongBar + 1)); CIC_add = 1 + 1/(LongBar + 1); } // Hamming window if selected if (Window == 1) { pi = atan(1) * 4; x = Cum(1); x = Ref(x,-1); x[0] = 0; W = 0.54 - 0.46*cos(2*pi*x/(LongBar-1)); } // Create data, forward and backward coefficients arrays y = Ref(data,BegBar); // y[0:LongBar-1] are the data y = IIf(BI < LongBar, y, 0); // to be sure not to compute future data f = b = y; // initialize forward and backward coefficients // Initialize noise variance estimate with data variance (= data autocorrelation[0]) noise_variance = Cum(y^2); noise_variance[0] = noise_variance[LongBar-1]/LongBar; // Main loop for (i = 1; i < OrderAR + 1; i++) { if (Window == 1) Wi = Ref(W,-i); // center Hamming Window else Wi = 1; b_shifted = Ref(b,-1); if (DoublePrecision == 0) { // single precision k_temp = Sum(Wi*f*b_shifted, LongBar - i)/Sum(Wi*(f^2 + b_shifted^2), LongBar - i); k[i] = 2*k_temp[LongBar - 1]; // k is reflection coefficient computed from i to LongBar - 1, like Burg tell it (!!! on Numerical Recipes it is computed from 1 to LongBar - i !!!) } /* -------------------------------------------------------------------------------------------------------------------------------------------- */ /* --- PART JUST BELOW ARE ONLY FOR EXPERIMENTATION ABOUT ROUNDING PROBLEM, COMPUTATION IS SLOWER AND THIS IS NOT NEEDED FOR SMALL AR ORDER --- */ // Use for FOR loop instead SUM function give different result (neither good, neither bad, but just different) because of rounding single-precision in AFL. De-comment this part to use FOR loop. /* Num = 0;Den = 0; for (j = i; j < LongBar; j++) { // compute from i to LongBar - 1, like Burg tell it (!!! on Numerical Recipes it is computed from 1 to LongBar - i !!!) Num = Num + Wi[j]*( f[j]*b[j-1] ); Den = Den + Wi[j]*( f[j]^2 + b[j-1]^2 ); } k[i] = 2*Num/Den; // k is reflection coefficient, a is AR coefficient */ /* --- END OF EXPERIMENTAL PART --- */ /* -------------------------------------------------------------------------------------------------------------------------------------------- */ // If you wish Double Precision, VBS script must be used (result are more precise than SUM or FOR loop, but computation is a lot more slower) if (DoublePrecision == 1) { // double precision KI_VBS = GetScriptObject(); KI = KI_VBS.Compute_KI(f, b, Wi, i, LongBar); k[i] = KI; } noise_variance[i] = (1 - k[i]^2)*noise_variance[i-1]; // update noise variance estimator if (AutoOrder == 1) { // Compute criterions for order AR selection FPE[i] = noise_variance[i]*(LongBar + (i + 1))/(LongBar - (i + 1)); // Final Prediction Error AIC[i] = log(noise_variance[i])+2*i/LongBar; // Akaine Information Criterion MDL[i] = log(noise_variance[i]) + i*log(LongBar)/LongBar; // Minimum Description Length CAT_factor = CAT_factor + (LongBar - i)/(LongBar*noise_variance[i]); CAT[i] = CAT_factor/LongBar - (LongBar - i)/(LongBar*noise_variance[i]); // Criterion Autoregressive Transfer CIC_product = CIC_product * (1 + 1/(LongBar + 1 - i))/(1 - 1/(LongBar + 1 - i)); CIC_add = CIC_add + (1 + 1/(LongBar + 1 - i)); CIC[i] = log(noise_variance[i]) + Max(CIC_product - 1,3*CIC_add); // Combined Information Criterion } // Update all AR coefficients for (j = 1; j < i; j++) a[j] = a_old[j] - k[i]*a_old[i-j]; a[i] = k[i]; // Store them for next iteration a_old = a; // Update forward and backward reflection coefficients f_temp = f - k[i]*b_shifted; b = b_shifted - k[i]*f; f = f_temp; // End of the main loop } if (AutoOrder == 1) { // Clean data because of rounding number for very low or very high value, and discard small changes FPE = IIf(abs(LinRegSlope(FPE, 2)/FPE[1]) < 0.005 OR abs(FPE) > 1e7, -1e10, FPE); AIC = IIf(log(abs(LinRegSlope(AIC, 2)/AIC[1])) < 0.005 OR abs(AIC) > 1e7, -1e10, AIC); MDL = IIf(log(abs(LinRegSlope(MDL, 2)/MDL[1])) < 0.005 OR abs(MDL) > 1e7, -1e10, MDL); CAT = IIf(log(abs(LinRegSlope(CAT, 2)/CAT[1])) < 0.005 OR abs(CAT) > 1e7, -1e10, CAT); CIC = IIf(abs(LinRegSlope(CIC, 2)/CIC[1]) < 0.005 OR abs(CIC) > 1e7, -1e10, CIC); // Find lower value Mixed_Order = 0; FPE_Order = Mixed_Order[1] = LastValue(Max(ValueWhen(FPE == Lowest(FPE) AND IsFinite(FPE), Cum(1), 1) - 1, 2)); AIC_Order = Mixed_Order[2] = LastValue(Max(ValueWhen(AIC == Lowest(AIC) AND IsFinite(AIC), Cum(1), 1) - 1, 2)); MDL_Order = Mixed_Order[3] = LastValue(Max(ValueWhen(MDL == Lowest(MDL) AND IsFinite(MDL), Cum(1), 1) - 1, 2)); CAT_Order = Mixed_Order[4] = LastValue(Max(ValueWhen(CAT == Lowest(CAT) AND IsFinite(CAT), Cum(1), 1) - 1, 2)); CIC_Order = Mixed_Order[5] = LastValue(Max(ValueWhen(CIC == Lowest(CIC) AND IsFinite(CIC), Cum(1), 1) - 1, 2)); // Mixed array is an averaging from all criterions taking in consideration order choose by criterions is often too low Mixed_Order_array = Median(Mixed_Order, 5); Mixed_Order = 2*ceil(Mixed_Order_array[5]); // Print informations about best order for each criterion printf("\nFPE Order : "+FPE_Order); printf("\nAIC Order : "+AIC_Order); printf("\nMDL Order : "+MDL_Order); printf("\nCAT Order : "+CAT_Order); printf("\nCIC Order : "+CIC_Order); printf("\n*** Mixed Order *** : "+Mixed_Order); // Mark best order in a[1] wich is returned at the end of the function if (AutoOrder_Criterion == "FPE") a[1] = FPE_Order; if (AutoOrder_Criterion == "AIC") a[1] = AIC_Order; if (AutoOrder_Criterion == "MDL") a[1] = MDL_Order; if (AutoOrder_Criterion == "CAT") a[1] = CAT_Order; if (AutoOrder_Criterion == "CIC (good)") a[1] = CIC_Order; if (AutoOrder_Criterion == "Mixed (best)") a[1] = Mixed_Order; } // End of the function, return AR coefficients and noise variance estimator for the current selected order in a[0] a = IIf(BI > OrderAR, -1e10, a); a[0] = noise_variance[i-1]; // usefull for AR_Pred and AR_Freq return a; } function AR_Predict(data, AR_Coeff, EndBar, ExtraF) { BI = BarIndex(); OrderAR = LastValue(BarCount - BarsSince(AR_Coeff) - 1); // Print some informations about AR coefficients and noise variance sum_coeffs = Cum(AR_Coeff) - AR_Coeff[0]; // ARCoeff[0] store noise_variance printf("\n\nNoise Variance Estimator : " + NumToStr(abs(AR_Coeff[0]), 1.9)); printf("\n\nSum of AR coeffs : " + NumToStr(sum_coeffs[OrderAR], 1.9)); for (i = 1; i < OrderAR + 1; i++) printf("\nCoeff AR " + NumToStr(i, 1.0) + " = " + NumToStr(AR_Coeff[i], 1.9)); // Pass the data into the AR filter data_predict = IIf(BI > EndBar, -1e10, Data); // clear data after EndBar for (i = Endbar + 1; i < EndBar + ExtraF + 1; i++) { data_predict[i] = 0; for (j = 1; j < OrderAR + 1; j++) data_predict[i] = data_predict[i] + AR_Coeff[j] * data_predict[i-j]; } /* -------------------------------------------------------------------------------------------------------------------------------------------- */ /* --- PART JUST BELOW IS ONLY IF YOU NEED RESIDUALS "u" FROM FILTERING PROCESS OR TO COMPARE IT WITH THE NOISE VARIANCE ESTIMATOR --- */ /* global BegBar; data_predict = IIf(BI > EndBar, -1e10, Data); for (i = BegBar + OrderAR; i < EndBar + 1 + ExtraF; i++) { data_predict[i] = 0; for (j = 1; j < OrderAR + 1; j++) { data_predict[i] = data_predict[i] + AR_Coeff[j] * data_predict[i-j]; } if (i > EndBar) u[i] = 0; else u[i] = data[i] - data_predict[i]; data_predict[i] = data_predict[i] + u[i]; } global noise_variance_filterburg; noise_variance_filterburg = StDev(u, EndBar - (BegBar + OrderAR) + 1); noise_variance_filterburg = noise_variance_filterburg[EndBar]^2; printf( "\n\nNoise variance from filtering process : " + NumToStr(noise_variance_filterburg, 1.9)); */ /* --- END OF RESIDUAL COMPUTATION PART --- */ /* -------------------------------------------------------------------------------------------------------------------------------------------- */ // Return data and data predicted from (EndBar + 1) to (EndBar + ExtraF) return data_predict; } function AR_Freq(AR_Coeff, step) { BI = BarIndex(); pi2 = atan(1) * 8; OrderAR = LastValue(BarCount - BarsSince(AR_Coeff) - 1); AR_Coeff=-AR_Coeff; noise_variance = abs(AR_Coeff[0]); if (noise_variance == 0) noise_variance = 0.000001; //seven-th digit to one S = -1e10; // usefull to determine the number of data for AR_Sin function f = Cum(1); f = Ref(f,-1); f[0] = 0; f = IIf(BI > 0.5/step, -1e10, f); f = step*f; // Danielson-Lanczos algorithm to fast compute exponential complex multiplication, using vector formulation AFL for multiple frequency in one-time recursion W_cos = cos(pi2*f); W_sin = sin(pi2*f); // initialize cos and sinus constant for each frequency f W_Re = 1; W_Im = 0; // initialize for recursion real and imaginary weight for AR coeffs Re = 1; Im = 0; // initialize real and imaginary part of the denominator from the spectrum function for (j = 1; j < OrderAR + 1; j++) { W_Re_temp = W_Re; // Begin Danielson-Lanczos part W_Re = W_Re*W_cos - W_Im*W_sin; W_Im = W_Im*W_cos + W_Re_temp*W_sin; // End Danielson-Lanczos part Re = Re + AR_Coeff[j]*W_Re; // real part of the denominator Im = Im + AR_Coeff[j]*W_Im; // imaginary part of the denominator } /* Just for experimentation about speed between classic and Danielson-Lanczos algorithm, here is basic computation */ //Re = 1; Im = 0; //for (j = 1; j < OrderAR + 1; j++) { Re = Re + AR_Coeff[j]*cos(pi2*f*j); Im = Im + AR_Coeff[j]*sin(pi2*f*j); } S = noise_variance/(Re^2+Im^2); // S the spectrum function Sdb = 10*log10(abs(s/noise_variance)); // Sdb the spectrum function in dB (power) with noise_variance as reference (so if Sdb is negative, power at this frequency is less than noise power) return Sdb; } function AR_Sin(S, nb_sinus) { // Initialization nb_data = LastValue(BarCount - BarsSince(S)); step = 0.5/nb_data; // Process data to keep only signifiant peaks slope = LinRegSlope(S,2); // derivation peaks = Ref(Cross(0, slope), 1); // find maximums of the spectrum value_peaks = IIf(peaks == 1 AND S > 0, S, 0); // erase maximum wich have less power than the noise // Find the reduced frequency of the most powerfull cycles sinus = -1e10; sinus[0] = 0; // to detect error or no cycle for (i = 0; i < nb_sinus; i++) { // save nb_sinus dominant cycles sinus[i] = BarCount - LastValue(HighestBars(value_peaks)) - 1; // save higher peak position value_peaks[sinus[i]] = 0; // erase new detected peak for next iteration } sinus = 1/(sinus*step); // convert reduced frequency in periods sinus[0] = Nz(sinus[0]); // no cycle found return sinus; } /* ---------------------------------------------------------------------- */ /* -------------------------------- DEMO -------------------------------- */ /* ---------------------------------------------------------------------- */ // Choice of the parameters empty = ParamList("Main parameters", "", 0); data_source = ParamField("Price field",-1); ARmodel = ParamList("AR Model", "Burg (best)|Yule-Walker", 0); length = Param("Length to look back", 200, 1, 5000, 1); OrderAR = Param("Order AR", 20, 0, 100, 1); ExtraF = Param("Number of bar to predict", 50, 0, 200, 1); AutoOrder = ParamToggle("Auto AR order", "No|Yes", 0); AutoOrder_Criterion = ParamList("Auto AR criterion", "FPE|AIC|MDL|CAT|CIC (good)|Mixed (best)", 5); HammingWindow = ParamToggle("Burg: Hamming Window", "No|Yes", 1); DoublePrecision = ParamToggle("Burg: Double Precision", "No|Yes", 0); Biased = ParamToggle("Y-W: Biased (Yes: best)", "No|Yes", 1); empty = ParamList("*** PRE-PROCESSING : ***", "", 0); empty = ParamList("1- Intraday EOD GAP Filter", "", 0); FiltrageGAPEOD = ParamToggle("Filtrage GAP EOD", "No|Yes", 0); empty = ParamList("2- Denoise", "", 0); periodsT3 = Param("Periods T3", 5, 1, 200, 1); slopeT3 = Param("Slope T3", 0.7, 0, 3, 0.01); empty = ParamList("3- Detrend", "", 0); method_detrend = ParamList("Detrending method", "None|Log10|Derivation|Linear Regression|PolyFit", 3); PF_order = Param("PolyFit Order", 3, 1, 9, 1); empty = ParamList("4- Center", "", 0); PreCenter = ParamToggle("Center data", "No|Yes", 1); empty = ParamList("5- Normalize", "", 0); PreNormalise = ParamToggle("Normalise data", "No|Yes", 1); empty = ParamList("6- Volume weight on data", "", 0); PonderVolHL = ParamToggle("Weighting Volume and H/L(Fractal)", "No|Yes", 0); coef_vol = Param( "Strength Volume (- +)", 0.5, 0.01, 0.99, 0.01); coefdim = Param( "Strength Fractal (- +)", 0.5, 0.01, 0.99, 0.01); period = Param( "Periods Fract (even)", 16, 2, 200, 2); scale = Param( "Scale Final Weights", 1, 0, 10, 0.01); translation = Param( "Translate Final Weights", 0.3, 0, 1, 0.01); empty = ParamList("7- Time weight on data", "", 0); PonderTime = ParamToggle("Weighting Time", "No|Yes", 0); PonderTimeWindow = ParamList("Weighting Time Window", "Log|Ramp|Exp", 0); empty = ParamList("*** POST-PROCESSING : ***", "", 0); method_retrend = ParamList("Retrending method", "Add back trend|Prediction without trend", 0); empty = ParamList("For Derivation or Log10 :", "add automatically the trend", 0); // Initialization SetBarsRequired(20000,20000); Title = ""; BI = BarIndex(); current_pos = SelectedValue( BI ) - BI[ 0 ];//1500 printf( "Position: " + NumToStr(current_pos) + "\n" ); // Adjust users choice depending number of bars data available or detrending/retrending necessity for derivation method if ( method_retrend == "Prediction without trend" AND (method_detrend == "Derivation" OR method_detrend == "Log10") ) method_retrend = "Add back trend"; BegBar = current_pos - length + 1; slide = floor(periodsT3/2); if (BegBar < 6*periodsT3) Title = Title + "\n\n\n\n\n\n!!! WARNING : YOU HAVE NOT ENOUGH DATA HISTORY FOR CORRECT T3 FILTERING - Reduce \"Periods T3\" parameter OR move Position Bar !!!\n\n\n\n\n\n"; if (BegBar < 1) { BegBar = 1; length = current_pos - slide; Title = Title + "\n\n\n\n\n\n!!! WARNING : YOU HAVE NOT ENOUGH DATA HISTORY - Reduce \"Length to look back\" parameter OR move Position Bar !!!\n\n\n\n\n\n"; } EndBar = current_pos - slide; if ( EndBar + ExtraF > BarCount - 1) { ExtraF = (BarCount - 1) - EndBar; } if (AutoOrder == 1) OrderAR = floor(length / 2); if (OrderAR >= length) { OrderAR = length - 1; Title = Title + "\n\n\n\n\n\n!!! WARNING : ORDER AR IS MORE HIGH THAN (LENGTH TO LOOK BACK - 1) - Reduce \"Order AR\" OR increase \"Length to look back\" parameters !!!\n\n\n\n\n\n"; } data = data_source; data_filtred = f_centeredT3(data, periodsT3, slopeT3); /* -------------------- BEGIN PROCESSING -------------------- */ // Filter GAP End of the days - only needed for intraday if (FiltrageGAPEOD == 1) data = Filter_GAP_EOD(data); // Denoise data data = f_centeredT3(data, periodsT3, slopeT3); // Detrend data if (method_detrend != "None") data = f_detrend(data, BegBar, EndBar, ExtraF, method_detrend, PF_order); data = IIf(BI < BegBar, 0, data); // fill with 0 before BegBar to be able to compute native MA Function AFL // Center data mean_data_before = MA(data, EndBar - BegBar + 1); printf( "\nMean data not centered : " + WriteVal(mean_data_before[EndBar]) + "\n" ); if (PreCenter == 1) { data = data - mean_data_before[EndBar]; mean_data_after = MA(data, EndBar - BegBar + 1); printf( "\nMean data centered : " + WriteVal(mean_data_after[EndBar]) + "\n\n" ); } // Normalize data if (PreNormalise == 1) { max_data = HHV(data, EndBar - BegBar + 1); data = data / max_data[EndBar]; } // Weigthing only for the data which will feed the AR_Burg function (modeling AR), not the AR_Pred function (prediction) data_weighted = data; // Volume and High/Low (Fractal) weighting if (PonderVolHL == 1) data_weighted = Volume_HighLow_weighting(data_weighted, coef_vol, coefdim, period, scale, translation); // Time weighting if (PonderTime == 1) data_weighted = Time_weighting(data_weighted, PonderTimeWindow, BegBar, EndBar); // Compute AR model if (ARmodel == "Burg (best)") { // Burg model (MEM method) (better than Yule-Walker for sharp spectrum and short data history) AR_Coeff = AR_Burg(data_weighted, BegBar, EndBar, OrderAR, HammingWindow, AutoOrder, AutoOrder_Criterion, DoublePrecision); if (AutoOrder == 1) { // In case of AutoOrder, a new computation to find coefficients with the ideal order is needed OrderAR = AR_Coeff[1]; AR_Coeff = AR_Burg(data_weighted, BegBar, EndBar, OrderAR, HammingWindow, 0, AutoOrder_Criterion, DoublePrecision); // Compute the AR from AutoOrder } } if (ARmodel == "Yule-Walker") { // Yule-Walker model (Autocorrelation method) AR_Coeff = AR_YuleWalker(data_weighted, BegBar, EndBar, OrderAR, Biased, AutoOrder, AutoOrder_Criterion); if (AutoOrder == 1) { // In case of AutoOrder, a new computation to find coefficients with the ideal order is needed OrderAR = AR_Coeff[1]; AR_Coeff = AR_YuleWalker(data_weighted, BegBar, EndBar, OrderAR, Biased, 0, AutoOrder_Criterion); // Compute the AR from AutoOrder } } noise_variance = abs(AR_Coeff[0]); // Prediction based on the computed AR model data_predict = AR_Predict(data, AR_Coeff, EndBar, ExtraF); // De-normalize if (PreNormalise == 1) { data_predict = data_predict * max_data[EndBar]; noise_variance = noise_variance * max_data[EndBar]; } // De-center if (PreCenter == 1) data_predict = data_predict + mean_data_before[EndBar]; // Add the trend back again if (method_detrend != "None" AND method_retrend == "Add back trend") data_predict = f_retrend(data_predict, data_filtred[EndBar], EndBar, EndBar + ExtraF, method_detrend); // Translate along value axis filtered EOD GAP data or not retrended data, so no gap occurs if (FiltrageGAPEOD == 1 OR method_retrend == "Prediction without trend") { delta = data_predict[EndBar + 1] - data_filtred[EndBar]; data_predict = data_predict - delta; data_predict = Ref(data_predict, 1); // so there is no discontinuity (but there is one data less for forward prediction) } // Plot AR Prediction and Burg predicted channels based on ATR and noise variance (if prediction is bad, channel will be larger) dataATR = ATR(periodsT3); // no need to detrend or center ATR before prediction (considerer centred without any trend) printf("\n\nATR AR model for Channel prediction :\n"); AR_Coeff_ATR = AR_Burg(dataATR, BegBar, EndBar, OrderAR, HammingWindow, OrderAR, AutoOrder_Criterion, DoublePrecision); data_predict_ATR = AR_Predict(dataATR, AR_Coeff_ATR, EndBar, ExtraF); DeltaBand = 2*(data_predict_ATR + noise_variance); Data_reconstruct = -1e10; Data_reconstruct = IIf( BI <= EndBar AND BI >= BegBar, data_filtred, IIf( BI > EndBar, data_predict, Data_reconstruct)); Plot(Data_reconstruct, "AR("+ NumToStr(OrderAR, 1.0) +") Prediction", IIf(BI > EndBar + slide, colorRed, IIf(BI > EndBar AND BI <= EndBar + slide, colorBlue, colorBrightGreen)), styleThick, Null, Null, 0); Plot(Data_reconstruct + DeltaBand, "AR("+ NumToStr(OrderAR, 1.0) +") Prediction Upper Channel", IIf(BI > EndBar + slide, colorRed, IIf(BI > EndBar AND BI <= EndBar + slide, colorBlue, colorBrightGreen)), styleDashed, Null, Null, 0); Plot(Data_reconstruct - DeltaBand, "AR("+ NumToStr(OrderAR, 1.0) +") Prediction Lower Channel", IIf(BI > EndBar + slide, colorRed, IIf(BI > EndBar AND BI <= EndBar + slide, colorBlue, colorBrightGreen)), styleDashed, Null, Null, 0); /* -------------------------------------------------------------------------------------- */ /* Demo for density spectrum power (DSP) analyse based on AR modeling (parametric method) */ // Compute spectrum based directly on AR model. Decomment following line to plot spectrum begining in first Bar (Bar[0]) Sdb = AR_Freq(AR_Coeff, 0.001); // 0.001 is the step for frequency resolution //Plot( Sdb, "Spectrum in decibels", ParamColor( "Color Spectrum in decibels", colorCycle ), ParamStyle("Style") ); // Look for the frequency which are the more powerfull (dominant cycles) sinus = AR_Sin(Sdb, 10); // 10 is the maximum number of frequency to look for Title = Title + "\nDominant periods: " + WriteIf(sinus[0] >= 0 AND IsFinite(sinus[0]), NumToStr(round(sinus[0]),1.0), ""); for (i = 1; i < 10; i++) Title = Title + WriteIf(sinus[i] > 0 AND IsFinite(sinus[i]), ", "+NumToStr(round(sinus[i]),1.0), ""); /* End DSP demo - For more information look for MEM or MESA */ /* -------------------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- */ /* ------------------------------- END DEMO ----------------------------- */ /* ---------------------------------------------------------------------- */
import React from 'react'; import Head from 'next/head'; import { seoData } from '../portfolio'; function SEO() { return ( <Head> <title>{seoData.title}</title> <meta name="title" content={seoData.title} /> <meta name="author" content={seoData.author} /> <meta name="description" content={seoData.description} /> <meta name="keywords" content={seoData.keywords.join(', ')} /> <link rel="canonical" href={seoData.url} /> {/* Open Graph / Facebook */} <meta property="og:type" content="website" /> <meta property="og:url" content={seoData.url} /> <meta property="og:title" content={seoData.title} /> <meta property="og:description" content={seoData.description} /> <meta property="og:image" content={seoData.image} /> <meta property="og:site_name" content={seoData.title} /> {/* Twitter */} <meta property="twitter:card" content="summary_large_image" /> <meta property="twitter:url" content={seoData.url} /> <meta property="twitter:title" content={seoData.title} /> <meta property="twitter:description" content={seoData.description} /> <meta property="twitter:image" content={seoData.image} /> <meta name="robots" content="Index" /> <link rel="manifest" href="/manifest.json" /> {/* Favicon */} <link rel="apple-touch-icon" sizes="120x120" href="./favicon.png" /> <link rel="icon" type="image/png" sizes="32x32" href="./favicon.png" /> <link rel="icon" type="image/png" sizes="16x16" href="./favicon.png" /> {/* Google Analytics */} <script async src="https://www.googletagmanager.com/gtag/js?id=G-YLRDM380QR"></script> <script dangerouslySetInnerHTML={{ __html: ` window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-YLRDM380QR'); `, }} /> </Head> ); } // SEO.prototype = { // data: PropTypes.shape({ // title: PropTypes.string.isRequired, // author: PropTypes.string, // description: PropTypes.string, // image: PropTypes.string, // url: PropTypes.string, // keywords: PropTypes.arrayOf(PropTypes.string), // }).isRequired, // }; export default SEO;
<?php use App\Http\Controllers\CommandeController; use App\Http\Controllers\ProduitController; use App\Http\Controllers\SuccursaleAmiController; use App\Http\Controllers\SuccursaleController; use App\Http\Controllers\UtilisateurController; use App\Models\Succursale; use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "api" middleware group. Make something great! | */ Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); }); // Route::group(['prefix' => 'auth'], function () { // Route::get('/login',"AuthController@login"); // Route::post('/login',"AuthController@authenticate"); // Route::get('/logout',"AuthController@logout"); // }); Route::apiResource('/succursale', SuccursaleController::class); Route::prefix('/succursale')->group(function () { Route::get('succursale/{id}/produit', [SuccursaleController::class, 'getProduitsBySuccursale']); }); Route::apiResource('/succursaleAmi', SuccursaleAmiController::class); Route::apiResource("/produit", ProduitController::class); Route::get('/produitByCode/{code}', [ProduitController::class, 'getProduitByCode']); Route::get('/produitByLibelle/{libelle}', [ProduitController::class, 'getProduitByLibelle']); Route::prefix("/utilisateur")->group(function () { Route::post("", [UtilisateurController::class, "store"]); Route::get('/{utilisateur}', [UtilisateurController::class, 'show']); }); Route::prefix('/commande')->group(function (){ Route::post("", [CommandeController::class, "store"]); Route::get("/{commande}", [CommandeController::class, 'show']); });
import { useNavigate } from "react-router-dom"; import "../../components/Navbar/main.css"; import { useEffect, useState } from "react"; import { getIdData, getprofileData } from "../../config/firebasemethods"; import UserCard from "../../components/UserCard"; import { Spinner } from "react-bootstrap"; import { removeUserDataFromAsyncStorage } from "../../config/redux/reducer/AuthReducer"; import { removeDataFromLocalStorage } from "../../Utils/getAndSetInLocalStorage"; import { useDispatch } from "react-redux"; export default function Allbookings() { const dispatch = useDispatch(); let nav = useNavigate(); const [listData, setListData] = useState([]); const [loader, setLoader] = useState(true); const handleLogoutButton = async () => { removeDataFromLocalStorage("token"); removeDataFromLocalStorage("user"); dispatch(removeUserDataFromAsyncStorage()); nav("/") }; const handleUsersClick = () => { nav("/adminportalhome"); }; const handleMessageClick = () => { nav("/message"); }; const handleCarsClick = () => { nav("/allcars"); }; const handleBookingClick = () => { nav("/allbookings"); }; const getProduct = (e) => { nav("/singlebooking", { state: e, }); // console.log(e) }; let getData = async () => { setLoader(true); await getIdData("customerbooking", "") .then((res) => { console.log("res on get id data on home page", res); console.log("object.keys(res)", Object.keys(res)); // console.log('necha wala chal rha hain'); const result = Object.values(res).flatMap((value) => Object.values(value).map( ({ ac, airBags, address, bluetooth, bookingType, cassettePlayer, color, companyName, cost, carNumber, description, engineType, frontCamera, gps, id, image1, image2, image3, image4, image5, image6, modelName, modelYear, sunRoof, usbPort, userName, userid, available, customerBookingId, customerid, customeruserName, selectedDate, selectedDateTime, transporterBookingId, }) => ({ ac, airBags, address, bluetooth, bookingType, cassettePlayer, color, companyName, cost, carNumber, description, engineType, frontCamera, gps, id, image1, image2, image3, image4, image5, image6, modelName, modelYear, sunRoof, usbPort, userName, userid, available, customerBookingId, customerid, customeruserName, selectedDate, selectedDateTime, transporterBookingId, }) ) ); console.log(result);// Store the original data setListData(result); setLoader(false); }) .catch((err) => { // console.log('no data found') setLoader(false); }); }; useEffect(() => { // async () => { setLoader(true); getData(); // console.log('else is working'); setLoader(false); }, []); console.log("listData on addmin", listData); return ( <> <div style={{ display: "flex" }}> <div style={{ height: "110vh" }}> <div className="mainSidebar"> <ul className="sidebarUl"> <li className="sidebarLi" onClick={handleUsersClick}> Users </li> <li className="sidebarLi" onClick={handleCarsClick}> Cars </li> <li className="sidebarLi" onClick={handleBookingClick} style={{ color: "#db2b39" }} > Bookings </li> <li className="sidebarLi" onClick={handleMessageClick}> Feedback </li> <li className="sidebarLi" onClick={handleLogoutButton}> Logout </li> </ul> </div> </div> <div style={{ width: "100%"}}> <div style={{ width: "100%", textAlign: 'center' }}> <h1 style={{fontWeight: 'bold'}}>Admin Portal</h1> </div> <div style={{ marginLeft: 30}}> <h2 style={{ fontWeight: "bold", marginBottom: 20 }}> All Bookings: </h2> </div> {loader ? ( <div style={{ width: "100%", display: "flex", justifyContent: "center", }} > <Spinner animation="border" style={{}} /> </div> ) : ( <div> {listData.length === 0 ? ( <div> <img src={require("../../Assets/Images/no_cars_search.png")} style={{ width: "100%", height: "100%", marginVerticle: "50px", }} /> </div> ) : ( <div style={{ display: "flex", justifyContent: "space-between", flexWrap: "wrap", marginLeft: "30px", }} > {listData // .filter((x) => // x.carName.toLowerCase().includes(searchProd) // ) .map((x, i) => { return ( <UserCard title={x.companyName + " " + x.modelName} src={x.image1} price={x.cost} onClick={() => getProduct(x)} /> ); })} </div> )} </div> )} </div> </div> </> ); }
import { Button, Card, Grid, InputAdornment, TextField, FormHelperText } from '@mui/material'; import { useCallback, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import HelperText from 'component/HelperText'; import ProgressDialog from 'component/ProgressDialog'; import { UnitFormats } from 'ethereum/helpers/math'; import { toFixedNumberOrUndefined } from 'ethereum/helpers/stringNumber'; import { useErrorDialog } from 'store/ErrorDialogProvider'; import { useNumericDisplayContext } from 'store/NumericDisplayProvider'; import Validation, { DepositError } from './Validation'; import type { FixedNumber } from 'ethers'; import type { ChangeEventHandler, FC, MouseEventHandler, ReactNode } from 'react'; export type FormProps = { balance: FixedNumber; buttonContent: ReactNode; deposit: (amount: FixedNumber) => Promise<void>; proxyAddress: string | undefined; increaseAllowance: (address: string, spendingAmount: FixedNumber) => Promise<void>; ensureProxy: () => Promise<string>; allowance: FixedNumber; onDialogClose: () => void; amountText: string; onAmountChange: (s: string) => void; }; const Form: FC<FormProps> = ({ deposit, buttonContent, balance, proxyAddress, increaseAllowance, ensureProxy, allowance, onDialogClose, amountText, onAmountChange, }) => { const { t } = useTranslation('common', { keyPrefix: 'pages.earn.deposit.form' }); const { t: units } = useTranslation('common', { keyPrefix: 'units' }); const { t: forms } = useTranslation('common', { keyPrefix: 'forms' }); const { t: error } = useTranslation('common', { keyPrefix: 'pages.earn.deposit.form.errors' }); const [dialogText, setDialogText] = useState(''); const [totalSteps, setTotalSteps] = useState(1); const [currentStep, setCurrentStep] = useState(1); const { openDialog } = useErrorDialog(); const { format } = useNumericDisplayContext(); const formats = UnitFormats.WAD; const amount = useMemo(() => toFixedNumberOrUndefined(amountText, formats), [amountText, formats]); // input as percentage, return as ratio const [depositing, setDepositing] = useState(false); const handleChange: ChangeEventHandler<HTMLInputElement> = useCallback( (event) => onAmountChange(event.target.value), [onAmountChange], ); const onButtonClick: MouseEventHandler<HTMLButtonElement> = useCallback(async () => { if (!amount) { return; } const f = async () => { setDepositing(true); const allowanceToIncrease = amount.subUnsafe(allowance); setCurrentStep(1); setTotalSteps(() => { let steps = 2; if (!proxyAddress) { steps += 1; } if (!allowanceToIncrease.isNegative() && !allowanceToIncrease.isZero()) { steps += 1; } return steps; }); let proxy = ''; if (!proxyAddress) { setDialogText(forms('createProxy')!); proxy = await ensureProxy(); setCurrentStep((prev) => prev + 1); } else { proxy = await ensureProxy(); } if (!allowanceToIncrease.isNegative() && !allowanceToIncrease.isZero()) { setDialogText(forms('increaseAllowance', { token: units('stableToken') })!); await increaseAllowance(proxy, amount); setCurrentStep((prev) => prev + 1); } setDialogText(t('processing')!); await deposit(amount); setCurrentStep((prev) => prev + 1); setDialogText(t('done')!); }; await f().catch((err) => { setDepositing(false); openDialog(error('errorWhileDeposit'), err); }); }, [amount, allowance, proxyAddress, t, deposit, forms, ensureProxy, units, increaseAllowance, openDialog, error]); const formErrors: DepositError[] = useMemo(() => { if (amount) { return Validation.canDeposit(balance, amount); } return []; }, [amount, balance]); const showErrorMessage = (e: DepositError) => { switch (e) { case DepositError.insufficientBalance: return error('insufficientBalance'); case DepositError.invalidAmount: return error('invalidAmount'); } }; return ( <Card component="form" elevation={0}> <ProgressDialog open={depositing} title={buttonContent} text={dialogText} totalStep={totalSteps} currentStep={currentStep} onClose={() => { setDepositing(false); onDialogClose(); }} /> <Grid container padding={2} spacing={2}> <Grid item xs={12} lg={6}> <TextField fullWidth label={t('label')} value={amountText} error={formErrors.length !== 0} onChange={handleChange} helperText={<HelperText>{`${forms('balance')}: ${format(balance)} ${units('stableToken')}`}</HelperText>} InputProps={{ endAdornment: <InputAdornment position="end">DAI</InputAdornment>, }} /> </Grid> <Grid item xs={12}> <Button variant="contained" fullWidth disabled={!amount || depositing || formErrors.length !== 0} onClick={onButtonClick} > {buttonContent} </Button> </Grid> <Grid item xs={12}> {formErrors.map((e) => ( <FormHelperText key={e} error> {showErrorMessage(e)} </FormHelperText> ))} </Grid> </Grid> </Card> ); }; export default Form;
# This file is copied to spec/ when you run "rails generate rspec:install" ENV["RAILS_ENV"] ||= "test" require "simplecov" SimpleCov.start require File.expand_path("../../config/environment", __FILE__) require "rspec/rails" require "database_cleaner" require "capybara/rspec" require "ruby-debug" if Gem::Specification::find_all_by_name("ruby-debug").any? # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } # Checks for pending migrations before tests are run. # If you are not using ActiveRecord, you can remove this line. ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration) RSpec.configure do |config| config.fixture_path = "#{::Rails.root}/spec/fixtures" config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" config.include FactoryGirl::Syntax::Methods ### DatabaseCleaner configuration config.before(:suite) do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with(:truncation) end config.before(:each) do FactoryGirl.reload DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean RedisLeaderboard.get.delete_leaderboard end config.include Devise::TestHelpers, type: :controller end RspecApiDocumentation.configure do |config| config.format = :json end Raddocs.configure do |config| config.docs_dir = "doc/api" end
scilla_version 0 (***************************************************) (* Associated library *) (***************************************************) import IntUtils ListUtils BoolUtils library GiveawayMinter (* Global variables *) let max_mint_quantity = Uint32 10 let zero = Uint128 0 let one = Uint256 1 let none = None {ByStr20} let false = False let true = True let empty = "" (* Library functions *) let one_msg = fun (msg : Message) => let nil_msg = Nil {Message} in Cons {Message} msg nil_msg let grow : Uint32 -> Uint128 = fun (var : Uint32) => let maybe_big = builtin to_uint128 var in match maybe_big with | Some big => big | None => Uint128 0 (* should never happen *) end let build_mint_msgs : ByStr20 -> ByStr20 -> Uint32 -> List (Message) = fun (nft_address : ByStr20) => fun (to: ByStr20) => fun (m: Uint32) => let z = Uint32 0 in let zero_lt_m = builtin lt z m in match zero_lt_m with | True => (* m is the nat to recurse on *) let m_nat = builtin to_nat m in let nil = Nil {Message} in let list_init = nil in let msg = { _tag: "Mint"; _recipient: nft_address; _amount: zero; to: to; token_uri: empty } in let step = fun (list : List (Message)) => fun (ignore : Nat) => let new_list = Cons {Message} msg list in new_list in let fold = @nat_fold (List (Message)) in let xs_m = fold step list_init m_nat in xs_m | False => Nil {Message} end (* Error exception *) type Error = | CodeNotOwner | CodeNotPendingOwner | CodePendingOwnerNotEmpty | CodeExceedMaxMintQuantity | CodeNotReservedToken let make_error = fun (result : Error) => let result_code = match result with | CodeNotOwner => Int32 -1 | CodeNotPendingOwner => Int32 -2 | CodePendingOwnerNotEmpty => Int32 -3 | CodeExceedMaxMintQuantity => Int32 -4 | CodeNotReservedToken => Int32 -5 end in { _exception : "Error"; code : result_code } (***************************************************) (* The contract definition *) (***************************************************) contract GiveawayMinter ( contract_owner: ByStr20, nft_address: ByStr20 ) (* Mutable fields *) field current_owner : Option ByStr20 = Some {ByStr20} contract_owner field pending_owner : Option ByStr20 = none (**************************************) (* Procedures *) (**************************************) procedure ThrowError(err : Error) e = make_error err; throw e end procedure IsOwner(address: ByStr20) maybe_current_owner <- current_owner; match maybe_current_owner with | Some current_contract_owner => is_owner = builtin eq current_contract_owner address; match is_owner with | True => | False => err = CodeNotOwner; ThrowError err end | None => err = CodeNotOwner; ThrowError err end end procedure IsPendingOwner(address: ByStr20) maybe_pending_owner <- pending_owner; match maybe_pending_owner with | Some current_pending_owner => is_pending_owner = builtin eq current_pending_owner address; match is_pending_owner with | True => | False => err = CodeNotPendingOwner; ThrowError err end | None => err = CodeNotPendingOwner; ThrowError err end end procedure NoPendingOwner() maybe_pending_owner <- pending_owner; match maybe_pending_owner with | Some p => err = CodePendingOwnerNotEmpty; ThrowError err | None => end end procedure IsWithinMintLimit(quantity: Uint32) is_not_exceeding = uint32_le quantity max_mint_quantity; match is_not_exceeding with | True => | False => err = CodeExceedMaxMintQuantity; ThrowError err end end (***************************************) (* Transitions *) (***************************************) (* @dev: Mint new tokens to contract owner *) (* @param: to - Recipient address of token *) (* @param: quantity - Number of tokens to mint *) transition MintForCommunity(to: ByStr20, quantity: Uint32) IsOwner _sender; IsWithinMintLimit quantity; msgs = build_mint_msgs nft_address to quantity; send msgs end (** Ownership lifecycle transitions *) (* @dev: Transfers contract ownership to a new address. The new address must call the AcceptOwnership transition to finalize the transfer. *) (* @param new_owner: Address of the new current_owner. *) transition TransferOwnership(new_owner: ByStr20) IsOwner _sender; o = Some {ByStr20} new_owner; pending_owner := o; e = {_eventname : "OwnershipTransferInitiated"; current_owner : _sender; pending_owner : new_owner}; event e end (* @dev: Finalizes transfer of contract ownership. Must be called by the new current_owner. *) transition AcceptOwnership() IsPendingOwner _sender; previous_current_owner <- current_owner; o = Some {ByStr20} _sender; current_owner := o; pending_owner := none; e = {_eventname : "OwnershipTransferAccepted"; previous_current_owner : previous_current_owner; current_owner : _sender}; event e end (* @dev: Removes the current_owner, meaning that new minters can no longer be added. Must not have a pending owner. *) transition RevokeOwnership() IsOwner _sender; NoPendingOwner; current_owner := none; e = {_eventname : "OwnershipRevoked"; current_owner : _sender}; event e end (*************************************) (* Callbacks *) (*************************************) transition MintCallBack(recipient: ByStr20, token_id: Uint256, token_uri: String) (* proxy callback to the recipient, who is always the minter *) msg_to_sender = { _tag : "MintCallBack"; _recipient : recipient; _amount : zero; recipient : recipient; token_id : token_id; token_uri : token_uri }; msgs = one_msg msg_to_sender; send msgs end
package org.mojodojocasahouse.extra.tests.service; import com.fasterxml.jackson.databind.ObjectMapper; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mojodojocasahouse.extra.dto.ApiResponse; import org.mojodojocasahouse.extra.dto.ExpenseAddingRequest; import org.mojodojocasahouse.extra.dto.ExpenseDTO; import org.mojodojocasahouse.extra.model.ExtraExpense; import org.mojodojocasahouse.extra.model.ExtraUser; import org.mojodojocasahouse.extra.repository.ExtraExpenseRepository; import org.mojodojocasahouse.extra.service.ExpenseService; import org.springframework.boot.test.json.JacksonTester; import java.math.BigDecimal; import java.sql.Date; import java.util.List; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; @ExtendWith(MockitoExtension.class) public class ExpensesServiceTest { @Mock private ExtraExpenseRepository expenseRepository; @InjectMocks private ExpenseService expenseService; @BeforeEach public void setup() { JacksonTester.initFields(this, new ObjectMapper()); } @Test public void testGettingAllExpensesByExistingUserIdReturnsList() { // Setup - data ExtraUser user = new ExtraUser( "Michael", "Jackson", "mj@me.com", "Somepassword1!" ); ExtraExpense savedExpense1 = new ExtraExpense(user, "Another Concept", new BigDecimal("10.11"), Date.valueOf("2023-09-11"), "test",(short) 1); ExtraExpense savedExpense2 = new ExtraExpense(user, "Another Concept", new BigDecimal("10.12"), Date.valueOf("2023-09-12"), "test",(short) 1); List<ExtraExpense> expectedExpenses = List.of( savedExpense1, savedExpense2 ); // Setup - expectations given(expenseRepository.findAllExpensesByUser(any())).willReturn(expectedExpenses); // exercise List<ExpenseDTO> foundExpenseDtos = expenseService.getAllExpensesByUserId(user); // verify Assertions .assertThat(foundExpenseDtos) .containsExactlyInAnyOrder(savedExpense1.asDto(), savedExpense2.asDto()); } @Test public void testGettingAllExpensesByNonExistingUserIdReturnsEmptyList() { // Setup - data ExtraUser user = new ExtraUser( "Michael", "Jackson", "mj@me.com", "Somepassword1!" ); // Setup - expectations given(expenseRepository.findAllExpensesByUser(any())).willReturn(List.of()); // exercise List<ExpenseDTO> foundExpenses = expenseService.getAllExpensesByUserId(user); // verify Assertions.assertThat(foundExpenses).isEqualTo(List.of()); } @Test public void testAddingAnExpenseToExistingUserReturnsSuccessfulResponse() { // Setup - data ExpenseAddingRequest request = new ExpenseAddingRequest( "A Concept", new BigDecimal("10.12"), Date.valueOf("2023-09-19"), "test", (short) 1 ); ExtraUser user = new ExtraUser( "Michael", "Jackson", "mj@me.com", "Somepassword1!" ); ApiResponse expectedResponse = new ApiResponse( "Expense added succesfully!" ); // exercise ApiResponse actualResponse = expenseService.addExpense(user, request); // verify Assertions.assertThat(actualResponse).isEqualTo(expectedResponse); } @Test public void testGettingAllExpensesByCategoryAndUser(){ ExtraUser user = new ExtraUser( "Michael", "Jackson", "mj@me.com", "Somepassword1!" ); ExtraExpense savedExpense1 = new ExtraExpense(user, "Another Concept", new BigDecimal("10.11"), Date.valueOf("2023-09-11"), "test1",(short) 1); new ExtraExpense(user, "Another Concept", new BigDecimal("10.12"), Date.valueOf("2023-09-12"), "test2",(short) 1); List<ExpenseDTO> expectedDtos = List.of(savedExpense1.asDto()); given(expenseRepository.findAllExpensesByUserAndCategory(any(), any())).willReturn(List.of(savedExpense1)); List<ExpenseDTO> foundExpenses = expenseService.getAllExpensesByCategoryByUserId(user, "test1"); Assertions.assertThat(foundExpenses).containsExactlyInAnyOrder(expectedDtos.toArray(ExpenseDTO[]::new)); } @Test public void testGettingAllDistinctCategoriesOfExpensesOfUser(){ ExtraUser user = new ExtraUser( "Michael", "Jackson", "mj@me.com", "Somepassword1!" ); List<String> expectedCategories = List.of("test1", "test2"); given(expenseRepository.findAllDistinctCategoriesByUser(any())).willReturn(expectedCategories); List<String> foundExpenses = expenseService.getAllCategories(user); Assertions.assertThat(foundExpenses).containsExactlyInAnyOrder(expectedCategories.toArray(String[]::new)); } }
import { Alchemy, Network } from "alchemy-sdk"; import { useState, useEffect } from "react"; import { NavLink } from "react-router-dom"; const settings = { apiKey: process.env.REACT_APP_ALCHEMY_API_KEY, network: Network.ETH_MAINNET, }; const alchemy = new Alchemy(settings); export function ContractTransactions(account) { const [transactions, setTransactions] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function getTransactions() { try { const newTransactions = await alchemy.core.getAssetTransfers({ maxCount: 10, toAddress: account.account, order: "desc", category: [ //"internal", "erc721", //"erc20", "external", "specialnft", ], }); const newFromTransactions = await alchemy.core.getAssetTransfers({ maxCount: 10, fromAddress: account.account, order: "desc", category: [ //"internal", "erc721", //"erc20", "external", "specialnft", ], }); setTransactions( newTransactions.transfers.concat(newFromTransactions.transfers) ); setLoading(false); } catch (err) { console.error( "Error while fetching contract transactions: ", err.message ); } } getTransactions(); }, []); return ( <> {loading ? ( <p>Loading...</p> ) : ( <> <table> <thead> <tr> <th>Hash</th> <th>Block</th> <th>From</th> <th>To</th> <th>value</th> </tr> </thead> <tbody> {transactions.map((tx) => ( <tr> <td>{tx.hash}</td> <td>{parseInt(tx.blockNum, 16)}</td> <td>{tx.from}</td> <td>{tx.to}</td> <td>{tx.value}</td> </tr> ))} </tbody> </table> </> )} </> ); } export function ContractInternalTransactions(account) { const [transactions, setTransactions] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function getTransactions() { try { const newTransactions = await alchemy.core.getAssetTransfers({ maxCount: 10, fromAddress: account.account, order: "desc", excludeZeroValue: true, category: ["internal"], }); const newFromTransactions = await alchemy.core.getAssetTransfers({ maxCount: 10, toAddress: account.account, order: "desc", excludeZeroValue: true, category: ["internal"], }); setTransactions( newTransactions.transfers.concat(newFromTransactions.transfers) ); setLoading(false); } catch (err) { console.error( "Error while fetching contract transactions: ", err.message ); } } getTransactions(); }, []); return ( <> {loading ? ( <p>Loading...</p> ) : ( <> <table> <thead> <tr> <th>Hash</th> <th>Block</th> <th>From</th> <th>To</th> <th>value</th> </tr> </thead> <tbody> {transactions.map((tx) => ( <tr> <td>{tx.hash}</td> <td>{parseInt(tx.blockNum, 16)}</td> <td>{tx.from}</td> <td>{tx.to}</td> <td>{tx.value}</td> </tr> ))} </tbody> </table> </> )} </> ); } export function ContractERC20Tokens(account) { const [transactions, setTransactions] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { async function getTransactions() { try { const newTransactions = await alchemy.core.getAssetTransfers({ maxCount: 10, toAddress: account.account, order: "desc", excludeZeroValue: true, category: ["erc20"], }); setTransactions(newTransactions.transfers); console.log(newTransactions); setLoading(false); } catch (err) { console.error( "Error while fetching contract transactions: ", err.message ); } } getTransactions(); }, []); return ( <> {loading ? ( <p>Loading...</p> ) : ( <> <table> <thead> <tr> <th>Hash</th> <th>Block</th> <th>From</th> <th>To</th> <th>value</th> </tr> </thead> <tbody> {transactions.map((tx) => ( <tr> <td>{tx.hash}</td> <td>{parseInt(tx.blockNum, 16)}</td> <td>{tx.from}</td> <td>{tx.to}</td> <td>{tx.value}</td> </tr> ))} </tbody> </table> </> )} </> ); }
# photo-manager-cli ## Build ```shell go build ```` ## Configure `photo-manager-cli` requires a `config.yaml` to work. The file consists on a list of actions to be performed. ### `config.yaml` Create a configuration file: ```yaml - action: "UPDATE_METADATA" path: "/Users/scalvetr/Pictures/upload/2002 - 12 Desembre - Canaries" regexp: "(.*)\\.JPG" update_metadata_config: override: false date: "2005-05-17T14:00:00+01:00" date_replaces: - day: "2005-04-03" new_day: "2006-05-16" - day: "2005-04-04" new_day: "2006-05-17" - action: "UPDATE_DATE_FROM_METADATA" path: "/Users/scalvetr/Pictures/upload" - action: "UPLOAD_ALBUMS" path: "/Users/scalvetr/Pictures/upload" - action: "CHECK_ALBUM_DATE_MISMATCH" path: "/Users/scalvetr/Pictures/upload" report_file: "check_album_date_report.txt" album_info: folder_regexp: "(?P<year>\d{4}) - (?P<month>\d{2})(.*) - (?P<name>.*)" album_name_pattern: {{printf "%04d" .Year}}-{{printf "%02d" .Month}} - {{.Name}} - action: "INCREASE_DATE" path: "/Users/scalvetr/Pictures/upload" increase_date_config: date_range_from: "2015-01-01" date_range_to: "2017-01-01" increase_seconds: 215568000 ``` Accepts 3 kind of actions: * UPDATE_METADATA: sets a specific date to the `jpeg` `exif` metadata. Requires a `update_metadata_config`. * UPDATE_DATE_FROM_METADATA: read the `exif` metadata and updates the file system date accordingly (creation and updated dates) * UPLOAD_ALBUMS: requires `google_client.json` configuration file. You can get more information [here](https://developers.google.com/photos/library/guides/get-started#configure-app) ## Run ```shell ./photo-manager-cli ```` # Videos Videos are not supported for now, so we suggest using an alternate method. For instance `exiftool`. ```shell brew install exiftool cd ~/Pictures/fix/2006\ -\ 05\ Maig\ -\ Final\ Champions # check the dates exiftool -a -G1 MOV00342.MPG # update exiftool -AllDates="2005:05:16 14:00:00" MOV00342.MPG ```
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Cores em CSS</title> </head> <body> <!-- Representação por nomes --> <h2 style="background-color: blue; color:white;">Exemplo de Cores</h2> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Atque ullam optio recusandae, quis quo vitae natus totam aliquid. Vitae consequuntur non amet sint doloribus id porro laborum recusandae inventore dolorem.</p> <!-- Representação por códigos Hexadecimais Decimal: 0 1 2 3 4 5 6 7 8 9 Hexadecimal: 0 1 2 3 4 5 6 7 8 9 A B C D E F --> <h2 style="background-color: #0000ff; color: #33ffff; ">Exemplo de Cores</h2> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Atque ullam optio recusandae, quis quo vitae natus totam aliquid. Vitae consequuntur non amet sint doloribus id porro laborum recusandae inventore dolorem.</p> <!-- Representação por RGB --> <h2 style="background-color: rgb(0, 0, 255); color: rgb(255, 255, 255); ">Exemplo de Cores</h2> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Atque ullam optio recusandae, quis quo vitae natus totam aliquid. Vitae consequuntur non amet sint doloribus id porro laborum recusandae inventore dolorem.</p> <!-- Representação por HSL(Hue,Saturation,Litghness) --> <h2 style="background-color: hsl(231, 100%, 50%); color: hsl(0, 0%, 100%);">Exemplo de Cores</h2> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Atque ullam optio recusandae, quis quo vitae natus totam aliquid. Vitae consequuntur non amet sint doloribus id porro laborum recusandae inventore dolorem.</p> <!-- Representação de cores transparentes --> <h2 style="background-color: hsl(231, 100%, 50%,0.5); color: rgba(255, 0, 0,0.1);">Exemplo de Cores</h2> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Atque ullam optio recusandae, quis quo vitae natus totam aliquid. Vitae consequuntur non amet sint doloribus id porro laborum recusandae inventore dolorem.</p> <!-- Utilizando o VSCODE para selecionar a cor (mouse sobre a função hsl ou rgb) --> <h2 style="background-color: hsla(108, 33%, 50%, 0.911); color: rgba(16, 56, 38, 0.533);">Exemplo de Cores</h2> <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Atque ullam optio recusandae, quis quo vitae natus totam aliquid. Vitae consequuntur non amet sint doloribus id porro laborum recusandae inventore dolorem.</p> </body> </html>
"use client"; import { Bubble, ColorRGBA } from "./bubble"; import React from "react"; export default function Bubbles({ quantity = 5, blur = 100, // px minSpeed = 5, // px/s maxSpeed = 25, // px/s minSize = 15, // window width % maxSize = 55, // window width %, colors, className, }: { quantity?: number; blur?: number; minSpeed?: number; maxSpeed?: number; minSize?: number; maxSize?: number; colors?: ColorRGBA[]; className?: string; }) { const canvasRef = React.useRef<HTMLCanvasElement>(null); const [hasStarted, setHasStarted] = React.useState(false); const [screenSize, setScreenSize] = React.useState({ x: 0, y: 0 }); const [bubbles, setBubbles] = React.useState<Bubble[]>([]); React.useEffect(() => { let bubbles: Bubble[] = []; for (let i = 0; i < quantity; i++) { bubbles.push( new Bubble({ blur: blur, minSpeed: minSpeed, maxSpeed: maxSpeed, minSize: minSize, maxSize: maxSize, colors: colors, }) ); } setBubbles([...bubbles]); setHasStarted(true); }, [quantity, blur, minSpeed, maxSpeed, minSize, maxSize, colors]); React.useEffect(() => { if (bubbles.length <= 0) return; const canvas = canvasRef.current; if (!canvas) { return; } const ctx = canvas.getContext("2d"); if (!ctx) { return; } let startTime = 0; const floatAnimId = requestAnimationFrame(function animate(currentTime) { ctx.clearRect(0, 0, canvas.width, canvas.height); const dt = (currentTime - startTime) / 1000; bubbles.forEach((bubble) => { // check if in view const bubbleY = bubble.position.y + (bubble.size + bubble.blur) / 2; if (bubbleY < 0) { bubble.resetBubble(); return; } // move bubble up const direction = bubble.getMoveDirection(); bubble.position.x += direction.x * bubble.speed * dt; bubble.position.y += direction.y * bubble.speed * dt; // draw bubble ctx.beginPath(); ctx.arc( bubble.position.x, bubble.position.y, bubble.size / 2, 0, Math.PI * 2 ); ctx.fillStyle = `rgba(${bubble.color.r}, ${bubble.color.g}, ${bubble.color.b}, ${bubble.color.a})`; ctx.fill(); }); startTime = currentTime; requestAnimationFrame(animate); }); function handleResize() { setScreenSize({ x: innerWidth, y: innerHeight }); } handleResize(); addEventListener("resize", handleResize); return () => { cancelAnimationFrame(floatAnimId); removeEventListener("resize", handleResize); }; }, [bubbles]); return ( <canvas ref={canvasRef} width={screenSize.x} height={screenSize.y} className={`-z-50 fixed top-0 left-0 transition-opacity duration-1000 ${className}`} style={{ filter: `blur(${blur}px)`, opacity: hasStarted ? 1 : 0, }} /> ); }
import { Component } from '@angular/core'; import { FormGroup,FormBuilder,Validators } from '@angular/forms' import { validateEmployeeCodeWithParameter } from './custom.validators'; @Component({ selector: 'app-custom-validation-with-parameters-demo', templateUrl: './custom-validation-with-parameters-demo.component.html', styleUrls: ['./custom-validation-with-parameters-demo.component.css'] }) export class CustomValidationWithParametersDemoComponent { form:FormGroup fb:FormBuilder constructor(fb:FormBuilder){ this.fb = fb } ngOnInit(): void { this.form = this.fb.group({ personalInfo :this.fb.group({ 'employeeName': ['',[Validators.required,Validators.minLength(4)]], 'employeeCode':['',[Validators.required,validateEmployeeCodeWithParameter('HP')]] }) }) } onSubmit(){ console.log(this.form) } ngDoCheck(){ console.log(this.form) } }
import React , { useState } from "react"; import { useDispatch } from "react-redux"; import { v4 as uuidv4 } from 'uuid' import { addPost } from "./action"; const PostForm = () => { const dispatch = useDispatch() //Adding Some CSS to give a good look const myStyle={ backgroundColor: "white", minHeight: "2rem", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", color: "black" } const [title, setTitle] = useState('') const [content, setContent] = useState('') const onTitleChanged = e => setTitle(e.target.value) const onContentChanged = e => setContent(e.target.value) const onSavePostClicked = () => { const newPost={ id: uuidv4(), // Generate a unique ID title: title, content: content } dispatch(addPost(newPost)) setTitle('') setContent('') } return ( <section> <h2>Add a New Post</h2> <form style={myStyle}> <label htmlFor="postTitle">Post Title:</label> <input type="text" id="postTitle" name="postTitle" value={title} onChange={onTitleChanged} /> <label htmlFor="postContent">Content:</label> <textarea id="postContent" name="postContent" value={content} onChange={onContentChanged} /> <button style={{margin:'10px'}} type="button" onClick={onSavePostClicked}> Save Post </button> </form> </section> ) } export default PostForm
<template> <div> <div class="mb-6"> <div class="text-h6 mb-2">Адрес</div> <v-text-field v-model="address" outlined flat disabled hide-details="auto" class="rounded-lg" ></v-text-field> </div> <div class="mb-8"> <v-row> <v-col> <v-sheet height="350px"> <yandex-map :settings="settings" :coords="coords" zoom="16" style="width: 100%; height: 100%" @map-was-initialized="initHandler" :controls="[ 'geolocationControl', 'zoomControl', 'trafficControl', ]" > <ymap-marker v-for="(billboard, index) in surfaces" :key="index" :marker-id="index" marker-type="placemark" :coords="billboard.coords" ></ymap-marker> </yandex-map> </v-sheet> </v-col> </v-row> <v-row> <v-col> <v-row> <v-col class="d-flex" cols="12" md="3"> <v-select :items="cities" :value="city" solo flat disabled class="my-auto" hide-details="auto" ></v-select> </v-col> <v-col class="d-flex pr-0" cols="12" md="9"> <v-select label="Метро" :items="mettro" :value="metro" @input="updateMetro" solo flat multiple disabled chips attach class="my-auto" hide-details="auto" ></v-select> </v-col> </v-row> <!-- <v-row> <v-col class="d-flex"> <v-text-field label="Широта" outlined :value="coordinate.lat" disabled flat hide-details="auto" class="rounded-lg mr-3" ></v-text-field> <v-text-field label="Долгота" outlined disabled :value="coordinate.lon" flat hide-details="auto" class="rounded-lg ml-3" ></v-text-field> </v-col> </v-row> --> </v-col> </v-row> </div> </div> </template> <script> import { yandexMap, ymapMarker } from "vue-yandex-maps"; import metros from "@/utils/metros"; import cities from "@/utils/cities"; export default { components: { yandexMap, ymapMarker, }, props: { address: { type: String, required: true }, city: { type: String, required: true, }, coordinate: { type: Object, required: true, }, metro: { type: Array, required: true, }, }, computed: { surfaces() { return [ { id: "1", city: this.city, address: this.address, coords: this.coords, }, ]; }, coords() { return [this.coordinate.lat, this.coordinate.lon]; }, }, data() { return { settings: { apiKey: "c845f0cd-98df-40dc-9d9b-a4d580c6e230", lang: "ru_RU", coordorder: "latlong", version: "2.1", }, cities: cities, mettro: metros, placeMark: null, }; }, methods: { initHandler(obj) { this.map = obj; // eslint-disable-next-line no-undef let mySearchControl = new ymaps.control.SearchControl({ options: { noPlacemark: true, }, }); this.map.controls.add(mySearchControl); this.map.events.add("click", (e) => { let coords = e.get("coords"); console.log(coords); this.map.geoObjects.removeAll(); this.getMetroByCoord(coords); this.assignCoordinates(coords); if (this.placeMark) { this.placeMark.geometry.setCoordinates(coords); } else { this.placeMark = this.createPlacemark(coords); this.map.geoObjects.add(this.placeMark); this.placeMark.events.add("dragend", () => { this.getAddress( this.placeMark.geometry.getCoordinates(), this.placeMark ); }); } this.getAddress(coords, this.placeMark); }); }, getMetroByCoord(coords) { // eslint-disable-next-line no-undef ymaps .geocode(coords, { // Ищем только станции метро. kind: "metro", // Запрашиваем не более 20 результатов. results: 3, }) .then((res) => { res.geoObjects.options.set("preset", "islands#redCircleIcon"); console.log(res.geoObjects.get(0).getAddressLine()); let metros = new Set(); res.geoObjects.each((metro) => { metros.add( metro.getAddressLine().split(",").pop().replace(" метро ", "") ); }); console.log(metros); this.$emit("update-metro", Array.from(metros)); // Добавляем коллекцию найденных геообъектов на карту. this.map.geoObjects.add(res.geoObjects); }); }, createPlacemark(coords) { // eslint-disable-next-line no-undef return new ymaps.Placemark( coords, { iconCaption: "поиск...", }, { preset: "islands#violetDotIconWithCaption", draggable: true, } ); }, // Определяем адрес по координатам (обратное геокодирование). getAddress(coords, myPlaceMark) { myPlaceMark.properties.set("iconCaption", "поиск..."); // eslint-disable-next-line no-undef ymaps.geocode(coords).then((res) => { var firstGeoObject = res.geoObjects.get(0); this.$emit("update-address", firstGeoObject.getAddressLine()); const city = firstGeoObject.getLocalities().length ? firstGeoObject.getLocalities() : ""; this.$emit("update-city", city[0]); console.log(city[0]); myPlaceMark.properties.set({ // Формируем строку с данными об объекте. iconCaption: [ // Название населенного пункта или вышестоящее административно-территориальное образование. firstGeoObject.getLocalities().length ? firstGeoObject.getLocalities() : firstGeoObject.getAdministrativeAreas(), // Получаем путь до топонима, если метод вернул null, запрашиваем наименование здания. firstGeoObject.getThoroughfare() || firstGeoObject.getPremise(), ] .filter(Boolean) .join(", "), // В качестве контента балуна задаем строку с адресом объекта. balloonContent: firstGeoObject.getAddressLine(), }); }); }, assignCoordinates(coords) { const coordinate = { lat: coords[0].toString(), lon: coords[1].toString(), }; this.$emit("update-coords", coordinate); }, updateMetro(event) { this.$emit("update-metro", event); }, }, }; </script> <style lang="scss" scoped> </style>
module FSMPack.Compile.Generator.Common open System open FSMPack.Compile.AnalyzeInputAssembly let __ = " " let indentLine count line = String.replicate count __ + line let msgpackTypes = dict [ typeof<unit>, "Nil" typeof<bool>, "Boolean" typeof<int>, "Integer" typeof<int64>, "Integer64" typeof<uint32>, "UInteger" typeof<uint64>, "UInteger64" typeof<single>, "FloatSingle" typeof<double>, "FloatDouble" typeof<string>, "RawString" typeof<byte[]>, "Binary" // TODO do I need to specialize these? (* typeof<_ array>, "ArrayCollection" *) (* typeof<IDictionary<_,_>>, "MapCollection" *) // TODO Extension ] type Field = { name : string typeFullName : string typ : Type } module TypeName = module Transform = let knownGenTypeNames = dict [ typedefof<Map<_,_>>, "Map" typedefof<_ list>, "List" typedefof<_ option>, "Option" ] /// Foo`2[[string, int]] -> Foo /// Bar`2 -> Bar /// Baz -> Baz let lexName (typName: string) = (typName.Split '`').[0] type FullNameNullReason = | GenericTypeParameter | ContainsGenPrmsNotTypeDef | ArrayWithGenPrms | Unknown let fullnameIsNullReason (typ: Type) = if typ.IsGenericTypeParameter then GenericTypeParameter else if typ.ContainsGenericParameters && typ.IsGenericType && not typ.IsGenericTypeDefinition then ContainsGenPrmsNotTypeDef else if typ.ContainsGenericParameters && typ.IsArray then ArrayWithGenPrms else Unknown // if a type and a module share a name, the module will be implicitly // suffixed with 'Module', e.g // ``` // type Foo = .. // module Foo = ... // ``` // will generate Foo and FooModule types let stripModuleSuffix (name: string) = name.Split(".") |> Array.map (fun segment -> let matched = Text.RegularExpressions.Regex.Match(segment, "(.+)Module$") if matched.Success then matched.Groups.[1].Value else segment ) |> String.concat "." /// Microsoft.Collections.FSharp`2[[string, int]] let fullCommonName (typ: Type) = if typ.FullName = null then match fullnameIsNullReason typ with | ContainsGenPrmsNotTypeDef -> typ.GetGenericTypeDefinition().FullName | ArrayWithGenPrms -> "'" + typ.Name | _ -> failwith <| sprintf "Type had null FullName: %A\nReason: %A" typ (fullnameIsNullReason typ) else typ.FullName /// MyNamespace.MyModule+MyType`2[[string, int]] let fullName (typ: Type) = match knownGenTypeNames.TryGetValue (generalize typ) with | true, typName -> typName | _ -> fullCommonName typ /// MyType`2 let simpleName (typ: Type) = match knownGenTypeNames.TryGetValue (generalize typ) with | true, typName -> typName | _ -> typ.Name let addArgsString (typ: Type) typName argMap = let args = typ.GetGenericArguments() |> Array.map argMap |> String.concat "," if args.Length > 0 then typName + "<" + args + ">" else typName /// MyTypeNameString -> MyTypeNameString<'A,'B> let addNamedArgs (typ: Type) typName = addArgsString typ typName (fun arg -> "'" + arg.Name) /// MyTypeNameString -> MyTypeNameString<_,_> let addAnonArgs (typ: Type) typName = addArgsString typ typName (fun _ -> "_") /// MyNamespace.MyModule+MyType -> MyNamespace.MyModule.MyType let canonName (typName: string) = typName.Replace ("+", ".") let declarableName (canonTypeName: string) = canonTypeName.Replace (".", "_") open Transform type GeneratorNames = { formatTypeNamedArgs : string formatTypeAnonArgs : string dataType : string dataTypeNamedArgs : string dataTypeAnonArgs : string } let getFullCanonName (typ: Type) = typ |> fullName |> lexName |> canonName |> stripModuleSuffix let getFullCommonName (typ: Type) = typ |> fullCommonName |> lexName |> canonName |> stripModuleSuffix let asFormatTypeName name = name |> declarableName |> (+) "FMT_" let getGeneratorNames (typ: Type) = let fullName = getFullCanonName typ let formatTypeName = fullName |> asFormatTypeName { formatTypeNamedArgs = formatTypeName |> addNamedArgs typ formatTypeAnonArgs = formatTypeName |> addAnonArgs typ dataType = fullName dataTypeNamedArgs = fullName |> addNamedArgs typ dataTypeAnonArgs = fullName |> addAnonArgs typ } /// If typ is generic parameter, then 'T else T let field (typ: Type) = if typ.IsGenericTypeParameter then typ |> simpleName |> (+) "'" else typ |> getFullCanonName |> addAnonArgs typ let writeCacheFormatLine (typ: Type) (names: TypeName.GeneratorNames) = if typ.IsGenericType then $"Cache<{names.dataTypeAnonArgs}>.StoreGeneric typedefof<{names.formatTypeAnonArgs}>" else $"Cache<{names.dataTypeAnonArgs}>.Store ({names.formatTypeNamedArgs}() :> Format<{names.dataTypeAnonArgs}>)" let getWriteFieldCall (field: Field) valueText = match msgpackTypes.TryGetValue field.typ with | true, mpType -> $"writeValue bw ({mpType} {valueText})" | _ -> $"Cache<{field.typeFullName}>.Retrieve().Write bw {valueText}" let getReadFieldCall (field: Field) assignVarText = match msgpackTypes.TryGetValue field.typ with | true, mpType -> $"let ({mpType} {assignVarText}) = readValue br &bytes" | _ -> $"let {assignVarText} = Cache<{field.typeFullName}>.Retrieve().Read(br, bytes)"
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Route, Router } from '@angular/router'; import { FormControl, FormGroup, FormBuilder, Validators } from '@angular/forms'; import { ApPortalService } from '@app/@core/services/ap-portal.service'; import { MatDialog } from '@angular/material/dialog'; import { DialogBoxComponent } from '@app/shared/dialog-box/dialog-box.component'; import { MatTableDataSource } from '@angular/material/table'; import { forkJoin, switchMap } from 'rxjs'; @Component({ selector: 'app-verify-screen', templateUrl: './verify-screen.component.html', styleUrls: ['./verify-screen.component.scss'] }) export class VerifyScreenComponent implements OnInit { public selectedRowImg: number; public form = this._formBuilder.group({ vendorName: ['', []], invoiceNumber: ['', []], invoiceDate: ['', []], dueDate: ['', []], paymentTerms: ['', []], poNumber: ['', []], netAmount: ['', []], totalAmount: ['', []], taxAmount: ['', []], currency: ['', []], shippingAmount: ['', []], items: ['', []] }); public selectedscreen = window.location.pathname public isCorrectionScreen = this.selectedscreen.split('/')[1] === 'invoice-correction' dataSource: any; displayedColumns: string[] columns: string[] cindex: number; constructor(private _router: Router, private _activatedRoute: ActivatedRoute, private _formBuilder: FormBuilder, private _apPortalService: ApPortalService, private _dialog: MatDialog) { this.selectedRowImg = -1 this.displayedColumns = []; this.columns = []; this.cindex = -1 } ngOnInit(): void { this._activatedRoute.params.subscribe(params => { this.selectedRowImg = params['id']; }); this.getInvoiceDetails() this.getColumns().then((cols: any) => { this.displayedColumns.unshift(...cols); this.columns = cols; }); } getInvoiceDetails() { this.getInvoiceData(); this.getInvoiceLineItems(); } getInvoiceData() { this._apPortalService.getInvoiceData(this.selectedRowImg).subscribe({ next: (data) => { this.form.patchValue({ vendorName: data['Vendor Name'], invoiceNumber: data['Invoice Number'], invoiceDate: data['Invoice Date'], dueDate: data['Due Date'], paymentTerms: data['Payment Terms'], poNumber: data['PO Number'], netAmount: data['Net Amount'], totalAmount: data['Total Amount'], taxAmount: data['Tax Amount'], currency: data['Currency'], shippingAmount: data['Shipping Amount'], items: data['Items'] }); } }) } getInvoiceLineItems() { this._apPortalService.getInvoiceLineItems(this.selectedRowImg).subscribe({ next: (data) => { this.dataSource = new MatTableDataSource(data) } }) } getColumns() { /*assume this is an api*/ return new Promise((resolve, reject) => { resolve(['Line Quantity', 'Line Amount', 'Invoice Number', 'Line Unit Price', 'Line Description']); }); } submit(formData: any) { if (formData.status === "VALID") { } } openDialog(isApproved?: boolean) { let formData: any = { 'Vendor Name': this.form.value.vendorName, 'Invoice Number': this.form.value.invoiceNumber, 'Invoice Date': this.form.value.invoiceDate, 'Due Date': this.form.value.dueDate, 'Payment Terms': this.form.value.paymentTerms, 'PO Number': this.form.value.poNumber, 'Net Amount': this.form.value.netAmount, 'Total Amount': this.form.value.totalAmount, 'Currency': this.form.value.currency, 'Shipping Amount': this.form.value.shippingAmount, 'Items': this.form.value.items, 'id': this.selectedRowImg } let data = { title: 'Confirmation', subTitle: 'Please add comment to approve the invoice', submitBtn: 'Approve' } let payload = { ...formData, "ApprovalPending": "FALSE" } if (!isApproved) { data = { title: 'Confirmation', subTitle: 'Please add comment to reject the invoice', submitBtn: 'Reject' } } if (this.isCorrectionScreen) { data = { title: 'Confirmation', subTitle: 'Are you sure , you want to send this invoice for approval', submitBtn: 'Approve' } payload = { ...formData, "ApprovalPending": "TRUE", "CorrectionNeeded": "FALSE" } } const dialogRef = this._dialog.open(DialogBoxComponent, { data: data }); dialogRef.afterClosed().subscribe(result => { if (result) { this._apPortalService.updateInvoiceDetails(payload).subscribe({ next: () => { this.dataSource.filteredData.forEach((e: any) => { this._apPortalService.updateInvoiceLineItems(e).subscribe({ next: () => { let url = this.isCorrectionScreen ? '/invoice-correction' : '/approve-invoice' this._router.navigate([url]) } }) }); } }) } }); } getRecord(row: any, index: any) { this.cindex = index } goBack() { let url = this.isCorrectionScreen ? '/invoice-correction' : '/approve-invoice' this._router.navigate([url]) } }
# 29CM_homework --- ### - 요구사항 - [x] 상품은 고유의 상품번호와 상품명, 판매가격, 재고수량 정보를 가지고 있습니다. - [x] 한 번에 여러개의 상품을 같이 주문할 수 있어야 한다. - [x] 상품번호, 주문수량은 반복적으로 입력 받을 수 있습니다. - [x] 주문은 상품번호, 수량을 입력받습니다. - 세부 요구사항 - [x] empty 입력(space + ENTER) 이 되었을 경우 해당 건에 대한 주문이 완료되고, 결제하는 것으로 판단합니다. - [x] 결지 시 재고 확인을 하여야 하며 재고가 부족할 경우 결제 시도하면 SoldOutException 이 발생되어야 합니다. - [x] 주문 금액이 5만원 미만일 경우 배송료 2,500원이 추가되어야 합니다. - [x] 주문이 완료되었을 경우 주문 내역과 주문 금액, 결제 금액 (배송비 포함) 을 화면에 display 합니다. - [x] 'q' 또는 'quit'을 입력하면 프로그램이 종료되어야 합니다. - [x] Test 에서는 반드시 multi thread 요청으로 SoldOutException 이 정상 동작하는지 단위테스트가 작성되어야 합니다. - [x] 상품의 데이터는 하단에 주어지는 데이터를 사용해주세요. - 데이터를 불러오는 방식은 자유입니다. - 코드에 포함되어도 좋고, 파일을 불러도 되고, in memory db를 사용하셔도 됩니다. - 하지만 상품에 대한 상품번호, 상품명, 판매가격, 재고수량 데이터는 그대로 사용하셔야 합니다. - 상품 데이터 csv 파일을 같이 제공합니다. --- ### - 프로젝트 구조 프로젝트 구조에서 게층형 구조를 사용하기 보다는 도메인을 기준으로 패키지를 나눠서 구현하였습니다. 패키지는 크게 3개로 나눴습니다. - app 패키지 - application이 run 돼었을 경우 처음으로 CLI 화면에 보이는 클래스를 정리해놓은 디렉터리입니다. - `view`: app 디렉터리에 위치함으로써 리턴되는 결과들을 CLI 화면에 표시되는 공간을 정리해놨습니다. - domain 패키지 - 핵심 로직들이 저장되는 디렉터리입니다. - `controller`, `enttiy`, `service`, `repository`, `dto`, `exception` 이 저장되는 공간입니다. - `controller`: 클라이언트로부터 요청이 들어오면 비즈니스 로직을 호출하는 역할을 담당합니다. - `service`: 비즈니스 로직을 처리하는 역할을 담당합니다. - `repository`: entity(객체)에 접근하는 역할을 담당합니다. - `entity`: 데이터의 모델을 관리하는 역할을 담당합니다.. - `dto`: 데이터를 전달하기 위한 단순한 객체를 담당하는 역할을 합니다. - `exception`: global exception을 상속받아 좀 더 구체적인 exception을 처리하는 역할을 담당합니다. - 도메인의 각각의 흐름을 간단하게 파악하기 위하여 Product, Order로 디렉터리를 나눴습니다. - global - 패키지 이름에서 알 수 있듯이 전역적으로 관리되어야 하는 부분에 대해서 관리해주는 디렉터리입니다. - `exception`, `factory`, `storage`, `util` 로 나눠서 구현하였습니다. - `exception`: domain 패키지 내부에서 관리되는 excpetion의 조상이 될만한 exception을 저장해줍니다. - `factory`: 생성자를 외부에서 생성하여 주입해주기 위하여 관리해주는 디렉터리입니다. - `storage`: storage는 초기에 생성되어야 하는 상품에 대한 정보를 application이 실행될 때 만드는 역할을 합니다. - `util`: 입력(Console)받기 위한 클래스를 저장해주기 위하여 생성한 디렉터리 입니다. --- ### - 구현 방향 최대한 Spring 프레임워크의 MVC 패턴과 학습하였던 JPA를 기반으로 모방하여 설계하였습니다. - **Model** : `Product`와 `Order` 엔티티를 표현하였으며 `OrderService`와 `ProductService`는 비즈니스 로직을 담당하였습니다. </br> Service에서 모델에 대해서 찾을 경우 `findByProductId` 또는 `findAll()` 과 같이 리스트를 뽑아야할 경우에는 `Repository`에서 찾아서 반환하도록 하였습니다. - **View** : 사용자에게 정보를 시각적으로 전달하기 위하여 View는 따로 패키지로 빼서 관리하였습니다. </br> 각각 사용자의 상품번호와 수량 입력, 상품 목록, 주문 목록을 담당하며 사용자에게 보여주었습니다. - **Controller** : 사용자의 입력을 받아와서 비즈니스 로직을 Service 계층으로 보내주는 역할을 하도록 구현하였습니다. </br> 또한 비즈니스 로직을 받아와서 사용자에게 보여지는 View로 보내주는 역할을 하였습니다. - **SingletonFactory** : 스프링 IOC 컨테이너처럼 관리하고자 하였습니다. 생성자를 외부에서 생성하여 주입하는 형식으로 진행하고 싶어 `SingletonFactory`를 만들어 객체의 외부에서 생성하여 주입해주는 방식으로 하였습니다. </br> 싱글톤을 만드는 형식에서는 Bill Pugh가 고안한 방식으로 진행하였는데, 이유로는 멀티쓰레드 환경에서도 안전하며 Lazy loading도 가능하여 메모리 누수에도 효과적인 방법이라 가장 적합한 싱글톤 생성 기법이라고 셍각하였습니다.
import React from 'react'; import './Blog.css' import { Button } from 'react-bootstrap'; import { FaDownload } from 'react-icons/fa'; import Pdf from "react-to-pdf"; const Blog = () => { const ref = React.createRef(); const options = { orientation: 'landscape', unit: 'in', format: [13,10] }; return ( <> <div> <Pdf targetRef={ref} filename="blog.pdf" options={options}> {({ toPdf }) => <Button onClick={toPdf} className='download-btn' variant="outline-secondary"><FaDownload/></Button>} </Pdf> </div> <div ref={ref} className='question-container'> <h1 className='p-7 text-center'>Blog Questions</h1> <div className='question'> <h4 className='font-bold'>Question 1: Tell us the differences between uncontrolled and controlled components?</h4> <p><span className='font-medium'>Answer:</span> <br /> Uncontrolled components are form inputs (such as text inputs or checkboxes) whose values are managed by the DOM, rather than by React. This means that when the user interacts with the input (by typing in a text box, for example), the value of the input is updated directly in the DOM, and not in React's state. Uncontrolled components are generally simpler to set up than controlled components, but they can be harder to work with if you need to access or update their values from React. <br /> Controlled components, on the other hand, are form inputs whose values are managed by React. This means that the value of the input is stored in React's state, and is only updated when the state changes. This allows you to easily access and update the value of the input from within your React code, and to perform actions based on the current value of the input. Controlled components are generally more powerful and flexible than uncontrolled components, but they can also be more complex to set up. </p> </div> <div className='question'> <h4 className='font-bold'>Question 2: How to validate React props using PropTypes?</h4> <p><span className='font-medium'>Answer:</span> <br /> PropTypes is a built-in library in React that allows you to validate the props passed to a component. You can use PropTypes to specify the type and shape of props that your component expects, and to provide error messages if the props do not match the expected type or shape. <br /> </p> </div> <div className='question'> <h4 className='font-bold'>Question 3: Tell us the difference between nodejs and express js?</h4> <p><span className='font-medium'>Answer:</span> <br /> Node.js and Express.js are both popular technologies used in building server-side applications. Node.js is a runtime environment that allows developers to build server-side applications using JavaScript, while Express.js is a web application framework that is built on top of Node.js. <br /> Here are some of the key differences between Node.js and Express.js: <br /> Routing: While Node.js provides basic routing capabilities, Express.js provides a more advanced routing system that allows developers to define routes for handling HTTP requests. This makes it easier to organize and manage the different parts of a web application. <br /> Middleware: Express.js provides a middleware system that allows developers to add functionality to their application at various stages of the request/response cycle. This makes it easier to add features such as authentication, error handling, and logging to a web application. </p> </div> <div className='question'> <h4 className='font-bold'>Question 4: What is a custom hook, and why will you create a custom hook??</h4> <p><span className='font-medium'>Answer:</span> <br /> A custom hook in React is a function that encapsulates reusable logic, and can be shared between multiple components. Custom hooks are a way to extract common functionality from components and share it between them, without having to duplicate code. Custom hooks can be used to perform a wide variety of tasks, such as managing state, handling events, and making network requests. By creating a custom hook, you can abstract away complex logic and provide a simpler interface for your components to use. </p> </div> </div> </> ); }; export default Blog;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> </body> <script> //for循环内部声明啦一个变量,在循环内操作给同一个变量多次赋值。 //在循环开始声明的变量i ; 之后每次循环都操作这个变量,“也就是对一个变量的重新赋值‘ ,因此i在最后只会存储一个值’所以在添加时间时等同于给一个元素重新添加啦多次事件‘。 var lis = document.querySelectorAll('li'); for(var i = 0 ; i<lis.length ; i++){ (function(i){ lis[i].onclick = function(){ console.log('我是'+i); } })(i); } //执行原理 //调用数组的每一个元素,将元素传递给回调函数"foreach没有变量名但实际上每次循环都会创建了一个独立的不同的变量,因此每个变量储存的本次数组元素,所以相互之间不会影响” //注意:forEach 内不能使用break 结束循环”使用return“,return仅仅是结束函数,不能返回任何内容。 // Array.from(lis).forEach(function(item,index,lis){ // item.onclick = function(){ // item.onclick = function(){ // if(index >3 ){ // return; // } // console.log(index); // } // } // }) </script> </html>
"use client"; import { COLORS } from "@/app/colors"; import { Avatar, Box, Button, Card, CardBody, CardHeader, Divider, FormControl, FormLabel, GridItem, Heading, Input, Radio, RadioGroup, SimpleGrid, Stack, Text, } from "@chakra-ui/react"; import { useRouter } from "next/navigation"; import React, { useContext, useEffect, useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import { FaRegCalendarAlt } from "react-icons/fa"; import { FaUserDoctor, FaMapLocationDot } from "react-icons/fa6"; import { CTX } from "@/context/context"; import { clearAppointmentDetails, postBookAppointmentAction, postRecheduleAppointmentAction, } from "@/store/actions/patient/appointmentActions"; import axios from "axios"; import LoadingBackdrop from "@/components/Loader"; const CryptoJS = require("crypto-js"); var crypto = require("crypto"); function page({ searchParams }: any) { const dispatch: any = useDispatch(); const authContext: any = useContext(CTX); const { userDetails, isAuthenticated }: any = authContext; const appointmentData = useSelector( (state: any) => state?.appointmentData?.appointmentBooking?.data ); const appointmentLoader = useSelector( (state: any) => state?.appointmentData?.appointmentBooking?.loading ); const router = useRouter(); // const searchParams: any = router?.query; const [bookFor, setBookFor]: any = useState("1"); const [paymentMethod, setPaymentMethod]: any = useState("1"); const [patientInfo, setPatientInfo] = useState({ full_name: "", email: "", contact_number: "", }); const [loading, setLoading] = useState(false); const [issue, setIssue] = useState(""); const [orderId, setOrderId] = useState(""); useEffect(() => { setPatientInfo((info: any) => ({ ...info, full_name: `${userDetails?.first_name} ${userDetails?.last_name}`, email: userDetails?.email, contact_number: userDetails?.phone_number, })); }, [isAuthenticated]); const handleBookAppointment = async ({ orderId }: any) => { setLoading(true); const payload = { doctorId: searchParams?.doctorId, patientId: userDetails?._id, date: searchParams?.selectedDate, time: searchParams?.selectedTimeSlot, onlineConsultation: searchParams?.onlineConsultation === "true" ? true : false, location: searchParams?.location, status: "Confirmed", patientInfo: patientInfo, paymentMode: paymentMethod === "1" ? "Online" : "pay_later", consultationFee: searchParams?.consultationFee, issue: issue, paymentId: orderId, }; var encryptedData = CryptoJS.AES.encrypt( JSON.stringify(payload), "pestohealth" ).toString(); await dispatch( postBookAppointmentAction({ appointmentData: encryptedData }) ); }; const loadRazorpay = (src: string) => { return new Promise((resolve) => { const script = document.createElement("script"); script.src = src; script.onload = () => { resolve(true); }; script.onerror = () => { resolve(false); }; document.body.appendChild(script); }); }; const handleCheckout = async () => { const res = await loadRazorpay( "https://checkout.razorpay.com/v1/checkout.js" ); if (!res) { alert("Failed to load Razorpay SDK. Are you online?"); return; } const { data } = await axios.post( "https://node-pesto-health.onrender.com/api/payment/checkout", { amount: searchParams?.consultationFee, } ); console.log("data", data); var options = { key: "rzp_test_5Jwy12U4I4bVdD", // Enter the Key ID generated from the Dashboard amount: data.amount, // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise currency: "INR", name: "Pesto Health", description: "Test Transaction", image: "https://example.com/your_logo", order_id: data.id, //This is a sample Order ID. Pass the `id` obtained in the response of Step 1 handler: function (response: { razorpay_payment_id: any; razorpay_order_id: any; razorpay_signature: any; }) { const body = response.razorpay_order_id + "|" + response.razorpay_payment_id; const generated_signature = crypto .createHmac("sha256", "0yBvx3BPsmqXm9oQtQ5869Wb") .update(body.toString()) .digest("hex"); if (generated_signature == response.razorpay_signature) { setOrderId(response.razorpay_order_id); handleBookAppointment({ orderId: response.razorpay_order_id }); } else { console.log("response", "payment failed"); } }, prefill: { name: `${userDetails?.first_name} ${userDetails?.last_name}`, email: userDetails?.email, contact: userDetails?.phone_number, }, notes: { address: "Razorpay Corporate Office", }, theme: { color: COLORS.primary, }, }; // @ts-ignore var rzp1 = new window.Razorpay(options); // @ts-ignore rzp1.open(); }; useEffect(() => { if (appointmentData?.status === 201) { router.replace( `/patient-home/bookappointment/appointmentstatus?id=${appointmentData?.data?.data?.appointmentId}&date=${appointmentData?.data?.data?.date}&time=${appointmentData?.data?.data?.time}&doctorId=${appointmentData.data?.data?.doctorId}` ); setLoading(false); // router.push({ // pathname: "/dashboard/patient/appointments/appointmentstatus", // query: { appointmentId: res?.data?.data?.appointmentId }, // }); } return () => { dispatch(clearAppointmentDetails()); }; }, [appointmentData]); console.log("paymentMethod", typeof paymentMethod); return ( <Box p={{ base: 4, sm: 16 }} pt={{ base: 2, sm: 8 }}> {appointmentLoader && <LoadingBackdrop />} <Text fontSize={"2xl"} fontWeight={"700"}> Booking Summary </Text> <SimpleGrid gap={8} h={"100vh"} dir="row" columns={{ sm: 1, md: 2 }} mt={8} > <GridItem> <Card maxW={"md"} borderRadius={20} boxShadow={"0px 4px 4px 0px rgba(0, 0, 0, 0.25)"} > <CardHeader borderBottomWidth={1}> <Stack direction={{ base: "column", sm: "row" }} alignItems={{ base: "flex-start", sm: "center" }} gap={10} > <Avatar name="Dan Abrahmov" src={ searchParams?.doctorGender === "male" ? "https://www.citizenshospitals.com/static/uploads/130789a4-764e-4ee3-88fe-68f9278452d6-1692966652977.png" : "https://img.freepik.com/premium-photo/indian-female-doctor-indian-nurse_714173-201.jpg" } size={"xl"} /> <Box> <Text fontSize={"2xl"} fontWeight={"700"} color={COLORS.secondary} > Dr. {searchParams?.doctorName} </Text> <Text fontSize={"sm"} // my={2} color={COLORS.text_gray} fontWeight={"400"} > {searchParams?.specialization} </Text> </Box> </Stack> </CardHeader> <CardBody> <Stack direction={"row"} alignItems={"center"} gap={{ base: 5, sm: 10 }} > <FaRegCalendarAlt size={"27px"} color={COLORS.primary} /> <Stack direction={"row"} alignItems={"center"}> <Text>{searchParams?.selectedDate}</Text> <Text>{searchParams?.selectedTimeSlot}</Text> </Stack> </Stack> <Divider orientation="horizontal" my={8} /> <Stack direction={"row"} alignItems={"center"} gap={{ base: 5, sm: 10 }} > <FaUserDoctor size={"27px"} color={COLORS.primary} /> <Text> {searchParams?.onlineConsultation === "true" ? "Online Consultation" : "In Clinic"} </Text> </Stack> <Divider orientation="horizontal" my={8} /> <Stack direction={"row"} alignItems={"center"} gap={10}> <FaMapLocationDot size={"27px"} color={COLORS.primary} /> <Text>{searchParams?.address}</Text> </Stack> </CardBody> </Card> </GridItem> <GridItem maxH={"100vh"} overflowY={"scroll"} borderRadius={20} boxShadow={"0px 4px 4px 0px rgba(0, 0, 0, 0.25)"} p={{ base: 4, sm: 8 }} > <RadioGroup defaultValue={bookFor} onChange={(e) => setBookFor(e)}> <Stack spacing={5}> <Radio value="1" size={"lg"}> Book for myself </Radio> <Radio value="2" size={"lg"}> Book for someone else </Radio> </Stack> </RadioGroup> <Divider orientation="horizontal" borderBottomWidth={2} my={8} /> <FormControl> <FormLabel> Describe Your Health Issue</FormLabel> <Input placeholder="Fever, Diziness ....." type="text" value={issue} onChange={(e) => setIssue(e.target.value)} /> </FormControl> <Divider orientation="horizontal" borderBottomWidth={2} my={8} /> <Text size={"md"} mb={4}> Confirm your details </Text> <FormControl isRequired> <FormLabel>Full name</FormLabel> <Input placeholder="Aditya D Tarar" type="text" value={patientInfo.full_name} onChange={(e) => setPatientInfo((value) => ({ ...value, full_name: e.target.value, })) } /> <FormLabel>Email</FormLabel> <Input placeholder="aditya@gmail.com" type="email" value={patientInfo.email} onChange={(e) => setPatientInfo((value) => ({ ...value, email: e.target.value, })) } /> <FormLabel>Contact Number</FormLabel> <Input placeholder="+91 8412962312" type="number" value={patientInfo.contact_number} onChange={(e) => setPatientInfo((value) => ({ ...value, contact_number: e.target.value, })) } /> </FormControl> <Divider orientation="horizontal" borderBottomWidth={2} my={8} /> <RadioGroup defaultValue={paymentMethod} onChange={(e) => setPaymentMethod(e)} > <Text size={"md"} mb={4}> Choose payment method </Text> <Stack spacing={5}> <Radio value="1" size={"lg"}> Pay online {searchParams?.consultationFee} ₹ </Radio> <Radio value="2" size={"lg"}> Pay {searchParams?.consultationFee} ₹ later at clinic </Radio> </Stack> </RadioGroup> <Button style={{ width: "70%" }} mt={8} onClick={() => paymentMethod === "1" ? handleCheckout() : handleBookAppointment({ orderId: "" }) } > Confirm Visit </Button> </GridItem> </SimpleGrid> </Box> ); } export default page;
package com.example.backend.controller.bookboardcontroller; import com.example.backend.controller.Controller; import com.example.backend.dao.BookBoardDao; import com.example.backend.dao.BookDao; import com.example.backend.model.Book; import com.example.backend.model.BookBoard; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Map; @MultipartConfig public class BookBoardRegisterController implements Controller { BookBoardDao bookBoardDao =new BookBoardDao(); BookDao bookDao = new BookDao(); @Override public void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { BookBoard bookboard = new BookBoard(); // 파일 업로드 처리 Part filePart = request.getPart("image"); if (filePart != null) { String filename = extractFileName(filePart); String savePath = request.getSession().getServletContext().getRealPath("/"); String imageUrl = request.getContextPath() + "/" + filename; File fileSaveDir = new File(savePath); if (!fileSaveDir.exists()) { fileSaveDir.mkdir(); } //파일 저장 filePart.write(savePath + File.separator + filename); //파일 경로를 BookBoard 객체에 저장 bookboard.setFilePath(imageUrl); } // 여기서 파일을 저장하고 파일의 URL을 얻을 수 있습니다. // 이 부분은 실제로 파일을 저장하고 데이터베이스에 파일의 URL을 저장하는 로직으로 변경해야 합니다. // JSON 데이터 처리 Part jsonPart = request.getPart("bookData"); if(jsonPart != null){ String jsonData = getJsonData(request); ObjectMapper objectMapper = new ObjectMapper(); try { // JSON 데이터를 Map<String, String>으로 파싱 Map<String, String> jsonMap = objectMapper.readValue(jsonData, new TypeReference<Map<String, String>>() {}); // 이후에 필요한 정보를 jsonMap에서 읽어와서 bookboard 객체에 설정 String title = jsonMap.get("title"); String text = jsonMap.get("text"); String userId = jsonMap.get("user_id"); String place = jsonMap.get("place"); String bookStatus = jsonMap.get("book_status"); // jsonData를 사용하여 데이터베이스에 필요한 처리 수행 Book book = bookDao.findByName(title); bookboard.setUser_id(userId); bookboard.setISBN(book.getIsbn()); bookboard.setTitle(title); bookboard.setPrice(book.getPrice()); bookboard.setPlace(place); bookboard.setContent(text); bookboard.setBook_status(Integer.valueOf(bookStatus)); bookboard.setIs_sale(true); } catch (JsonProcessingException e) { // JSON 파싱 오류 처리 response.setStatus(HttpServletResponse.SC_BAD_REQUEST); e.printStackTrace(); return; // 오류 발생 시 종료 } } // 성공적인 응답 int querySuccessCheck = bookBoardDao.register(bookboard); response.getWriter().write("{\"querySuccessCheck\" : \"" + querySuccessCheck + "\"}"); } catch (Exception e) { // 오류 응답 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); e.printStackTrace(); } } private String extractFileName(Part part) { String contentDisp = part.getHeader("content-disposition"); String[] items = contentDisp.split(";"); for (String item : items){ if(item.trim().startsWith("filename")){ return item.substring(item.indexOf("=") + 2, item.length() - 1); } } return ""; } private String getJsonData(HttpServletRequest request) throws IOException { StringBuilder sb = new StringBuilder(); String line; try { request.setCharacterEncoding("UTF-8"); Part jsonPart = request.getPart("bookData"); if (jsonPart != null) { InputStream inputStream = jsonPart.getInputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { sb.append(new String(buffer, 0, bytesRead, "UTF-8")); } } } catch (Exception e) { e.printStackTrace(); } return sb.toString(); } }
import mongoose from "mongoose"; // Define a MongoDB schema for driver data const DriverSchema = new mongoose.Schema( { // Name of the Driver username: { type: String, required: [true, "Please add a name"], }, // Email of the driver email: { type: String, required: [true, "Please add an email"], unique: true, trim: true, // Regular expression for email validation match: [ /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, "Please enter a valid email", ], }, // Password of the driver password: { type: String, required: [true, "Please add a password"], // Password length constraints minLength: [6, "Password must be at least 6 characters"], }, // Phone of the driver phone: { type: String, required: [true, "Please add a phone number"], default: "+91", }, savedInfo: [{ type: mongoose.Schema.Types.ObjectId, ref: "drivers" }], }, { // Automatically add 'createdAt' and 'updatedAt' timestamps timestamps: true, } ); // Create a Driver model based on the schema export const DriverModel = mongoose.model("drivers", DriverSchema);
package com.example.springapp.controller; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.example.springapp.model.Student; import com.example.springapp.service.StudentService; @RestController public class StudentController { private StudentService studentService; public StudentController(StudentService studentService) { this.studentService = studentService; } @PostMapping("/student") public ResponseEntity<Student> saveStudent(@RequestBody Student student) { if(studentService.saveStudent(student)) return new ResponseEntity<>(student, HttpStatus.CREATED); else return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @GetMapping("/student") public ResponseEntity<List<Student>> getStudents() { List<Student> studentList = studentService.getStudents(); if(studentList.isEmpty()) return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); else return new ResponseEntity<>(studentList, HttpStatus.OK); } @GetMapping("/student/{studentId}") public ResponseEntity<Student> getStudentById(@PathVariable("studentId") int studentId) { Student student = studentService.getStudentById(studentId); if(student == null) return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); else return new ResponseEntity<>(student, HttpStatus.OK); } @PutMapping("/student/{studentId}") public ResponseEntity<Student> updateStudent(@PathVariable("studentId") int studentId, @RequestBody Student student) { Student updatedStudent = studentService.updateStudent(studentId, student); if(updatedStudent != null) return new ResponseEntity<>(updatedStudent, HttpStatus.OK); else return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } @DeleteMapping("/student/{studentId}") public ResponseEntity<Boolean> deleteStudent(@PathVariable("studentId") int studentId) { if(studentService.deleteStudent(studentId)) return new ResponseEntity<>(true, HttpStatus.OK); else return new ResponseEntity<Boolean>(false, HttpStatus.INTERNAL_SERVER_ERROR); } }
# app/models/genre.py from app import db from .base_model import BaseModel class GenreModel(BaseModel): __tablename__ = "genres" id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(255), nullable=False, unique=True, index=True) description = db.Column(db.Text, nullable=False) imageref = db.Column(db.String(255)) def caption(self): return f"{self.name}" def to_dict(self) -> dict: instance_data = super().to_dict() instance_data.update( { "name": self.name, "description": self.description, "imageref": self.imageref, } ) return instance_data @classmethod def from_dict(cls, data: dict) -> "GenreModel": genre_model = super().from_dict(data) genre_model.name = data.get("name", "") genre_model.description = data.get("description", "") genre_model.imageref = data.get("imageref", "") return genre_model def __repr__(self) -> str: return f"<GenreModel id={self.id}, name='{self.name}'>"
import { mkdirSync } from 'fs' import path from 'path' import type { BufferedWriteStream } from './stream' import { createBufferedWriteStream } from './stream' export type StringDictionary<T = unknown> = { [index: string]: T } const crs = 'urn:ogc:def:crs:OGC:1.3:CRS84' const geojsonStart = `{ "type": "FeatureCollection", "crs": { "type": "name", "properties": { "name": "${crs}" } }, "features": [` const geojsonEnd = ']}' export default class WritePool { private encoding: BufferEncoding private toGeoJson: boolean private writeStreams: StringDictionary<BufferedWriteStream> = {} constructor(encoding: BufferEncoding, toGeoJson: boolean) { this.encoding = encoding this.toGeoJson = toGeoJson } /** Returns a `WriteStream` for the given file and opens a new one * if there is none open yet. */ private getWriteStream(filePath: string): BufferedWriteStream { let stream = this.writeStreams[filePath] if (!stream) { // Create directory mkdirSync(path.dirname(filePath), { recursive: true }) stream = createBufferedWriteStream(filePath, 2, this.encoding) if (this.toGeoJson) { // Append start of GeoJSON stream.write(geojsonStart) } this.writeStreams[filePath] = stream } return stream } write(filePath: string, content: string): void { const stream = this.getWriteStream(filePath) stream.write(`${content}${this.toGeoJson ? ',' : ''}\n`) } /** Closes all created instances of `WriteStream` and returns * the corresponding file paths. */ async close(): Promise<string[]> { const closings = Object.values(this.writeStreams).map(async stream => { if (this.toGeoJson) { // Get last line const withCommaNewLine = stream.getBuffer(0) // Remove comma and new line const withoutCommaNewLine = withCommaNewLine.substring( 0, withCommaNewLine.length - 2 ) // Add new line const withoutComma = `${withoutCommaNewLine}\n` // Set line without comma stream.setBuffer(0, withoutComma) // Append end of GeoJSON stream.write(geojsonEnd) } await stream.close() return stream.getPath() as string }) return await Promise.all(closings) } }