text
stringlengths
184
4.48M
import { OrderStatus } from '@bxtickets/common'; import { Types } from 'mongoose'; import request from 'supertest'; import { app } from '../../app'; import { Order } from '../../models/order'; import { natsWrapper } from '../../nats'; import { createTicket } from './index.test'; it('marks an order as cancelled', async () => { const ticket = await createTicket(); const user = global.getCookie(); const { body: order } = await request(app) .post('/api/orders') .set('Cookie', user) .send({ ticketId: ticket.id }) .expect(201); await request(app) .patch(`/api/orders/${order.id}`) .set('Cookie', user) .send() .expect(204); const cancelledOrder = await Order.findById(order.id); expect(cancelledOrder!.status).toEqual(OrderStatus.CancelledByUser); }); it('returns 404 if the order is not found', async () => { const orderId = Types.ObjectId(); await request(app) .patch(`/api/orders/${orderId}`) .set('Cookie', global.getCookie()) .send() .expect(404); }); it("returns an error if an user tries to cancel another user's order", async () => { const ticket = await createTicket(); const user = global.getCookie(); const { body: order } = await request(app) .post('/api/orders') .set('Cookie', user) .send({ ticketId: ticket.id }) .expect(201); await request(app) .patch(`/api/orders/${order.id}`) .set('Cookie', global.getCookie()) .send() .expect(401); }); it('emits an order cancelled event', async () => { const ticket = await createTicket(); const user = global.getCookie(); const { body: order } = await request(app) .post('/api/orders') .set('Cookie', user) .send({ ticketId: ticket.id }) .expect(201); await request(app) .patch(`/api/orders/${order.id}`) .set('Cookie', user) .send() .expect(204); expect(natsWrapper.client.publish).toHaveBeenCalled(); });
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Copyright (C) 2011-2020 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. Author Alexander Jarosch research@alexj.at \*---------------------------------------------------------------------------*/ #include "muI.H" #include "addToRunTimeSelectionTable.H" #include "surfaceFields.H" #include "fvcGrad.H" // * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * // namespace Foam { namespace viscosityModels { defineTypeNameAndDebug(muI, 0); addToRunTimeSelectionTable ( viscosityModel, muI, dictionary ); } } // * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * * // Foam::tmp<Foam::volScalarField> Foam::viscosityModels::muI::calcNu() const { const objectRegistry& db = U_.db(); if (db.foundObject<volScalarField>("p")) { Info<< "Calculate mu(I) based on pressure" << endl; return ( max( min( (mu_*peff_)/(2.0*rhog_*normD_), nuMax_ ), nuMin_ ) ); } else{ Info<< "Pressure not found for mu(I), return zero" << endl; return tmp<volScalarField> ( new volScalarField ( IOobject ( "nuis0", U_.time().timeName(), U_.db(), IOobject::NO_READ, IOobject::NO_WRITE, false ), U_.mesh(), dimensionedScalar("nuis0", dimViscosity, 0.0) ) ); } } Foam::tmp<Foam::volScalarField> Foam::viscosityModels::muI::calcMu() const { const objectRegistry& db = U_.db(); if (db.foundObject<volScalarField>("p")) { return ( (mus_*I0_ + mud_*I_)/ (I0_ + I_) ); } else { Info<< "Pressure not found for mu(I), return mus" << endl; return mus_*calcI(); } } Foam::tmp<Foam::volScalarField> Foam::viscosityModels::muI::calcI() const { const objectRegistry& db = U_.db(); if (db.foundObject<volScalarField>("p")) { // Info<< "Calculate I based on pressure" << endl; return ( 2.0*dg_*normD_*pow(peff_/rhog_, -0.5) ); } else { Info<< "Pressure not found for I, return zero" << endl; return tmp<volScalarField> ( new volScalarField ( IOobject ( "II0", U_.time().timeName(), U_.db(), IOobject::NO_READ, IOobject::NO_WRITE, false ), U_.mesh(), dimensionedScalar("II0", dimless, 0.0) ) ); } } Foam::tmp<Foam::volScalarField> Foam::viscosityModels::muI::calcPeff() const { const objectRegistry& db = U_.db(); const Time& runTime= db.time(); if (db.foundObject<volScalarField>("p") && runTime.timeIndex() > 1) { // Info<< "Calculate I based on pressure" << endl; const volScalarField& ptot = U_.mesh().lookupObject<volScalarField>("p"); const volScalarField& gh = U_.mesh().lookupObject<volScalarField>("gh"); if (rmHydAirP_) { Info<< "Hydrostatic pressure of air phase removed" << endl; return max(ptot - rhoAir_*gh, pMin_); } else { return max(ptot, pMin_); } } else { Info<< "Effective pressure not calculated, return zero" << endl; return tmp<volScalarField> ( new volScalarField ( IOobject ( "peff0", U_.time().timeName(), U_.db(), IOobject::NO_READ, IOobject::NO_WRITE, false ), U_.mesh(), dimensionedScalar("peff0", dimPressure, SMALL) ) ); } } Foam::tmp<Foam::volScalarField> Foam::viscosityModels::muI::calcNormD() const { // note this is different than the classical OpenFOAM strainRate return max(mag(symm(fvc::grad(U_)))/sqrt(2.0), dimensionedScalar ("vSmall", dimless/dimTime, VSMALL)); } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // Foam::viscosityModels::muI::muI ( const word& name, const dictionary& viscosityProperties, const volVectorField& U, const surfaceScalarField& phi ) : viscosityModel(name, viscosityProperties, U, phi), muICoeffs_(viscosityProperties.optionalSubDict(typeName + "Coeffs")), mus_("mus", dimless, muICoeffs_), mud_("mud", dimless, muICoeffs_), I0_("I0", dimless, muICoeffs_), dg_("dg", dimLength, muICoeffs_), rhog_("rhog", dimDensity, muICoeffs_), nuMax_("nuMax", dimViscosity, muICoeffs_), nuMin_("nuMin", dimViscosity, muICoeffs_), pMin_("pMin", dimPressure, muICoeffs_), rhoAir_("rhoAir", dimDensity, muICoeffs_), rmHydAirP_(muICoeffs_.lookupOrDefault<Switch>("rmHydAirP", false)), nu_ ( IOobject ( name, U_.time().timeName(), U_.db(), IOobject::NO_READ, IOobject::AUTO_WRITE ), calcNu() ), mu_ ( IOobject ( "mu", U_.time().timeName(), U_.db(), IOobject::NO_READ, IOobject::AUTO_WRITE ), calcMu() ), I_ ( IOobject ( "I", U_.time().timeName(), U_.db(), IOobject::NO_READ, IOobject::AUTO_WRITE ), calcI() ), peff_ ( IOobject ( "peff", U_.time().timeName(), U_.db(), IOobject::NO_READ, IOobject::AUTO_WRITE ), calcPeff() ), normD_ ( IOobject ( "normD", U_.time().timeName(), U_.db(), IOobject::NO_READ, IOobject::AUTO_WRITE ), calcNormD() ) {} // * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * * // bool Foam::viscosityModels::muI::read ( const dictionary& viscosityProperties ) { viscosityModel::read(viscosityProperties); muICoeffs_ = viscosityProperties.optionalSubDict(typeName + "Coeffs"); muICoeffs_.lookup("mus") >> mus_; muICoeffs_.lookup("mud") >> mud_; muICoeffs_.lookup("I0") >> I0_; muICoeffs_.lookup("dg") >> dg_; muICoeffs_.lookup("rhog") >> rhog_; muICoeffs_.lookup("nuMax") >> nuMax_; muICoeffs_.lookup("nuMin") >> nuMin_; muICoeffs_.lookup("pMin") >> pMin_; muICoeffs_.lookup("rmHydAirP_") >> rmHydAirP_; muICoeffs_.lookup("rhoAir") >> rhoAir_; return true; } // ************************************************************************* //
import { Button, Divider, Flex, FormControl, FormLabel, Input, Stack, } from "@chakra-ui/react"; import React, { useRef, useState } from "react"; import { User } from "../../types/user"; import UserImageBox from "./UserImageBox"; type EditProfileInputsProps = { selectedUser: User; loading: boolean; handleEditUser: (user: User, selectedFile?: string) => void; handleRemovePhoto: (user: User) => void; }; const EditProfileInputs: React.FC<EditProfileInputsProps> = ({ selectedUser, loading, handleEditUser, handleRemovePhoto, }) => { const [selectedFile, setSelectedFile] = useState(""); const [updateUserForm, setUpdateUserForm] = useState<User>(selectedUser); const selectedFileRef = useRef<HTMLInputElement>(null); const onSelectImage = (event: React.ChangeEvent<HTMLInputElement>) => { const reader = new FileReader(); if (event.target.files?.[0]) { reader.readAsDataURL(event.target.files[0]); } reader.onload = (readerEvent) => { if (readerEvent.target?.result) { setSelectedFile(readerEvent.target?.result as string); } }; }; const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => { setUpdateUserForm((prev) => ({ ...prev, [event.target.name]: event.target.value, })); }; const handleSubmit = () => { handleEditUser(updateUserForm, selectedFile); }; const handleRemove = () => { if (selectedFile) { setSelectedFile(""); } handleRemovePhoto(selectedUser); }; return ( <Flex width="100%" direction="column"> <Flex align="center" justify="center" width="100%"> <Stack align="center" justify="center"> <UserImageBox selectedFile={selectedFile} imageURL={selectedUser.imageURL} /> <input ref={selectedFileRef} type="file" hidden onChange={onSelectImage} /> <Stack direction="row" spacing={2} align="center" justify="center"> <Button height="30px" variant="link" onClick={() => selectedFileRef.current?.click()} > Upload Photo </Button> {(selectedUser.imageURL || selectedFile) && ( <> <Divider orientation="vertical" color="gray" height="18px" /> <Button height="30px" variant="link" onClick={handleRemove}> Remove Photo </Button> </> )} </Stack> </Stack> </Flex> <Flex p={6}> <FormControl color="#aaaaaa" onSubmit={handleSubmit}> <Stack spacing={4}> <Flex direction="column"> <FormLabel>Username</FormLabel> <Input type="text" name="displayName" width="100%" variant="flushed" maxLength={32} borderColor="#aaaaaa" placeholder={selectedUser.displayName} _placeholder={{ color: "#cbd5e0" }} onChange={handleChange} /> </Flex> <Flex direction="column"> <FormLabel>Email</FormLabel> <Input type="text" name="email" width="100%" variant="flushed" maxLength={254} color="#cbd5e0" borderColor="#aaaaaa" placeholder={selectedUser.email} _placeholder={{ color: "#cbd5e0" }} onChange={handleChange} /> </Flex> <Flex direction="column"> <FormLabel>Bio</FormLabel> <Input type="text" name="bio" width="100%" variant="flushed" color="#cbd5e0" maxLength={140} borderColor="#aaaaaa" placeholder={selectedUser.bio} _placeholder={{ color: "#cbd5e0" }} onChange={handleChange} /> </Flex> <Flex direction="column"> <FormLabel>School</FormLabel> <Input type="text" name="school" width="100%" variant="flushed" color="#cbd5e0" maxLength={64} borderColor="#aaaaaa" placeholder={selectedUser.school} _placeholder={{ color: "#cbd5e0" }} onChange={handleChange} /> </Flex> <Flex direction="column"> <FormLabel>Company</FormLabel> <Input type="text" name="company" width="100%" maxLength={64} variant="flushed" color="#cbd5e0" borderColor="#aaaaaa" placeholder={selectedUser.company} _placeholder={{ color: "#cbd5e0" }} onChange={handleChange} /> </Flex> <Flex justify="flex-end"> <Button height="30px" type="submit" onClick={handleSubmit} mt={3} isLoading={loading} > Save </Button> </Flex> </Stack> </FormControl> </Flex> </Flex> ); }; export default EditProfileInputs;
import React, { createElement as e } from "react"; import { withTranslation } from "react-i18next"; import { markup } from "../shortcuts.js"; import { TranslatableGenericVoteCandidatesList } from "./GenericVoteCandidatesList.js"; import { TranslatableClassicVoteCandidatesList } from "./ClassicVoteCandidatesList.js"; // FIXME: We have to import TranslatableClassicVoteCandidatesList instead of ClassicVoteCandidatesList, because otherwise Storybook throws a hook error. import { TranslatableMajorityJudgmentVoteCandidatesList } from "./MajorityJudgmentVoteCandidatesList.js"; import { TranslatablePreferentialVotingCandidatesList } from "./PreferentialVotingCandidatesList.js"; import { TranslatablePreferentialVotingWithoutEqualityCandidatesList } from "./PreferentialVotingWithoutEqualityCandidatesList.js"; import { QuestionTypeEnum, detectQuestionType } from "../election_utils.js"; function TranslatableQuestionWithVotableAnswers({ question, identifierPrefix, visible, currentUserVoteForQuestion, currentAlertsTextsForQuestion, currentCandidatesHavingAlertsForQuestion, dispatchUpdateUserVoteForQuestion, t, }) { let description; let rendered_answers; if (question.type === QuestionTypeEnum.MAJORITY_JUDGMENT) { description = t("majority_judgment_question_description"); rendered_answers = e(TranslatableMajorityJudgmentVoteCandidatesList, { identifierPrefix, candidates: question.answers, blankVoteIsAllowed: question.blankVoteIsAllowed, availableGrades: question.availableGrades, currentUserVoteForQuestion, currentCandidatesHavingAlertsForQuestion, dispatchUpdateUserVoteForQuestion, t, }); } else if ( question.type === QuestionTypeEnum.PREFERENTIAL_VOTING_WITH_EQUALITY ) { description = t("preferential_voting_question_description"); rendered_answers = e(TranslatablePreferentialVotingCandidatesList, { identifierPrefix, candidates: question.answers, blankVoteIsAllowed: question.blankVoteIsAllowed, currentUserVoteForQuestion, currentCandidatesHavingAlertsForQuestion, dispatchUpdateUserVoteForQuestion, t, }); } else if ( question.type === QuestionTypeEnum.PREFERENTIAL_VOTING_WITHOUT_EQUALITY ) { description = t("preferential_voting_question_description"); rendered_answers = e( TranslatablePreferentialVotingWithoutEqualityCandidatesList, { identifierPrefix, candidates: question.answers, blankVoteIsAllowed: question.blankVoteIsAllowed, currentUserVoteForQuestion, currentCandidatesHavingAlertsForQuestion, dispatchUpdateUserVoteForQuestion, t, }, ); } else if (question.type === QuestionTypeEnum.CLASSIC) { let minimumAnswers = question.min; let maximumAnswers = question.max; let classic_question_subtype = "checkbox"; if (minimumAnswers === 1 && maximumAnswers === 1) { classic_question_subtype = "radio"; } if (minimumAnswers === maximumAnswers) { description = t("ask_to_select_x_answers", { count: minimumAnswers }); } else { description = t("ask_to_select_between_x_and_y_answers", { min: minimumAnswers, count: maximumAnswers, }); } rendered_answers = e(TranslatableClassicVoteCandidatesList, { type: classic_question_subtype, identifierPrefix, candidates: question.answers, blankVoteIsAllowed: question.blankVoteIsAllowed, currentUserVoteForQuestion, currentCandidatesHavingAlertsForQuestion, dispatchUpdateUserVoteForQuestion, t, }); } else if (question.type === QuestionTypeEnum.GENERIC) { rendered_answers = e(TranslatableGenericVoteCandidatesList, { identifierPrefix, candidates: question.answers, currentUserVoteForQuestion, currentCandidatesHavingAlertsForQuestion, dispatchUpdateUserVoteForQuestion, t, }); } const bemBlockName = "question-with-votable-answers"; const containerClassNames = visible ? bemBlockName : `${bemBlockName} ${bemBlockName}--hidden`; const alertsElements = currentAlertsTextsForQuestion.reduce( (accumulator, value) => { if (value) { accumulator.push(e("p", null, value)); } return accumulator; }, [], ); return e( "div", { className: containerClassNames, }, e( "h3", { className: `${bemBlockName}__question-title`, }, markup(question.title), ), e( "p", { className: `${bemBlockName}__question-description`, }, description, ), rendered_answers, e( "div", { className: `${bemBlockName}__alerts`, }, ...alertsElements, ), ); } TranslatableQuestionWithVotableAnswers.defaultProps = { identifierPrefix: "question_1_", visible: true, currentUserVoteForQuestion: [], currentAlertsTextsForQuestion: [], currentCandidatesHavingAlertsForQuestion: [], dispatchUpdateUserVoteForQuestion: () => {}, }; const QuestionWithVotableAnswers = withTranslation()( TranslatableQuestionWithVotableAnswers, ); export { QuestionWithVotableAnswers, TranslatableQuestionWithVotableAnswers }; export default QuestionWithVotableAnswers;
import React from "react"; import { View, Text, StyleSheet, Image, FlatList, TouchableOpacity, } from "react-native"; import { FontAwesome5 } from "@expo/vector-icons"; import Colors from "./Colors"; import { useNavigation } from "@react-navigation/native"; const SwiperComponent = () => { const cards = [ { image: require("../../assets/image22.jpg"), title: "Mosu #1930", time: "102d Left", userprofile: require("../../assets/image2.jpg"), username: "Karafuru", price: "2,75 ", description: "Karafuru is home to 5,555 generative arts where colors reign supreme Leave the drab reality and enter the world of Karafuru by Museum of Toys", }, { image: require("../../assets/image21.jpg"), title: "Mosu #1930", time: "102d Left", userprofile: require("../../assets/image2.jpg"), username: "Karafuru", price: "3,75 ", description: "Karafuru is home to 5,555 generative arts where colors reign supreme Leave the drab reality and enter the world of Karafuru by Museum of Toys", }, { image: require("../../assets/image2.jpg"), title: "Mosu #1930", time: "102d Left", userprofile: require("../../assets/image2.jpg"), username: "Karafuru", price: "4,75 ", description: "Karafuru is home to 5,555 generative arts where colors reign supreme Leave the drab reality and enter the world of Karafuru by Museum of Toys", }, { image: require("../../assets/image8.jpg"), title: "Mosu #1930", time: "102d Left", userprofile: require("../../assets/image2.jpg"), username: "Karafuru", price: "5,75 ", description: "Karafuru is home to 5,555 generative arts where colors reign supreme Leave the drab reality and enter the world of Karafuru by Museum of Toys", }, { image: require("../../assets/image7.jpg"), title: "Mosu #1930", time: "102d Left", userprofile: require("../../assets/image2.jpg"), username: "Karafuru", price: "1,75 ", description: "Karafuru is home to 5,555 generative arts where colors reign supreme Leave the drab reality and enter the world of Karafuru by Museum of Toys", }, ]; const navigation = useNavigation(); const handleCardPress = (selectedCard) => { navigation.navigate("nftdetails", { selectedCard }); }; const renderItem = ({ item }) => ( <TouchableOpacity onPress={() => handleCardPress(item)}> <View style={styles.card}> <Image source={item.image} style={styles.cardImage} /> <View style={{ display: "flex", flexDirection: "row", marginTop: 24 }}> <Text style={styles.cardTitle}>{item.title}</Text> <Text style={styles.cardTime}>{item.time}</Text> </View> <View style={{ display: "flex", flexDirection: "row", marginTop: 24 }}> <View style={{ display: "flex", flexDirection: "row" }}> <Image source={item.userprofile} style={styles.cardProfile} /> <Text style={styles.cardUsername}>{item.username}</Text> </View> <View style={{ display: "flex", flexDirection: "row", marginLeft: 100, borderWidth: 2, borderColor: Colors.primary, borderRadius: 10, paddingHorizontal: 15, }} > <FontAwesome5 name="ethereum" size={20} color={Colors.gray} /> <Text style={styles.cardPrice}>{item.price}</Text> <Text style={styles.cardEth}>ETH</Text> </View> </View> </View> </TouchableOpacity> ); return ( <View> <FlatList data={cards} renderItem={renderItem} style={{ height: "80%" }} /> </View> ); }; const styles = StyleSheet.create({ card: { flex: 1, display: "flex", flexDirection: "column", padding: 16, borderRadius: 10, width: "80%", height: 400, backgroundColor: Colors.secondary, marginLeft: 44, marginTop: 20, }, cardImage: { width: "100%", height: "70%", }, cardTitle: { fontSize: 18, fontWeight: "bold", color: Colors.white, }, cardTime: { fontSize: 12, fontWeight: "bold", color: Colors.gray, marginLeft: 150, }, cardProfile: { width: 32, height: 32, borderRadius: 100, }, cardUsername: { fontSize: 15, fontWeight: "bold", color: Colors.white, marginLeft: 8, marginTop: 5, }, cardPrice: { fontSize: 15, fontWeight: "bold", color: Colors.white, marginLeft: 8, marginTop: 5, }, cardEth: { fontSize: 15, fontWeight: "bold", color: Colors.white, marginLeft: 5, marginTop: 5, }, }); export default SwiperComponent;
<template> <button :class="variant"><slot></slot></button> </template> <script setup lang="ts"> const props = defineProps({ name: { type: String, default: 'John Doe' }, variant: { type: String, default: 'primary' }, }); </script> <style lang="scss" scoped> button { padding: var(--vue-spacing-00) var(--vue-spacing-2); border-radius: var(--vue-border-radius-pill); border: 1px solid var(--vue-color-border); font-family: var(--vue-font-family); font-size: var(--vue-font-size-00); font-weight: var(--vue-font-weight-button); letter-spacing: var(--vue-letter-spacing-button); text-transform: uppercase; &.primary { background-color: var(--vue-color-primary); color: var(--vue-color-text-on-primary); } &.secondary { background-color: var(--vue-color-secondary); color: var(--vue-color-text-on-secondary); } &.disabled, &:disabled { background-color: transparent; pointer-events: none; filter: brightness(50%); } &:hover { color: var(--vue-color-text-on-primary); filter: brightness(1.1); } } </style>
<script setup> import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue'; import {Head} from '@inertiajs/vue3'; import {ref} from 'vue'; import {Bar,Pie} from 'vue-chartjs'; import {Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale, ArcElement} from 'chart.js' ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale, ArcElement) const props = defineProps({ data: {type: Object} }); const departments = ref([]); const employees = ref([]); const chartData = ref([]); const chartOptions = ref([]); const colors = ref([]); /** FUNCION RANDOM PARA COLORES*/ const random = () => { return Math.floor(Math.random() * 256); } props.data.map((row) => ( departments.value.push(row.name), employees.value.push(row.count), colors.value.push("rgb(" + random() + "," + random() + "," + random() + ")") )); chartOptions.value = { responsive: true } chartData.value = { labels: departments.value, datasets: [ { label: 'Employees', data: employees.value, backgroundColor: colors } ] } </script> <template> <Head title="Graphic"/> <AuthenticatedLayout> <template #header> <h2 class="font-semibold text-xl text-gray-800 leading-tight">Graphic</h2> </template> <div class="py-12"> <div class="max-w-5xl mx-auto sm:px-6 lg:px-8"> <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg"> <Bar :data="chartData" :options="chartOptions"></Bar> </div> </div> </div> </AuthenticatedLayout> </template>
package LC001_300; import java.util.*; public class LC72_EditDistance { /** * Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. * * You have the following three operations permitted on a word: * * Insert a character * Delete a character * Replace a character * * Input: word1 = "horse", word2 = "ros" * Output: 3 * * Constraints: * * 0 <= word1.length, word2.length <= 500 * word1 and word2 consist of lowercase English letters. * @param word1 * @param word2 * @return */ // time = O(m * n), space = O(m * n) public int minDistance(String word1, String word2) { // corner case if (word1 == null || word2 == null) return 0; int m = word1.length(), n = word2.length(); int[][] dp = new int[m + 1][n + 1]; // dp[0][0] = 0; for (int i = 1; i <= m; i++) dp[i][0] = i; for (int j = 1; j <= n; j++) dp[0][j] = j; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (word1.charAt(i - 1) == word2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; // => Math.min(Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1), dp[i - 1][j - 1]); } else { dp[i][j] = Math.min(Math.min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1; } } } return dp[m][n]; } // time = O(n * m), space = O(n * m) public int minDistance2(String a, String b) { int n = a.length(), m = b.length(); a = "#" + a; b = "#" + b; int[][] f = new int[n + 1][m + 1]; for (int i = 0; i <= n; i++) f[i][0] = i; for (int i = 0; i <= m; i++) f[0][i] = i; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { f[i][j] = Math.min(f[i - 1][j], f[i][j - 1]) + 1; int t = a.charAt(i) != b.charAt(j) ? 1 : 0; f[i][j] = Math.min(f[i][j], f[i - 1][j - 1] + t); } } return f[n][m]; } } /** * 状态表示:f(i,j) * 集合:将A[1~i]变成B[1~j]的所有按顺序操作的方案 * 属性:min * 状态计算:f(i,j) */
/// Validate user input and data class Validator { /// Validates Full Name and needs to be more than 4 characters static String? name(String? value) { const pattern = r'(^[a-zA-Z ]*$)'; final regExp = RegExp(pattern); if (regExp.hasMatch(value!) && value.trim().length > 4) { return null; } else if (value.trim().length < 5) { return 'Full name must be more than 4 characters'; } return null; } /// Pattern checks for valid phone Numbers // static String? phoneNumber(String? value) { // const pattern = r'(^[+]*[(]{0,1}[0-9]{1,4}[)]{0,1}[-\s\./0-9]*$)'; // final regExp = RegExp(pattern); // if (value!.isEmpty) { // return '😉 Come on, don\'t be shy, enter your number'; // } else if (!regExp.hasMatch(value)) { // return "Hmm 🤔, that doesn't look like a valid phone number"; // } else if (value.length > 16 || value.length < 9) { // return "Hmm 🤔, that doesn't look like a valid phone number"; // } else if (value.startsWith('0') && value.length < 10) { // return "👏 Come on, ${10 - value.length} digits more"; // } else if (value.startsWith('0') && value.length > 10) { // return "📢 Valid phone numbers are 10 digits right ?"; // } else if (value.startsWith("") && value.length < 12) { // return "Not sure if this is a valid phone number"; // } // return null; // } static String? phoneNumber(String? value) { if (value!.isEmpty) { return '😉 Come on, don\'t be shy, enter your number'; } else if (value.length < 10) { return '👏 Come on, ${10 - value.length} digits more'; } /// When [value] is greater than 10 else if (value.length > 10) { return '📢 Valid phone numbers are 10 digits right ?'; } return null; } /// pattern for a valid code must start with either grp_ or comm_ and the length is 10 plus the prefix static String? validCode(String? value) { if (value!.isEmpty) { return "Come on, enter the code"; } else if (!value.startsWith("grp_") && !value.startsWith("comm_")) { return "Invalid community or group code"; } else if (value.startsWith('grp_') && value.length != 14) { return "Invalid group code"; } else if (value.startsWith('comm_') && value.length != 15) { return "Invalid Community code"; } return null; } }
import { useState, useEffect } from "react"; const useResize = () => { // filter section visibility states for small screens // size tracks the window width const [windowSize, setWindowSize] = useState<number>(window.innerWidth); // expandForm tracks the visibility of the entire form const [expandForm, setExpandForm] = useState<boolean>(false); // states to track individual parts of the form const [showSearch, setShowSearch] = useState<boolean>(false); const [showCategory, setShowCategory] = useState<boolean>(false); const [showCompany, setShowCompany] = useState<boolean>(false); const [showColor, setShowColor] = useState<boolean>(false); const [showPrice, setShowPrice] = useState<boolean>(false); const [showShipping, setShowShipping] = useState<boolean>(false); // useEffect adds and removes window resize event useEffect(() => { window.addEventListener("resize", () => setWindowSize(window.innerWidth)); if (windowSize >= 1025) { setExpandForm(true); setShowSearch(true); setShowCategory(true); setShowCompany(true); setShowColor(true); setShowPrice(true); setShowShipping(true); } else { setExpandForm(false); setShowSearch(false); setShowCategory(false); setShowCompany(false); setShowColor(false); setShowPrice(false); setShowShipping(false); } return () => window.removeEventListener("resize", () => setWindowSize(window.innerWidth) ); }, [windowSize]); return { windowSize, expandForm, setExpandForm, showSearch, setShowSearch, showCategory, setShowCategory, showCompany, setShowCompany, showColor, setShowColor, showPrice, setShowPrice, showShipping, setShowShipping, }; }; export default useResize;
<?xml version="1.0" encoding="UTF-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core"> <h:head> <h:outputStylesheet library="css" name="styles.css" /> <title>#{msgs.windowTitle}</title> </h:head> <h:body> <h:form> <h:panelGrid columns="2"> #{msgs.radioBtnPrompt}<h:selectBooleanCheckbox value="#{user.contactMe}" /> #{msgs.checkBoxes} <h:selectManyCheckbox value="#{user.colors}" layout="lineDirection" border="1" enabledClass="enabled"> <f:selectItem itemValue="Red" itemLabel="Red" /> <f:selectItem itemValue="Blue" itemLabel="Blue" /> <f:selectItem itemValue="Yellow" itemLabel="Yellow" /> <f:selectItem itemValue="Green" itemLabel="Green" /> <f:selectItem itemValue="Orange" itemLabel="Orange" /> </h:selectManyCheckbox> #{msgs.radioButtons} <h:selectOneRadio value="#{user.education}" layout="pageDirection" border="2"> <f:selectItem itemValue="High School" itemLabel="High School" /> <f:selectItem itemValue="Bachelor's" itemLabel="Bachelor's" /> <f:selectItem itemValue="Master's" itemLabel="Mater's" /> <f:selectItem itemValue="Doctorate" itemLabel="Doctorate" /> </h:selectOneRadio> #{msgs.yearPrompt} <h:selectOneListbox value="#{user.year}" size="5"> <f:selectItem itemValue="1900" itemLabel="1900" /> <f:selectItem itemValue="1910" itemLabel="1910" /> <f:selectItem itemValue="1980" itemLabel="1980" /> <f:selectItem itemValue="2000" itemLabel="2000" /> <f:selectItem itemValue="2010" itemLabel="2010" /> <f:selectItem itemValue="2020" itemLabel="2020" /> <f:selectItem itemValue="2030" itemLabel="2020" /> </h:selectOneListbox> #{msgs.languagePrompt} <h:selectManyListbox value="#{user.languages}" size="5"> <f:selectItem itemValue="English" itemLabel="English" /> <f:selectItem itemValue="French" itemLabel="French" /> <f:selectItem itemValue="Italian" itemLabel="Italian" /> <f:selectItem itemValue="Spanish" itemLabel="Spanish" /> <f:selectItem itemValue="Russian" itemLabel="Russian" /> <f:selectItem itemValue="Portuguese" itemLabel="Portuguese" /> <f:selectItem itemValue="Chinese" itemLabel="Chinese" /> </h:selectManyListbox> </h:panelGrid> <h:commandButton action="thankYou" value="#{msgs.btnConfirm}" /> </h:form> </h:body> </html>
require('pg') require_relative("../db/sql_runner.rb") require_relative("album.rb") class Artist attr_reader :id, :first_name, :last_name def initialize (options) @id = options['id'].to_i if options['id'] @first_name = options['first_name'] @last_name = options['last_name'] end def save() sql = "INSERT INTO artists ( first_name, last_name ) VALUES ( $1, $2 ) RETURNING id" values = [@first_name, @last_name] @id = SqlRunner.run(sql, values)[0]["id"].to_i end def albums() sql = "SELECT * FROM albums WHERE artist_id = $1" values = [@id] results = SqlRunner.run(sql, values) albums = results.map { |album| Album.new(album) } return albums end def self.delete_all() sql = "DELETE FROM artists" SqlRunner.run(sql) end def self.all() sql = "SELECT * FROM artists" artists = SqlRunner.run(sql) return artists.map { |artist| Artist.new(artist)} end end
import {combineEpics, Epic, ofType} from "redux-observable"; import {from, map, mergeMap, Observable} from "rxjs"; import { createBudgetAction, deleteBudgetAction, editBudgetAction, fetch_budget, fetchBudgetAction } from "./Budgets.slice"; import {request} from "../../api/core"; import {CreateBudget, DeleteBudget, EditBudget, GetBudgets} from "../../api/queries/Budgets"; const GetBudgetsEpic: Epic = (action$: Observable<ReturnType<typeof fetchBudgetAction>>) => { return action$.pipe( ofType(fetchBudgetAction.type), mergeMap(() => from(request(GetBudgets)).pipe( map(response => { console.log(response) return fetch_budget(response.data.budget.getBudgets) }) )) ) } const EditBudgetsEpic: Epic = (action$: Observable<ReturnType<typeof editBudgetAction>>) => { return action$.pipe( ofType(editBudgetAction.type), mergeMap(action => from(request(EditBudget, {budget: action.payload})).pipe( map(response => { if (response.data.budget.editBudget){ return fetchBudgetAction("") } }) )) ) } const CreateBudgetsEpic: Epic = (action$: Observable<ReturnType<typeof createBudgetAction>>) => { return action$.pipe( ofType(createBudgetAction.type), mergeMap(action => from(request(CreateBudget, {budget: action.payload})).pipe( map(response => { if (response.data.budget.createBudget){ return fetchBudgetAction("") } }) )) ) } const DeleteBudgetsEpic: Epic = (action$: Observable<ReturnType<typeof deleteBudgetAction>>) => { return action$.pipe( ofType(deleteBudgetAction.type), mergeMap(action => from(request(DeleteBudget, {id: action.payload})).pipe( map(response => { if (response.data.budget.deleteBudget){ return fetchBudgetAction("") } }) )) ) } export const BudgetEpics = combineEpics(GetBudgetsEpic, EditBudgetsEpic, CreateBudgetsEpic, DeleteBudgetsEpic)
import { Link } from "react-router-dom"; import Authorization from "./Authorization"; import logo from "../assest/img/epicEats.png"; import shoppingCart from "../assest/img/shoppingCart.png"; import { useSelector, useDispatch } from "react-redux"; const Topic = () => { return ( <> <img className="h-24 w-24 p-1" src={logo} alt="Epic Eats Logo" /> </> ); }; const Header = () => { const items = useSelector((state) => state.cart.items); return ( <div className="bg-white flex justify-between items-center px-3 shadow-sm text-not-perfect-grey font-mono text-lg sticky top-0 left-0 right-0 z-10"> <Topic /> <ul className="flex space-x-4 "> <Link to="/home"> <li className="text-gray-700 hover:text-vibrant-red focus:text-vibrant-red cursor-pointer transition-colors duration-300"> Home </li> </Link> </ul> <div className="flex mr-4"> <Link to="/cart"> <div className="flex "> <img src={shoppingCart} className="h-8 w-8 p-1" /> <div className=" mr-4 text-gray-700 hover:text-vibrant-red focus:text-vibrant-red cursor-pointer transition-colors duration-300"> Cart {items.length > 0 ? <>({items.length})</> : null } </div> </div> </Link> <Authorization /> </div> </div> ); }; export default Header;
using Arepas.Api.Dtos; using Arepas.Application.Interfaces; using Arepas.Domain.Dtos; using Arepas.Domain.Models; using AutoMapper; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Arepas.Api.Controllers { [Route("api/v1.0/[controller]")] [ApiController] public class CustomersController : ControllerBase { private readonly ICustomerService _customerService; private readonly IMapper _mapper; public CustomersController(IMapper mapper, ICustomerService customerService) { _mapper = mapper; _customerService = customerService; } // GET: api/<CustomersController> [HttpGet] public async Task<IActionResult> GetAll([FromQuery] QueryParams queryParams) { if (queryParams.Page == 0 && queryParams.Limit == 0) { return Ok(_mapper.Map<IEnumerable<Customer>, IEnumerable<CustomerDto>>(await _customerService.GetAllAsync())); } var responseData = await _customerService.GetByQueryParamsAsync(queryParams); Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(responseData.XPagination)); return Ok(_mapper.Map<IEnumerable<CustomerDto>>(responseData.Items)); } // GET api/<CustomersController>/5 [HttpGet("{id}")] public async Task<IActionResult> GetById(int id) { return Ok(_mapper.Map<CustomerDto>(await _customerService.GetByIdAsync(id))); } // POST api/<CustomersController> [HttpPost] public async Task<IActionResult> Post([FromBody] CustomerDto customerDto) { return Ok(_mapper.Map<CustomerDto>(await _customerService.AddAsync(_mapper.Map<Customer>(customerDto)))); } // PUT api/<CustomersController>/5 [HttpPut("{id}")] public async Task<IActionResult> Put(int id, [FromBody] CustomerDto customerDto) { return Ok(_mapper.Map<CustomerDto>(await _customerService.UpdateAsync(id, _mapper.Map<Customer>(customerDto)))); } // DELETE api/<CustomersController>/5 [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { await _customerService.RemoveAsync(id); return Ok(); } // GET api/<CustomersController>/5 [HttpGet("{id}/orders")] public async Task<IActionResult> GetOrdersByCustomerId(int id) { // Return OK (CustomerOrderDto) throw new NotImplementedException(); } } }
package de.nenick.quacc.view.bookingentries; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.androidannotations.annotations.AfterInject; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.InstanceState; import org.androidannotations.annotations.OptionsItem; import org.androidannotations.annotations.OptionsMenu; import org.joda.time.DateTime; import de.nenick.quacc.R; import de.nenick.quacc.core.common.util.QuAccDateUtil; import de.nenick.quacc.core.i18n.MonthTranslator; @EFragment @OptionsMenu(R.menu.date_selector) public class BookingEntriesFragment extends Fragment implements BookingEntriesView.ViewCallback { @Bean protected BookingEntriesView view; @Bean protected BookingEntriesListAdapter adapter; @Bean protected QuAccDateUtil quAccDateUtil; @Bean protected MonthTranslator monthTranslator; @InstanceState protected boolean switchDateExpanded; @InstanceState protected DateTime selectedDate; private long account; @AfterInject protected void onAfterInjectBeans() { if (selectedDate == null) { // else it was restored from instance state selectedDate = quAccDateUtil.today(); } view.setViewCallback(this); } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return view.root(); } @AfterViews void onAfterViewsCreated() { if (switchDateExpanded) { view.toggleDateSelector(); } view.setAdapter(adapter); updateSelectedDateText(); } public void setAccount(long account) { this.account = account; updateSelectedDateText(); updateBookingList(); } @OptionsItem(R.id.dateSelectorToggle) public void onClickDateSelectorToggle() { switchDateExpanded = !switchDateExpanded; view.toggleDateSelector(); } @Override public void onClickMonthUp() { selectedDate = selectedDate.plusMonths(1); updateSelectedDateText(); updateBookingList(); } @Override public void onClickMonthDown() { selectedDate = selectedDate.minusMonths(1); updateSelectedDateText(); updateBookingList(); } @Override public void onClickYearUp() { selectedDate = selectedDate.plusYears(1); updateSelectedDateText(); updateBookingList(); } @Override public void onClickYearDown() { selectedDate = selectedDate.minusYears(1); updateSelectedDateText(); updateBookingList(); } private void updateSelectedDateText() { int month = selectedDate.getMonthOfYear(); view.setMonth(monthTranslator.translate(month)); int year = selectedDate.getYear(); view.setYear(String.valueOf(year)); } private void updateBookingList() { adapter.update(account, quAccDateUtil.firstDayOfMonth(selectedDate), quAccDateUtil.lastDayOfMonth(selectedDate)); } }
import { BaseSlackAPIClient } from "./base-client.ts"; import { BaseResponse, SlackAPIClient, SlackAPIMethodArgs } from "./types.ts"; type APICallback = { (method: string, payload?: SlackAPIMethodArgs): Promise<BaseResponse>; }; export const ProxifyAndTypeClient = (baseClient: BaseSlackAPIClient) => { // This callback handles making the correct apiCall() that the Proxy() object defers to const apiCallHandler = (method: string, payload?: SlackAPIMethodArgs) => { return baseClient.apiCall(method, payload); }; // Create a subset of the client that we want to wrap our Proxy() around const clientToProxy = { setSlackApiUrl: baseClient.setSlackApiUrl.bind(baseClient), apiCall: baseClient.apiCall.bind(baseClient), response: baseClient.response.bind(baseClient), }; // Create our proxy, and type it w/ our api method types const client = APIProxy( clientToProxy, apiCallHandler, ); return client; }; export const APIProxy = ( // deno-lint-ignore no-explicit-any rootClient: any | null, apiCallback: APICallback, ...path: (string | undefined)[] ): SlackAPIClient => { const method = path.filter(Boolean).join("."); // We either proxy the object passed in, which we do for the top level client, // or a function that wraps the api callback. This allows each node of the // proxied object to be called, which will attempt an api call using the path as the method const objectToProxy = rootClient !== null ? rootClient : (payload?: SlackAPIMethodArgs) => { return apiCallback(method, payload); }; const proxy = new Proxy(objectToProxy, { get(obj, prop) { // We're attempting to access a property that doesn't exist, so create a new nested proxy if (typeof prop === "string" && !(prop in obj)) { return APIProxy(null, apiCallback, ...path, prop); } // Fallback to trying to access it directly // deno-lint-ignore no-explicit-any return Reflect.get.apply(obj, arguments as any); }, }); return proxy; };
import "./App.css"; import Map from "./components/map/Map"; import { useJsApiLoader } from "@react-google-maps/api"; import ControlPanel from "./components/control-panel/ControlPanel"; import RouteSummary from "./components/route-summary/RouteSummary"; import data from "../data/data.json"; import { useState } from "react"; import { Marker } from "./model/marker"; import { findDirections } from "./services/directions-service"; import SummaryContextProvider from "./state/SummaryContext"; const API_KEY = process.env.REACT_APP_API_KEY; const CENTER_POINT = { lng: 26.364, lat: 58.2456 }; function App() { const { isLoaded } = useJsApiLoader({ id: "google-map-script", googleMapsApiKey: API_KEY!, }); const markers = data as Marker[]; const [filteredWaypoints, setFilteredWaypoints] = useState<Marker[]>([]); const [directions, setDirections] = useState<google.maps.DirectionsResult | null>(null); const calculateDistance = async (currentWaypoints: Marker[]) => { if (currentWaypoints.length < 2) return; const directions = await findDirections(currentWaypoints); setDirections(directions); }; const filterWaypoints = (from: string, to: string) => { const filtered = markers.filter((marker) => { const markerDate = marker.date_created.split(" ")[0]; return markerDate >= from && markerDate <= to; }); setFilteredWaypoints(filtered); }; const clearFilter = () => { setFilteredWaypoints([]); }; return ( <SummaryContextProvider> <div className="App"> {isLoaded ? ( <> <Map center={CENTER_POINT} markers={filteredWaypoints} directions={directions} /> <ControlPanel directions={directions} setDirections={setDirections} filterWaypoints={filterWaypoints} clearFilter={clearFilter} calculateDistance={calculateDistance} /> <RouteSummary directions={directions} /> </> ) : ( <h2>Loading</h2> )} </div> </SummaryContextProvider> ); } export default App;
# -*- coding: utf-8 -*- """ icservice.__init__.py ~~~~~~~~~~~~~~~~~~~~~ icservice transaction processing library for infocognito """ import queue import threading from icservice.models import User, Operator from icservice.transactions import Reservation from icservice.messenger import Messenger #create test user and operator objects user = User(1) operator = Operator(1) #create a master data structures for the user and operator queues user_queue_dic = {user.id:queue.PriorityQueue()} operator_queue_dic = {operator.id:queue.PriorityQueue()} #main queue data structure to route transactions sent from users transaction_queue = queue.Queue() #create a messenger object which relays the transactions messenger = Messenger(transaction_queue,user_queue_dic,operator_queue_dic) #main worker thread def route_queue(): '''this defines the main queue manager worker thread function.''' ''' It process the main transction_queue one after another as the queue is filled up. The daemon threads go in to a infinite loop and will only terminate as the main thread is termined.this thread can start even before there is any transaction in the main queue ''' def message(s): print('{}: {}'.format(threading.current_thread().name,s)) while True: if not messenger.IsQueueEmpty(): transaction = messenger.NextTransaction() message('found a new transaction {} job in master queue'.format(transaction.GetNonce().code)) ''' routing of the transaction from the user to the operator happens depending on the transaction type given in the transaction object or based on a load balancing alorithm. for testing we assume the test user sends to test operator. ''' message('send transaction {} to operator queue'.format(transaction.GetNonce().code)) messenger.Dispatch_OperatorQueue(operator,transaction) # 1 is the test operator queue_manager = threading.Thread(target=route_queue) queue_manager.setDaemon(True) queue_manager.start()
--- title: "REM" --- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Document</title> <style> html { font-size: 32px; } div { font-size: 0.5rem; } </style> </head> <body> <div>请尝试缩放窗口看效果</div> <div>Hello World</div> <div id="html">html: 100px</div> <div>div: 0.5rem</div> <div id="computed">div 的 computed value 是 50px</div> <div>这意味着 rem/px = 1/1</div> </body> <script> function setRem() { const html = document.getElementsByTagName("html")[0]; const uiWidth = 750; const maxSize = 100; let clientWidth = document.documentElement.clientWidth; if (clientWidth > uiWidth) { clientWidth = uiWidth; } const htmlFontSize = (clientWidth * (maxSize / uiWidth)).toFixed(1); html.style.fontSize = htmlFontSize + "px"; document.querySelector("#html").innerHTML = `html: ${htmlFontSize}px`; document.querySelector( "#computed" ).innerHTML = `div 的 computed value 是 ${htmlFontSize * 0.5}px`; } function debounce(method, context) { clearTimeout(method.tId); method.tId = setTimeout(function() { method.call(context); }, 200); } // 注意此处要防抖 window.addEventListener("resize", function() { debounce(setRem, this); }); // 类似 trigger window.dispatchEvent(new Event("resize")); </script> </html>
import type { Metadata } from 'next'; import { Analytics } from '@vercel/analytics/react'; import { SpeedInsights } from '@vercel/speed-insights/next'; import { DM_Sans, Roboto_Mono } from 'next/font/google'; import MainHeader from '@/app/main-header'; import './globals.scss'; const dm_sans = DM_Sans({ subsets: ['latin'], variable: '--font-dmsans', }); const roboto_mono = Roboto_Mono({ subsets: ['latin'], display: 'swap', variable: '--font-roboto-mono', }); export const metadata: Metadata = { title: 'React United States SVG Map', description: 'Easily create stunning interactive maps of the United States using this React SVG component. The component is coded using Typescript but can be used in plain Javascript React projects.', openGraph: { title: 'React United States SVG Map', description: 'Easily create stunning interactive maps of the United States using this React SVG component. The component is coded using Typescript but can be used in plain Javascript React projects.', url: 'https://reactusmap.vercel.app/', siteName: 'React United States Map', images: [ { url: 'https://reactusmap.vercel.app/images/react-united-states-map.jpg', width: 1200, height: 630, }, ], locale: 'en_US', type: 'website', }, }; export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en" className={`${dm_sans.variable} ${roboto_mono.variable}`}> <body> <MainHeader /> {children} <Analytics /> <SpeedInsights /> </body> </html> ); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - Web</title> <link rel="stylesheet" href="~/lib/bootstrap5.2.3/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/Web.styles.css" asp-append-version="true" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css"> </head> <body> <header> <nav class="navbar mb-3"> <div class="col-3"> <button class="btn" data-bs-toggle="offcanvas" data-bs-target="#category"><i class="bi bi-list h4"></i></button> </div> <div class="offcanvas offcanvas-size-sm offcanvas-start" data-bs-scroll="true" data-bs-backdrop="true" tabindex="-1" id="category"> <div class="offcanvas-header"> <h5 class="offcanvas-title">Kategorier</h5> <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button> </div> <div class="offcanvas-body"> @await Component.InvokeAsync("Categories") </div> </div> <a class="col-3">EShop</a> <input class="col-3" type="text" placeholder="Søg" /> <div class="col-3 text-end"> <div class="btn-group"> <button type="button" class="btn dropdown-toggle" data-bs-toggle="dropdown"><i class="bi bi-basket2-fill h4"></i></button> @await Component.InvokeAsync("Basket") </div> @if (Context.Session.GetInt32("login").HasValue) { <a class="btn me-3"><i class="bi bi-person-circle h4"></i></a> } else { <a class="btn btn-primary me-3" asp-page="Login">Login</a> } </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> &copy; 2023 - Web - <a asp-area="" asp-page="/Privacy">Privacy</a> </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap5.2.3/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
from rest_framework import serializers from .models import MyUser, AcademicProfile, PersonalProfile class PersonalProfileSerializer(serializers.ModelSerializer): class Meta: model = PersonalProfile fields = '__all__' class AcademicProfileSerializer(serializers.ModelSerializer): class Meta: model = AcademicProfile fields = '__all__' class MyUserSerializer(serializers.ModelSerializer): academic_profile = AcademicProfileSerializer(read_only=True) personal_profile = PersonalProfileSerializer(read_only=True) class Meta: model = MyUser fields = ('email', 'role','password', 'academic_profile', 'personal_profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = MyUser.objects.create_user(**validated_data) return user
import time from multiprocessing import Queue import numpy as np import uvicorn from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from starlette.responses import StreamingResponse, Response app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) LAST_FRAMES_QUEUE = Queue(maxsize=1) @app.get("/video_feed") async def video_feed(): def streamer(): try: while True: if LAST_FRAMES_QUEUE.empty(): yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + b'\r\n') else: frame = LAST_FRAMES_QUEUE.get() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + bytearray(frame) + b'\r\n') time.sleep(0.1) except GeneratorExit: print("cancelled") return StreamingResponse(streamer(), media_type="multipart/x-mixed-replace;boundary=frame") @app.get("/") async def last_frame(): if LAST_FRAMES_QUEUE.empty(): return Response(content=b"", media_type="image/jpeg") return Response(content=LAST_FRAMES_QUEUE.get(), media_type="image/jpeg") def run_uvicorn_process(manager_memory, frame_queue): global LAST_FRAMES_QUEUE LAST_FRAMES_QUEUE = frame_queue try: uvicorn.run(app, host="0.0.0.0", port=8080, log_level="info") except Exception as e: print(e) manager_memory['server_process_running'] = False print("server process crashed") pass print("server process stopped") manager_memory['server_process_running'] = False return
package com.justin.facade.basic; public class Test3 { public static void main(String[] args){ Fund fund1 = new Fund(); //基金购买 fund1.buyFund(); //基金赎回 fund1.sellFund(); } } //基金类 class Fund{ Stock1 stock1; Stock2 stock2; NationalDebt1 nd1; Realty1 rt1; public Fund(){ stock1 = new Stock1(); stock2 = new Stock2(); nd1 = new NationalDebt1(); rt1 = new Realty1(); } public void buyFund(){ stock1.buy(); stock2.buy(); nd1.buy(); rt1.buy(); } public void sellFund(){ stock1.sell(); stock2.sell(); nd1.sell(); rt1.sell(); } //基金很多买入卖出操作,持仓比例等, //无需提前告知客户 } //股票1 class Stock1{ //卖股票 public void sell(){ System.out.println("股票1卖出"); } //买股票 public void buy(){ System.out.println("股票1买入"); } } //股票2 class Stock2{ //卖股票 public void sell(){ System.out.println("股票2卖出"); } //买股票 public void buy(){ System.out.println("股票2买入"); } } //国债1 class NationalDebt1{ //卖国债 public void sell(){ System.out.println("国债1卖出"); } //买国债 public void buy(){ System.out.println("国债1买入"); } } //房地产1 class Realty1{ //卖房地产 public void sell(){ System.out.println("房地产1卖出"); } //买房地产 public void buy(){ System.out.println("房地产1买入"); } }
import { Location } from '@angular/common'; import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { MathLogicService } from '../../services/math-logic.service'; interface ScoreMessage { message: string; }; /** * Render the results to the user after their game expires */ @Component({ selector: 'app-results', template: ` <div class="results-container"> <p>You scored {{ score }} points!</p> <ol> <li *ngFor="let question of (mathService.questions | async)">{{ removeLatex(question.equation) }}</li> </ol> </div> `, styles: [ `.results-container { margin-bottom: 1rem; }` ] }) export class ResultsComponent implements OnInit { score: number; constructor(public mathService: MathLogicService, private router: Router, private activatedRoute: ActivatedRoute, private location: Location) { } ngOnInit(): void { this.mathService.questions.subscribe(questions => { if (questions.length === 0) { this.router.navigate(['../'], { relativeTo: this.activatedRoute }); } }); } ngAfterContentInit(): void { this.score = Number((this.location.getState() as ScoreMessage).message || 0); } removeLatex(equation: string): string { return equation.replaceAll('\\times', '×') .replaceAll('\\div', '÷') .replaceAll('\\big(', '(') .replaceAll('\\bigg(', '(') .replaceAll('\\Big(', '(') .replaceAll('\\Bigg(', '(') .replaceAll('\\big)', ')') .replaceAll('\\bigg)', ')') .replaceAll('\\Big)', ')') .replaceAll('\\Bigg)', ')'); } }
import { AccountApi, ActionApi, ApplicationApi, ChargeApi, type Config, DatabaseApi, DatabaseBackupApi, DiskImagesApi, DNSDomainApi, FirewallApi, InstancesApi, IPApi, KfClusterApi, KubernetesApi, LoadBalancerApi, NetworksApi, ObjectStoreApi, OrganizationApi, PermissionApi, PoolApi, QuotaApi, RegionsApi, RoleApi, SSHKeyApi, SubnetsApi, TeamApi, UserApi, VolumeApi, WebhookApi, } from './resources'; /** * A comprehensive API client for the Civo cloud platform. */ export class Civo { accounts: AccountApi; actions: ActionApi; applications: ApplicationApi; charges: ChargeApi; databases: DatabaseApi; databaseBackups: DatabaseBackupApi; diskImages: DiskImagesApi; dns: DNSDomainApi; firewalls: FirewallApi; instances: InstancesApi; ips: IPApi; kfclusters: KfClusterApi; kubernetes: KubernetesApi; loadbalancers: LoadBalancerApi; networks: NetworksApi; subnets: SubnetsApi; objectStore: ObjectStoreApi; organizations: OrganizationApi; permissions: PermissionApi; pools: PoolApi; quotas: QuotaApi; regions: RegionsApi; roles: RoleApi; sshKeys: SSHKeyApi; teams: TeamApi; users: UserApi; volumes: VolumeApi; webhooks: WebhookApi; /** * Creates a new Civo API client. * * @param config The Civo API key and other configuration options. */ constructor(config: Config) { this.accounts = new AccountApi(config); this.actions = new ActionApi(config); this.applications = new ApplicationApi(config); this.charges = new ChargeApi(config); this.databases = new DatabaseApi(config); this.databaseBackups = new DatabaseBackupApi(config); this.diskImages = new DiskImagesApi(config); this.dns = new DNSDomainApi(config); this.firewalls = new FirewallApi(config); this.instances = new InstancesApi(config); this.ips = new IPApi(config); this.kfclusters = new KfClusterApi(config); this.kubernetes = new KubernetesApi(config); this.loadbalancers = new LoadBalancerApi(config); this.networks = new NetworksApi(config); this.subnets = new SubnetsApi(config); this.objectStore = new ObjectStoreApi(config); this.organizations = new OrganizationApi(config); this.permissions = new PermissionApi(config); this.pools = new PoolApi(config); this.quotas = new QuotaApi(config); this.regions = new RegionsApi(config); this.roles = new RoleApi(config); this.sshKeys = new SSHKeyApi(config); this.teams = new TeamApi(config); this.users = new UserApi(config); this.volumes = new VolumeApi(config); this.webhooks = new WebhookApi(config); } }
/* * Copyright (c) 2023 Zander Schwid & Co. LLC. * SPDX-License-Identifier: BUSL-1.1 */ package cmd import ( "github.com/pkg/errors" "github.com/codeallergy/glue" "github.com/sprintframework/template/pkg/api" "github.com/sprintframework/sprint" ) type implAdminCommand struct { Context glue.Context `inject` Application sprint.Application `inject` ApplicationFlags sprint.ApplicationFlags `inject` } func AdminCommand() sprint.Command { return &implAdminCommand{} } func (t *implAdminCommand) BeanName() string { return "admin" } func (t *implAdminCommand) Desc() string { return "admin commands: [list, add, remove]" } func (t *implAdminCommand) Run(args []string) error { if len(args) == 0 { return errors.Errorf("admin command needs argument, %s", t.Desc()) } cmd := args[0] args = args[1:] return doWithAdminClient(t.Context, func(client api.AdminClient) error { content, err := client.AdminCommand(cmd, args) if err == nil { println(content) } return err }) }
from linked_list import Linked_List from node import Node import unittest class TestLinked_List(unittest.TestCase): """ This test suite includes test cases for various methods and behaviors of the Linked_List class. """ def setUp(self) -> None: """Create a new Linked_List instance before each test""" self.linked_list = Linked_List() def tearDown(self) -> None: """Reset the state of the linked list after each test""" self.linked_list = None def test_insertAtBeginning(self) -> None: """Test inserting a node at the beginning of the linked list. - First, insert a node in an empty list and assert the expected behavior. - Second, insert another node and verify that it becomes the new head of the list. """ # first insert in list data = 42 self.linked_list.insertAtBeginning(data) self.assertEqual(self.linked_list.head.data, data) self.assertIsNone(self.linked_list.head.next) # second insert in list data = 95 self.linked_list.insertAtBeginning(data) self.assertEqual(self.linked_list.head.data, data) # third insert in list data = 55 self.linked_list.insertAtBeginning(data) self.assertEqual(self.linked_list.head.data, data) def test_insertAtIndex(self) -> None: """Test inserting a new node at a specified index in the linked list.""" self.test_insertAtBeginning() index, data = 2, 101 self.linked_list.insertAtIndex(data, index) current_node = self.getposition(index) self.assertEqual(current_node.data, data) def test_insertAtEnd(self) -> None: """Test inserting a new node at the end of the linked list.""" self.test_insertAtBeginning() index, data = 3, -5 self.linked_list.insertAtEnd(data) current_node = self.getposition(index) self.assertEqual(current_node.data, data) def test_updateNode(self) -> None: """Test updating a node's data of the linked list.""" self.test_insertAtBeginning() index, new_data = 2, 1000 self.linked_list.updateNode(new_data, index) current_node = self.getposition(index) self.assertEqual(current_node.data, new_data) # test for negative index index, new_data = -2, 100 with self.assertRaises(IndexError): self.linked_list.updateNode(new_data, index) def getposition(self, index:int) -> Node: """ Get the node at a specified index in the linked list. Args: index (int): The index of the node to retrieve. Returns: Node: The node at the specified index. """ current_node = self.linked_list.head position = 0 while position != index: current_node = current_node.next position += 1 return current_node if __name__ == '__main__': unittest.main()
package kotlinbook import com.google.gson.Gson import com.typesafe.config.ConfigFactory import com.zaxxer.hikari.HikariDataSource import io.ktor.http.* import io.ktor.http.content.* import io.ktor.server.application.* import io.ktor.server.engine.* import io.ktor.server.netty.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.util.pipeline.* import kotlinx.html.Entities import kotlinx.html.InputType import org.flywaydb.core.Flyway import org.slf4j.LoggerFactory import java.lang.foreign.MemorySegment.copy import javax.sql.DataSource import kotlin.reflect.full.declaredMemberProperties private val log = LoggerFactory.getLogger("kotlinbook.Main") fun createAppConfig(env: String) = ConfigFactory .parseResources("app-${env}.conf") .withFallback(ConfigFactory.parseResources("app.conf")) .resolve() .let { WebappConfig( httpPort = it.getInt("httpPort"), dbUser = it.getString("dbUser"), dbPassword = it.getString("dbPassword"), dbUrl = it.getString("dbUrl") ) } fun createDataSource(config: WebappConfig) = HikariDataSource().apply { jdbcUrl = config.dbUrl username = config.dbUser password = config.dbPassword } fun main() { val env = System.getenv("KOTLINBOOK_ENV") ?: "local" val config = createAppConfig(env) createAndMigrateDataSource(config) val secretsRegex = "password|secret|key" .toRegex(RegexOption.IGNORE_CASE) WebappConfig::class.declaredMemberProperties .sortedBy { it.name } .map { if (secretsRegex.containsMatchIn(it.name)) { "${it.name} = ${it.get(config).toString().take(2)}*****" } else { "${it.name} = ${it.get(config)}" } } .joinToString(separator = "\n") val dataSource = createDataSource(config) dataSource.getConnection().use { conn -> conn.createStatement().use { stmt -> stmt.executeQuery("SELECT 1") } } log.debug("Testing my logger") embeddedServer(Netty, port = 4207) { createKtorApplication() }.start(wait = true) } fun Application.createKtorApplication() { install(StatusPages) { exception<Throwable> { call, cause -> kotlinbook.log.error("An unknown error occurred", cause) call.respondText( text = "500: $cause", status = HttpStatusCode.InternalServerError ) } } routing { get("/") { call.respondText("Hello, World!") } get("/", webResponse { TextWebResponse("Hello, world!") }) get("/param_test", webResponse { TextWebResponse( "The param is: ${call.request.queryParameters["foo"]}" ) }) get("/json_test", webResponse { JsonWebResponse(mapOf("foo" to "bar")) }) get("/json_test_with_header", webResponse { JsonWebResponse(mapOf("foo" to "bar")) .header("X-Test-Header", "Just a test!") }) } } data class WebappConfig( val httpPort: Int, val dbUser: String, val dbPassword: String, val dbUrl: String ) sealed class WebResponse { abstract val statusCode: Int abstract val headers: Map<String, List<String>> abstract fun copyResponse( statusCode: Int, headers: Map<String, List<String>>) : WebResponse fun header(headerName: String, headerValue: String) = header(headerName, listOf(headerValue)) fun header(headerName: String, headerValue: List<String>) = copyResponse( statusCode, headers.plus(Pair( headerName, headers.getOrDefault(headerName, listOf()) .plus(headerValue) )) ) fun headers(): Map<String, List<String>> = headers .map { it.key.lowercase() to it.value } .fold(mapOf()) { res, (k, v) -> res.plus(Pair( k, res.getOrDefault(k, listOf()).plus(v) )) } } data class TextWebResponse( val body: String, override val statusCode: Int = 200, override val headers: Map<String, List<String>> = mapOf() ) : WebResponse() { override fun copyResponse(statusCode: Int, headers: Map<String, List<String>>): WebResponse = copy(body, statusCode, headers) } data class JsonWebResponse( val body: Any?, override val statusCode: Int = 200, override val headers: Map<String, List<String>> = mapOf() ) : WebResponse() { override fun copyResponse(statusCode: Int, headers: Map<String, List<String>>): WebResponse = copy(body, statusCode, headers) } class KtorJsonWebResponse ( val body: Any?, override val status: HttpStatusCode = HttpStatusCode.OK ) : OutgoingContent.ByteArrayContent() { override val contentType: ContentType = ContentType.Application.Json.withCharset(Charsets.UTF_8) override fun bytes() = Gson().toJson(body).toByteArray( Charsets.UTF_8 ) } fun webResponse( handler: suspend PipelineContext<Unit, ApplicationCall>.( ) -> WebResponse ): PipelineInterceptor<Unit, ApplicationCall> { return { val resp = this.handler() for ((name, values) in resp.headers()) for (value in values) call.response.header(name, value) val statusCode = HttpStatusCode.fromValue( resp.statusCode ) when (resp) { is TextWebResponse -> { call.respondText( text = resp.body, status = statusCode ) } is JsonWebResponse -> { call.respond(KtorJsonWebResponse(body =resp.body,status = statusCode)) } } } } fun migrateDataSource(dataSource: DataSource) { Flyway.configure() .dataSource(dataSource) .locations("db/migration") .table("flyway_schema_history") .load() .migrate() } fun createAndMigrateDataSource(config: WebappConfig) = createDataSource(config).also(::migrateDataSource)
/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "fmt" "github.com/ctron/hono-qdrouter-proxy/pkg/apis/iotproject/v1alpha1" "reflect" "strconv" "time" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/util/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "k8s.io/klog" clientset "github.com/ctron/hono-qdrouter-proxy/pkg/client/clientset/versioned" iotscheme "github.com/ctron/hono-qdrouter-proxy/pkg/client/clientset/versioned/scheme" informers "github.com/ctron/hono-qdrouter-proxy/pkg/client/informers/externalversions/iotproject/v1alpha1" listers "github.com/ctron/hono-qdrouter-proxy/pkg/client/listers/iotproject/v1alpha1" "github.com/ctron/hono-qdrouter-proxy/pkg/qdr" ) // Controller is the controller implementation for Foo resources type Controller struct { // kubeclientset is a standard kubernetes clientset kubeclientset kubernetes.Interface // sampleclientset is a clientset for our own API group iotclientset clientset.Interface projectLister listers.IoTProjectLister projectsSynced cache.InformerSynced // workqueue is a rate limited work queue. This is used to queue work to be // processed instead of performing it as soon as a change happens. This // means we can ensure we only process a fixed amount of resources at a // time, and makes it easy to ensure we are never processing the same item // simultaneously in two different workers. workqueue workqueue.RateLimitingInterface manage *qdr.Manage } func NewController( kubeclientset kubernetes.Interface, iotclientset clientset.Interface, projectInformer informers.IoTProjectInformer) *Controller { utilruntime.Must(iotscheme.AddToScheme(scheme.Scheme)) controller := &Controller{ kubeclientset: kubeclientset, iotclientset: iotclientset, projectLister: projectInformer.Lister(), projectsSynced: projectInformer.Informer().HasSynced, workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "IoTProjects"), manage: qdr.NewManage(), } klog.Info("Setting up event handlers") // listen for events on the project resource projectInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { klog.Infof("Add: %s", obj) controller.enqueueProject(obj) }, UpdateFunc: func(old, new interface{}) { klog.Infof("Update - old: %s, new: %s", old, new) controller.enqueueProject(new) }, DeleteFunc: func(obj interface{}) { klog.Infof("Deleted: %s", obj) controller.enqueueProject(obj) }, }) return controller } func (c *Controller) enqueueProject(obj interface{}) { var key string var err error if key, err = cache.MetaNamespaceKeyFunc(obj); err != nil { runtime.HandleError(err) return } c.workqueue.AddRateLimited(key) } // Run main controller // // This will run until the `stopCh` is closed, which will then shutdown the // workqueue, wait for workers to complete, and then return. func (c *Controller) Run(threadiness int, stopCh <-chan struct{}) error { defer runtime.HandleCrash() defer c.workqueue.ShutDown() klog.Info("Starting IoTProjects controller") // prepare the caches klog.Info("Waiting for informer caches to sync") if ok := cache.WaitForCacheSync(stopCh, c.projectsSynced); !ok { return fmt.Errorf("failed to wait for caches to sync") } // start the workers klog.Infof("Starting %s worker(s)", threadiness) for i := 0; i < threadiness; i++ { go wait.Until(c.runWorker, time.Second, stopCh) } // wait for shutdown klog.Info("Started workers") <-stopCh klog.Info("Shutting down workers") // return return nil } // fetch any process work func (c *Controller) runWorker() { for c.processNextWorkItem() { } } // fetch and process the next work item func (c *Controller) processNextWorkItem() bool { obj, shutdown := c.workqueue.Get() if shutdown { return false } // scope next section in order to use "defer", poor man's try-finally err := func(obj interface{}) error { // by the end of the function, we are done with this item // either we Forget() about it, or re-queue it defer c.workqueue.Done(obj) // try-cast to string key, ok := obj.(string) // the work queue should only contain strings if !ok { // if it doesn't, drop the item c.workqueue.Forget(obj) runtime.HandleError(fmt.Errorf("expected string in workqueue but got %#v", obj)) return nil } // try-sync change event, on error -> re-queue if err := c.syncHandler(key); err != nil { c.workqueue.AddRateLimited(key) return fmt.Errorf("error syncing '%s': %s, requeuing", key, err.Error()) } // handled successfully, drop from work queue c.workqueue.Forget(obj) klog.Infof("Successfully synced '%s'", key) return nil }(obj) // if an error occurred ... if err != nil { // ... handle error ... runtime.HandleError(err) // ... and continue processing return true } // return, indicating that we want more return true } // Synchronize the requested state with the actual state func (c *Controller) syncHandler(key string) error { // parse into namespace + name namespace, name, err := cache.SplitMetaNamespaceKey(key) if err != nil { runtime.HandleError(fmt.Errorf("invalid resource key: %s", key)) return nil } // read requested state project, err := c.projectLister.IoTProjects(namespace).Get(name) if err != nil { // something went wrong if errors.IsNotFound(err) { // we didn't find the object klog.Info("Item got deleted. Deleting configuration.") err = c.deleteLinkRoute(namespace, name) // if something went wrong deleting, then returning // and error will re-queue the item return err } return err } // sync add or update _, err = c.syncProject(project) // something went wrong syncing the project // we will re-queue this by returning the error state if err != nil { return err } return nil } func (c *Controller) syncResource(currentPointer interface{}, resource interface{}, creator func() map[string]string) (bool, error) { r, ok := resource.(qdr.RouterResource) if !ok { return false, fmt.Errorf("requested resource must implement 'qdr.RouterResource'") } found, err := c.manage.ReadAsObject(r, currentPointer) if err != nil { return false, err } klog.V(4).Infof("Found: %s", found) klog.V(4).Infof("Current: %s", currentPointer) klog.V(4).Infof("Request: %s", resource) if found { equals := reflect.DeepEqual(currentPointer, resource) klog.V(4).Infof("Equals: %s", equals) if equals { return false, nil } } if found { c.manage.Delete(r) } _, err = c.manage.Create(r, creator()) return true, err } func (c *Controller) syncLinkRoute(route qdr.LinkRoute) (bool, error) { return c.syncResource(&qdr.LinkRoute{}, &route, func() map[string]string { return map[string]string{ "direction": route.Direction, "pattern": route.Pattern, "connection": route.Connection, } }) } func (c *Controller) syncConnector(connector qdr.Connector) (bool, error) { return c.syncResource(&qdr.Connector{}, &connector, func() map[string]string { return map[string]string{ "host": connector.Host, "port": connector.Port, "role": connector.Role, "saslUsername": connector.SASLUsername, "saslPassword": connector.SASLPassword, } }) } func (c *Controller) syncProject(project *v1alpha1.IoTProject) (bool, error) { tenantName := project.Namespace + "." + project.Name baseName := tenantName addressTenantName := tenantName connectorName := "connector-" + baseName klog.Infof("Create link routes - tenant: %s", tenantName) var change bool = false res, err := c.syncConnector(qdr.Connector{ NamedResource: qdr.NamedResource{Name: connectorName}, Host: project.Spec.Host, Port: strconv.Itoa(int(project.Spec.Port)), Role: "route-container", SASLUsername: project.Spec.Username, SASLPassword: project.Spec.Password, }) if err != nil { return false, err } change = change || res res, err = c.syncLinkRoute(qdr.LinkRoute{ NamedResource: qdr.NamedResource{Name: "linkRoute/t/" + baseName}, Direction: "in", Pattern: "telemetry/" + addressTenantName + "/#", Connection: connectorName, }) if err != nil { return false, err } change = change || res res, err = c.syncLinkRoute(qdr.LinkRoute{ NamedResource: qdr.NamedResource{Name: "linkRoute/e/" + baseName}, Direction: "in", Pattern: "event/" + addressTenantName + "/#", Connection: connectorName, }) if err != nil { return false, err } change = change || res res, err = c.syncLinkRoute(qdr.LinkRoute{ NamedResource: qdr.NamedResource{Name: "linkRoute/c_i/" + baseName}, Direction: "in", Pattern: "control/" + addressTenantName + "/#", Connection: connectorName, }) if err != nil { return false, err } change = change || res res, err = c.syncLinkRoute(qdr.LinkRoute{ NamedResource: qdr.NamedResource{Name: "linkRoute/c_o/" + baseName}, Direction: "out", Pattern: "control/" + addressTenantName + "/#", Connection: connectorName, }) if err != nil { return false, err } change = change || res return change, nil } func (c *Controller) deleteLinkRoute(namespace string, name string) error { tenantName := namespace + "." + name baseName := tenantName connectorName := "connector-" + baseName klog.Infof("Delete link routes - tenant: %s", tenantName) if err := c.manage.Delete(qdr.TypeAndName(qdr.TypeNameLinkRoute, "linkRoute/t/"+baseName)); err != nil { return err } if err := c.manage.Delete(qdr.TypeAndName(qdr.TypeNameLinkRoute, "linkRoute/e/"+baseName)); err != nil { return err } if err := c.manage.Delete(qdr.TypeAndName(qdr.TypeNameLinkRoute, "linkRoute/c_i/"+baseName)); err != nil { return err } if err := c.manage.Delete(qdr.TypeAndName(qdr.TypeNameLinkRoute, "linkRoute/c_o/"+baseName)); err != nil { return err } if err := c.manage.Delete(qdr.TypeAndName(qdr.TypeNameLinkRoute, connectorName)); err != nil { return err } return nil }
(ns bank-ocr.core (:require [clojure.java.io :as io])) (def grid-to-number {[[" " "_" " "] ["|" " " "|"] ["|" "_" "|"]] 0 [[" " " " " "] [" " " " "|"] [" " " " "|"]] 1 [[" " "_" " "] [" " "_" "|"] ["|" "_" " "]] 2 [[" " "_" " "] [" " "_" "|"] [" " "_" "|"]] 3 [[" " " " " "] ["|" "_" "|"] [" " " " "|"]] 4 [[" " "_" " "] ["|" "_" " "] [" " "_" "|"]] 5 [[" " "_" " "] ["|" "_" " "] ["|" "_" "|"]] 6 [[" " "_" " "] [" " " " "|"] [" " " " "|"]] 7 [[" " "_" " "] ["|" "_" "|"] ["|" "_" "|"]] 8 [[" " "_" " "] ["|" "_" "|"] [" " "_" "|"]] 9}) (defn rotate [grid] (apply map vector grid)) (defn digit-grid [digit] (for [line digit] (for [char line] (str char)))) (defn read-digits [rdr] (->> (line-seq rdr) (remove empty?) (apply map vector) (partition-all 3) (map (comp rotate digit-grid)) (map (fn [g] (grid-to-number g \?))))) (defn read-file [filename] (with-open [rdr (io/reader filename)] (read-digits rdr)))
import { useState, useRef, createContext, useEffect, useId } from 'react' import Navbar from '../Navbar'; import ExerciseCard from './ExerciseCard'; import axios from 'axios'; import key from '../../ApiKey'; import './SearchStyles.css' export default function Search() { const [search, setSearch] = useState(''); const [exercises, setExercises] = useState([]); const [bodyParts, setBodyParts] = useState([]); // TODO: get random exercises instead of alphabetical const optionsExercises = { method: 'GET', url: 'https://exercisedb.p.rapidapi.com/exercises/bodyPart/back', params: { limit: '12' }, headers: { 'X-RapidAPI-Key': key, 'X-RapidAPI-Host': 'exercisedb.p.rapidapi.com' } }; const optionsBodyParts = { method: 'GET', url: 'https://exercisedb.p.rapidapi.com/exercises/bodyPartList', headers: { 'X-RapidAPI-Key': key, 'X-RapidAPI-Host': 'exercisedb.p.rapidapi.com' } }; // requesting all possible body parts for searching useEffect(() => { const bodyPartsFunction = async () => { try { const response = await axios.request(optionsBodyParts); let data = await response.data; setBodyParts(b => data); console.log(data) } catch (error) { console.log(error); } } bodyPartsFunction(); }, []); // requesting/storing all exercises related to search async function handleSubmit() { if (bodyParts.includes(search)) { try { const response = await axios.request({ ...optionsExercises, url: `https://exercisedb.p.rapidapi.com/exercises/bodyPart/${search}` }); setExercises(b => response.data); console.log(response.data); } catch (error) { console.error(error); } } } const allCards = exercises.map(exercise => { return <ExerciseCard key={exercise.id} exerciseObj={exercise} /> }) return ( <div className="search-container"> <form> <div className="label-input" id='search'> <label>Search</label> <input type="text" name="search" onChange={(e) => setSearch(e.target.value.toLowerCase())} value={search} /> </div> </form> <button onClick={handleSubmit}>Submit</button> <div className="exercise-cards"> {allCards} </div> </div> ); }
import React from "react"; import NavAndSidebar from "./components/navbar/NavAndSidebar"; import { Route, Routes, useLocation } from "react-router-dom"; import "./_app.scss"; import Home from "./pages/home"; import SignUp from "./pages/signup"; import Footer from "./components/footer"; import Contact from "./pages/contact"; import News from "./pages/news"; import About from "./pages/about"; import Community from "./pages/community"; import Events from "./pages/events"; import Carrier from "./pages/carrier"; const App = () => { const { pathname } = useLocation(); return ( <> {/* {pathname === "/sign-up" ? ( <> <div style={{ position: "fixed", width: "100%", background: "#fff", zIndex: "9999999999999999999", top: 0, }} > <NavAndSidebar /> </div> <div style={{ marginBottom: "6.5rem" }}></div> </> ) : ( <NavAndSidebar /> )} */} <NavAndSidebar /> <Routes> <Route index element={<Home />} /> <Route path="sign-up" element={<SignUp />} /> <Route path="contact" element={<Contact />} /> <Route path="news" element={<News />} /> <Route path="about" element={<About />} /> <Route path="community" element={<Community />} /> <Route path="events" element={<Events />} /> <Route path="carrier" element={<Carrier />} /> </Routes> <Footer /> </> ); }; export default App;
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AuthGuardGuard } from '../Services/auth-guard.guard'; import { DepartmentResolverService } from '../Services/department-resolver.service'; import { Guard1Guard } from '../Services/guard1.guard'; import { AdminHomeComponent } from './admin-home/admin-home.component'; import { AdminComponent } from './admin/admin.component'; import { DepartmentComponent } from './department/department.component'; import { DeptJobTitleComponent } from './dept-job-title/dept-job-title.component'; import { EmployeeComponent } from './employee/employee.component'; const routes: Routes = [ {path:'',component:AdminComponent,children: [ {path:'Admin',component:AdminHomeComponent,canActivate:[AuthGuardGuard]}, {path:'Admin/Employee',component:EmployeeComponent,data:{AnimationTrigger:"AdminEmployee"},canActivate:[AuthGuardGuard]}, {path:'Admin/Department',component:DepartmentComponent,resolve:{department:DepartmentResolverService},canActivate:[AuthGuardGuard],canActivateChild:[Guard1Guard], children: [ {path:'Employees/:id',component:DeptJobTitleComponent} ] }, ] } , ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class AdminRoutingModule { }
package com.example.myMoneyapp.models; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.List; import java.util.UUID; @Data @Entity(name = "billing_cycles") @Table(name = "billing_cycles") @AllArgsConstructor @NoArgsConstructor public class BillingCycle { @Id @GeneratedValue(strategy = GenerationType.AUTO) private UUID id; @Column(nullable = false) private String name; @Column(nullable = false) private int month; @Column(nullable = false) private int year; @OneToMany(cascade = CascadeType.ALL) private List<Credit> credits; @OneToMany(cascade = CascadeType.ALL) private List<Debit> debits; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>weatherAppJS</title> <link rel="icon" type="image/x-icon" href="/public/imgs/sunburst_icon.ico"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Roboto+Slab"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.1/css/all.css"> <link rel="stylesheet" href="/public/styles/main.css"> </head> <body> <div id="shell"> <nav class="navbar navbar-expand-lg navbar-dark m-0 p-2"> <a href="#" class="navbar-brand"><i class="fas fa-sun"></i> Weather App JS</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarContent"> <form class="form-inline"> <div class="form-group"> <!-- trigger modal --> <button type="button" class="btn btn-dark" data-toggle="modal" data-target="#locModal"> <i class="fas fa-globe mr-2"></i>Lat & Long </button> <button type="button" class="btn btn-dark mr-3" id="getLocalWeather"><i class="fas fa-map-marker-alt mr-2"></i>Local</button> </div> <div class="form-group"> <input id="newLocation" class="form-control controls" type="text" placeholder="New Weather Location&hellip;"> </div> <!-- set user unit preference --> <div class="form-group"> <div class="btn-group ml-4"> <div class="btn btn-outline-secondary" id="fahrenheit">°F</div> <div class="btn btn-outline-secondary" id="celsius">°C</div> </div> </div> </form> </div> </nav> <div class="container"> <div class="row pr-1 pl-1" id="alertBody"> <div class="weatherBlock col-sm-12 mx-auto text-center mt-4 p-3 pb-4 rounded"> <h1 id="placeName"></h1> <h5 class="w-latLon"></h5> <h5 id="w-timezone"></h5> <canvas id="skycon"></canvas> <h3 id="w-summary"></h3> <div class="container"> <div class="row"> <div class="col-sm-6"> <ul id="w-details" class="list-group mt-3"> <li class="list-group-item" id="w-temp"></li> <li class="list-group-item" id="w-apparent-temp"></li> <li class="list-group-item" id="w-dewPoint"></li> </ul> </div> <div class="col-sm-6"> <ul id="w-details" class="list-group mt-3"> <li class="list-group-item" id="w-wind"></li> <li class="list-group-item" id="w-cloudCover"></li> <li class="list-group-item" id="w-humidity"></li> </ul> </div> </div> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="locModal" tabindex="-1" role="dialog" aria-labelledby="locModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="locModalLabel">Choose Weather Location with Lat and Long</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form id="w-form"> <div class="form-group"> <label for="lat">Latitude</label> <input type="number" class="form-control" id="lat" placeholder="Enter Latitude Coordinate"> </div> <div class="form-group"> <label for="lon">Longitude</label> <input type="number" class="form-control" id="lon" placeholder="Enter Longitude Coordinate"> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-dark" data-dismiss="modal">Close</button> <button id="w-change-btn" type="button" class="btn btn-dark">Save changes</button> </div> </div> </div> </div> <footer> <span>belQati ©2018</span> <a class="footerLink" href="https://github.com/belqati/" target="blank"><i class="fab fa-github"></i></a> <div class="float-right"> <img id="darkskylogo" src="/public/imgs/darkskylogo.png"> <a href="https://darksky.net/poweredby/" target="blank">Powered by Dark Sky</a> </div> </footer> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script> <script src="public/scripts/storage.js"></script> <script src="public/scripts/weather.js"></script> <script src="public/scripts/skycons.js"></script> <script src="public/scripts/ui.js"></script> <script src="app.js"></script> <!-- for geocoder via app.js --> <script src='https://unpkg.com/axios/dist/axios.min.js'></script> </body> </html>
import { createTheme, DefaultGlobalStyles, defaultTheme } from '@gsandf/ui'; import React from 'react'; import { createGlobalStyle } from 'styled-components'; import * as componentStyles from './component-styles'; const themeColors = { ...defaultTheme.colors, primary: 'tan', onPrimary: '#121' }; /** * Add global styles here. This is mainly used for styling general HTML elements. */ const GlobalStyles = createGlobalStyle` a:not([class]) { color: inherit; text-decoration: underline; :hover { text-decoration: none; } } code { background-color: ${themeColors.darken}; border-radius: ${defaultTheme.radii.sm}; color: ${themeColors.onDarken}; padding: .1em .2em; } `; /** * `globalStyles()` combines the default global styles with additional global * styles. * * The default global styles include a CSS normalize and various basic defaults, * including `box-sizing: border-box`, removed body margin, default text styles, * etc. If you don't need these, this can be removed, and `GlobalStyles` can be * passed directly to `createTheme()`. For example: * * ```ts * createTheme({ styles: GlobalStyles }) * ``` */ const globalStyles = () => ( <> <DefaultGlobalStyles /> <GlobalStyles /> </> ); export const theme = createTheme({ colors: themeColors, components: { Button: { baseStyle: componentStyles.baseButtonStyles, variants: { dark: componentStyles.buttonVariantDark, control: componentStyles.buttonVariantControl } } }, styles: globalStyles }); export const { breakpoints, borders, colors, components, fontSizes, fontWeights, fonts, lineHeights, media, mixins, radii, shadows, sizes, space, styles, zIndices } = theme; export default theme;
Tener presente la página de documentación, para estar actualizada con los comandos. Hasta la version: 14.2.3, así se levantaba un proyecto en angular npm install -g @angular/cli Comandos para ver la versión: ng version ó ng v Creación: ng new my-first-project cd 01-bases ng serve Recordar guardar el Node_modules en gitIgnore, ya que al clonarlo en otro lugar, de igual modo debemos instalar el paquete de Node (npm init) y, en este caso, de angular(npm install -g @angular/cli): .gitignore (se crea la carpeta) /node_modules (se escribe este comando) EN ANGULAR NO ES NECESARIO. /*******Pasar a un directorio*********/ se llama al comando CD y se escribe el nombre del directorio: cd 01-bases es lo mismo que: cd \Users\tic.medellin\Documents\GitHub\Angular-bases\01-bases> /****Levantar el servidor***/ ng serve ng serve -o //apenas esté listo, se abrirá /***AppComponent***/ Aquí podemos manipular el decorador @Component, este recibe un objeto como argumento. Es importante definir los argumentos del mismo: Selector recibe el app routing que conecta el index html a los diferentes componentes de la app. templateUrl: se puede escribir la ruta. template: se escribe el código de inicio directamente. Se aconseja que sí se pasa de mas de 3 líneas, se cree el AppComponent.html. Se aconseja que la lógica se mantega en el AppComponent y no en el template /***Creación de un componente****/ Siempre describir la función del componente. contador.component.ts Si es un nombre compuesto, separarlo por guiones: acumulador-simple.component.ts -Se debe agregar la ruta de nuestro componente creado en: app.component.html aplicando la siguiente sintaxis: <app-acumulador></app-acumulador> -Se debe importar y agregar el componente en app.module.ts: import { AcumuladorComponent } from './acumulador.component'; En el @NgModule, en las declarations: AcumuladorComponent **También se pueden crear componentes de forma automática: ng generate component nombre de archivo ruta ng g c nombre de archivo//versión simplificada Si se desea agregar dentro de otro componente: ng g c componente/nombre de archivo ng g c heroes/listado Si se quiere quitar el Test: ng g c onePiece/mainPage --skip-tests Si se quiere quitar el archivo de CSS: ng g c auth/pages/login --skip-tests --inline-style /*****Componentes del decorador @NgModule***/ @NgModule({ declarations: [ // ACÁ VAN LOS COMPONENTES AppComponent, AcumuladorComponent ], imports: [//ACÁ VAN LOS MODULOS BrowserModule ], providers: [], // ACÁ VAN LOS SERVICIOS bootstrap: [AppComponent] }) /****COMPONENTES CREADOS****/ Los módulos nos permiten encapsular el código y optimizar mejor la app. Las declaraciones básicamente dicen qué cosas contiene este módulo. EXPORTS: Los export significan qué cosas quiero hacer públicas o visibles fuera de este módulo. IMPORTS: modulos /***NG'S*** -NgFor es ítil para imprimir duplicados en el HTML. Como es un For, para hacerlo necesito de un ciclo, arreglo o algo iterable -NgIf condiciona lo que se imprime en el HTML, se maneja como un IF, entoces se puede condicionar con Else, sí no cumple nuestra primera expresión. En el Else, se puede usar el ng-template para crear un Template Local. OJO: está en el lado del HTML, no de la lógica /****Modulos*****/ El objetivo de los módulos es ayudarnos a agrupar componentes y piezas de nuestra aplicación que tienen sentido entre sí. Uno de ellos es encapsular las cosas y otro principal es ayudarnos con la carga perezosa (lazyLoad) Para crearlo manualmente, basta con crear un archivo y poner module.ts al final: heroes.module.ts HAcer la creación del export class con el nombre del módulo, y a continuación, crear el @NgModule con las declarations, los import, exports y los components, también es importante importantar el CommonModule para que funciones los NgFor, NgIf y otros métodos correctamente. Para crear los módulos de forma automática se escribe ng generate module nombre archivo ng g m nombre archivo Para crearlo con el routing: ng g m protected --routing /*****EVENTOS DE JS EN ANGULAR*********/ Cuando se vaya a llamar, en el HTML, se debe colocar la etiqueta estricta $ $event /*********Forms Module************/ se debe importar la librería FormsModule en el NgModule del módulo en el que vamos a trabajar nuestro formulario. La ngModel directiva realizará un seguimiento del valor ingresado por el usuario con cada tecla presionada, y también realizará un seguimiento del estado de validez de ese control de formulario en particular solamente. La ngForm directiva principal luego interactuará con todas sus ngModeldirectivas secundarias y construirá un modelo de todo el formulario, con todos sus valores de campo y estados de validez. /***********NgModule**********/ [(ngModel)] acá utilizamos two data binding, las llaves [] son para establecer alguna propiedad; los parentesis () es para emitir o escuchar eventos; al utilizarlos juntos, se pretende escuchar, emitir el evento y que la propiedad se enlace: La sintaxis de enlace bidireccional de Angular es una combinación de corchetes y paréntesis, [()]. La [()]sintaxis combina los corchetes del enlace de propiedades [], con los paréntesis del enlace de eventos (), de la siguiente manera. [(ngModel)]="nuevo.nombre" /***Herencia del componente padre hacia el hijo********/ En el componente hijo se agrega el decorador @Input() cuando el hijo necesita emitir un valor al padre /*****SERVICIOS*****/ Un servicio es un proveedor de datos, que mantiene lógica de acceso a ellos y operativa relacionada con el negocio y las cosas que se hacen con los datos dentro de una aplicación. Los servicios serán consumidos por los componentes, que delegarán en ellos la responsabilidad de acceder a la información y la realización de operaciones con los datos. Sirven como singleton, es decir, una única instancia que se va a tener lo largo de todo el módulo, en este caso el de onePiece Es una clase que tiene un decorador de tipo: @Injectable. La sintaxis para su generació es: ng generate service nombre servicio ng g s nombre servicio La sintaxis para crear el servicio es: @Injectable() //decorador que se debe importar desde @angular/core export class OnePieceService{ //se crea la clase(en angular todo son clases, lo que difiere es el decorador) y se agrega el export para que pueda ser consumido constructor(){//Se agrega el contructor } } En el módulo en que el servicio va ser consumido, se agrega el servicio en los Providers @NgModule({ declarations: [ MainPageComponent, PersonajesComponent, AgregarComponent ], exports: [ MainPageComponent ], imports: [ CommonModule, FormsModule ], providers: [ OnePieceService//Recordar importar el servicio ] }) El servicio es, por decirlo así, una clase abstracta en la cual ustedes van a colocar la información y los métodos para interactuar con fuentes externas o para manipular el estado de la información en su aplicación. Para hacer uso del servidor, utilizamos el contructor en donde queramos inyectar sus propiedades (a esto se le conoce como inyección de dependencias): constructor( private OnePieceService: OnePieceService){} Como se está inyectando la dependencia, se debe importar. OJO: Se recomienda hacer la manipulación de la información, en el servicio, no en los componentes /*******Angular flex-layout********/ Angular Flex Layout proporciona una API de diseño sofisticada utilizando Flexbox CSS + mediaQuery. Este módulo proporciona a los desarrolladores de Angular funciones de diseño de componentes mediante una API de diseño personalizada, observables de mediaQuery y estilos CSS DOM flexbox-2016 inyectados Comando para instalar: npm i -s @angular/flex-layout @angular/cdk import { FlexLayoutModule } from '@angular/flex-layout'; ... @NgModule({ ... imports: [ FlexLayoutModule ], ... }); /****JSON server***/ comando para instalar: npm install -g json-server comando para levantar: json-server --watch db.json Ojo, el Json server corre en el puerto 3000 http://localhost:3000/ /*******GUARDS******/ Los protectores de ruta de Angular son interfaces proporcionadas por Angular que, cuando se implementan, nos permiten controlar la accesibilidad de una ruta en función de las condiciones proporcionadas en la implementación de clase de esa interfaz. Estos son algunos tipos de protecciones angulares: CanActivate, CanActivateChild, CanLoad, CanDeactivate y Resolve -(CanActivate) Antes de cargar los componentes de la ruta. -(CanLoad) Antes de cargar los recursos (assets) de la ruta. -(CanDeactivate) Antes de intentar salir de la ruta actual (usualmente utilizado para evitar salir de una ruta, si no se han guardado los datos). -(CanActivateChild) Antes de cargar las rutas hijas de la ruta actual. Comando para crearlo: ng g guard nombre modulo/nombre del guard ng g guard auth/guards/auth /****Operatot OF*******/ of se utiliza para emitir argumentos como valores en una secuencia y luego completar la secuencia. A diferencia de from, no hace ningún aplanamiento o conversión y emite cada argumento con el mismo tipo que recibe como argumentos. Si se le pasa una matriz (incluidos los objetos similares a una matriz), una promesa y un objeto iterable, no se aplanará en una secuencia observable de valores. Esos argumentos se emitirán como del mismo tipo, es decir, una matriz, una promesa o un objeto iterable sin ninguna conversión. Si necesita emitir elementos de forma asíncrona, el operador toma un planificador como segundo argumento. Más información: https://indepth.dev/reference/rxjs/operators/of import { of } from 'rxjs'; of(10, 20, 30) .subscribe({ next: value => console.log('next:', value), error: err => console.log('error:', err), complete: () => console.log('the end'), });
import _merge from 'lodash.merge'; import { RemeshDomainContext, Remesh, DomainConceptName, } from 'remesh'; import { from, asyncScheduler, merge, } from 'rxjs'; import { switchMap, throttleTime, catchError, map, } from 'rxjs/operators'; import { ResourceModule } from './resource-module'; /** * Capitalize is a helper type to constraint the name should start with upper case. */ export type ListResourceModuleOptions<P, R extends { id: string | number }> = { name: DomainConceptName<'ListResourceModule'> fetch: (arg: P) => Promise<R[]>; update: (id: TIdType, data: Partial<R>) => Promise<R>; isEqual: (a: R, b: R) => boolean, default: R[], }; type TIdType = string | number; /** * ListResourceModule is a module for text. * Receiving a domain as fixed argument, you can use it in any domain by passing domain as argument. * The second argument is your custom options. */ export const ListResourceModule = <P, R extends { id: TIdType }>( domain: RemeshDomainContext, options: ListResourceModuleOptions<P, R>, ) => { const UpdateSingleEvent = domain.event<[TIdType, Partial<R>]>({ name: `${options.name}.UpdateSingleEvent` }); const UpdateSingleSuccessEvent = domain.event<[TIdType, Partial<R>]>({ name: 'UpdateSingleSuccessEvent' }); const UpdateSingleFailEvent = domain.event<string>({ name: `${options.name}.UpdateSingleFailEvent` }); const { update, isEqual, ...restOption } = options; const Resource = ResourceModule<P, R[]>(domain, restOption); const GetOneResourceByIdQuery = domain.query({ name: `${options.name}.GetOneResourceByIdQuery`, impl: ({ get }, id: string) => { const list = get(Resource.query.ResourceQuery()); return list.find((item) => item.id === id) ?? null; }, }); const UpdateListResourceCommand = domain.command({ name: `${options.name}.UpdateListResourceCommand`, impl({ get }, [id, partialItem]: [TIdType, Partial<R>]) { const list = get(Resource.query.ResourceQuery()); const newList = list.map((item) => { if (item.id === id) { return _merge({}, item, partialItem); } return item; }); return [ Resource.command.UpdateResourceCommand(newList), UpdateSingleSuccessEvent([id, partialItem]), ]; }, }); const UpdateSingleCommand = domain.command({ name: `${options.name}.UpdateSingleCommand`, impl(_ctx, [id, partialItem]: [TIdType, Partial<R>]) { return [ UpdateSingleEvent([id, partialItem]), ]; }, }); domain.effect({ name: `${options.name}.UpdateSingleEffect`, impl({ fromEvent }) { const source = fromEvent(UpdateSingleEvent); return merge( source.pipe( // 先更新本地状态 map((args) => UpdateListResourceCommand([args[0], { ...args[1] }])), ), // 延时更新服务断状态 source .pipe( throttleTime(1000, asyncScheduler, { leading: false, trailing: true, }), switchMap((args) => from(options.update(...args))), // 最后同步服务器状态 map((data) => UpdateListResourceCommand([data.id, data])), catchError(async (err) => UpdateSingleFailEvent(err?.message ?? '更新组件信息失败')), ), ); }, }); return Remesh.module({ query: { ResourceQuery: Resource.query.ResourceQuery, LoadingQuery: Resource.query.LoadingQuery, GetOneResourceByIdQuery, }, command: { UpdateSingleCommand, FetchCommand: Resource.command.FetchCommand, }, event: { FetchEvent: Resource.event.FetchEvent, FetchSuccessEvent: Resource.event.SuccessEvent, ListChangedEvent: Resource.event.ChangedEvent, FetchFailedEvent: Resource.event.FailedEvent, LoadingStartEvent: Resource.event.LoadingStartEvent, LoadingFinishEvent: Resource.event.LoadingFinishEvent, UpdateSingleFailEvent, UpdateSingleSuccessEvent, }, }); };
import Container from 'react-bootstrap/esm/Container'; import './App.css'; import AppBar from './components/appBar'; import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'; import HomeScreen from './screens/homeScreen'; import RegisterScreen from './screens/registerScreen'; import LoginuScreen from './screens/loginuScreen'; import LogineScreen from './screens/logineScreen'; import { useState } from 'react'; import { Toaster } from 'react-hot-toast'; import MatchesScreen from './screens/matchesScreen'; import MatchInfoScreen from './screens/matchScreen'; function App() { const[user, setUser] = useState(null); return ( <div className="App"> <Router> <AppBar user={user} setUser={setUser} /> <main className='py-2'> <Container> <Routes> <Route path='/' element={<HomeScreen user={user}/>} exact /> <Route path='/matches' element={<MatchesScreen/>} /> <Route path='/loginu' element={<LoginuScreen setUser={setUser}/>} /> <Route path='/logine' element={<LogineScreen setUser={setUser}/>} /> <Route path="/register" element={<RegisterScreen/>} /> <Route path="/matches/:matchID" element={<MatchInfoScreen/>} /> </Routes> </Container> </main> <Toaster toastOptions={{duration:2000}} /> </Router> </div> ); } export default App;
package oops object Enums extends App { enum Permissions{ case READ, WRITE, EXECUTE, NONE //add fields, methods def openDocument(): Unit = if(this == READ) println("Opening Document") else println("Reading not allowed") } val somePermission: Permissions = Permissions.READ println(somePermission) somePermission.openDocument() enum PermisisonWithBits(bits: Int){ case READ extends PermisisonWithBits(4) case WRITE extends PermisisonWithBits(2) case EXECUTE extends PermisisonWithBits(1) case NONE extends PermisisonWithBits(0) } object PermisisonWithBits{ def fromBits(bits: Int): PermisisonWithBits = PermisisonWithBits.NONE } //standard API val somePermissionOrdinal = somePermission.ordinal val allPermissions = PermisisonWithBits.values val readPermissions = Permissions.valueOf("READ") println(allPermissions) }
// InformeEstadistico.jsx import React, { useEffect, useState } from 'react'; import axios from 'axios'; import { Card, Container, Row, Col } from 'react-bootstrap'; const InformeEstadistico = () => { const [usuarios, setUsuarios] = useState([]); useEffect(() => { const fetchUsuarios = async () => { try { const response = await axios.get('http://localhost:8000/informe_estadistico/'); setUsuarios(response.data); } catch (error) { console.error('Error fetching usuarios:', error); } }; fetchUsuarios(); }, []); return ( <Container> <Row> {usuarios.map((usuario) => ( <Col key={usuario.usuario_id} sm={12} md={6} lg={4} className="mb-4"> <Card> <Card.Body> <Card.Title>{usuario.nombre}</Card.Title> <Card.Subtitle className="mb-2 text-muted">ID: {usuario.usuario_id}</Card.Subtitle> <Card.Text> <strong>Conexiones Salientes:</strong> <ul> {usuario.conexiones_salientes.map((conexion) => ( <li key={conexion.id}>{conexion.nombre}</li> ))} </ul> <strong>Conexiones Entrantes:</strong> <ul> {usuario.conexiones_entrantes.map((conexion) => ( <li key={conexion.id}>{conexion.nombre}</li> ))} </ul> </Card.Text> </Card.Body> </Card> </Col> ))} </Row> </Container> ); }; export default InformeEstadistico;
! User Material Subroutine for Isotropic Elasto-Visco-Plasticity ! CDD-based Material Model ! Semi-Implicit Constitutive Integration with Stress-based Return Mapping ! ! Author: Seyed Amir Hossein Motaman ! Steel Institute (IEHK), RWTH Aachen University ! ! References: ! Motaman, S.A.H.; Prahl, U.; 2019. ! Microstructural constitutive model for polycrystal viscoplasticity ! in cold and warm regimes based on continuum dislocation dynamics. ! Journal of the Mechanics and Physics of Solids 122, 205–243. ! doi: https://doi.org/10.1016/j.jmps.2018.09.002 ! ! Motaman, S.A.H.; Schacht K.; Haase, C.; Prahl, U.; 2019. ! Thermo-micro-mechanical simulation of metal forming processes. ! International Journal of Solids and Structures. ! doi: https://doi.org/10.1016/j.ijsolstr.2019.05.028 !*********************************************************************** ! including other modules and subroutines #include 'controls_module.f90' #include 'strings_module.f90' #include 'material_properties_module.f90' #include 'viscoplasticity_subroutine.f90' !*********************************************************************** ! subroutine header subroutine umat(sigma, sv, C, sse, delta_w_p, & scd, q_dot_p, dsigma_dT, dq_deps, dq_dT, & eps, delta_eps, t, delta_t, T_n, & delta_temp, pfv, delta_pfv, cmname, n_dir, & n_shr, n_total, n_sv, props, n_props, & coords, delta_R, pnewdt, l_element, F_n, & F, i_el, i_ip, i_layer, i_sp, & i_step, i_increment) !----------------------------------------------------------------------- ! pre-processing !----------------------------------------------------------------------- ! use of global variables use controls use material_properties !----------------------------------------------------------------------- ! declaration of subroutine's variables implicit none character(len = 64), intent(in) :: & cmname ! uses-specified material name, left justified integer(pInt), intent(in) :: & n_dir, & ! number of independent direct components of strain and stress tensors n_shr, & ! number of independent shear components of strain and stress tensors n_total, & ! number of independent total components of strain and stress tensors n_sv, & ! number of user-defined state variables n_props, & ! number of user-defined material parameters i_el, & ! element number i_ip, & ! integration point number i_layer, & ! layer number i_sp, & ! section point number within the current layer i_step, & ! step number i_increment ! increment number real(pReal), intent(in) :: & delta_t, & ! time increment [s] T_n, & ! temperature at the beginning of the time increment [C] delta_temp, & ! increment of temperature [C] l_element ! characteristic element length [mm] real(pReal), dimension(1), intent(in) :: & pfv, & ! array of interpolated values of predefined field variables at the beginning of the time increment delta_pfv ! array of increments of predefined field variables real(pReal), dimension(2), intent(in) :: & t ! t(1): step time and t(2): total time, at the beginning of the time increment [s] real(pReal), dimension(3), intent(in) :: & coords ! coordinates of the integration point [mm] real(pReal), dimension(n_total), intent(in) :: & eps, & ! (total) strain tensor (voigt notation, vector form) at beginning of the increment [-] delta_eps ! (total) strain increment tensor (voigt notation, vector form) [-] real(pReal), dimension(n_props), intent(in) :: & props ! material constants array real(pReal), dimension(3,3), intent(in) :: & delta_R, & ! Incremental rotation matrix [-] F_n, & ! deformation gradient tensor at the beginning of the time increment [-] F ! deformation gradient tensor at the end of the time increment [-] real(pReal), intent(inout) :: & sse, & ! specific elastic strain energy delta_w_p, & ! specific plastic dissipation scd, & ! specific creep dissipation q_dot_p, & ! volumetric heat generation per unit time at the end of the increment caused by mechanical working of the material dq_dT, & ! variation of volumetric heat generation per unit time w.r.t. temperature pnewdt ! ratio of suggested new time increment to the time increment being used (delta_t_next/delta_t_current) real(pReal), dimension(n_total), intent(inout) :: & sigma ! stress tensor (voigt notation, vector form) at the beginning of the time increment, needs to be updated at the end of the time increment [MPa] real(pReal), dimension(n_sv), intent(inout) :: & sv ! (solution-dependent) state variables array at the beginning of the time increment, needs to be updated at the end of the time increment real(pReal), dimension(n_total), intent(out) :: & dsigma_dT, & ! derivative of stress tensor w.r.t. temperature (voigt notation, vector form) [MPa/T] dq_deps ! derivative of heat generation w.r.t. strain tensor (voigt notation, vector form) real(pReal), dimension(n_total,n_total), intent(out) :: & C ! consistent/algorithmic tangent stiffness tensor or dsigma_deps (constitutive/material Jacobian) (voigt notation, vector form) [MPa] !----------------------------------------------------------------------- ! declaration of subroutines' local variables logical :: & trial_flag ! flag to determine whether the call to the yield function is for calculation of trial stress or not integer(pInt) :: & i_material, & ! index number associated with each material i, & ! loop counter variable i j, & ! loop counter variable j k_NR ! newton-raphson (NR) iterative loop index real(pReal) :: & rho_hat_cm_n, & ! normalized cell mobile dislocation density at the beginning of the time increment [-] rho_hat_ci_n, & ! normalized cell immobile dislocation density at the beginning of the time increment [-] rho_hat_wi_n, & ! normalized wall immobile dislocation density at the beginning of the time increment [-] rho_hat_cm, & ! normalized cell mobile dislocation density at the end of the time increment [-] rho_hat_ci, & ! normalized cell immobile dislocation density at the end of the time increment [-] rho_hat_wi, & ! normalized wall immobile dislocation density at the end of the time increment [-] eps_bar_p, & ! equivalent plastic strain [-] eps_bar_dot_p, & ! equivalent plastic strain rate [s^-1] T_hat_n, & ! normalized absolute temperature at the beginning of the time increment [-] nu, & ! poisson's ratio [-] G, & ! shear modulus [MPa] K, & ! bulk modulus [MPa] sigma_bar_trial, & ! equivalent trial stress [MPa] eps_dot_p_min, & ! minimum plastic strain rate [s^-1] eps_bar_dot_p_corr, & ! corrected equivalent plastic strain rate [s^-1] delta_eps_bar_p, & ! equivalent plastic strain increment [-] sigma_y, & ! yield stress [MPa] sigma_y_trial, & ! trial yield stress [MPa] H_vp, & ! viscoplastic tangent modulus (derivative of yield stress w.r.t. equivalent plastic strain increment) [MPa] beta, & ! dissipation factor [-] R, & ! residual/yield function to be solved using the newton-raphson method [MPa] G_eff, & ! effective modulus mu [MPa] H_eff ! effective viscoplastic tangent modulus [MPa] real(pReal), dimension(n_total) :: & eps_e, & ! elastic strains tensor (vector form) [-] eps_p, & ! plastic strains tensor (vector form) [-] sigma_h, & ! hydrostatic stress tensor (vector form) [MPa] sigma_d_trial, & ! trial deviatoric stress tensor (vector form) [MPa] delta_eps_p, & ! plastic strain increment tensor [-] N, & ! flow direction tensor (vector form) [-] sigma_d ! deviatoric stress tensor (vector form) [MPa] !----------------------------------------------------------------------- ! assigning values to (initializing) global variables associated with material parameters if (.not. material_parameters_assigned) then call MutexInit(1) call MutexLock(1) if (.not. material_parameters_assigned) then call assign_material_parameters() end if call MutexUnlock(1) end if !----------------------------------------------------------------------- ! reading the material index number associated with the current material point i_material = int(props(1)) !----------------------------------------------------------------------- ! initializing/retrieving state variables ! ! state variables array: ! 2D case (*DEPVAR = n_sv = 13) ! sv(1) : cell mobile dislocation density [m^-2] ! sv(2) : cell immobile dislocation density [m^-2] ! sv(3) : wall immobile dislocation density [m^-2] ! sv(4:7) : elastic strain tensor (vector form) [-] ! sv(8:11) : plastic strain tensor (vector form) [-] ! sv(12) : equivalent plastic strain [-] ! sv(13) : equivalent plastic strain rate [s^-1] ! ! 3D case (*DEPVAR = n_sv = 17) ! sv(1) : cell mobile dislocation density [m^-2] ! sv(2) : cell immobile dislocation density [m^-2] ! sv(3) : wall immobile dislocation density [m^-2] ! sv(4:9) : elastic strain tensor (vector form) [-] ! sv(10:15) : plastic strain tensor (vector form) [-] ! sv(16) : equivalent plastic strain [-] ! sv(17) : equivalent plastic strain rate [s^-1] if (t(2) <= delta_t) then ! initializing state variables for undeformed state rho_hat_cm_n = rho_hat_cm0(i_material) rho_hat_ci_n = rho_hat_ci0(i_material) rho_hat_wi_n = rho_hat_wi0(i_material) eps_e = 0.0e0 eps_p = 0.0e0 eps_bar_p = 0.0e0 eps_bar_dot_p = 0.0e0 else ! retrieving state variables at the beginning of the time increment (end of the last time step) [-] rho_hat_cm_n = sv(1) / rho_0(i_material) ! {Eq. 59(b,c)} rho_hat_ci_n = sv(2) / rho_0(i_material) ! {Eq. 59(b,c)} rho_hat_wi_n = sv(3) / rho_0(i_material) ! {Eq. 59(b,c)} call rotsig (sv(4 ), delta_R, eps_e, 2, n_dir, n_shr) call rotsig (sv(n_total + 4), delta_R, eps_p, 2, n_dir, n_shr) eps_bar_p = sv(2 * n_total + 4) eps_bar_dot_p = sv(2 * n_total + 5) end if !----------------------------------------------------------------------- ! processing !----------------------------------------------------------------------- ! calculation of normalized relative temperatures {Eq. 93(d)} T_hat_n = (T_n - T_abs0) / (T_0(i_material) - T_abs0) ! calculation of elastic stiffness moduli nu = nu_0(i_material) * (1.0e0 + r_nu(i_material) * (T_hat_n - 1.0e0)**s_nu(i_material)) ! {Eq. 118} G = G_0 (i_material) * (1.0e0 + r_G (i_material) * (T_hat_n - 1.0e0)**s_G (i_material)) ! {Eq. 117} K = 2.0e0 / 3.0e0 * (1.0e0 + nu) / (1.0e0 - 2.0e0 * nu) * G ! {Eq. Box 1.1(b)} ! constructing elastic stiffness tensor {Eq. Box 1.1} C = 0.0e0 do i = 1, n_dir do j = 1, n_dir C(i,j) = K - 2.0e0 / 3.0e0 * G end do end do do i = 1, n_total C(i,i) = C(i,i) + 2.0e0 * G end do ! calculation of trial stress tensor {Eq. Box 1.2, Eq. Box 1.5} do i = 1, n_total do j = 1, n_total sigma(i) = sigma(i) + C(i,j) * delta_eps(j) end do end do ! calculation of hydrostatic stress tensor {Eq. Box 1.3(b,c)} sigma_h = 0.0e0 sigma_h(1:n_dir) = sum(sigma(1:n_dir)) / 3.0e0 ! calculation of trial deviatoric stress tensor {Eq. Box 1.3} sigma_d_trial = sigma - sigma_h ! calculation of equivalent trial stress {Eq. Box 1.4(b)} sigma_bar_trial = 0.0e0 do i = 1, n_dir sigma_bar_trial = sigma_bar_trial + sigma_d_trial(i)**2 end do do i = n_dir + 1, n_total sigma_bar_trial = sigma_bar_trial + 2.0e0 * sigma_d_trial(i)**2 end do sigma_bar_trial = sqrt(3.0e0 / 2.0e0 * sigma_bar_trial) ! calculation of corrected equivalent strain rate {Eq. 99} eps_dot_p_min = xi_min * eps_bar_dot_0(i_material) if (eps_bar_dot_p > eps_dot_p_min) then eps_bar_dot_p_corr = eps_bar_dot_p else eps_bar_dot_p_corr = eps_dot_p_min end if ! initializing (trial) plastic strain increments {Eq. Box 1.5(d)} delta_eps_bar_p = 0.0e0 delta_eps_p = 0.0e0 ! calculation of trial plastic stress {Eq. 97} trial_flag = .true. call viscoplasticity(trial_flag, i_material, delta_t, T_hat_n, eps_bar_dot_p_corr, delta_eps_bar_p, rho_hat_cm_n, rho_hat_ci_n, rho_hat_wi_n, rho_hat_cm, rho_hat_ci, rho_hat_wi, sigma_y, H_vp, beta) sigma_y_trial = sigma_y ! checking for plastic yielding: plastic yielding occurs if equivalent trial stress is greater than trial plastic stress if(sigma_bar_trial > sigma_y_trial) then ! {Eq. 89} ! initializing variables for return mapping trial_flag = .false. delta_eps_bar_p = eps_bar_dot_p_corr * delta_t ! {Eq. 102} ! return mapping loop: solving for equivalent plastic strain increment using newton-raphson iterative method do k_NR = 1, k_NR_max call viscoplasticity(trial_flag, i_material, delta_t, T_hat_n, eps_bar_dot_p_corr, delta_eps_bar_p, rho_hat_cm_n, rho_hat_ci_n, rho_hat_wi_n, rho_hat_cm, rho_hat_ci, rho_hat_wi, sigma_y, H_vp, beta) R = sigma_bar_trial - sigma_y - 3.0e0 * G * delta_eps_bar_p ! {Eq. 96} if (abs(R) < chi * sigma_y_trial) exit ! {Eq. 103} delta_eps_bar_p = delta_eps_bar_p + R / (H_vp + 3.0e0 * G) ! {Eq. 105} end do ! checking for divergence: reducing time step size and writing warning message if (abs(R) > chi * sigma_y_trial) then pnewdt = 0.5e0 write(6,"('warning: return mapping algorithm for element ', i5, ', integration point ', i2, ' did not converge after ', i2,' iterations')") i_el, i_ip, k_NR return end if ! calculation of flow direction tensor {Eq. Box 1.6(c)} N = 3.0e0 / 2.0e0 * sigma_d_trial / sigma_bar_trial ! updating stress tensor sigma_d = 2.0e0 / 3.0e0 * sigma_y * N ! {Eq. Box 1.6(b)} sigma = sigma_d + sigma_h ! {Eq. Box 1.6} ! calculation of effective moduli G_eff = sigma_y / sigma_bar_trial * G ! {Eq. Box 1.7(b)} H_eff = 4.0e0 / 3.0e0 * (G / (1.0e0 + 3.0e0 * G / H_vp) - G_eff) ! {Eq. Box 1.7} ! updating consistent tangent stiffness tensor {Eq. Box 1.8} C = 0.0e0 do i = 1, n_dir do j = 1, n_dir C(i,j) = K - 2.0e0 / 3.0e0 * G_eff end do end do do i = 1, n_total C(i,i) = C(i,i) + 2.0e0 * G_eff end do do i = 1, n_total do j = 1, n_total C(i,j) = C(i,j) + H_eff * N(i) * N(j) end do end do ! updating plastic strain increment tensor {Eq. Box 1.6(c)} delta_eps_p = delta_eps_bar_p * N end if ! calculation of plastic dissipation work and plastic heat generation {Eqs. Box 1.9, 68} delta_w_p = delta_eps_bar_p * sigma_y q_dot_p = beta * delta_w_p / delta_t ! calculation of strains {Eq. 68} eps_e = eps_e + delta_eps - delta_eps_p eps_p = eps_p + delta_eps_p eps_bar_p = eps_bar_p + delta_eps_bar_p eps_bar_dot_p = delta_eps_bar_p / delta_t !----------------------------------------------------------------------- ! post-processing !----------------------------------------------------------------------- ! updating state variables sv(1) = rho_hat_cm * rho_0(i_material) ! {Eq. 59(b,c)} sv(2) = rho_hat_ci * rho_0(i_material) ! {Eq. 59(b,c)} sv(3) = rho_hat_wi * rho_0(i_material) ! {Eq. 59(b,c)} sv(4 : n_total + 3) = eps_e sv(n_total + 4 : 2 * n_total + 3) = eps_p sv(2 * n_total + 4) = eps_bar_p sv(2 * n_total + 5) = eps_bar_dot_p return end subroutine umat
#### 테이블 통계정보 테이블의 통계정보는 중요하다. 실제 데이터가 어떻게 분포되어 있는지, 각 인덱스는 어떤 특징을 가지고 있는지는 더 나은 실행계획을 세울때에 도움이 된다. ~~~sql select * from employees where gender = 'M' and first_name = 'Matt'; ~~~ 예를 들어, 위의 쿼리는 `ix_gender_birthdate`, `ix_firstname` 두 개의 인덱스를 모두 사용할 수 있다. 그런데 `ix_gender_birthdate`에서 `gender`만 사용하면 인덱스의 거의 절반을 스캔해야하고, `ix_firstname`의 경우는 일부만 스캔해야 할 것이다. 이러한 정보는 테이블 통계정보를 사용하여 확인할 수 있으며 더 나은 실행계획을 수립하는데에 사용할 수 있다. 인덱스 통계 테이블을 직접 확인해보자. ~~~sql use mysql; select * from innodb_index_stats where table_name = 'employees' ; ~~~ ![status1](../img/status1.png) 첫번째 초록박스는 `ix_firstname` 인덱스를 나타내고 그 중 `first_name` 컬럼만을 분석한 정보이다. `stat_value` 컬럼을 보면 유니크한 값을 `1255`개로 찾은 것을 볼 수 있다. 이는 `sample_size`의 `20`개의 innoDB 페이지개수를 샘플링하여 얻어낸 정보이다. 두번째 초록박스는 `ix_gender_birthdate` 인덱스를 나타내고 그중 `gender` 컬럼만을 분석한 정보이다. 마찬가지로 `stat_value` 컬럼을 보면 유니크한 값을 `1`개로 찾은 것을 볼 수 있다. 실제 성별은 `2`개여서 `2`가 맞지만 샘플링한 `20`개의 페이지에서는 하나의 정보만 들어있던 것이다. 여튼, 위의 쿼리중 두개의 인덱스중 하나를 선택해야 한다면 `stat_value`가 더 많은 `ix_firstname`를 선택하는게 좋아보인다. 이런식으로 인덱스 통계정보는 더 나은 실행계획을 수립할때에 중요하다. 넘어가기 전 `stat_name` 컬럼의 `n_leaf_pages`는 인덱스의 `리프노드 페이지 개수`이고, `size`는 `인덱스 전체 페이지 개수`이다. #### 히스토그램 mysql은 인덱스의 통계정보관리를 넘어 `히스토그램`이라는 것도 관리할 수 있다. `히스토그램`은 테이블의 컬럼단위로 통계정보를 관리하는 데이터이다. 현재는 자동이 아니며 수동으로 수집해야 한다. 명령어는 아래와 같다. ~~~sql ANALYZE TABLE ... UPDATE HISTOGRAM ON ... ~~~ 일단 수행하여 `히스토그램`에는 어떤 정보들이 들어있는 지 확인해보자. ~~~sql analyze table employees update histogram on gender, hire_date; use information_schema; select * from column_statistics ; ~~~ 결과값의 `histogram` 컬럼은 json 형식이며 아래와 같이 출력되었다. ~~~json ## gender 컬럼 { "buckets": [ [ 1, 0.5978844027951035 ], [ 2, 1 ] ], "data-type": "enum", "null-values": 0, "collation-id": 45, "last-updated": "2023-11-17 01:44:24.954174", "sampling-rate": 0.34747935694636256, "histogram-type": "singleton", "number-of-buckets-specified": 100 } ## hire_date 컬럼 { "buckets": [ [ "1985-02-01", "1985-03-01", 0.009989756696179552, 29 ], [ "1985-03-02", "1985-03-28", 0.01990852019756392, 27 ], ... [ "1997-12-08", "1998-07-29", 0.9899798176489082, 231 ], [ "1998-07-30", "2000-01-28", 1, 419 ] ], "data-type": "date", "null-values": 0, "collation-id": 8, "last-updated": "2023-11-17 01:44:24.955128", "sampling-rate": 0.34747935694636256, "histogram-type": "equi-height", "number-of-buckets-specified": 100 } ~~~ 먼저 `histogram-type` 부분을 보면 `sigleton`은 데이터의 값 단위로 `buckets`에 데이터를 저장한다. `equi-height`는 각 버킷의 `시작과 마지막 값`, `발생빈도` 그리고 `유니크한 값의 개수` 총 `4`개의 데이터를 저장한다. `sampling-rate` 는 이 히스토그램 데이터를 만들기위해 전체 데이터 중 스캔한 비율이다. `number-of-buckets-specified`는 말 그대로 버킷의 개수인데 디폴트는 `100`이고 `100`이면 충분한 것으로 알려져있다. 이렇게 설정한 `히스토그램`은 쿼리 실행계획에서 이용할지의 세팅은 `condition_fanout_filter`라는 변수로 한다. 그러면 이 `히스토그램`이 구체적으로 쿼리 실행계획에서 어떻게 이용되는지 살펴보자. ~~~sql explain select * from employees where first_name = 'Zita' and birth_date BETWEEN '1950-01-01' and '1960-01-01' ; ~~~ ![histogram1](../img/histogram1.png) 실행계획을 분석해보면 `ix_firstname` 인덱스가 사용되었고, `first_name = 'Zita'` 조건으로 `224`개의 데이터가 있을 것으로 예상했으며, 이 중 `birth_date` 조건으로 `11.11 %`의 데이터만 유용할 것이라고 판단하였다. `first_name = 'Zita'` 조건으로 `224`개의 데이터가 있는것은 맞으나, 최종 데이터 개수는 `143`개로 무려 `63 %`가 유용한 데이터이다. `히스토그램`을 생성하고 다시 위의 실행계획을 분석하면 아래와 같이 `filtered`의 비율이 꽤나 정확해진 것을 볼 수 있다. ![histogram2](../img/histogram2.png) 이러한 비율이 실행계획에 어떤 영향을 미칠 수 있다는 것일까? 근접한 `filtered` 비율을 유추할 수 있다면 더 정확한 실행계획을 세울 수 있다. 특히나 조인순서에 영향을 미칠 수 있다. ~~~sql explain select * from salaries s inner join employees e on e.emp_no and s.emp_no and e.birth_date BETWEEN '1950-01-01' and '1950-02-01' where s.salary BETWEEN 40000 and 70000 ; ~~~ ![histogram3](../img/histogram3.png) 위의 실행계획은 `employees` 테이블을 풀스캔하여 `299,778`번의 조인이 일어났을 것이다. `salaries` 테이블의 `filter` 비율이 `90`이고 이를 드라이빙 테이블로 했다면 `1,395,843 * 0.9` 만큼 조인해야 하기때문이다. 그러나 히스토그램을 분석하고 실제 `filter` 비율이 `10`이었다면 약 `139,584`번만 조인하면 되기 때문에 드라이빙 테이블을 바꿨을 수 있다. 그렇다면 `히스토그램`이 있는 컬럼이면 무조건 사용할까? ~~~sql select * from employees where first_name = 'Tonny' and birth_date between '2954-01-01' and '1955-01-01' ; ~~~ 위 예시에서 `first_name`은 `인덱스`와 `히스토그램`이 둘 다 있다고 가정해보자. `mysql 8` 버전에서는 `인덱스`가 있고 `히스토그램`이 있다면 `히스토그램`을 굳이 사용하지 않는다. 그대신 `인덱스`를 활용하여 실제로 데이터를 샘플링해서 조금 읽어본다. 이를 `인덱스 다이브`라고 한다. 이 정보는 실제 데이터 조회이므로 더 정확하다고 판단하는 것이다. `인덱스 다이브`는 실행비용이 있고 `히스토그램`은 이미 만들어진 데이터를 조회하므로, `히스토그램`이 비용은 적게 들 것이다. 이후 버전에서는 `인덱스 다이브`보다 `히스토그램`을 사용하는 방향으로 나올지 기대할수도 있을 것이다.
<!-- <h2>{{item.name | uppercase}} --> <!-- Pipes are a good way to format strings, currency amounts, dates and other display data. Angular ships with several built-in pipes and you can create your own. --> <!-- Details --> <!-- </h2> --> <!-- <div><span>id: </span>{{item.id}}</div> --> <!-- <div> --> <!-- <label for="name"></label> --> <!-- [(ngModel)] is Angular's two-way data binding syntax. --> <!-- Here it binds the item.name property to the HTML textbox so that data can flow in both directions: --> <!-- From the item.name property to the textbox and from the textbox back to the item.name. --> <!-- imports for the module added in app.module.ts --> <!-- <input id="name" [(ngModel)]="item.name" placeholder="name"> --> <!-- </div> --> <h2>Menu Items</h2> <ul class="items"> <!--*ngFor; Angular's repeater directive --> <li *ngFor="let item of items"> <!-- https://angular.io/guide/class-binding --> <!-- [class.some-css-class]="some-condition" angular's css class binding --> <button type="button" [class.selected]="item == selectedItem"> <!-- Angular's event binding syntex --> <a routerLink="/detail/{{item.id}}"> <span class="badge">{{item.id}}</span>{{item.name}} </a> </button> </li> </ul> <!-- // binding item to selectedItem --> <!-- it is a one way data binding --> <!-- <app-item-details [item]="selectedItem"></app-item-details> -->
<!DOCTYPE html> <html lang="ru"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Mesto</title> </head> <body class="page"> <header class="header"> <img class="header__logo" src="<%=require('./images/logo.svg')%>" alt="Логотип"> </header> <main class="content"> <section class="profile"> <div class="profile__container"> <img class="profile__avatar" src="<%=require('./images/avatar.png')%>" alt="Ваш аватар"> <button class="profile__avatar-button" type="button"></button> </div> <h1 class="profile__name">Жак-Ив Кусто</h1> <p class="profile__about">Исследователь океана</p> <button class="button profile__edit-button" type="button"></button> <button class="button profile__add-button" type="button"></button> </section> <section class="card-grid"> </section> </main> <footer class="footer"> <p class="footer__copyright">&copy; 2022 Mesto Russia x Владислав Смирнов</p> </footer> <div class="popup popup-edit"> <div class="popup__container"> <button class="button popup__close-button close-edit" type="button"></button> <h2 class="popup__title">Редактировать профиль</h2> <form class="form form-edit" name="profile" novalidate> <fieldset class="form__set"> <label class="form__field"> <input id="name-input" class="form__input form__input_type_name" name="name" type="text" value="" minlength="2" maxlength="40" placeholder="Имя" required> <span class="form__input-error name-input-error"></span> </label> <label class="form__field"> <input id="about-input" class="form__input form__input_type_about" name="about" type="text" value="" minlength="2" maxlength="200" placeholder="Вид деятельности" required> <span class="form__input-error about-input-error"></span> </label> <button class="button form__submit-button submit-edit" type="submit">Сохранить</button> </fieldset> </form> </div> </div> <div class="popup popup-add"> <div class="popup__container"> <button class="button popup__close-button" type="button"></button> <h2 class="popup__title">Новое место</h2> <form class="form form-add" name="place" novalidate> <fieldset class="form__set"> <label class="form__field"> <input id="title-input" class="form__input form__input_type_title" name="title" type="text" value="" minlength="2" maxlength="30" placeholder="Название" required> <span class="form__input-error title-input-error"></span> </label> <label class="form__field"> <input id="link-input" class="form__input form__input_type_link" name="link" type="url" placeholder="Ссылка на картинку" required> <span class="form__input-error link-input-error"></span> </label> <button class="button form__submit-button submit-add" type="submit">Создать</button> </fieldset> </form> </div> </div> <div class="popup popup-img"> <div class="popup__img-container"> <button class="button popup__close-button" type="button"></button> <img class="popup__img" src=" " alt="Фотография карточки"> <p class="popup__discripton"></p> </div> </div> <div class="popup popup-avatar"> <div class="popup__container"> <button class="button popup__close-button" type="button"></button> <h2 class="popup__title">Обновить аватар</h2> <form class="form form-avatar" name="avatar" novalidate> <fieldset class="form__set"> <label class="form__field"> <input id="avatar-input" class="form__input form__input_type_avatar" name="avatar" type="url" placeholder="Ссылка на картинку" required> <span class="form__input-error avatar-input-error"></span> </label> <button class="button form__submit-button submit-avatar" type="submit">Сохранить</button> </fieldset> </form> </div> </div> <div class="popup popup-confirm"> <div class="popup__container"> <button class="button popup__close-button" type="button"></button> <h2 class="popup__title">Вы уверены?</h2> <form class="form form-confirm"> <button class="button form__submit-button submit-confirm" type="submit">Да</button> </form> </div> </div> <template id="card-template"> <article class="card"> <img class="card__img" src=" " alt="Фотография карточки"> <button class="button card__delete-button" type="button"></button> <h2 class="card__title"></h2> <button class="button card__like-button" type="button"></button> <span class="card__like-counter">0</span> </article> </template> </body> </html>
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, OneToMany, } from "typeorm"; import { Product } from "./product"; @Entity() export class User { @PrimaryGeneratedColumn() declare id: number; @Column({ type: "text", }) declare firstName: string; @Column({ type: "text", }) declare lastName: string; @Column({ type: "text", nullable: true, }) declare email?: string; @Column({ type: "boolean", default: true, }) declare isActive: boolean; @OneToMany(() => Product, (product) => product.user) declare products: Product[]; @CreateDateColumn() declare createdAt: Date; @UpdateDateColumn() declare updatedAt: Date; }
// // HomeStatusCell.swift // WeiboSwift // // Created by zhanghan on 2022/10/13. // import UIKit class HomeStatusCell: UITableViewCell { var statusViewModel: HomeItemViewModel? { didSet { topView.statusViewModel = statusViewModel contentLabel.text = statusViewModel?.status.text pictureView.viewModel = statusViewModel pictureView.snp.updateConstraints { make in make.width.equalTo(pictureView.bounds.width) make.height.equalTo(pictureView.bounds.height) let offset = statusViewModel?.thumbnailUrls?.count ?? 0 > 0 ? sideMargin_ : 0 make.top.equalTo(contentLabel.snp.bottom).offset(offset) } } } private lazy var headSepView: UIView = { let view = UIView() view.backgroundColor = BackColor return view }() private lazy var topView = HomeStatusTopView() private lazy var contentLabel = UILabel(title: "微博正文", fontSize: 15, align: .left, screenInset: sideMargin_) private lazy var pictureView = StatusPicureView() private lazy var bottomView = HomeStatusBottomView() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none setupUI() } func rowHeight(vm: HomeItemViewModel) -> CGFloat { statusViewModel = vm contentView.layoutIfNeeded() return CGRectGetMaxY(bottomView.frame) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } } extension HomeStatusCell { private func setupUI() { contentView.addSubview(headSepView) contentView.addSubview(topView) contentView.addSubview(contentLabel) contentView.addSubview(pictureView) contentView.addSubview(bottomView) headSepView.snp.makeConstraints { make in make.top.left.right.equalTo(contentView) make.height.equalTo(sideMargin_) } topView.snp.makeConstraints { make in make.top.equalTo(headSepView.snp.bottom) make.left.right.equalTo(contentView) } contentLabel.snp.makeConstraints { make in make.top.equalTo(topView.snp.bottom).offset(sideMargin_) make.left.equalTo(contentView).offset(sideMargin_) } pictureView.snp.makeConstraints { make in make.top.equalTo(contentLabel.snp.bottom).offset(sideMargin_) make.left.equalTo(contentLabel) make.width.equalTo(300) make.height.equalTo(90) } bottomView.snp.makeConstraints { make in make.top.equalTo(pictureView.snp.bottom).offset(sideMargin_) make.left.right.equalTo(contentView) make.height.equalTo(44) // make.bottom.equalTo(contentView) } } }
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700;900&family=Playfair+Display:ital,wght@0,600;0,700;0,900;1,700&family=Quicksand:wght@300;400;500;600;700&display=swap'); //Variables $playfair: 'PlayFair Dispaly', serif; $quicksand: 'Quicksand', serif; $roboto: 'Roboto', serif; $dark: #3c393d; $exdark: #2b2b2b; * { padding: 0; margin: 0; font-family: $quicksand; text-decoration: none; } body { line-height: 1.4; color: $dark; } img { width: 100%; display: block; } .container { max-width: 1320px; margin: 0 auto; padding: 0 1.2rem; } header { min-height: 100vh; background: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.4)), url(/uploads/banner-bg.jpg) center/cover no-repeat fixed; display: flex; justify-content: stretch; flex-direction: column; } .navbar { background: rgba(0, 0, 0, 0.6); padding: 1.2rem; } .navbar-brand { color: #fff; font-size: 2rem; display: block; text-decoration: none; text-align: center; font-family: $playfair; letter-spacing: 1px; } .navbar-nav { padding: 0.8rem 0 0.2rem 0; text-align: center; a { text-transform: uppercase; color: #fff; font-family: $roboto; letter-spacing: 3px; font-weight: 300; text-decoration: none; transition: opacity 0.5 ease; } a:hover { opacity: 0.5; } } .banner { display: flex; flex: 1; align-items: center; text-align: center; justify-content: center; color: #fff; .banner-title { font-size: 3rem; font-family: $playfair; line-height: 1.2; } span { color: $exdark; } p { padding: 1rem 0 2rem 0; font-size: 1.2rem; text-transform: capitalize; font-weight: 500; font-family: $roboto; word-spacing: 2px; } form { background: #fff; padding: 0.6rem 1rem; border-radius: 2rem; display: flex; justify-content: space-between; .search-input { font-family: $roboto; font-size: 1rem; width: 100%; border: none; outline: 0; } .search-input::placeholder { text-transform: capitalize; } .search-btn { width: 40px; color: $dark; outline: 0; border: none; cursor: pointer; font-size: 1rem; background-color: transparent; } } } // Home .title { text-align: center; padding: 1rem 0; h2 { font-family: $playfair; font-size: 2.4rem; } p { text-transform: uppercase; padding: 0.5rem 0; } } .design { padding: 2rem 0; .design-content { margin: 2rem 0; .design-item { cursor: pointer; } .design-img { position: relative; overflow: hidden; img { transition: all 0.2s ease; } } .design-img::after { position:absolute; content: ""; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.3); } .design-img span:first-of-type { position: absolute; top: 10px; left: 10px; z-index: 1; background: $exdark; color: #fff; padding: 0.25rem 1rem; } .design-img span:first-of-type:hover { color: rgb(238, 54, 54); } .design-img span:last-of-type { position: absolute; bottom: 10px; right: 10px; z-index: 1; color: #fff; font-size: 1.2rem; font-weight: 700; } .design-item:hover img { transform: scale(1.2); } .design-title { padding: 1rem; font-size: 1.2rem; text-align: center; width: 70%; margin: 0 auto; a { color: $dark; text-transform: capitalize; font-family: $playfair; } } } } // Blog .blog { background: #f9f9f9; padding: 2rem 0; } .blog-content { margin: 2rem 0; } .blog-img { cursor: pointer; overflow: hidden; img { transition: all 0.5s ease; } } .blog-img:hover img { transform: scale(1.2); } .blog-img { position: relative; } .blog-img span { position: absolute; top: 10px; left: 10px; z-index: 1; background: $exdark; color: #fff; padding: 0.25rem 1rem; } .blog-text { margin: 2.2rem 0; padding: 0 1rem; span { font-weight: 300; padding-bottom: 0.5rem; } h2 { font-family: $playfair; padding: 1rem 0; font-size: 1.65rem; font-weight: 500; } p { font-weight: 300; font-size: 1.1rem; opacity: 0.9; padding-bottom: 1.2rem; } a { font-family: $roboto; font-size: 1.1rem; color: #fff; background: $dark; padding: 0.55rem 1.2rem; border-radius: 5px; } } // Footer footer { background: $exdark; color: #fff; text-align: center; padding: 1rem 0; } .social-link { display: flex; justify-content: center; margin-bottom: 1rem; a { text-decoration: none; border: 2px solid #fff; display: block; width: 40px; height: 40px; display: flex; justify-content: center; align-items: center; border-radius: 50%; color: #fff; margin: 0 10px; } } // Post .post { background-color: #f6f6f7!important; } .btn { display: block; padding: 7px 15px; background: #31c230; color: #fff; border: none; cursor: grabbing; margin: 10px auto; font-size: 1.2rem; } .form-control { font-family: $playfair; font-weight: 500; font-size: 1.2rem; padding-top: 1rem; .input-inner { margin-top: 10px; width: 100%; padding: 10px 10px; border: 1px solid #dcdfe6; outline: none; font-size: 1.1rem; background: none repeat scroll 0 0 rgba(0, 0, 0, 0.07); } .input-inner:focus { border: 2px solid #409eff; } textarea { margin-top: 10px; width: 100%; min-height: 50vh; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-right-colors: none; -moz-border-top-colors: none; background: none repeat scroll 0 0 rgba(0, 0, 0, 0.07); border-color: -moz-use-text-color #FFFFFF #FFFFFF -moz-use-text-color; border-image: none; border-radius: 6px 6px 6px 6px; border-style: none solid solid none; border-width: medium 1px 1px medium; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12) inset; color: #555555; font-family: $roboto; font-size: 1em; line-height: 1.4em; padding: 5px 8px; transition: background-color 0.2s ease 0s; } textarea:focus { border: 2px solid #409eff; } } .post-content { margin-top: 50px; margin-bottom: 50px; font-size: 1.5rem; font-family: $roboto; line-height: 2rem; color: #000; p { margin: 12px 0; } h1 { font-size: 3rem; margin: 10px 0; } h2 { font-size: 1.8rem; margin: 10px 0; } li { margin: 12px 23px; } } //Reponsive @media screen and (min-width: 540px) { .navbar-nav a { padding-right: 1.2rem; padding-left: 1.2rem; } .banner-title { font-size: 5rem; } .banner form { margin-top: 1.4rem; width: 80%; margin-right: auto; margin-left: auto; } } @media screen and (min-width: 768px) { .navbar .container { display: flex; justify-content: space-between; align-items: center; } .design-content { display: grid; grid-template-columns: repeat(2, 1fr); gap: 2rem; } .design-item { margin: 0; } .blog-content { display: grid; grid-template-columns: repeat(2, 1fr); gap: 2rem; } .banner form { width: 100%; } } @media screen and (min-width: 992px) { .blog-content { grid-template-columns: repeat(3, 1fr); } } @media screen and (min-width: 1200px) { .design-content { grid-template-columns: repeat(3, 1fr); } }
package ma.digital.prospace.domain; import java.io.Serializable; import java.time.Instant; import java.util.UUID; import jakarta.persistence.*; import ma.digital.prospace.domain.enumeration.StatutAssociation; import ma.digital.prospace.domain.enumeration.StatutInvitation; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import org.hibernate.annotations.GenericGenerator; /** * A Procuration. */ @Entity @Table(name = "procuration") @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) @SuppressWarnings("common-java:DuplicatedBlocks") public class Procuration implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") @Column(name = "id", updatable = false, nullable = false) private UUID id; @Transient @Column(name = "date_effet") private Instant dateEffet; @Transient @Column(name = "date_fin") private Instant dateFin; @Enumerated(EnumType.STRING) @Column(name = "statut") private StatutInvitation statut; @ManyToOne @JsonIgnoreProperties(value = { "entrepriseGeree", "mandataires", "mandants", "associations" }, allowSetters = true) private ComptePro gestionnaireEspacePro; @ManyToOne @JsonIgnoreProperties(value = { "entrepriseGeree", "mandataires", "mandants", "associations" }, allowSetters = true) private ComptePro utilisateurPro; // jhipster-needle-entity-add-field - JHipster will add fields here public UUID getId() { return this.id; } public Procuration id(UUID id) { this.setId(id); return this; } public void setId(UUID id) { this.id = id; } public Instant getDateEffet() { return this.dateEffet; } public Procuration dateEffet(Instant dateEffet) { this.setDateEffet(dateEffet); return this; } public void setDateEffet(Instant dateEffet) { this.dateEffet = dateEffet; } public Instant getDateFin() { return this.dateFin; } public Procuration dateFin(Instant dateFin) { this.setDateFin(dateFin); return this; } public void setDateFin(Instant dateFin) { this.dateFin = dateFin; } public StatutInvitation getStatut() { return statut; } public void setStatut(StatutInvitation statut) { this.statut = statut; } public ComptePro getGestionnaireEspacePro() { return this.gestionnaireEspacePro; } public void setGestionnaireEspacePro(ComptePro comptePro) { this.gestionnaireEspacePro = comptePro; } public Procuration gestionnaireEspacePro(ComptePro comptePro) { this.setGestionnaireEspacePro(comptePro); return this; } public ComptePro getUtilisateurPro() { return this.utilisateurPro; } public void setUtilisateurPro(ComptePro comptePro) { this.utilisateurPro = comptePro; } public Procuration utilisateurPro(ComptePro comptePro) { this.setUtilisateurPro(comptePro); return this; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Procuration)) { return false; } return id != null && id.equals(((Procuration) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "Procuration{" + "id=" + id + ", dateEffet=" + dateEffet + ", dateFin=" + dateFin + ", gestionnaireEspacePro=" + gestionnaireEspacePro + ", utilisateurPro=" + utilisateurPro + ", statut=" + statut + '}'; } }
### 解题思路 对数组排序之后,用同时遍历两个数组,把相同元素放在第三个数组中,直到一个数组遍历完,结束。 ### 代码 ```golang func intersect(nums1 []int, nums2 []int) []int { sort.Ints(nums1) sort.Ints(nums2) result := []int{} i,j := 0,0 for i < len(nums1) && j < len(nums2) { if nums1[i] < nums2[j] { i++ }else if nums1[i] > nums2[j] { j++ }else { result = append(result,nums1[i]) i++ j++ } } return result } ```
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginPageComponent } from './pages/login-page/login-page.component'; import { HomePageComponent } from './pages/home-page/home-page.component'; import { RegisterPageComponent } from './pages/register-page/register-page.component'; import { ForgotPasswordComponent } from './pages/forgot-password/forgot-password.component'; import { ProfilePageComponent } from './pages/profile-page/profile-page.component'; const routes: Routes = [ {path: "",redirectTo:"login",pathMatch: 'full'}, {path: "login", component : LoginPageComponent }, {path: "home", component : HomePageComponent }, {path: "forgotpassword", component : ForgotPasswordComponent }, {path: "register", component : RegisterPageComponent }, {path: "profile", component : HomePageComponent }, // {path: } ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="./lib/node_modules/vue/dist/vue.js"></script> <title>Document</title> <style> .inner { height: 150px; background-color: darkcyan; } </style> </head> <body> <div id="app" class="inner" @click="divHandler"> <!-- 使用 .stop 阻止事件冒泡 --> <input type="button" value="emmm" @click.stop="btnHandler"> <!-- 使用 .prevent 组织默认行为 --> <a href="http://www.baidu.com" @click.prevent.once="linkClick">百度</a> </div> <!-- 使用 .capture 实现捕获出发事件的机制 --> <!-- <div id="app" class="inner" @click.capture="divHandler"> <input type="button" value="emmm" @click="btnHandler"> </div> --> <!-- 使用 .self 实现只有点击自身的时候才会触发事件处理函数 --> <div id="app" class="inner" @click.self="divHandler"> <input type="button" value="emmm" @click="btnHandler"> </div> <a href="http://www.baidu.com" @click.prevent.once="linkClick">百度</a> <script> let vm = new Vue({ el: '#app', data: {}, methods: { divHandler() { console.log("出发了innerdiv 的点击事件") }, btnHandler() { console.log("触发了btn 的点击事件 ") }, linkClick() { console.log("出发了link 点击事件") } } }) </script> </body> </html>
import { Utils } from '../../utils'; interface Hand { cards: Card[]; bid: number; score: number; } interface Card { name: string; value: number; } const strengthOrder = ['A', 'K', 'Q', 'T', '9', '8', '7', '6', '5', '4', '3', '2', 'J'].reverse(); export const solve = (input: string): string => { const lines = input.split('\n'); const hands: Hand[] = lines.map((l) => { const parts = l.split(' '); const bid = parseInt(parts[1]); const cards = parts[0].split('').map( (c): Card => ({ name: c, value: strengthOrder.findIndex((s) => c === s), }), ); return { cards, bid, score: getScoreForHand(cards), }; }); const scoredHands = hands .sort((a, b) => { if ((a.score < 20 && b.score < 20) || a.score === b.score) { for (let i = 0; i < 5; i++) { const ac = a.cards[i].value; const bc = b.cards[i].value; if (ac !== bc) { return bc - ac; } } } return b.score - a.score; }) .map((h, i) => ({ ...h, winAmount: h.bid * (hands.length - i), rank: hands.length - i, })); const result = scoredHands.map((h) => h.winAmount).reduce(Utils.Reducers.add); return '' + result; }; const getScoreForHand = (hand: Card[]): number => { let mostCommonCard: Card; let maxOccurence = 0; hand.forEach((card) => { if (card.name == 'J') return; const count = hand.filter((c) => c.name === card.name).length; if (count > maxOccurence) { maxOccurence = count; mostCommonCard = card; } }); const newHand = hand.map((card) => (card.name == 'J' ? mostCommonCard ?? card : card)); const cards = newHand.map((c) => c.value); const uniqueCards = new Set(cards).size; // Check five of a kind if (uniqueCards === 1) { return 70; } // Check four of a kind if (cards.some((card) => cards.filter((c) => c === card).length === 4)) { return 60; } // Check full house if ( cards.some((card) => cards.filter((c) => c === card).length === 3) && cards.some((card) => cards.filter((c) => c === card).length === 2) ) { return 50; } // Check three of a kind if (cards.some((card) => cards.filter((c) => c === card).length === 3)) { return 40; } // Check two pair if (getPairs(cards) === 2) { return 30; } // Check one pair if (getPairs(cards) === 1) { return 20; } // get high card return Math.max(...cards); }; const getPairs = (cards: number[]): number => { return cards.filter((rank) => cards.filter((r2) => r2 === rank).length === 2).length / 2; };
#ifndef MATRIX_CALCULATOR_MATRIXEXPRESSION_H #define MATRIX_CALCULATOR_MATRIXEXPRESSION_H // abstract class of expression with matrices // T - type of elements of matrix obtained by evaluating expression // E - subclass of MatrixExpression template<typename T, typename E> class MatrixExpression { public: using value_type = T; // has_data equals true if class contains data (not reference to data) about elements of matrix static constexpr bool has_data = false; // returns copy of element on i-th row and j-th column of matrix obtained by evaluating expression T operator[](std::size_t i, std::size_t j) const; // return size of matrix obtained by evaluating expression std::size_t n() const; std::size_t m() const; }; // throw exception if matrices are not match by row count, column count or column-row count respectively template<typename T1, typename E1, typename T2, typename E2> void check_n(const MatrixExpression<T1, E1> &first, const MatrixExpression<T2, E2> &second); template<typename T1, typename E1, typename T2, typename E2> void check_m(const MatrixExpression<T1, E1> &first, const MatrixExpression<T2, E2> &second); template<typename T1, typename E1, typename T2, typename E2> void check_mn(const MatrixExpression<T1, E1> &first, const MatrixExpression<T2, E2> &second); // class of negation operation // T - type of elements of matrix obtained by evaluating negation of the expression // E - type of expression for negation template<typename T, typename E> class Negation : public MatrixExpression<T, Negation<T, E>> { protected: std::conditional_t<E::has_data, const E&, E> expression; public: // returns copy of element on i-th row and j-th column of matrix obtained by evaluating negation of the expression T operator[](std::size_t i, std::size_t j) const; // return size of matrix obtained by evaluating negation of the expression std::size_t n() const; std::size_t m() const; explicit Negation(const MatrixExpression<T, E>& expression); }; // class of summation operation // T - type of elements of matrix obtained by evaluating summation of the expressions // E1, E2 - types of expressions for summation template<typename T, typename E1, typename E2> class Summation : public MatrixExpression<T, Summation<T, E1, E2>> { protected: std::conditional_t<E1::has_data, const E1&, E1> first; std::conditional_t<E2::has_data, const E2&, E2> second; public: // returns copy of element on i-th row and j-th column of matrix obtained by evaluating summation of the expressions T operator[](std::size_t i, std::size_t j) const; // return size of matrix obtained by evaluating summation of the expressions std::size_t n() const; std::size_t m() const; template<typename T1, typename T2> Summation(const MatrixExpression<T1, E1> &first, const MatrixExpression<T2, E2> &second); }; // class of subtraction operation // T - type of elements of matrix obtained by evaluating subtraction of the expressions // E1, E2 - types of expressions for subtraction template<typename T, typename E1, typename E2> class Subtraction : public MatrixExpression<T, Subtraction<T, E1, E2>> { protected: std::conditional_t<E1::has_data, const E1&, E1> first; std::conditional_t<E2::has_data, const E2&, E2> second; public: // returns copy of element on i-th row and j-th column of matrix obtained by evaluating subtraction of the expressions T operator[](std::size_t i, std::size_t j) const; // return size of matrix obtained by evaluating subtraction of the expressions std::size_t n() const; std::size_t m() const; template<typename T1, typename T2> Subtraction(const MatrixExpression<T1, E1> &first, const MatrixExpression<T2, E2> &second); }; // class of product operation // T - type of elements of matrix obtained by evaluating product of the expressions // E1, E2 - types of expressions for product template<typename T, typename E1, typename E2> class Product : public MatrixExpression<T, Product<T, E1, E2>> { protected: std::conditional_t<E1::has_data, const E1&, E1> first; std::conditional_t<E2::has_data, const E2&, E2> second; public: // returns copy of element on i-th row and j-th column of matrix obtained by evaluating product of the expressions T operator[](std::size_t i, std::size_t j) const; // return size of matrix obtained by evaluating product of the expressions std::size_t n() const; std::size_t m() const; template<typename T1, typename T2> Product(const MatrixExpression<T1, E1> &first, const MatrixExpression<T2, E2> &second); }; // class of product of matrix and scalar // T - type of elements of matrix obtained by evaluating product of the expression and scalar // E - type of expression for product // V - type of scalar for product template<typename T, typename E, typename V> class ScalarProduct : public MatrixExpression<T, ScalarProduct<T, E, V>> { protected: std::conditional_t<E::has_data, const E&, E> expression; V val; public: // returns copy of element on i-th row and j-th column of matrix obtained by evaluating product of the expression and scalar T operator[](std::size_t i, std::size_t j) const; // return size of matrix obtained by evaluating product of the expression and scalar std::size_t n() const; std::size_t m() const; ScalarProduct(const MatrixExpression<T, E> &expression, V val); }; // class of division of matrix by scalar // T - type of elements of matrix obtained by evaluating division of the expression by scalar // E - type of expression for division // V - type of scalar for division template<typename T, typename E, typename V> class ScalarDivision : public MatrixExpression<T, ScalarDivision<T, E, V>> { private: std::conditional_t<E::has_data, const E&, E> expression; V val; public: // returns copy of element on i-th row and j-th column of matrix obtained by evaluating division of the expression by scalar T operator[](std::size_t i, std::size_t j) const; // return size of matrix obtained by evaluating division of the expression by scalar std::size_t n() const; std::size_t m() const; ScalarDivision(const MatrixExpression<T, E> &expression, V val); }; // expression surface-operations functions // // NOTE: for reasons of possibility of deduction of return type of surface-operations, // those functions can be used only with expressions/scalars with a same value_type template<typename T, typename E> Negation<T, E> operator-(const MatrixExpression<T, E> &expression); template<typename T, typename E1, typename E2> Summation<T, E1, E2> operator+(const MatrixExpression<T, E1> &first, const MatrixExpression<T, E2> &second); template<typename T, typename E1, typename E2> Subtraction<T, E1, E2> operator-(const MatrixExpression<T, E1> &first, const MatrixExpression<T, E2> &second); template<typename T, typename E1, typename E2> Product<T, E1, E2> operator*(const MatrixExpression<T, E1> &first, const MatrixExpression<T, E2> &second); template<typename T, typename E> ScalarProduct<T, E, T> operator*(const MatrixExpression<T, E> &expression, T val); template<typename T, typename E> ScalarProduct<T, E, T> operator*(T val, const MatrixExpression<T, E> &expression); template<typename T, typename E> ScalarDivision<T, E, T> operator/(const MatrixExpression<T, E> &expression, T val); // output function // template<typename T, typename E> std::ostream& operator<<(std::ostream &ostream, const MatrixExpression<T, E> &expression); #include "matrix-expression.tpp" #endif //MATRIX_CALCULATOR_MATRIXEXPRESSION_H
/** * This file is part of PhysicsSynth. * * Created by Jonathan Hook (jonathan.hook@ncl.ac.uk) * Copyright (c) 2010-2012 Jonathan Hook. All rights reserved. * * PhysicsSynth 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. * * PhysicsSynth 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 PhysicsSynth. If not, see <http://www.gnu.org/licenses/>. */ #include <assert.h> #include <JDHUtility/Ndelete.h> #include "MappingButton.h" #include "MappingGrid.h" namespace PhysicsSynth { /* Constructors */ MappingGrid::MappingGrid(std::vector<MappingGridItem> froms, std::vector<MappingGridItem> tos, std::string label, const Point2i &position, const Point2i &dimensions) : LabelledUIElement(label, position, dimensions.getX()) { this->froms = froms; this->tos = tos; mappingChanged = NULL; init(); } MappingGrid::~MappingGrid(void) { for(unsigned int i = 0; i < mappingButtons.size(); i++) { NDELETE(mappingButtons[i]); } mappingButtons.clear(); } /* Public Member Functions */ void MappingGrid::render(void) { LabelledUIElement::render(); for(unsigned int i = 0; i < mappingButtons.size(); i++) { MappingButton *mb = mappingButtons[i]; assert(mb); mb->render(); } } void MappingGrid::setMapping(unsigned int from, unsigned int to) { for(unsigned int i = 0; i < mappingButtons.size(); i++) { MappingButton *mb = mappingButtons[i]; assert(mb); if(mb->getFrom().item == from) { for(unsigned int j = 0; j < tos.size(); j++) { if(tos[j].item == to) { mb->setTo(tos[j]); } } } } } void MappingGrid::setMappingChangedCallback(MappingChangedCallback mappingChanged) { this->mappingChanged = mappingChanged; } /* Private Member Functions */ void MappingGrid::init(void) { unsigned int width = dimensions.getX(); unsigned int height = getLabelHeight() * 2; Point2i itemDimensions = Point2i(width, height); for(unsigned int i = 0; i < froms.size(); i++) { MappingGrid::MappingGridItem from = froms[i]; Point2i itemPos(0, height * i); itemPos.translateY(getLabelHeight()); itemPos.translate(position.getX(), position.getY()); MappingButton *mb = new MappingButton(from, tos, itemPos, itemDimensions); mb->setMappingChangedCallback(MakeDelegate(this, &MappingGrid::mappingButton_MappingChanged)); registerEventHandler(mb); mappingButtons.push_back(mb); } dimensions.setY((height * froms.size()) + getLabelHeight()); } void MappingGrid::mappingButton_MappingChanged(MappingGridItem from, MappingGridItem to) { if(mappingChanged != NULL) { mappingChanged(from, to); } } }
import { createSlice } from "@reduxjs/toolkit"; // object definitions const emptySet = { "reps" : "", "weight" : "", "set_difficulty" : "", "set_notes" : "" } const emptyExercise = { "exercise_name" : "", "exercise_notes" : "", "sets" : [emptySet] } const emptyWorkout = { "workout_name" : "", "workout_date" : "", "workout_notes" : "", "exercies" : [ emptyExercise ] } // helper functions const deleteEmptyExercises = (workoutState) => { var workout = workoutState; const numExercise = workout.exercies.length; for(var repeat = 2; repeat>0; repeat--){ for(var i=0; i<=numExercise; i++){ const prevExercise = JSON.stringify({...workout.exercies[i-1]}); const currExercise = JSON.stringify({...workout.exercies[i]}); const empty = JSON.stringify(emptyExercise) if(prevExercise === empty && currExercise === empty){ workout.exercies.splice(i, 1) }}} return workout; } const deleteEmptySets = (workoutState, exerciseId) => { var workout = workoutState; const numSets = workout.exercies[exerciseId].sets.length; for(var repeat = 2; repeat>0; repeat--){ for(var i=0; i<=numSets; i++){ const prevSet = JSON.stringify({...workout.exercies[exerciseId].sets[i-1]}); const currSet = JSON.stringify({...workout.exercies[exerciseId].sets[i]}); const empty = JSON.stringify(emptySet) if(prevSet === empty && currSet === empty){ workout.exercies[exerciseId].sets.splice(i, 1) }}} } // slice definition const workoutSlice = createSlice({ name: "workout", initialState: emptyWorkout, reducers: { updateWorkout: (workout, action) => { const { param, value } = action.payload; workout[param] = value; }, updateExercise: (workout, action) => { const { param, value, exerciseId } = action.payload; workout.exercies[exerciseId][param] = value; if(exerciseId === workout.exercies.length-1){ workout.exercies.push(emptyExercise); } if(!value){ workout = deleteEmptyExercises(workout); } }, updateSet: (workout, action) => { const { param, value, exerciseId, setId } = action.payload; workout.exercies[exerciseId].sets[setId][param] = value; if(setId === workout.exercies[exerciseId].sets.length-1){ workout.exercies[exerciseId].sets.push(emptySet); } if(!value){ workout = deleteEmptyExercises(workout); workout = deleteEmptySets(workout, exerciseId); } }, } }); // export actions and reducers export const { updateWorkout, updateExercise, updateSet } = workoutSlice.actions; export default workoutSlice.reducer;
// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from "vscode"; import { shiftLeft, shiftRight } from "./arg_methods"; // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log('Extension "argumentative" is now active!'); // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json const shiftLeftCommand = vscode.commands.registerCommand( "argumentative.shiftArgLeft", () => { // The code you place here will be executed every time your command is executed shiftLeft(); } ); const shiftRightCommand = vscode.commands.registerCommand( "argumentative.shiftArgRight", () => { // The code you place here will be executed every time your command is executed shiftRight(); } ); context.subscriptions.push(shiftLeftCommand); context.subscriptions.push(shiftRightCommand); } // this method is called when your extension is deactivated export function deactivate() {}
/* eslint-disable prettier/prettier */ import { Field, Int, InputType } from '@nestjs/graphql'; import { IsAlphanumeric, IsDate, IsEmail, IsInt, IsNotEmpty, IsNumber, IsOptional, IsString, Max, MaxLength, Min, } from 'class-validator'; import { CreatePersonneInput } from './../../candidat/dto/create-personne.input'; import { Index } from 'typeorm'; import { UserRole } from '../../enum/UserRole'; import { Equipe } from '../entities/equipe.entity'; @InputType() //representation mta3 input = dto export class CreateColInput extends CreatePersonneInput { @IsNumber() @Index({ unique: true }) @IsNotEmpty() @Field((type) => Int) cin: number; @IsOptional() @IsInt() @Field((type) => Int, { nullable: true }) telPro?: number; @IsNotEmpty() @Field((type) => UserRole) role: UserRole; @IsNotEmpty() @IsEmail() @Field() emailPro: string; @IsString() @IsNotEmpty() @Field() poste: string; @IsNumber() @IsNotEmpty() @Field((type) => Int) salaire: number; @IsDate() @IsNotEmpty() @Field() dateEmb: Date; @MaxLength(20, { message: 'Nom utilisateur is too long', }) @IsAlphanumeric() @IsNotEmpty() @Field() nomUtilisateur: string; @IsNotEmpty() @Field((type) => UserRole) @Max(5, { message: 'Evaluation max=5', }) @Min(0, { message: 'Evaluation min=0', }) @IsNumber() @IsOptional() @Field((type) => Int, { nullable: true }) evaluation?: number; @IsNumber() @IsOptional() @Field((type) => Int, { nullable: true }) equipeId?: number; // @IsOptional() // @Field(type => ID) // equipeId :number; // @IsOptional() // @Field(type => Equipe, {nullable:true}) // equipe? :Equipe; // @IsNumber() // @IsNotEmpty() // @Field(type => Int) // cvId :number; } /*@Contains('hello') @IsEnum(entity: object) @IsMilitaryTime() @IsHash(algorithm: strin */
<!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>Rebound Exercise</title> <link rel="stylesheet" href="assets/styles/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.10.5/font/bootstrap-icons.css"> </head> <body class="bg-dark bg-opacity-25"> <header class="header"> <nav class="navbar navbar-expand-lg bg-dark"> <div class="container-fluid"> <a class="navbar-brand text-white fw-bold" href="#">FlyNow</a> <button class="navbar-toggler border-1 border-white" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="bi bi-list text-white "></span> </button> </div> </nav> </header> <div class="contenedor text-center"> <section class="contenedor__header"> <h1>¿Adónde quieres ir?</h1> <p> Estás a solo unos pasos de estar en el destino de tus sueños para tus vacaciones. A continuación cuéntanos adonde quieres ir. </p> </section> <section class="contenedor__body"> <div class="origen"> <p>Origen:</p> <select name="origin" id="origin"> <option value="New York">New York, USA</option> <option value="Boston">Boston, USA</option> <option value="Chicago">Chicago, USA</option> </select> <br><br> <input type="date" name="fechaIda" id="fechaIda"> </div> <div class="destino"> <p>Destino:</p> <select name="destino" id="destino"> <option value="London">London, UK</option> <option value="Paris">Paris, FR</option> <option value="Venecia">Venecia, IT</option> </select> <br><br> <input type="date" name="fechaDes" id="fechaDes"> </div> </section> </div> <div class="informacion container bg-light my-5 p-3"> <h1 class="text-center">Itinerario</h1> <div class="informacion__vuelo"> <div class="row"> <div class="col-sm-3"> <div class="card-body text-center"> <p class="text-info fw-bold bg-info bg-opacity-10" id="dateIda"> </p> <p class="card-text text-center fw-bold" id="infoIda"> Origen </p> <button type="button" class="btn btn-primary btn-sm">Ver más información</button> </div> </div> <div class="col-sm-6 text-center my-5"> <div class="card-body"> <p class="card-text fw-bold" id="escala"> </p> </div> </div> <div class="col-sm-3"> <div class="card-body text-center"> <p class="text-info fw-bold bg-info bg-opacity-10" id="dateDes"> </p> <p class="card-text text-center fw-bold" id="infoDes"> Destino </p> <button type="button" class="btn btn-primary btn-sm">Ver más información</button> </div> </div> </div> </div> </div> <script src="assets/js/main.js"></script> <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>
package main import ( "bytes" "context" "fmt" "net/http" "net/url" "strings" "sync/atomic" comatproto "github.com/bluesky-social/indigo/api/atproto" "github.com/bluesky-social/indigo/atproto/syntax" "github.com/bluesky-social/indigo/automod" "github.com/bluesky-social/indigo/events/schedulers/autoscaling" "github.com/bluesky-social/indigo/events/schedulers/parallel" lexutil "github.com/bluesky-social/indigo/lex/util" "github.com/bluesky-social/indigo/events" "github.com/bluesky-social/indigo/repo" "github.com/bluesky-social/indigo/repomgr" "github.com/carlmjohnson/versioninfo" "github.com/gorilla/websocket" ) func (s *Server) RunConsumer(ctx context.Context) error { // TODO: persist cursor in a database or local disk cur, err := s.ReadLastCursor(ctx) if err != nil { return err } dialer := websocket.DefaultDialer u, err := url.Parse(s.relayHost) if err != nil { return fmt.Errorf("invalid relayHost URI: %w", err) } u.Path = "xrpc/com.atproto.sync.subscribeRepos" if cur != 0 { u.RawQuery = fmt.Sprintf("cursor=%d", cur) } s.logger.Info("subscribing to repo event stream", "upstream", s.relayHost, "cursor", cur) con, _, err := dialer.Dial(u.String(), http.Header{ "User-Agent": []string{fmt.Sprintf("hepa/%s", versioninfo.Short())}, }) if err != nil { return fmt.Errorf("subscribing to firehose failed (dialing): %w", err) } rsc := &events.RepoStreamCallbacks{ RepoCommit: func(evt *comatproto.SyncSubscribeRepos_Commit) error { atomic.StoreInt64(&s.lastSeq, evt.Seq) return s.HandleRepoCommit(ctx, evt) }, RepoHandle: func(evt *comatproto.SyncSubscribeRepos_Handle) error { atomic.StoreInt64(&s.lastSeq, evt.Seq) did, err := syntax.ParseDID(evt.Did) if err != nil { s.logger.Error("bad DID in RepoHandle event", "did", evt.Did, "handle", evt.Handle, "seq", evt.Seq, "err", err) return nil } if err := s.engine.ProcessIdentityEvent(ctx, "handle", did); err != nil { s.logger.Error("processing handle update failed", "did", evt.Did, "handle", evt.Handle, "seq", evt.Seq, "err", err) } return nil }, RepoIdentity: func(evt *comatproto.SyncSubscribeRepos_Identity) error { atomic.StoreInt64(&s.lastSeq, evt.Seq) did, err := syntax.ParseDID(evt.Did) if err != nil { s.logger.Error("bad DID in RepoIdentity event", "did", evt.Did, "seq", evt.Seq, "err", err) return nil } if err := s.engine.ProcessIdentityEvent(ctx, "identity", did); err != nil { s.logger.Error("processing repo identity failed", "did", evt.Did, "seq", evt.Seq, "err", err) } return nil }, RepoTombstone: func(evt *comatproto.SyncSubscribeRepos_Tombstone) error { atomic.StoreInt64(&s.lastSeq, evt.Seq) did, err := syntax.ParseDID(evt.Did) if err != nil { s.logger.Error("bad DID in RepoTombstone event", "did", evt.Did, "seq", evt.Seq, "err", err) return nil } if err := s.engine.ProcessIdentityEvent(ctx, "tombstone", did); err != nil { s.logger.Error("processing repo tombstone failed", "did", evt.Did, "seq", evt.Seq, "err", err) } return nil }, // TODO: other event callbacks as needed } var scheduler events.Scheduler if s.firehoseParallelism > 0 { // use a fixed-parallelism scheduler if configured scheduler = parallel.NewScheduler( s.firehoseParallelism, 1000, s.relayHost, rsc.EventHandler, ) s.logger.Info("hepa scheduler configured", "scheduler", "parallel", "initial", s.firehoseParallelism) } else { // otherwise use auto-scaling scheduler scaleSettings := autoscaling.DefaultAutoscaleSettings() // start at higher parallelism (somewhat arbitrary) scaleSettings.Concurrency = 4 scaleSettings.MaxConcurrency = 200 scheduler = autoscaling.NewScheduler(scaleSettings, s.relayHost, rsc.EventHandler) s.logger.Info("hepa scheduler configured", "scheduler", "autoscaling", "initial", scaleSettings.Concurrency, "max", scaleSettings.MaxConcurrency) } return events.HandleRepoStream(ctx, con, scheduler) } // TODO: move this to a "ParsePath" helper in syntax package? func splitRepoPath(path string) (syntax.NSID, syntax.RecordKey, error) { parts := strings.SplitN(path, "/", 3) if len(parts) != 2 { return "", "", fmt.Errorf("invalid record path: %s", path) } collection, err := syntax.ParseNSID(parts[0]) if err != nil { return "", "", err } rkey, err := syntax.ParseRecordKey(parts[1]) if err != nil { return "", "", err } return collection, rkey, nil } // NOTE: for now, this function basically never errors, just logs and returns nil. Should think through error processing better. func (s *Server) HandleRepoCommit(ctx context.Context, evt *comatproto.SyncSubscribeRepos_Commit) error { logger := s.logger.With("event", "commit", "did", evt.Repo, "rev", evt.Rev, "seq", evt.Seq) logger.Debug("received commit event") if evt.TooBig { logger.Warn("skipping tooBig events for now") return nil } did, err := syntax.ParseDID(evt.Repo) if err != nil { logger.Error("bad DID syntax in event", "err", err) return nil } rr, err := repo.ReadRepoFromCar(ctx, bytes.NewReader(evt.Blocks)) if err != nil { logger.Error("failed to read repo from car", "err", err) return nil } // empty commit is a special case, temporarily, basically indicates "new account" if len(evt.Ops) == 0 { if err := s.engine.ProcessIdentityEvent(ctx, "create", did); err != nil { s.logger.Error("processing handle update failed", "did", evt.Repo, "rev", evt.Rev, "seq", evt.Seq, "err", err) } } for _, op := range evt.Ops { logger = logger.With("eventKind", op.Action, "path", op.Path) collection, rkey, err := splitRepoPath(op.Path) if err != nil { logger.Error("invalid path in repo op") return nil } ek := repomgr.EventKind(op.Action) switch ek { case repomgr.EvtKindCreateRecord, repomgr.EvtKindUpdateRecord: // read the record bytes from blocks, and verify CID rc, recCBOR, err := rr.GetRecordBytes(ctx, op.Path) if err != nil { logger.Error("reading record from event blocks (CAR)", "err", err) break } if op.Cid == nil || lexutil.LexLink(rc) != *op.Cid { logger.Error("mismatch between commit op CID and record block", "recordCID", rc, "opCID", op.Cid) break } var action string switch ek { case repomgr.EvtKindCreateRecord: action = automod.CreateOp case repomgr.EvtKindUpdateRecord: action = automod.UpdateOp default: logger.Error("impossible event kind", "kind", ek) break } recCID := syntax.CID(op.Cid.String()) err = s.engine.ProcessRecordOp(ctx, automod.RecordOp{ Action: action, DID: did, Collection: collection, RecordKey: rkey, CID: &recCID, RecordCBOR: *recCBOR, }) if err != nil { logger.Error("engine failed to process record", "err", err) continue } case repomgr.EvtKindDeleteRecord: err = s.engine.ProcessRecordOp(ctx, automod.RecordOp{ Action: automod.DeleteOp, DID: did, Collection: collection, RecordKey: rkey, CID: nil, RecordCBOR: nil, }) if err != nil { logger.Error("engine failed to process record", "err", err) continue } default: // TODO: other event types: update, delete } } return nil }
import { isArray, isNumber, isUndefined, isNull, isString, isEqual, orderBy } from "lodash"; import { genericSeriesDataTransformer, seriesDataTransformer, SCMPRReportsTransformer } from "../seriesData.helper"; import { seriesDataHelperMock } from "./helper.mock"; import SCMPRReportsTransformerData from "../__mocks__/SCMPRReportsTransformer.json"; describe("Series Data Helper Tests", () => { test("test parameters for genericSeriesDataTransformer", () => { const param1: any = []; const param2 = 10; const param3 = undefined; genericSeriesDataTransformer(param1, param2, param3); expect(isArray(param1)).toBeTruthy(); expect(isNumber(param2) || isNull(param2) || isUndefined(param2)).toBeTruthy(); expect(isString(param3) || isNull(param3) || isUndefined(param3)).toBeTruthy(); }); test("test result for genericSeriesDataTransformer should be an array", () => { const param1: any = []; const param2 = 10; const param3 = undefined; const transformer = genericSeriesDataTransformer(param1, param2, param3); expect(isArray(transformer)).toBeTruthy(); }); test("test parameter for seriesDataTransformer case1: should be an object", () => { const param1: any = {}; const transformer = seriesDataTransformer(param1); expect(typeof param1 === "object" && !isArray(param1)).toBeTruthy(); }); test("test parameter for seriesDataTransformer case2: should have apiData and apiData should be an array", () => { const param1: any = { apiData: [] }; const transformer = seriesDataTransformer(param1); expect(param1.hasOwnProperty("apiData") && isArray(param1.apiData)).toBeTruthy(); }); test("test parameter for seriesDataTransformer case3: should have reportType and reportType should be a string", () => { const param1: any = { reportType: "" }; const transformer = seriesDataTransformer(param1); expect(param1.hasOwnProperty("reportType") && isString(param1.reportType)).toBeTruthy(); }); test("test parameter for seriesDataTransformer case4: should have widgetFilters and widgetFilters should be an object", () => { const param1: any = { widgetFilters: {} }; const transformer = seriesDataTransformer(param1); expect( param1.hasOwnProperty("widgetFilters") && typeof param1.widgetFilters === "object" && !isArray(param1.widgetFilters) ).toBeTruthy(); }); test("test result for seriesDataTransformer ", () => { const transformer = seriesDataTransformer({}); expect(typeof transformer === "object" && transformer.hasOwnProperty("data")).toBeTruthy(); }); test("test mock parameters and response for seriesDataTransformer ", () => { const transformer = orderBy(seriesDataTransformer(seriesDataHelperMock.parameters)?.data, "total_tickets", "asc"); const mockResponse = orderBy(seriesDataHelperMock.response.data, "total_tickets", "asc"); expect(isEqual(transformer, mockResponse)).toBeTruthy(); }); test("test result for SCMPRReportsTransformer should get all key along with stack items", () => { const result = SCMPRReportsTransformer(SCMPRReportsTransformerData); const keyInAllData = result.data.every((item: any) => item?.key && typeof item?.key === "string"); expect(keyInAllData).toBeTruthy(); }); });
import React, {useState} from "react"; import PropTypes from "prop-types"; import {Badge, Button, Card, Col, FloatingLabel, Form, Stack} from "react-bootstrap"; import {microAlgosToString, truncateAddress} from "../../utils/conversions"; import Identicon from "../utils/Identicon"; const Product = ({address, product, buyProduct, deleteProduct}) => { const {name, image, document, date, description, price, sold, appId, owner} = product; const [count, setCount] = useState(1) return ( <Col key={appId}> <Card className="h-100"> <Card.Header> <Stack direction="horizontal" gap={2}> <span className="font-monospace text-secondary">{truncateAddress(owner)}</span> <Identicon size={28} address={owner}/> <Badge bg="secondary" className="ms-auto"> {sold} Tender applications: </Badge> </Stack> </Card.Header> <div className="ratio-4x3" style={{display: "flex"}}> <img src={image} alt={name} style={{objectFit: "cover", width: 200, margin: "auto"}}/> </div> <Card.Body className="d-flex flex-column text-center"> <Card.Title>{name}</Card.Title> <Card.Link className="flex-grow-1" href={document} target="_blank">Link to the tender documents</Card.Link> <Card.Text className="flex-grow-1" style={{color: "red"}}>{`Document submission due date: ${date}`}</Card.Text> <Card.Subtitle>Contract description</Card.Subtitle> <Card.Text className="flex-grow-1">{description}</Card.Text> <Form className="d-flex align-content-stretch flex-row gap-2"> {/* <FloatingLabel controlId="inputCount" label="Count" className="w-25" > <Form.Control type="number" value={count} min="1" max="10" onChange={(e) => { setCount(Number(e.target.value)); }} /> </FloatingLabel> */} <Button variant="outline-dark" onClick={() => buyProduct(product, count)} className="w-75 py-3" > Accept tender for:{microAlgosToString(price) * count} ALGO </Button> {product.owner === address && <Button variant="outline-danger" onClick={() => deleteProduct(product)} className="btn" > <i className="bi bi-trash"></i> </Button> } </Form> </Card.Body> </Card> </Col> ); }; Product.propTypes = { address: PropTypes.string.isRequired, product: PropTypes.instanceOf(Object).isRequired, buyProduct: PropTypes.func.isRequired, deleteProduct: PropTypes.func.isRequired }; export default Product;
import Header from "../components/header.jsx"; import Footer from "../components/footer.jsx"; import PropTypes from "prop-types"; export default function About({ auth }) { return ( <> <main> <section className="bg-white"> <div className="container max-w-screen-xl mx-auto px-4"> <Header auth={auth} /> <div className="flex items-center justify-center"> <div className="mt-28 text-center"> <h1 className="font-semibold text-4xl md:text-6xl lg:text-7xl text-gray-900 leading-normal mb-6">About Us</h1> <div className="max-w-4xl mx-auto"> <p className="font-normal text-xl text-gray-400 leading-relaxed mb-12"> <span className="font-semibold">Our Mission:</span> A subsection that describes the mission of the academic institution. It conveys a dedication to providing high-quality education and fostering a learning community where students can thrive. </p> <p className="font-normal text-xl text-gray-400 leading-relaxed mb-12"> <span className="font-semibold">Our Vision:</span> Another subsection that introduces the team of the institution. It emphasizes the commitment of experienced instructors and administrators to the success of students. The team is described as passionate about education and helping students achieve their academic goals. </p> <p className="font-normal text-xl text-gray-400 leading-relaxed mb-12"> <span className="font-semibold">Our History:</span> This subsection provides a brief overview of the institution's history. It mentions the year of establishment and highlights the institution's tradition of excellence in education. It also states that the institution has a track record of assisting numerous students in reaching their full </p> </div> <button className="px-6 py-4 bg-blue-700 text-white font-semibold text-lg rounded-xl hover:bg-blue-900 transition ease-in-out duration-500">Start Your Journey</button> </div> </div> <section className="bg-white py-50"> <div className="container max-w-screen-xl mx-auto px-4 xl:relative"> <p className="font-normal text-gray-400 text-lg md:text-xl text-center uppercase mb-6">Testimonial</p> <h1 className="font-semibold text-gray-900 text-2xl md:text-4xl text-center leading-normal mb-14">What People Say <br /> About Canva</h1> <div className="hidden xl:block xl:absolute top-0"> <img src="/images/testimoni-1.png" alt="Image" /> </div> <div className="hidden xl:block xl:absolute top-32"> <img src="/images/testimoni-2.png" alt="Image" /> </div> <div className="flex flex-col md:flex-row md:items-center justify-center md:space-x-8 lg:space-x-12 mb-10 md:mb-20"> <div className="bg-gray-100 rounded-lg mb-10 md:mb-0"> <img src="/images/testimoni-3.png" alt="Image" className="mx-8 my-8" /> <div className="flex items-center gap-5 mx-8"> <i data-feather="star" className="text-yellow-500"></i> <i data-feather="star" className="text-yellow-500"></i> <i data-feather="star" className="text-yellow-500"></i> <i data-feather="star" className="text-yellow-500"></i> <i data-feather="star" className="text-yellow-500"></i> </div> <p className="font-normal text-sm lg:text-md text-gray-400 mx-8 my-8">flexible in pace and customizable by design. <br />You can study part time, choosing courses that fit your schedule<br /> and align with your professional goals.</p> <h3 className="font-semibold text-gray-900 text-xl md:text-2xl lg:text-3xl mx-8 mb-8">Brooklyn Simmons</h3> </div> <div className="bg-gray-100 rounded-lg"> <img src="/images/testimoni-4.png" alt="Image" className="mx-8 my-8" /> <div className="flex items-center gap-5 mx-8"> <i data-feather="star" className="text-yellow-500"></i> <i data-feather="star" className="text-yellow-500"></i> <i data-feather="star" className="text-yellow-500"></i> <i data-feather="star" className="text-yellow-500"></i> <i data-feather="star" className="text-yellow-500"></i> </div> <p className="font-normal text-sm lg:text-md text-gray-400 mx-8 my-8">flexible in pace and customizable by design. You can study part time,<br /> choosing courses that fit your schedule and align with<br /> your professional goals.</p> <h3 className="font-semibold text-gray-900 text-xl md:text-2xl lg:text-3xl mx-8 mb-8">Ralph Edwards</h3> </div> </div> </div> </section> </div> </section> </main> <Footer /> </> ); } // prop validation About.propTypes = { auth: PropTypes.shape({ user: PropTypes.shape({ name: PropTypes.string, }), }), };
<!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" /> <script src="https://cdn.tailwindcss.com"></script> <title>Filters</title> </head> <body class="mb-8 mx-8"> <h2 class="bg-yellow-300">Blur:</h2> <code class="bg-gray-300">class="mb-8 blur"</code> <div class="mb-8 blur"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere, laborum tempore aut et dicta in. Hic atque rerum fugit beatae? </div> <h2 class="bg-yellow-300">Brightness:</h2> <div class="flex gap-4 mb-8"> <div> <code class="bg-gray-300">class="brightness-50 w-60"</code> <img src="../assets/img/img1.jpg" class="brightness-50 w-60" alt="an opened laptop" /> </div> <div> <code class="bg-gray-300">class="brightness-100 w-60"</code> <img src="../assets/img/img1.jpg" class="brightness-100 w-60" alt="an opened laptop" /> </div> <div> <code class="bg-gray-300">class="brightness-150 w-60"</code> <img src="../assets/img/img1.jpg" class="brightness-150 w-60" alt="an opened laptop" /> </div> </div> <h2 class="bg-yellow-300">Contrast:</h2> <div class="flex gap-4 mb-8"> <div> <code class="bg-gray-300">class="contrast-50 w-60"</code> <img src="../assets/img/img2.jpg" class="contrast-50 w-60" alt="code on a screen" /> </div> <div> <code class="bg-gray-300">class="contrast-100 w-60"</code> <img src="../assets/img/img2.jpg" class="contrast-100 w-60" alt="code on a screen" /> </div> <div> <code class="bg-gray-300">class="contrast-200 w-60"</code> <img src="../assets/img/img2.jpg" class="contrast-200 w-60" alt="code on a screen" /> </div> </div> <h2 class="bg-yellow-300">Grayscale:</h2> <div class="mb-8"> <code class="bg-gray-300">class="grayscale w-60"</code> <img src="../assets/img/img3.jpg" class="grayscale w-60" alt="code on a screen" /> </div> <h2 class="bg-yellow-300">Invert:</h2> <div class="mb-8"> <code class="bg-gray-300">class="invert w-60"</code> <img src="../assets/img/img4.jpg" class="invert w-60" alt="an opened laptop on a chair" /> </div> <h2 class="bg-yellow-300">Sepia:</h2> <div class="mb-8"> <code class="bg-gray-300">class="sepia w-60"</code> <img src="../assets/img/img5.jpg" class="sepia w-60" alt="inside a gamer desktop" /> </div> <h2 class="bg-yellow-300">Hue Rotate:</h2> <div class="flex gap-8"> <div> <code class="bg-gray-300">class="hue-rotate-15 w-60"</code> <img src="../assets/img/img6.jpg" class="hue-rotate-15 w-60" alt="a wireless headphone" /> </div> <div> <code class="bg-gray-300">class="hue-rotate-90 w-60"</code> <img src="../assets/img/img6.jpg" class="hue-rotate-90 w-60" alt="a wireless headphone" /> </div> <div> <code class="bg-gray-300">class="hue-rotate-180 w-60"</code> <img src="../assets/img/img6.jpg" class="hue-rotate-180 w-60" alt="a wireless headphone" /> </div> </div> </body> </html> <!-- Blur blur-none filter: blur(0); blur-sm filter: blur(4px); blur filter: blur(8px); blur-md filter: blur(12px); blur-lg filter: blur(16px); blur-xl filter: blur(24px); blur-2xl filter: blur(40px); blur-3xl filter: blur(64px); --> <!-- Brightness brightness-0 filter: brightness(0); brightness-50 filter: brightness(.5); brightness-75 filter: brightness(.75); brightness-90 filter: brightness(.9); brightness-95 filter: brightness(.95); brightness-100 filter: brightness(1); brightness-105 filter: brightness(1.05); brightness-110 filter: brightness(1.1); brightness-125 filter: brightness(1.25); brightness-150 filter: brightness(1.5); brightness-200 filter: brightness(2); --> <!-- Contrast contrast-0 filter: contrast(0); contrast-50 filter: contrast(.5); contrast-75 filter: contrast(.75); contrast-100 filter: contrast(1); contrast-125 filter: contrast(1.25); contrast-150 filter: contrast(1.5); contrast-200 filter: contrast(2); --> <!-- Hue Rotate hue-rotate-0 filter: hue-rotate(0deg); hue-rotate-15 filter: hue-rotate(15deg); hue-rotate-30 filter: hue-rotate(30deg); hue-rotate-60 filter: hue-rotate(60deg); hue-rotate-90 filter: hue-rotate(90deg); hue-rotate-180 filter: hue-rotate(180deg); -->
package com.abiruchi.foodorderservice.service.impl; import com.abiruchi.foodorderservice.dto.ItemDto; import com.abiruchi.foodorderservice.entity.ItemDetails; import com.abiruchi.foodorderservice.excepion.ItemNotAvailableException; import com.abiruchi.foodorderservice.excepion.ItemNotFoundException; import com.abiruchi.foodorderservice.repository.ItemsRepository; import com.abiruchi.foodorderservice.service.ItemsService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * @author hp ON 09-06-2023 * @Description **/ @Service public class ItemsServiceImpl implements ItemsService { @Autowired private ItemsRepository itemsRepository; @Override public ItemDto saveItems(ItemDto itemDto) { ItemDetails savedItemDetails = itemsRepository.save(buildItemDetails(itemDto)); ItemDto savedDto = buildItemDto(savedItemDetails); return savedDto; } @Override public List<ItemDto> getAllItems() { //List<ItemDto> itemsList = new ArrayList<>(); List<ItemDetails> list = itemsRepository.findAll(); List<ItemDto> itemsList = list.stream().map(item -> buildItemDto(item)).collect(Collectors.toList()); return itemsList; } @Override public ItemDto getItemByName(String itemName) throws ItemNotAvailableException { Optional<ItemDetails> optionalItemDetails = itemsRepository.findByItemName(itemName); //ItemDetails itemDetails = null; // if(optionalItemDetails.isPresent()){ //itemDetails = optionalItemDetails.get(); return buildItemDto(optionalItemDetails.get()); }else{ throw new ItemNotAvailableException("item404","item not available at restaurent"); } // return buildItemDto(optionalItemDetails.get()); } private static ItemDto buildItemDto(ItemDetails savedItemDetails) { ItemDto itemDto = new ItemDto(); itemDto.setItemId(savedItemDetails.getItemId()); itemDto.setItemName(savedItemDetails.getItemName()); itemDto.setPrice(savedItemDetails.getPrice()); itemDto.setItemType(savedItemDetails.getItemType()); itemDto.setDescription(savedItemDetails.getDescription()); return itemDto; } private static ItemDetails buildItemDetails(ItemDto itemDto) { ItemDetails itemDetails = new ItemDetails(); itemDetails.setItemName(itemDto.getItemName()); itemDetails.setDescription(itemDto.getDescription()); itemDetails.setPrice(itemDto.getPrice()); itemDetails.setItemType(itemDto.getItemType()); return itemDetails; } }
// This file is part of the Acts project. // // Copyright (C) 2016-2020 CERN for the benefit of the Acts project // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <boost/test/unit_test.hpp> #include "Acts/Definitions/Algebra.hpp" #include "Acts/Definitions/Direction.hpp" #include "Acts/Definitions/TrackParametrization.hpp" #include "Acts/Definitions/Units.hpp" #include "Acts/EventData/GenericCurvilinearTrackParameters.hpp" #include "Acts/EventData/MultiTrajectory.hpp" #include "Acts/EventData/TrackParameters.hpp" #include "Acts/EventData/TrackStatePropMask.hpp" #include "Acts/EventData/VectorMultiTrajectory.hpp" #include "Acts/EventData/detail/TestSourceLink.hpp" #include "Acts/Propagator/EigenStepper.hpp" #include "Acts/Propagator/Navigator.hpp" #include "Acts/Propagator/Propagator.hpp" #include "Acts/Propagator/StraightLineStepper.hpp" #include "Acts/Tests/CommonHelpers/LineSurfaceStub.hpp" #include "Acts/TrackFitting/GainMatrixSmoother.hpp" #include "Acts/TrackFitting/GainMatrixUpdater.hpp" #include "Acts/TrackFitting/KalmanFitter.hpp" #include "Acts/Utilities/Delegate.hpp" #include "Acts/Utilities/Logger.hpp" #include <algorithm> #include <functional> #include <map> #include <memory> #include <optional> #include <random> #include <utility> #include "FitterTestsCommon.hpp" namespace { using namespace Acts; using namespace Acts::Test; using namespace Acts::detail::Test; using namespace Acts::UnitLiterals; using StraightPropagator = Acts::Propagator<Acts::StraightLineStepper, Acts::Navigator>; using ConstantFieldStepper = Acts::EigenStepper<>; using ConstantFieldPropagator = Acts::Propagator<ConstantFieldStepper, Acts::Navigator>; using KalmanUpdater = Acts::GainMatrixUpdater; using KalmanSmoother = Acts::GainMatrixSmoother; using KalmanFitter = Acts::KalmanFitter<ConstantFieldPropagator, VectorMultiTrajectory>; static const auto pion = Acts::ParticleHypothesis::pion(); KalmanUpdater kfUpdater; KalmanSmoother kfSmoother; // Construct initial track parameters. Acts::CurvilinearTrackParameters makeParameters() { // create covariance matrix from reasonable standard deviations Acts::BoundVector stddev; stddev[Acts::eBoundLoc0] = 100_um; stddev[Acts::eBoundLoc1] = 100_um; stddev[Acts::eBoundTime] = 25_ns; stddev[Acts::eBoundPhi] = 2_degree; stddev[Acts::eBoundTheta] = 2_degree; stddev[Acts::eBoundQOverP] = 1 / 100_GeV; Acts::BoundSquareMatrix cov = stddev.cwiseProduct(stddev).asDiagonal(); // define a track in the transverse plane along x Acts::Vector4 mPos4(-3_m, 0., 0., 42_ns); return Acts::CurvilinearTrackParameters(mPos4, 0_degree, 90_degree, 1_e / 1_GeV, cov, pion); } // Instantiate the tester const FitterTester tester; // reconstruction propagator and fitter auto kfLogger = getDefaultLogger("KalmanFilter", Logging::INFO); const auto kfZeroPropagator = makeConstantFieldPropagator<ConstantFieldStepper>(tester.geometry, 0_T); const auto kfZero = KalmanFitter(kfZeroPropagator, std::move(kfLogger)); std::default_random_engine rng(42); auto makeDefaultKalmanFitterOptions() { KalmanFitterExtensions<VectorMultiTrajectory> extensions; extensions.calibrator .connect<&testSourceLinkCalibrator<VectorMultiTrajectory>>(); extensions.updater.connect<&KalmanUpdater::operator()<VectorMultiTrajectory>>( &kfUpdater); extensions.smoother .connect<&KalmanSmoother::operator()<VectorMultiTrajectory>>(&kfSmoother); extensions.surfaceAccessor.connect< &Acts::detail::Test::TestSourceLink::SurfaceAccessor::operator()>( &tester.surfaceAccessor); return KalmanFitterOptions(tester.geoCtx, tester.magCtx, tester.calCtx, extensions, PropagatorPlainOptions()); } } // namespace BOOST_AUTO_TEST_SUITE(TrackFittingKalmanFitter) BOOST_AUTO_TEST_CASE(ZeroFieldNoSurfaceForward) { auto start = makeParameters(); auto kfOptions = makeDefaultKalmanFitterOptions(); bool expected_reversed = false; bool expected_smoothed = true; tester.test_ZeroFieldNoSurfaceForward(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); } BOOST_AUTO_TEST_CASE(ZeroFieldWithSurfaceForward) { auto start = makeParameters(); auto kfOptions = makeDefaultKalmanFitterOptions(); // regular smoothing kfOptions.reversedFiltering = false; bool expected_reversed = false; bool expected_smoothed = true; tester.test_ZeroFieldWithSurfaceForward(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); // reverse filtering instead of smoothing kfOptions.reversedFiltering = true; kfOptions.reversedFilteringCovarianceScaling = 100.0; expected_reversed = true; expected_smoothed = false; tester.test_ZeroFieldWithSurfaceForward(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); } BOOST_AUTO_TEST_CASE(ZeroFieldWithSurfaceBackward) { auto start = makeParameters(); auto kfOptions = makeDefaultKalmanFitterOptions(); // regular smoothing kfOptions.reversedFiltering = false; bool expected_reversed = false; bool expected_smoothed = true; tester.test_ZeroFieldWithSurfaceBackward(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); // reverse filtering instead of smoothing kfOptions.reversedFiltering = true; kfOptions.reversedFilteringCovarianceScaling = 100.0; expected_reversed = true; expected_smoothed = false; tester.test_ZeroFieldWithSurfaceBackward(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); } BOOST_AUTO_TEST_CASE(ZeroFieldWithSurfaceAtExit) { auto start = makeParameters(); auto kfOptions = makeDefaultKalmanFitterOptions(); bool expected_reversed = false; bool expected_smoothed = true; tester.test_ZeroFieldWithSurfaceAtExit(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); } BOOST_AUTO_TEST_CASE(ZeroFieldShuffled) { auto start = makeParameters(); auto kfOptions = makeDefaultKalmanFitterOptions(); bool expected_reversed = false; bool expected_smoothed = true; tester.test_ZeroFieldShuffled(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); } BOOST_AUTO_TEST_CASE(ZeroFieldWithHole) { auto start = makeParameters(); auto kfOptions = makeDefaultKalmanFitterOptions(); bool expected_reversed = false; bool expected_smoothed = true; tester.test_ZeroFieldWithHole(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); } BOOST_AUTO_TEST_CASE(ZeroFieldWithOutliers) { auto start = makeParameters(); // fitter options w/o target surface. outlier distance is set to be below the // default outlier distance in the `MeasurementsCreator` auto kfOptions = makeDefaultKalmanFitterOptions(); TestOutlierFinder tof{5_mm}; kfOptions.extensions.outlierFinder .connect<&TestOutlierFinder::operator()<VectorMultiTrajectory>>(&tof); bool expected_reversed = false; bool expected_smoothed = true; tester.test_ZeroFieldWithOutliers(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); } BOOST_AUTO_TEST_CASE(ZeroFieldWithReverseFiltering) { auto start = makeParameters(); auto test = [&](double threshold, bool reverse, bool expected_reversed, bool expected_smoothed) { auto kfOptions = makeDefaultKalmanFitterOptions(); TestReverseFilteringLogic trfl{threshold}; kfOptions.extensions.reverseFilteringLogic .connect<&TestReverseFilteringLogic::operator()<VectorMultiTrajectory>>( &trfl); kfOptions.reversedFiltering = reverse; kfOptions.reversedFilteringCovarianceScaling = 100.0; tester.test_ZeroFieldWithReverseFiltering(kfZero, kfOptions, start, rng, expected_reversed, expected_smoothed, true); }; // Track of 1 GeV with a threshold set at 0.1 GeV, reversed filtering should // not be used test(0.1_GeV, false, false, true); // Track of 1 GeV with a threshold set at 10 GeV, reversed filtering should // be used test(10._GeV, false, true, false); // Track of 1 GeV with a threshold set at 10 GeV, reversed filtering should // be used test(0.1_GeV, true, true, false); } // TODO this is not really Kalman fitter specific. is probably better tested // with a synthetic trajectory. BOOST_AUTO_TEST_CASE(GlobalCovariance) { auto start = makeParameters(); auto kfOptions = makeDefaultKalmanFitterOptions(); tester.test_GlobalCovariance(kfZero, kfOptions, start, rng); } BOOST_AUTO_TEST_SUITE_END()
import { context as globalContext, setContext } from '../../globalContext' import { getAsyncStoreInstance } from '../../globalContextStore' describe('Global context with context isolation', () => { it('Should work when assigning directly into context', async () => { const asyncStore = getAsyncStoreInstance() asyncStore.run(new Map(), () => { // This is the actual test globalContext.myNewValue = 'bazinga' expect(globalContext.myNewValue).toBe('bazinga') }) // Check that context was isolated expect(globalContext.myNewValue).not.toBe('bazinga') }) it('Should work when using setContext', async () => { const asyncStore = getAsyncStoreInstance() asyncStore.run(new Map(), () => { // This is the actual test setContext({ anotherValue: 'kittens' }) expect(globalContext.anotherValue).toBe('kittens') }) // Check that context was isolated expect(globalContext.anotherValue).not.toBe('kittens') }) it('setContext replaces global context', async () => { const asyncStore = getAsyncStoreInstance() asyncStore.run(new Map(), () => { // This is the actual test globalContext.myNewValue = 'bazinga' setContext({ anotherValue: 'kittens' }) expect(globalContext.myNewValue).toBeUndefined() expect(globalContext.anotherValue).toBe('kittens') }) // Check that context was isolated expect(globalContext.myNewValue).toBeUndefined() expect(globalContext.anotherValue).toBeUndefined() }) })
class BallancesController < ApplicationController before_action :authenticate_user! before_action :set_ballance, only: %i[ show edit update destroy ] def show @spi = @ballance.spi if @ballance.spi @scis = @ballance.scis if @ballance.scis @allocates = @ballance.ballance_projects end def index @q = Ballance.ransack(params[:q]) @ballances = @q.result.order(updated_at: :desc) end def new @ballance = Ballance.new end def create @ballance = Ballance.new(ballance_params) respond_to do |format| if @ballance.save format.html { redirect_to ballance_url(@ballance), notice: "Balance was successfully created." } format.json { render :show, status: :created, location: @ballance } else format.turbo_stream { render turbo_stream: turbo_stream.replace('remote_modal', partial: 'shared/turbo_modal', locals: { form_partial: 'ballances/form', modal_title: 'Add new Balance' })} end end end def edit end def update end def destroy end private def set_ballance @ballance = Ballance.find(params[:id]) end def ballance_params params.require(:ballance).permit(:number, :status, :name, :product, :supplier_id) end end
import { Body, Controller, Delete, Get, HttpCode, Param, Post, Put, Query, UsePipes, ValidationPipe } from '@nestjs/common'; import {VideoService} from './video.service'; import {Types} from "mongoose"; import {VideoDto} from "./dto/video.dto"; import {Auth} from "../auth/decorators/auth.decorator"; import {IdValidationPipe} from "../pipes/id.validation.pipe"; import {CurrentUser} from "../user/decorators/user.decorator"; @Controller('video') export class VideoController { constructor(private readonly videoService: VideoService) { } @Get('by-user/:userId') async getVideoByUserId(@Param('userId', IdValidationPipe) userId: Types.ObjectId) { return this.videoService.getByUserId(userId) } @Get('by-user-private') @Auth() async getVideoByUserIdPrivate(@CurrentUser('_id') _id: Types.ObjectId) { return this.videoService.getByUserId(_id, true) } @Get('most-popular') async getMostPopularByViews() { return this.videoService.getMostPopularByViews() } @Get('private/:id') @Auth() async getByVideoIdPrivate(@Param('id', IdValidationPipe) id: string) { return this.videoService.getByVideoId(new Types.ObjectId(id), false) } @Get() async getAllVideos(@Query('searchTerm') searchTerm?: string) { return this.videoService.getAll(searchTerm) } @Get(':id') async getByVideoId(@Param('id', IdValidationPipe) id: Types.ObjectId) { return this.videoService.getByVideoId(id) } @UsePipes(new ValidationPipe()) @HttpCode(200) @Put(':id') @Auth() async updateVideo(@Param('id', IdValidationPipe) id: string, @Body() dto: VideoDto) { return this.videoService.update(id, dto) } @UsePipes(new ValidationPipe()) @HttpCode(200) @Post() @Auth() async createVideo(@CurrentUser('_id') _id: Types.ObjectId) { return this.videoService.create(_id) } @UsePipes(new ValidationPipe()) @HttpCode(200) @Delete(':id') @Auth() async deleteVideo(@Param('id', IdValidationPipe) id: string) { return this.videoService.delete(id) } @HttpCode(200) @Put('update-views/:videoId') async updateViews(@Param('videoId', IdValidationPipe) videoId: Types.ObjectId) { return this.videoService.updateViewsCount(videoId) } @UsePipes(new ValidationPipe()) @HttpCode(200) @Put('update-likes/:videoId') @Auth() async updateLikes(@CurrentUser('_id') _id:Types.ObjectId, @Param('videoId', IdValidationPipe) videoId: string) { return this.videoService.updateLikes(videoId, _id) } }
import test from 'ava'; import { Tsv, NdJson, Frontmatter, Plist } from '../src/index.js'; test('ndjson lifecycle', t => { const input = [ { key: 'string1', value: 12345 }, { key: 'string2', value: 67890 }, ]; const serialized = NdJson.stringify(input); t.deepEqual(NdJson.parse(serialized), input); }); test('tsv lifecycle', t => { const input = [ { key: 'string1', value: 12345 }, { key: 'string2', value: 67890 }, ]; const serialized = Tsv.stringify(input); t.deepEqual(Tsv.parse(serialized), input); }); test.skip('tsv arrays', t => { const input = [ ['string1', 12345], ['string2', 67890], ]; const serialized = Tsv.stringify(input); t.deepEqual(Tsv.parse(serialized), input); // this should pass in another param, but ugh }); test('plist lifecycle', t => { const input = [ { key: 'string1', value: 12345 }, { key: 'string2', value: 67890 }, ]; const serialized = Plist.stringify(input); t.deepEqual(Plist.parse(serialized), input); }); test('frontmatter roundtrip', t => { const input = { data: { title: 'title', date: '2000-01-01', layout: 'page', tags: ['tag1', 'tag2'], }, content: 'Full content', }; const serialized = Frontmatter.stringify(input); const output = Frontmatter.parse(serialized); t.deepEqual(output.data, input.data); t.deepEqual(output.content.trim(), input.content.trim()); });
package artgallery.hsboxoffice.configuration; import artgallery.hsboxoffice.configuration.CustomAuthFilter; import feign.FeignException; import lombok.RequiredArgsConstructor; import org.springframework.boot.autoconfigure.web.WebProperties; import org.springframework.boot.web.reactive.error.DefaultErrorAttributes; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.SecurityWebFiltersOrder; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.web.server.SecurityWebFilterChain; import org.springframework.web.server.ResponseStatusException; import java.util.Map; @Configuration @EnableWebFluxSecurity @RequiredArgsConstructor @EnableReactiveMethodSecurity public class SecurityConfiguration { private final String[] WHITE_LIST_URLS = { "/api-docs", "/api-docs/**", "/swagger-ui", "/swagger-ui/**", "/webjars/**" }; @Bean public SecurityWebFilterChain filterChain(ServerHttpSecurity http, ReactiveAuthenticationManager reactiveAuthenticationManager) { http .authorizeExchange(exchange -> exchange .pathMatchers(WHITE_LIST_URLS).permitAll() .anyExchange().authenticated() ) .csrf(ServerHttpSecurity.CsrfSpec::disable) .cors(ServerHttpSecurity.CorsSpec::disable) .formLogin(ServerHttpSecurity.FormLoginSpec::disable) .logout(ServerHttpSecurity.LogoutSpec::disable) .addFilterAt(customAuthFilter(reactiveAuthenticationManager), SecurityWebFiltersOrder.AUTHENTICATION); return http.build(); } @Bean public CustomAuthFilter customAuthFilter(ReactiveAuthenticationManager reactiveAuthenticationManager) { return new CustomAuthFilter(reactiveAuthenticationManager); } @Bean @Order(-2) public CustomWebExceptionHandler customExceptionHandler(WebProperties webProperties, ApplicationContext applicationContext, ServerCodecConfigurer configurer) { CustomWebExceptionHandler exceptionHandler = new CustomWebExceptionHandler( new DefaultErrorAttributes(), webProperties.getResources(), applicationContext, exceptionToStatusCode(), HttpStatus.INTERNAL_SERVER_ERROR ); exceptionHandler.setMessageWriters(configurer.getWriters()); exceptionHandler.setMessageReaders(configurer.getReaders()); return exceptionHandler; } @Bean public Map<Class<? extends Exception>, HttpStatus> exceptionToStatusCode() { return Map.of( ResponseStatusException.class, HttpStatus.NOT_FOUND ); } }
import { SquareArrowDown } from 'tabler-icons-react' import { useQuery } from '@tanstack/react-query' import { useContext } from 'react' import { NavLink } from 'react-router-dom' import s from './AssetsTable.module.scss' import { TableHeading, tableHeadings } from 'src/utils/cryptoTableHeaders' import { cryptoAPI } from 'src/services/clientService' import { CryptoCoin } from 'src/types/cryptocoin.interface' import { TableLayout } from 'src/components/layouts/tableLayout/TableLayout' import { PageContext } from 'src/contexts/Contexts' import { TABLE_LIMIT } from 'src/utils/constantData' import { ControlWrapper } from 'src/components/control/Control' export const CryptoAssetsTable = () => { return ( <> <TableLayout> <TableHeadings /> <TableBody /> </TableLayout> </> ) } export const TableHeadings = () => { const completedHeadings = tableHeadings.map((heading: TableHeading) => ( <th className={s.tableHeadingTitle} key={heading.id} > {heading.name} <SquareArrowDown className={s.icon} viewBox="0 -5 24 24" height={16} width={26} /> </th> )) return ( <thead > <tr>{completedHeadings}</tr> </thead > ) } export const TableBody = () => { const page = useContext(PageContext) const { data: assets = [] } = useQuery({ queryKey: ['assets', page], queryFn: () => cryptoAPI.fetchAssets({ offset: page, limit: TABLE_LIMIT }), keepPreviousData: true, staleTime: Infinity, }) const assetsRows = assets.map((asset: CryptoCoin) => { return ( <UserTableInfo key={asset.id} asset={asset} /> ) }) return ( <tbody> {assetsRows} </tbody> ) } const UserTableInfo = ({ asset }: { asset: CryptoCoin }) => { return ( <tr className={s.userTableRow} > <Td dataTh='Name:' value={asset.name} id={asset.id} /> <Td dataTh='Symbol:' value={asset.symbol} id={asset.id} /> <Td dataTh='Vwap24Hr:' value={asset.vwap24Hr} id={asset.id} /> <Td dataTh='PriceUsd:' value={asset.priceUsd} id={asset.id} /> <td className={s.assetTd}> <ControlWrapper asset={asset} /> </td> </tr> ) } interface TdProps { dataTh: string; value: string; id: string; } export const Td = ({ dataTh, value, id }: TdProps) => { return ( <td className={s.assetTd} data-th={dataTh}> <NavLink to={`/cryptoDataPage/${id}`}> {value} </NavLink> </td> ) }
import { useEffect, useState } from "react"; import { MapContainer, TileLayer, FeatureGroup, Circle, Popup, Marker } from "react-leaflet"; import ImageFlag from "./../Card/imageFlag"; import styles from "../../styles/Country/countryMapView.module.css" import "leaflet/dist/leaflet.css"; const CountryMapView = (props) => { const purpleOptions = { color: 'purple' } const [property, setProperty] = useState(null); const [geoCap, setgeoCap] = useState(null) useEffect(() => { // charge icon const L = require("leaflet"); delete L.Icon.Default.prototype._getIconUrl; L.Icon.Default.mergeOptions({ iconRetinaUrl: require("leaflet/dist/images/marker-icon-2x.png"), iconUrl: require("leaflet/dist/images/marker-icon.png"), shadowUrl: require("leaflet/dist/images/marker-shadow.png") }); const defineProperty = () => { if (props.capitals !== undefined) { setProperty(props.capitals.join(", ")); setgeoCap(props.geoCap); } } defineProperty(); }) return ( <div> <MapContainer center={props.geoLoc} zoom={props.capitals === undefined ? 1 : 5} scrollWheelZoom={true} > <TileLayer attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' url={"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"} /> {geoCap !== null && ( <> <FeatureGroup pathOptions={purpleOptions}> <Popup> {property} </Popup> <Circle center={geoCap} radius={3000} /> </FeatureGroup> </> )} <> <Marker position={props.geoLoc} > <Popup> <div className={styles.popupMap}> <p><strong>Country</strong></p> <p>{props.name}</p> <div> <p><strong>Coat of Arms</strong></p> <ImageFlag imgWidth="5em" imgHeight="7em" name="Coast Of Arms" img={props.coatOfArms} /> </div> </div> </Popup> </Marker> </> </MapContainer> </div> ); }; export default CountryMapView;
import React from "react"; export interface BaseInputDefinition<T> { label?: string; repeat?: boolean; default?: T; required?: boolean; } export interface Notification { level: string; sourceAction: string; msg: string; } export interface BooleanInputDefinition extends BaseInputDefinition<boolean> { type: "boolean"; } export interface NumberInputDefinition extends BaseInputDefinition<number> { type: "number"; nonNegative?: boolean; } export interface StringInputDefinition extends BaseInputDefinition<string> { type: "string"; placeholder?: string; } export interface ComplexInputDefinition<T = any> extends BaseInputDefinition<null> { type: "complex"; inputs: T; } interface SelectInputDefinitionOption<T> { name: string; value: T; // ? } export interface SelectInputDefinition<T = string> extends BaseInputDefinition<string> { type: "select"; options: SelectInputDefinitionOption<T>[]; } export interface AttributeInputDefinition extends BaseInputDefinition<{ device: null; attribute: null; }> { type: "attribute"; dataFormat?: "scalar" | "spectrum" | "image"; dataType?: "numeric"; device?: string; attribute?: string; invalidates?: string[]; } export interface ColorInputDefinition extends BaseInputDefinition<string> { type: "color"; } export interface DeviceInputDefinition extends BaseInputDefinition<null> { type: "device"; publish?: string; } export interface CommandInputDefinition extends BaseInputDefinition<null> { type: "command"; device?: string; command?: string; intype?: string; invalidates?: string[]; parameter?: string; } export interface CommandInputWithParameterDefinition extends BaseInputDefinition<null> { type: "command"; device?: string; command?: string; intype?: string; invalidates?: string[]; parameter?: string; } export type InputDefinition = | BooleanInputDefinition | NumberInputDefinition | StringInputDefinition | ComplexInputDefinition | AttributeInputDefinition | SelectInputDefinition | ColorInputDefinition | DeviceInputDefinition | CommandInputDefinition; export interface InputDefinitionMapping { [name: string]: InputDefinition; } export interface Widget { type: string; id: string; valid: boolean; canvas: string; x: number; y: number; width: number; height: number; inputs: InputMapping; } export interface DashboardEditHistory{ undoActions: Record<string, Widget>[], redoActions: Record<string, Widget>[], undoIndex: number, redoIndex: number, undoLength: number, redoLength: number, } export interface Dashboard { id: string; name: string; user: string; redirect: boolean; insertTime: Date | null; updateTime: Date | null; history: DashboardEditHistory; } export interface InputMapping { [name: string]: any; } export interface WidgetDefinition<T extends InputDefinitionMapping> { type: string; name: string; defaultWidth: number; defaultHeight: number; inputs: T; } export interface WidgetBundle<T extends InputDefinitionMapping> { definition: WidgetDefinition<T>; component: React.ElementType; } export type IndexPath = Array<string | number>; interface AttributeValue<ValueT> { value: ValueT; writeValue: ValueT; timestamp: number; } export interface AttributeInput<ValueT = any> extends AttributeValue<ValueT> { device: string; attribute: string; history: Array<AttributeValue<ValueT>>; dataType: string; dataFormat: string; isNumeric: boolean; unit: string; write: (value: ValueT) => void; } export interface CommandInput<OutputT = any> { device: string; command: string; parameter?: string; dataType?: string; output: OutputT; execute: (argin?: any) => void; } export interface DeviceInput { name: string; alias: string; } export interface CommandInputWithParameter<OutputT = any> { device: string; command: string; parameter?: string; dataType?: string; output: OutputT; execute: (value: OutputT) => void; } export type ComplexInput<T> = any; export interface Canvas { id: string; name: string; }
/************************************************************************************ * EMStudio - Open Source ECU tuning software * * Copyright (C) 2013 Michael Carpenter (malcom2073@gmail.com) * * * * This file is a part of EMStudio * * Author: Ari "MrOnion" Karhu (ari@baboonplanet.com) * * * * EMStudio is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation, version * * 2.1 of the License. * * * * EMStudio is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this program; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ************************************************************************************/ #ifndef ABSTRACTGAUGEITEM_H #define ABSTRACTGAUGEITEM_H #include <QPen> #include <QDeclarativeItem> #include <QPainter> #include <QTimer> enum GaugeStatus { STATUS_OK = 1, STATUS_WARNING = 2, STATUS_DANGER = 3 }; class AbstractGaugeItem : public QDeclarativeItem { Q_OBJECT public: explicit AbstractGaugeItem(QDeclarativeItem *parent = 0); Q_PROPERTY(QString title READ getTitle WRITE setTitle) Q_PROPERTY(QString unit READ getUnit WRITE setUnit) Q_PROPERTY(double low READ getLow WRITE setLow) Q_PROPERTY(double high READ getHigh WRITE setHigh) Q_PROPERTY(double lowDanger READ getLowDanger WRITE setLowDanger) Q_PROPERTY(double highDanger READ getHighDanger WRITE setHighDanger) Q_PROPERTY(double lowWarning READ getLowWarning WRITE setLowWarning) Q_PROPERTY(double highWarning READ getHighWarning WRITE setHighWarning) Q_PROPERTY(int decimal READ getDecimal WRITE setDecimal) Q_PROPERTY(double value READ getValue WRITE setValue) protected: void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry); virtual void init() = 0; virtual void drawBackground() = 0; QImage *m_background; bool m_redrawBackground; QString m_title; QString m_unit; double m_low; double m_high; //boost::optional<double> m_lowDanger; //boost::optional<double> m_lowWarning; //boost::optional<double> m_highDanger; //boost::optional<double> m_highWarning; double m_lowDanger; double m_lowWarning; double m_highDanger; double m_highWarning; bool m_lowDangerSet; bool m_lowWarningSet; bool m_highDangerSet; bool m_highWarningSet; int m_decimal; double m_value; static const QColor colorOk; static const QColor colorWarning; static const QColor colorDanger; static const QColor colorValue; bool isRangeSet(); int getStatus(); bool isHighlighted(); QColor getStatusColor(); private: bool m_isResized; signals: void updated(); public slots: double getLow(); void setLow(double low); double getHigh(); void setHigh(double high); double getLowWarning(); void setLowWarning(double lowWarning); double getLowDanger(); void setLowDanger(double lowDanger); double getHighWarning(); void setHighWarning(double highWarning); double getHighDanger(); void setHighDanger(double highDanger); QString getTitle(); void setTitle(QString title); QString getUnit(); void setUnit(QString unit); int getDecimal(); void setDecimal(int decimal); double getValue(); void setValue(double value); }; #endif // ABSTRACTGAUGEITEM_H
"use client"; import { Button } from "@/components/ui/button"; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage, } from "@/components/ui/form"; import { Input } from "@/components/ui/input"; import { zodResolver } from "@hookform/resolvers/zod"; import React from "react"; import { useForm } from "react-hook-form"; import { BasicInformationFormSchema, BasicInformationFormType, } from "@/lib/zodSchema/basicInformation"; import { updateBasicInformation } from "@/actions/update-basic-information"; import { Textarea } from "@/components/ui/textarea"; type Props = { basicInformationData: BasicInformationFormType | null; }; const UpdateBasicInformationForm = ({ basicInformationData }: Props) => { const form = useForm<BasicInformationFormType>({ resolver: zodResolver(BasicInformationFormSchema), defaultValues: basicInformationData ? basicInformationData : { name: "", username: "", firstName: "", lastName: "", shortIntro: "", mediumIntro: "", longIntro: "", userLocation: "", }, }); function onSubmit(values: BasicInformationFormType) { console.log(values); updateBasicInformation(values); } return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)}> <div className="flex flex-col gap-2 hover:bg-primary/10 p-8"> <FormField control={form.control} name="username" render={({ field }) => ( <FormItem> <FormLabel>Username</FormLabel> <FormControl> <Input placeholder="Enter your preferred username..." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="name" render={({ field }) => ( <FormItem> <FormLabel>Name</FormLabel> <FormControl> <Input placeholder="Enter your name" {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="firstName" render={({ field }) => ( <FormItem> <FormLabel>First Name</FormLabel> <FormControl> <Input placeholder="Enter your first name..." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="lastName" render={({ field }) => ( <FormItem> <FormLabel>Last Name</FormLabel> <FormControl> <Input placeholder="Enter your last name..." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="shortIntro" render={({ field }) => ( <FormItem> <FormLabel>Short Introduction</FormLabel> <FormControl> <Input placeholder="Enter your short introduction..." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="mediumIntro" render={({ field }) => ( <FormItem> <FormLabel>General Introduction</FormLabel> <FormControl> <Textarea placeholder="Enter your general introduction..." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="longIntro" render={({ field }) => ( <FormItem> <FormLabel>Overview</FormLabel> <FormControl> <Textarea className="h-[150px]" placeholder="Enter your detailed introduction..." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> <FormField control={form.control} name="userLocation" render={({ field }) => ( <FormItem> <FormLabel>Location</FormLabel> <FormControl> <Input placeholder="Enter your location..." {...field} /> </FormControl> <FormMessage /> </FormItem> )} /> </div> <Button type="submit" className="my-4"> Update </Button> </form> </Form> ); }; export default UpdateBasicInformationForm;
import React, { useEffect, useState , useContext } from 'react'; import { useNavigate } from 'react-router-dom'; import RenderCards from './RenderCards'; import backendContext from '../contex/backend/backendContext'; const Profile = () => { const context = useContext(backendContext); const { host } = context; const [recipes, setRecipes] = useState([]); const navigate = useNavigate(); const handleLogOut = () => { localStorage.removeItem('culinashareToken'); navigate('/'); }; const getUserCreatedRecipes = async () => { try { const response = await fetch(`${host}/api/foodresp/user-created`, { method: 'GET', headers: { 'auth-token': localStorage.getItem('culinashareToken'), } }); if (response.ok) { const createdRecipes = await response.json(); setRecipes(createdRecipes); } else { const errorData = await response.json(); console.error('Error fetching user-created recipes:', errorData.msg); } } catch (error) { console.error('Error fetching user-created recipes:', error); } }; useEffect(() => { getUserCreatedRecipes(); }, []); // Empty dependency array means this effect runs once when the component mounts return ( <div className="profile2 "> <h1 className='mb-4'>Created Recipes By You</h1> { (!recipes) ? <p>loading data....</p> : <RenderCards recipes={recipes} />} <button onClick={handleLogOut} className="custom_btn mt-4"> Log-Out </button> </div> ); }; export default Profile;
// // FeedbackView.swift // // // Created by Kevin Waltz on 13.04.23. // import SwiftUI struct FeedbackView: View { var body: some View { VStack(spacing: 0) { NavigationBar(header: Strings.feedbackHeader, showButtonToCloseView: true, foregroundColor: foregroundColor, action: dismissView) if feedbackSent { FeedbackPlaceholderView(image: Image(systemName: "hands.clap"), description: Strings.placeholderFeedbackSent) } else { VStack { VStack(spacing: LayoutValues.minorPadding) { VStack(spacing: LayoutValues.majorPadding) { FeedbackTypeSelectionView(backgroundColor: secondaryBackgroundColor, foregroundColor: foregroundColor, type: $type) CustomTextEditor(placeholder: type.placeholder, text: $description) .padding(.horizontal, LayoutValues.minorPadding) .background(secondaryBackgroundColor) .cornerRadius(LayoutValues.cornerRadius) } PrimaryButton(foregroundColor: foregroundColor, title: Strings.send, isDisabled: disableButton, action: sendFeedback) } .padding(.bottom, LayoutValues.majorPadding + LayoutValues.minorPadding) } .adaptsToKeyboard() .edgesIgnoringSafeArea(.bottom) .padding(.horizontal, LayoutValues.minorPadding) } } .background(primaryBackgroundColor) #if os(macOS) .frame(minWidth: 600, maxWidth: 600, minHeight: 600, maxHeight: 600) #endif } // MARK: - Variables let primaryBackgroundColor: Color let secondaryBackgroundColor: Color let foregroundColor: Color @State var type = RoadKitTopicType.feedback @State var description = "" @State var feedbackSent = false @Binding var isPresented: Bool // MARK: - Computed Properties var disableButton: Bool { description.isEmpty } // MARK: - Functions private func sendFeedback() { RoadKitTopicsViewModel.shared.sendFeedback(type: type, description: description) withAnimation { feedbackSent.toggle() } DispatchQueue.main.asyncAfter(deadline: .now() + 2) { dismissView() } } private func dismissView() { isPresented = false } }
import { useMutation, useQueryClient } from '@tanstack/react-query'; import { supabase } from './supabase'; import { useAuth } from '@/store/global'; export interface SignInForm { email: string; password: string; } /** * Hook for signing in with email and password. */ export const useEmailSignInMutation = () => { return useMutation({ mutationFn: async ({ email, password }: SignInForm) => { const response = await supabase.auth.signInWithPassword({ email, password, }); if (response.error) throw response.error; return response.data; }, }); }; export const enum UserRole { USER = 'USER', ADMIN = 'ADMIN', } /** * Hook for signing out the current user. * Invalidates all queries on success. */ export const useSignoutMutation = () => { const qc = useQueryClient(); const { logout } = useAuth(); return useMutation({ mutationFn: async () => { await supabase.auth.signOut(); logout(); }, onSuccess: () => { // invalidates any cache entries qc.invalidateQueries(); }, }); };
import { configureStore, ThunkAction, Action } from "@reduxjs/toolkit"; import { createWrapper } from "next-redux-wrapper"; import createProductReducer from "./features/products/createProduct"; import createEditProductReducer from "./features/products/editProduct"; import userReducer from "./features/user/userSlice"; import { nextReduxCookieMiddleware, wrapMakeStore, } from "next-redux-cookie-wrapper"; export const makeStore = wrapMakeStore(() => configureStore({ reducer: { createProduct: createProductReducer, editProduct: createEditProductReducer, user: userReducer, }, middleware: (getDefaultMiddleware) => getDefaultMiddleware().prepend( nextReduxCookieMiddleware({ // maxAge: 30, maxAge: 60 * 60 * 24 * 10, subtrees: [`createProduct`, `user`], }) ), }) ); export type AppStore = ReturnType<typeof makeStore>; export type AppState = ReturnType<AppStore["getState"]>; export type AppDispatch = AppStore["dispatch"]; export type AppThunk<ReturnType = void> = ThunkAction< ReturnType, AppState, unknown, Action<string> >; export const wrapper = createWrapper<AppStore>(makeStore);
package com.example.controller; import com.example.dto.TransactionDTO; import com.example.exceptions.NoTransactionsFoundException; import com.example.model.DailyReport; import com.example.service.TransactionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; /** * Controller class for managing transactions and generating daily reports. */ @RestController @RequestMapping("/api/transactions") public class TransactionController { @Autowired private TransactionService transactionService; /** * Save a new transaction. * * @param transactionDTO The details of the transaction to be saved. * @return ResponseEntity with the saved TransactionDTO and HTTP status OK. */ @PostMapping("/save") public ResponseEntity<TransactionDTO> saveTransaction(@RequestBody TransactionDTO transactionDTO) { TransactionDTO savedTransaction = transactionService.saveTransaction(transactionDTO); return ResponseEntity.ok(savedTransaction); } /** * Get the daily report for a specific user. * * @param userId The ID of the user for whom the daily report is requested. * @return ResponseEntity with the DailyReport and HTTP status OK if transactions are found. * If no transactions are found, returns HTTP status NOT_FOUND. */ @GetMapping("/dailyReport/{userId}") public ResponseEntity<DailyReport> getDailyReport(@PathVariable Long userId) { try { DailyReport dailyReport = transactionService.getDailyReport(userId); return new ResponseEntity<>(dailyReport, HttpStatus.OK); } catch (NoTransactionsFoundException e) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } }
import '/auth/firebase_auth/auth_util.dart'; import '/backend/backend.dart'; import '/components/changeprofileimage_widget.dart'; import '/flutter_flow/flutter_flow_theme.dart'; import '/flutter_flow/flutter_flow_util.dart'; import '/flutter_flow/flutter_flow_widgets.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:google_fonts/google_fonts.dart'; import 'package:provider/provider.dart'; import 'home_model.dart'; export 'home_model.dart'; class HomeWidget extends StatefulWidget { const HomeWidget({Key? key}) : super(key: key); @override _HomeWidgetState createState() => _HomeWidgetState(); } class _HomeWidgetState extends State<HomeWidget> { late HomeModel _model; final scaffoldKey = GlobalKey<ScaffoldState>(); @override void initState() { super.initState(); _model = createModel(context, () => HomeModel()); _model.textController ??= TextEditingController(); } @override void dispose() { _model.dispose(); super.dispose(); } @override Widget build(BuildContext context) { context.watch<FFAppState>(); return GestureDetector( onTap: () => FocusScope.of(context).requestFocus(_model.unfocusNode), child: Scaffold( key: scaffoldKey, backgroundColor: FlutterFlowTheme.of(context).primaryBackground, body: SafeArea( top: true, child: Container( width: double.infinity, height: double.infinity, decoration: BoxDecoration( color: FlutterFlowTheme.of(context).secondaryBackground, ), child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 14.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 0.0, 0.0), child: AuthUserStreamWidget( builder: (context) => Text( 'Hi, ${currentUserDisplayName}👋', style: FlutterFlowTheme.of(context).bodyMedium, ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 20.0, 0.0), child: AuthUserStreamWidget( builder: (context) => InkWell( splashColor: Colors.transparent, focusColor: Colors.transparent, hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { await showModalBottomSheet( isScrollControlled: true, backgroundColor: Colors.transparent, enableDrag: false, context: context, builder: (context) { return GestureDetector( onTap: () => FocusScope.of(context) .requestFocus(_model.unfocusNode), child: Padding( padding: MediaQuery.viewInsetsOf(context), child: ChangeprofileimageWidget(), ), ); }, ).then((value) => setState(() {})); }, child: Container( width: 30.0, height: 30.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context) .secondaryBackground, image: DecorationImage( fit: BoxFit.cover, image: Image.network( valueOrDefault<String>( currentUserPhoto, 'https://media.istockphoto.com/id/1214428300/fr/vectoriel/photo-de-profil-par-d%C3%A9faut-avatar-photo-placeholder-illustration-de-vecteur.jpg?s=612x612&w=0&k=20&c=uUjAtTWbGO-cpetR5zDdwkcQdTxcnetQW4wWczPwiZY=', ), ).image, ), borderRadius: BorderRadius.circular(8.0), ), ), ), ), ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 8.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, children: [ Flexible( child: Padding( padding: EdgeInsetsDirectional.fromSTEB( 20.0, 0.0, 140.0, 0.0), child: Text( 'Keep taking ', style: FlutterFlowTheme.of(context) .bodyMedium .override( fontFamily: 'Readex Pro', fontSize: 28.0, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 8.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 0.0, 0.0), child: Text( 'care of your heath', style: FlutterFlowTheme.of(context).bodyMedium.override( fontFamily: 'Readex Pro', fontSize: 28.0, fontWeight: FontWeight.bold, ), ), ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 24.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, children: [ Flexible( child: Padding( padding: EdgeInsetsDirectional.fromSTEB( 20.0, 0.0, 0.0, 0.0), child: Container( width: double.infinity, height: 56.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context) .secondaryBackground, borderRadius: BorderRadius.circular(8.0), ), child: Row( mainAxisSize: MainAxisSize.max, children: [ Expanded( child: Padding( padding: EdgeInsetsDirectional.fromSTEB( 8.0, 0.0, 8.0, 0.0), child: TextFormField( controller: _model.textController, autofocus: true, obscureText: false, decoration: InputDecoration( labelText: 'Search', labelStyle: FlutterFlowTheme.of(context) .labelMedium, hintStyle: FlutterFlowTheme.of(context) .labelMedium, enabledBorder: InputBorder.none, focusedBorder: InputBorder.none, errorBorder: InputBorder.none, focusedErrorBorder: InputBorder.none, prefixIcon: Icon( Icons.search, ), ), style: FlutterFlowTheme.of(context) .bodyMedium, validator: _model.textControllerValidator .asValidator(context), ), ), ), Container( height: 100.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context) .secondaryBackground, ), ), ], ), ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 10.0, 0.0, 20.0, 0.0), child: Container( width: 56.0, height: 56.0, decoration: BoxDecoration( color: Color(0xFF5146D9), borderRadius: BorderRadius.circular(8.0), ), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: [ FaIcon( FontAwesomeIcons.slidersH, color: FlutterFlowTheme.of(context) .secondaryBackground, size: 24.0, ), ], ), ), ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 24.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 0.0, 0.0), child: Text( 'Service category', style: FlutterFlowTheme.of(context).bodyMedium.override( fontFamily: 'Readex Pro', fontSize: 16.0, fontWeight: FontWeight.w600, ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 20.0, 0.0, 20.0, 0.0), child: Text( 'See all', style: FlutterFlowTheme.of(context).bodyMedium.override( fontFamily: 'Readex Pro', color: Color(0xFF5146D9), ), ), ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 16.0, 0.0, 0.0), child: Container( width: double.infinity, height: 100.0, decoration: BoxDecoration(), child: ListView( padding: EdgeInsets.zero, scrollDirection: Axis.horizontal, children: [ Row( mainAxisSize: MainAxisSize.max, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB( 20.0, 0.0, 0.0, 0.0), child: Container( width: 100.0, height: 100.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context) .secondaryBackground, borderRadius: BorderRadius.circular(8.0), ), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: [ ClipRRect( borderRadius: BorderRadius.circular(0.0), child: Image.network( 'https://cdn-icons-png.flaticon.com/128/2785/2785482.png', width: 50.0, height: 50.0, fit: BoxFit.cover, ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 0.0, 12.0, 0.0, 0.0), child: Text( 'Doctor', style: FlutterFlowTheme.of(context) .bodyMedium, ), ), ], ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 20.0, 0.0, 0.0, 0.0), child: Container( width: 100.0, height: 100.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context) .secondaryBackground, borderRadius: BorderRadius.circular(8.0), ), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: [ ClipRRect( borderRadius: BorderRadius.circular(0.0), child: Image.network( 'https://cdn-icons-png.flaticon.com/128/1165/1165602.png', width: 50.0, height: 50.0, fit: BoxFit.cover, ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 0.0, 12.0, 0.0, 0.0), child: Text( 'Nurse', style: FlutterFlowTheme.of(context) .bodyMedium, ), ), ], ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 20.0, 0.0, 0.0, 0.0), child: Container( width: 100.0, height: 100.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context) .secondaryBackground, borderRadius: BorderRadius.circular(8.0), ), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: [ ClipRRect( borderRadius: BorderRadius.circular(0.0), child: Image.network( 'https://cdn-icons-png.flaticon.com/128/4320/4320365.png', width: 50.0, height: 50.0, fit: BoxFit.cover, ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 0.0, 12.0, 0.0, 0.0), child: Text( 'Drug', style: FlutterFlowTheme.of(context) .bodyMedium, ), ), ], ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 20.0, 0.0, 20.0, 0.0), child: Container( width: 100.0, height: 100.0, decoration: BoxDecoration( color: FlutterFlowTheme.of(context) .secondaryBackground, borderRadius: BorderRadius.circular(8.0), ), child: Column( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.center, children: [ ClipRRect( borderRadius: BorderRadius.circular(0.0), child: Image.network( 'https://cdn-icons-png.flaticon.com/128/2515/2515014.png', width: 50.0, height: 50.0, fit: BoxFit.cover, ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 0.0, 12.0, 0.0, 0.0), child: Text( 'Caregiver', style: FlutterFlowTheme.of(context) .bodyMedium, ), ), ], ), ), ), ], ), ], ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 24.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 0.0, 0.0), child: Text( 'Popular Doctors', style: FlutterFlowTheme.of(context).bodyMedium.override( fontFamily: 'Readex Pro', fontSize: 16.0, fontWeight: FontWeight.w600, ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 20.0, 0.0, 20.0, 0.0), child: InkWell( splashColor: Colors.transparent, focusColor: Colors.transparent, hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { context.pushNamed( 'Alldoctors', extra: <String, dynamic>{ kTransitionInfoKey: TransitionInfo( hasTransition: true, transitionType: PageTransitionType.bottomToTop, duration: Duration(milliseconds: 500), ), }, ); }, child: Text( 'See all', style: FlutterFlowTheme.of(context) .bodyMedium .override( fontFamily: 'Readex Pro', color: Color(0xFF5146D9), ), ), ), ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(0.0, 24.0, 0.0, 0.0), child: Container( width: double.infinity, height: 250.0, decoration: BoxDecoration(), child: StreamBuilder<List<PopulardoctorsRecord>>( stream: queryPopulardoctorsRecord(), builder: (context, snapshot) { // Customize what your widget looks like when it's loading. if (!snapshot.hasData) { return Center( child: SizedBox( width: 50.0, height: 50.0, child: CircularProgressIndicator( valueColor: AlwaysStoppedAnimation<Color>( FlutterFlowTheme.of(context).primary, ), ), ), ); } List<PopulardoctorsRecord> listViewPopulardoctorsRecordList = snapshot.data!; return ListView.builder( padding: EdgeInsets.zero, scrollDirection: Axis.horizontal, itemCount: listViewPopulardoctorsRecordList.length, itemBuilder: (context, listViewIndex) { final listViewPopulardoctorsRecord = listViewPopulardoctorsRecordList[listViewIndex]; return Row( mainAxisSize: MainAxisSize.max, children: [ Padding( padding: EdgeInsetsDirectional.fromSTEB( 20.0, 0.0, 0.0, 0.0), child: InkWell( splashColor: Colors.transparent, focusColor: Colors.transparent, hoverColor: Colors.transparent, highlightColor: Colors.transparent, onTap: () async { context.pushNamed( 'doctorsdetailpage', queryParameters: { 'populardoctorsRef': serializeParam( listViewPopulardoctorsRecord .reference, ParamType.DocumentReference, ), }.withoutNulls, extra: <String, dynamic>{ kTransitionInfoKey: TransitionInfo( hasTransition: true, transitionType: PageTransitionType.rightToLeft, duration: Duration(milliseconds: 500), ), }, ); }, child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.start, children: [ ClipRRect( borderRadius: BorderRadius.circular(12.0), child: Image.network( listViewPopulardoctorsRecord.image, width: 150.0, height: 150.0, fit: BoxFit.cover, ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 0.0, 8.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: [ Icon( Icons.star_rounded, color: FlutterFlowTheme.of(context) .warning, size: 24.0, ), Text( listViewPopulardoctorsRecord .rating .toString(), style: FlutterFlowTheme.of(context) .bodyMedium, ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 0.0, 8.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, children: [ Text( listViewPopulardoctorsRecord .name, style: FlutterFlowTheme.of(context) .bodyMedium .override( fontFamily: 'Readex Pro', fontSize: 20.0, fontWeight: FontWeight.bold, ), ), ], ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB( 0.0, 4.0, 0.0, 0.0), child: Row( mainAxisSize: MainAxisSize.max, children: [ Text( listViewPopulardoctorsRecord .specialty, style: FlutterFlowTheme.of(context) .bodyMedium .override( fontFamily: 'Readex Pro', fontSize: 16.0, fontWeight: FontWeight.normal, ), ), ], ), ), ], ), ), ), ], ); }, ); }, ), ), ), Padding( padding: EdgeInsetsDirectional.fromSTEB(20.0, 0.0, 0.0, 0.0), child: FFButtonWidget( onPressed: () async { GoRouter.of(context).prepareAuthEvent(); await authManager.signOut(); GoRouter.of(context).clearRedirectLocation(); context.goNamedAuth('splash', context.mounted); }, text: 'Logout', options: FFButtonOptions( height: 40.0, padding: EdgeInsetsDirectional.fromSTEB(24.0, 0.0, 24.0, 0.0), iconPadding: EdgeInsetsDirectional.fromSTEB(0.0, 0.0, 0.0, 0.0), color: Color(0xFFF87265), textStyle: FlutterFlowTheme.of(context).titleSmall.override( fontFamily: 'Readex Pro', color: Colors.white, ), elevation: 3.0, borderSide: BorderSide( color: Colors.transparent, width: 1.0, ), borderRadius: BorderRadius.circular(8.0), ), ), ), ], ), ), ), ), ); } }
/* github.com/tcrain/cons - Experimental project for testing and scaling consensus algorithms. Copyright (C) 2020 The project authors - tcrain This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. */ package currency import ( "bytes" "github.com/tcrain/cons/consensus/auth/sig" "github.com/tcrain/cons/consensus/types" "github.com/tcrain/cons/consensus/utils" "io" "math" ) var InitUniqueName = types.GetHash([]byte("should be some unique name")) // InitBlock represents the initial balances and participants in the currency. type InitBlock struct { InitPubs []sig.Pub // The initial public keys. InitBalances []uint64 // The initial balances. InitUniqueName types.HashBytes // Should be a unique string. NewPubFunc func() sig.Pub // Used during deserialization, should return an empty public key of the type being used. } func (ib *InitBlock) Decode(reader io.Reader) (n int, err error) { var nxtN int ib.InitUniqueName = make(types.HashBytes, types.GetHashLen()) nxtN, err = reader.Read(ib.InitUniqueName) n += nxtN if err != nil { return } var pubCount uint16 pubCount, nxtN, err = utils.ReadUint16(reader) n += nxtN if err != nil { return } ib.InitPubs = make([]sig.Pub, int(pubCount)) ib.InitBalances = make([]uint64, int(pubCount)) for i := range ib.InitPubs { ib.InitPubs[i] = ib.NewPubFunc() nxtN, err = ib.InitPubs[i].Decode(reader) n += nxtN if err != nil { return } ib.InitBalances[i], nxtN, err = utils.ReadUint64(reader) n += nxtN if err != nil { return } } return } func (ib *InitBlock) Encode(writer io.Writer) (n int, err error) { if len(ib.InitPubs) > math.MaxUint16 { panic(1) } if !bytes.Equal(InitUniqueName, ib.InitUniqueName) { panic("should set unique name") } var nxtN int nxtN, err = writer.Write(InitUniqueName) n += nxtN if err != nil { return } nxtN, err = utils.EncodeUint16(uint16(len(ib.InitPubs)), writer) n += nxtN if err != nil { return } for i, pub := range ib.InitPubs { nxtN, err = pub.Encode(writer) n += nxtN if err != nil { return } nxtN, err = utils.EncodeUint64(ib.InitBalances[i], writer) n += nxtN if err != nil { return } } return }
dataset=read.csv('Social_Network_Ads.csv') dataset=dataset[,3:5] #Splitting the dataset into training and test set #install.packages('caTools') library(caTools) set.seed(123) split=sample.split(dataset$Purchased,SplitRatio = 0.75) training_set=subset(dataset,split==TRUE) test_set=subset(dataset,split==FALSE) #Feature SCaling Excluding categorical values training_set[,1:2]=scale(training_set[,1:2]) test_set[,1:2]=scale(test_set[,1:2]) #Fitting Logistic Regression to the Training Set classifier = glm(formula = Purchased ~ ., family = binomial, data = training_set) # Doubt binomial family #Predicting the Test set results prob_pred=predict(classifier, type = 'response', newdata = test_set[-3]) y_pred=ifelse(prob_pred > 0.5, 1, 0) # Making the confusion metrics (Number correct and incorrect predictions) cm = table(test_set[,3],y_pred) #Visualising the Training set results #install.packages('ElemStatLearn') #Point is the truth and region is the prediction #Straight line is called the prediction boundary and it is a staright line because #Logistic Regression is Linear Classifier (here 2D). #(in a 3D it will be a straight plane). library(ElemStatLearn) set=training_set X1=seq(min(set[,1])-1,max(set[,1])+1, by = 0.01) X2=seq(min(set[,2])-1,max(set[,2])+1, by = 0.01) grid_set=expand.grid(X1,X2) colnames(grid_set)=c('Age','EstimatedSalary') prob_set = predict(classifier, type = 'response', newdata = grid_set) y_grid = ifelse(prob_set > 0.5, 1, 0) plot(set[,-3], main = 'Logistic Regression (Training Set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1,X2,matrix(as.numeric(y_grid),length(X1),length(X2)),add = TRUE) points(grid_set,pch = '.',col = ifelse(y_grid==1,'springgreen3','tomato')) points(set,pch = 21,bg=ifelse(set[,3]==1,'green4','red3')) #Visualising the Test set results set=test_set X1=seq(min(set[,1])-1,max(set[,1])+1, by = 0.01) #Making the pixel values X2=seq(min(set[,2])-1,max(set[,2])+1, by = 0.01) #Same as Python grid_set=expand.grid(X1,X2) #Now making the pixel grid for real as well as imaginary users. colnames(grid_set)=c('Age','EstimatedSalary') #Giving name to the columns of matrix prob_set = predict(classifier, type = 'response', newdata = grid_set) #Predicting for grid_set matrix for each skills y_grid = ifelse(prob_set > 0.5, 1, 0) plot(set[,-3], main = 'Logistic Regression (Test Set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1,X2,matrix(as.numeric(y_grid),length(X1),length(X2)),add = TRUE) points(grid_set,pch = '.',col = ifelse(y_grid==1,'springgreen3','tomato')) #For Backgroound Predictions points(set,pch = 21,bg=ifelse(set[,3]==1,'green4','red3')) #For true points
using FluentAssertions; using System.Diagnostics; using Xunit; namespace JanHafner.TypeNameR.Tests.ExceptionStackTraceManipulatorTests; public sealed class TryRestoreOriginalStackTrace { private Exception exception = new(); [Fact] public void ThrowsArgumentNullExceptionIfExceptionIsNull() { // Arrange #pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type. exception = null; #pragma warning restore CS8625 // Cannot convert null literal to non-nullable reference type. // Act, Assert var argumentNullException = Assert.Throws<ArgumentNullException>(() => Call()); argumentNullException.ParamName.Should().Be(nameof(exception)); } [Fact] public void ReturnsFalseIfOriginalStacktraceIsNotStored() { // Act var result = Call(); // Assert result.Should().BeFalse(); } [Fact] public void ReturnsTrueAndRestoresTheOriginalStackTrace() { // Arrange var originalStackTrace = Guid.NewGuid().ToString(); exception.Data[ExceptionStackTraceManipulator.OriginalStackTraceKey] = originalStackTrace; // Act var result = Call(); // Assert result.Should().BeTrue(); exception.Data.Keys.Count.Should().Be(0); exception.StackTrace.Should().Be(originalStackTrace); } [DebuggerStepThrough] private bool Call() => exception.TryRestoreOriginalStackTrace(); }
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { Observable } from 'rxjs/Observable'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { fromPromise } from 'rxjs/observable/fromPromise'; import { map, tap, catchError } from 'rxjs/operators'; import { of } from 'rxjs/observable/of'; import { AmplifyService } from 'aws-amplify-angular'; import { environment } from './../../environments/environment'; @Injectable() export class AuthService { public loggedIn: BehaviorSubject<boolean>; constructor( private router: Router, private amplifyService: AmplifyService ) { this.loggedIn = new BehaviorSubject<boolean>(false); } /** signup */ public signUp(email, password): Observable<any> { return fromPromise(this.amplifyService.auth().signUp(email, password)); } /** confirm code */ public confirmSignUp(email, code): Observable<any> { return fromPromise(this.amplifyService.auth().confirmSignUp(email, code)); } /** signin */ public signIn(email, password): Observable<any> { return fromPromise(this.amplifyService.auth().signIn(email, password)).pipe( tap(() => this.loggedIn.next(true)) ); } /** get authenticat state */ public isAuthenticated(): Observable<boolean> { return fromPromise(this.amplifyService.auth().currentAuthenticatedUser()).pipe( map(result => { this.loggedIn.next(true); return true; }), catchError(error => { this.loggedIn.next(false); return of(false); }) ); } /** signout */ public signOut() { fromPromise(this.amplifyService.auth().signOut()).subscribe( result => { this.loggedIn.next(false); this.router.navigate(['/login']); }, error => console.log(error) ); } }
import { useContext } from "react"; import classes from "./MealItem.module.css"; import MealItemForm from "./MealItemForm"; import CartContext from "../../../store/cart-context"; const MealItem = (props) => { const cartCnxt = useContext(CartContext); const price = `$${props.price.toFixed(2)}`; const addToCartHandler = (amount) => { cartCnxt.addItem({ id: props.id, name: props.name, amount: amount, price: props.price, }); }; return ( <li className={classes.meal}> <div> <h2>{props.name} </h2> <div className={classes.description}>{props.description}</div> <div className={classes.price}> {price} </div> </div> <div> {/* <MealItemForm id={props.id} item={props} /> */} <MealItemForm onAddToCart={addToCartHandler} /> </div> </li> ); }; export default MealItem;
/* Copyright 2023 Jacob Green Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ use super::*; use lazy_static::lazy_static; #[derive(Debug)] struct ImageUniform { transform: Mat4, } #[derive(Debug)] pub struct VisualImage { uniform: UniformBuffer<ImageUniform>, bind_group: wgpu::BindGroup, } impl VisualImage { pub fn new(rect: Rect, texture_view: &wgpu::TextureView) -> Self { let uniform = UniformBuffer::new_initialized(ImageUniform { transform: model_projection(rect, 0.0), }); let bind_group = get_device().create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &IMAGE_BIND_GROUP_LAYOUT, entries: &[ wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Buffer( uniform.as_ref().as_entire_buffer_binding(), ), }, wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(texture_view), }, ], }); Self { uniform, bind_group, } } } impl Visual for VisualImage { fn draw<'a>(&'a self, render_pass: &mut wgpu::RenderPass<'a>) { // render_pass.set_pipeline(&IMAGE_PIPELINE); // render_pass.set_bind_group(1, &self.bind_group, &[]); // render_pass.draw(0..6, 0..1); draw_quad( render_pass, &IMAGE_PIPELINE, &[BindGroupBinding { index: 1, bind_group: &self.bind_group, }], ) } } struct BindGroupBinding<'a> { index: u32, bind_group: &'a wgpu::BindGroup, } #[inline(always)] fn draw_quad<'a>( render_pass: &mut wgpu::RenderPass<'a>, pipeline: &'a wgpu::RenderPipeline, bind_groups: &[BindGroupBinding<'a>], ) { render_pass.set_pipeline(pipeline); bind_groups.iter().for_each(|bind_group| { render_pass.set_bind_group(bind_group.index, bind_group.bind_group, &[]); }); render_pass.draw(0..6, 0..1); } lazy_static! { static ref IMAGE_VERTEX_SHADER: wgpu::ShaderModule = unsafe { get_device().create_shader_module_spirv(&include_spirv_raw!(concat!( env!("OUT_DIR"), "/shaders/image.vert.spv" ))) }; static ref IMAGE_FRAGMENT_SHADER: wgpu::ShaderModule = unsafe { get_device().create_shader_module_spirv(&include_spirv_raw!(concat!( env!("OUT_DIR"), "/shaders/image.frag.spv" ))) }; static ref IMAGE_BIND_GROUP_LAYOUT: wgpu::BindGroupLayout = { get_device().create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("Image Binding Layout"), entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStages::VERTEX, ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None, }, count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, count: None, ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false, }, visibility: wgpu::ShaderStages::FRAGMENT, }, ], }) }; static ref IMAGE_PIPELINE_LAYOUT: wgpu::PipelineLayout = { get_device().create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("Image Pipeline Layout"), bind_group_layouts: &[&RENDER_INFO_BIND_LAYOUT, &IMAGE_BIND_GROUP_LAYOUT], push_constant_ranges: &[], }) }; static ref IMAGE_PIPELINE: wgpu::RenderPipeline = { get_device().create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some("Image Render Pipeline"), layout: Some(&IMAGE_PIPELINE_LAYOUT), vertex: wgpu::VertexState { module: &IMAGE_VERTEX_SHADER, entry_point: "main", buffers: &[], }, primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleList, strip_index_format: None, front_face: wgpu::FrontFace::Ccw, cull_mode: None, unclipped_depth: false, polygon_mode: wgpu::PolygonMode::Fill, conservative: false, }, depth_stencil: None, multisample: wgpu::MultisampleState { count: 1, mask: !0, alpha_to_coverage_enabled: false, }, fragment: Some(wgpu::FragmentState { module: &IMAGE_FRAGMENT_SHADER, entry_point: "main", targets: &[Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Bgra8UnormSrgb, blend: Some(wgpu::BlendState::ALPHA_BLENDING), write_mask: wgpu::ColorWrites::ALL, })], }), multiview: None, }) }; }
// Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 // Package image scan and provide image info package image import ( _ "embed" // need for embedding "fmt" "os" "path/filepath" "github.com/clarketm/json" pol "github.com/kubearmor/KubeArmor/pkg/KubeArmorController/api/security.kubearmor.com/v1" "github.com/packer-plugin-kubearmor/recommend/common" log "github.com/sirupsen/logrus" ) // Info contains image information type Info struct { FileList []string TempDir string } func addPolicyRule(policy *pol.KubeArmorHostPolicy, r pol.KubeArmorHostPolicySpec) { if len(r.File.MatchDirectories) != 0 || len(r.File.MatchPaths) != 0 { policy.Spec.File = r.File } if len(r.Process.MatchDirectories) != 0 || len(r.Process.MatchPaths) != 0 { policy.Spec.Process = r.Process } if len(r.Network.MatchProtocols) != 0 { policy.Spec.Network = r.Network } } func (img *Info) createPolicy(ms common.MatchSpec) (pol.KubeArmorHostPolicy, error) { policy := pol.KubeArmorHostPolicy{ Spec: pol.KubeArmorHostPolicySpec{ Severity: 1, // by default NodeSelector: pol.NodeSelectorType{ MatchLabels: map[string]string{}}, }, } policy.APIVersion = "security.kubearmor.com/v1" policy.Kind = "KubeArmorHostPolicy" policy.ObjectMeta.Name = ms.Name policy.Spec.Action = ms.Spec.Action policy.Spec.Severity = ms.Spec.Severity if ms.Spec.Message != "" { policy.Spec.Message = ms.Spec.Message } if len(ms.Spec.Tags) > 0 { policy.Spec.Tags = ms.Spec.Tags } addPolicyRule(&policy, ms.Spec) return policy, nil } // GetPolicy - creates policy and return back func (img *Info) GetPolicy(ms common.MatchSpec, options common.Options) ([]byte, string) { policy, err := img.createPolicy(ms) if err != nil { log.WithError(err).WithFields(log.Fields{ "image": img, "spec": ms, }).Error("create policy failed, skipping") } arr, _ := json.Marshal(policy) outFile := filepath.Join(options.OutDir, ms.Name) err = os.MkdirAll(filepath.Dir(outFile), 0750) if err != nil { log.WithError(err).Error("failed to create directory") } _, err = os.Create(filepath.Clean(outFile)) if err != nil { log.WithError(err).Error(fmt.Sprintf("create file %s failed", outFile)) } return arr, outFile }
@block @block_opencast Feature: Add Opencast Video Provider series module as Teacher In order to provide the uploaded videos to my students As teacher I need to be able to add an Opencast series module to my course Background: Given the following "users" exist: | username | firstname | lastname | email | idnumber | | teacher1 | Teacher | 1 | teacher1@example.com | T1 | And the following "courses" exist: | fullname | shortname | format | category | id | | Course 1 | C1 | topics | 0 | 123 | And the following "course enrolments" exist: | user | course | role | | teacher1 | C1 | editingteacher | And I setup the default settigns for opencast plugins And the following config values are set as admin: | config | value | plugin | | apiurl_1 | http://testapi:8080 | tool_opencast | | apipassword_1 | opencast | tool_opencast | | apiusername_1 | admin | tool_opencast | | ocinstances | [{"id":1,"name":"Default","isvisible":true,"isdefault":true}] | tool_opencast | | limituploadjobs_1 | 0 | block_opencast | | limitvideos_1 | 5 | block_opencast | | group_creation_1 | 0 | block_opencast | | group_name_1 | Moodle_course_[COURSEID] | block_opencast | | series_name_1 | Course_Series_[COURSEID] | block_opencast | | addactivityenabled_1 | 1 | block_opencast | | addactivityintro_1 | 1 | block_opencast | | addactivitysection_1 | 1 | block_opencast | | addactivityavailability_1 | 1 | block_opencast | And I setup the opencast test api And I upload a testvideo And I log in as "admin" And I am on "Course 1" course homepage with editing mode on And I add the "Opencast Videos" block And I log out Scenario: Teachers should be able to add a series module to the course Given I log in as "teacher1" And I am on "Course 1" course homepage And I click on "Go to overview..." "link" And I click on "Add Opencast Video Provider activity to course" "link" And I set the following fields to these values: | Opencast series module intro | <p>This is a nice intro</p><p>Watch my videos!</p> | And I click on "Add module and return to course" "button" And I should see "The 'Opencast videos' series module has been added to this course." And I should see "This is a nice intro" in the "li.activity" "css_element" And I should see "Opencast videos" in the "li.activity" "css_element" When I click on "Go to overview..." "link" Then "View Opencast series module in course" "link" should exist And "Add Opencast Video Provider activity to course" "button" should not exist @javascript Scenario: Teachers should be able to add a series module to the course when there are multiple series Given I log in as "teacher1" And I create a second series And I am on "Course 1" course homepage And I click on "Go to overview..." "link" And I click on "Add Opencast Video Provider activity to course" "link" And I set the following fields to these values: | Opencast series module intro | <p>This is a nice intro</p><p>Watch my videos!</p> | And I click on "Add module and return to course" "button" And I should see "The 'Opencast videos' series module has been added to this course." And I should see "This is a nice intro" in the "li.activity" "css_element" And I should see "Opencast videos" in the "li.activity" "css_element" When I click on "Go to overview..." "link" Then "View Opencast series module in course" "link" should exist Then "Add Opencast Video Provider activity to course" "link" should exist
import argparse import json import cv2 from flask import Flask, render_template, redirect, send_file, url_for, request, jsonify, Response import os import numpy as np import supervision as sv from ultralytics import YOLO model = YOLO('model/best.pt') # model = YOLO('runs/detect/train/weights/best.pt') app = Flask(__name__) @app.route("/") def hello_word(): with open('static/constants/helpline.json') as f: data = json.load(f) # return render_template('result.html') return render_template('index.html', json_data=data) @app.route('/', methods=['POST']) def upload_data(result_image_path=None, speed=None): if 'file' in request.files: image_file = request.files['file'] if not image_file.filename: return redirect(url_for('hello_word')) else: basepath = os.path.dirname(__file__) filepath = os.path.join(basepath, 'uploads', image_file.filename) image_file.save(filepath) file_extension = image_file.filename.rsplit('.', 1)[1].lower() if file_extension == 'mp4': video_path = filepath print("video path", video_path) cap = cv2.VideoCapture(video_path) frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter('output.mp4', fourcc, 30.0, (frame_width, frame_height)) while cap.isOpened(): ret, frame = cap.read() if not ret: break result = model(frame, save=True) cv2.waitKey(1) res_plotted = result[0].plot() out.write(res_plotted) if cv2.waitKey(1) == ord('q'): break out.release() cap.release() cv2.destroyAllWindows() # Download the file send_file('output.mp4', as_attachment=True) return redirect(url_for('hello_word')) else: # img = cv2.imread(filepath) # frame = cv2.imencode('.'+file_extension, cv2.UMat(img))[1].tobytes() filepath_new = f"uploads/{image_file.filename}" detections = model.predict(filepath_new, save=True, project="static/output", name="predict") print('test', detections) for res in detections: result_image_path = res.save_dir speed = res.speed return render_template('result.html', result_speed=speed, result_image_path="../" + result_image_path + "/" + image_file.filename) else: print("nothing") return 'No image provided.' @app.route("/live") def liveDetection(): return render_template('live.html') @app.route("/detect_objects", methods=['GET']) def detectObject(): cap = cv2.VideoCapture(0) box_annotator= sv.BoxAnnotator( thickness=2, text_thickness=2, text_scale=1 ) while True: _,frame = cap.read() result = model(frame)[0] detection= sv.Detections.from_ultralytics(result) frame= box_annotator.annotate(scene=frame,detections=detection) cv2.imshow('Camera', frame) # Check for the 'q' key to exit if cv2.waitKey(1) & 0xFF == ord('q'): break # cap.release() # cv2.destroyAllWindows() # results = model.predict(source=0, show=True,stream=True) return "hey" if __name__ == "__main__": parser = argparse.ArgumentParser(description="Aerial Object Detection") parser.add_argument("--port", default=5000, type=int, help="port number") args = parser.parse_args()
# Pastas de Trabalho para arquivos java: ## <a id="instalacao">🔨 Instalação do Ambiente</a> Obs: Estes exemplos foram formulados totalmente em um ambiente computacional dentro da nuvem. Particulamente no codespace do Github e Gitpod. Na atualidade são as melhores plataformas para isto, balanceando os custos e beneficios. Se você não conhece ou não sabe como acessa-los, [clique aqui.](https://docs.github.com/en/codespaces/developing-in-codespaces/opening-an-existing-codespace/) No codespace abra um terminal ou teclas use <kbd>Ctrl</kbd> + <kbd>'</kbd> Para criar os códigos fonte, via terminal, é só digitar ```bash $ touch meuPrimeiro.java ``` Vai abrir o editor do Visual Studio, depois é só digitar conforme a necessidade do programa. Também pode ser aberto na janela gráfica, através dos menus da barra superior. Após aberto e salvo, pode ser feita a compilação pelo editor javac: ```bash $ javac meuPrimeiro.java ``` Se não apresentar nenhum erro, pode ser executado pelo comando: ``` $ Java meuPrimeiro ``` Abaixo um exemplo de um arquivo basico: ```java import java.lang.*; public class First { public static void main(String[] args) { System.out.println("Hello World!!");// exibir um texto com quebra de linha System.out.println(args[0]);// exibir texto apos linnha de comando System.out.println(args[1]);// exibir texto 2 apos linha de comando } } ``` Aqui somente para traçar as diretrizes iniciais básicas. - Você pode clonar este repositório: ```bash # Clone <https://github.com/joseivangeraldo/Java> ```
/** * This file is part of the IC reverse engineering tool Degate. * * Copyright 2008, 2009, 2010 by Martin Schobert * Copyright 2019-2020 Dorian Bachelot * * Degate 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. * * Degate 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 degate. If not, see <http://www.gnu.org/licenses/>. * */ #ifndef __CONNECTIONINSPECTOR_H__ #define __CONNECTIONINSPECTOR_H__ #include "Core/Project/Project.h" #include <QDialog> #include <QVBoxLayout> #include <QTableWidget> #include <QPushButton> #include <QLabel> #include <vector> namespace degate { /** * Store information about objects (previous, current and next objects) for a row. * * @see ConnectionInspector */ struct ConnectionRow { ConnectedLogicModelObject_shptr previous; ConnectedLogicModelObject_shptr current; ConnectedLogicModelObject_shptr next; }; /** * @class ConnectionInspector * @brief Display connection information about an object. */ class ConnectionInspector : public QDialog { Q_OBJECT public: /** * Create the connection inspector window. * * @param widget : the parent widget. * @param project : the current project. */ ConnectionInspector(QWidget* widget, Project_shptr project); ~ConnectionInspector() override = default; /** * Set an object that should be inspected. * @param object : the object to inspect. */ void set_object(const degate::PlacedLogicModelObject_shptr& object); /** * Disable inspection, clear all elements. */ void disable_inspection(); protected slots: /** * Jump to selected object. Will call jump_to_object(). */ void jump_to_selected_object(); /** * Goto previous inspected object. */ void back(); /** * Called when an item is double clicked. * * @param item : the double clicked item. * * @see QTreeWidget */ void on_item_double_clicked(QTableWidgetItem* item); protected: /** * Show connections of a specific object. */ void show_connections(const ConnectedLogicModelObject_shptr& object); /** * Clear table contents. */ void clear(); /** * Jump to object. Will emit goto_object(). * * @param row : the object row. * @param column : the object column. */ void jump_to_object(int row, int column); signals: /** * Sent when the "goto" button is clicked. * * @param object : the concerned object to go to. */ void goto_object(PlacedLogicModelObject_shptr& object); private: Project_shptr project = nullptr; QVBoxLayout layout; std::vector<PlacedLogicModelObject_shptr> back_list; // Object identity QGridLayout object_layout; QLabel object_name_label; QLabel object_name_value; QLabel object_type_label; QLabel object_type_value; // Object connections QTableWidget connections_table; std::map<int, ConnectionRow> connections; // Control QGridLayout control_layout; QPushButton back_button; QPushButton goto_button; QPushButton close_button; }; } #endif //__CONNECTIONINSPECTOR_H__
import { useState, useRef } from 'react' import { uid } from 'uid' import { rotateIcon } from './assets/svg/rotate' import { TiDelete } from 'react-icons/ti' import Draggable from 'react-draggable' import TruckBody from '../TruckBody/TruckBody' import logo from './assets/logo.png' import './Control.scss' const Control = () => { const elementLength = useRef() const elementWidth = useRef() const elementColor = useRef() const elementQuantity = useRef() const elementNote = useRef() const [elements, setElements] = useState([]) const [errorLength, setErrorLength] = useState(false) const [errorWidth, setErrorWidth] = useState(false) const [zIndex, setZIndex] = useState(null) const errorCheckLenght = errorLength ? 'form-control error' : 'form-control' const errorCheckWidth = errorWidth ? 'form-control error' : 'form-control' const validateInput = () => { !elementLength.current.value ? setErrorLength(true) : setErrorLength(false) !elementWidth.current.value ? setErrorWidth(true) : setErrorWidth(false) !/^\d+$/.test(elementLength.current.value) ? setErrorLength(true) : setErrorLength(false) !/^\d+$/.test(elementWidth.current.value) ? setErrorWidth(true) : setErrorWidth(false) } const handleRemoveElement = (key) => { setElements((prevElements) => prevElements.filter((e) => e.key !== key)) } const handleResetBtn = (e) => { e.preventDefault() setElements([]) } const createNewElement = (e) => { e.preventDefault() validateInput() if (!elementWidth.current.value || !elementLength.current.value) return if (!errorLength && !errorWidth) { const newElement = Array.from( { length: +elementQuantity.current.value }, (_, index) => { const key = uid() return ( <div className="div_element" key={key} style={{ width: `${elementWidth.current.value}px`, height: `${elementLength.current.value}px`, backgroundColor: elementColor.current.value, }} > <div className="dimensions"> {elementLength.current.value}x{elementWidth.current.value} </div> <div className="icons__wrap"> <div className="delete__icon" onClick={() => handleRemoveElement(key)} > <TiDelete /> </div> <div className="rotate__icon" onClick={() => handleElementRotate(key)} > {rotateIcon} </div> </div> <div className="note">{elementNote.current.value}</div> </div> ) } ) setElements((prevElements) => [...prevElements, ...newElement]) } } const handleElementRotate = (key) => { setElements((prevElements) => { return prevElements.map((element) => { if (element.key === key) { return ( <div className="flipped" key={element.key}> {element} </div> ) } return element }) }) } const divElement = ( <div className="elements__container"> {elements.map((element, index) => ( <Draggable key={index}> <div className={index === zIndex ? 'z_index' : ''} onMouseEnter={() => setZIndex(index)} > {element} </div> </Draggable> ))} </div> ) return ( <> <div className="control__main"> <div className="logo__block"> <img src={logo} alt="logo" /> <h1> Truck <span>space planner</span> </h1> </div> <div className="operations__block"> <form> <div> <label>Quantity</label> <input type="number" min={1} className="form-control" ref={elementQuantity} defaultValue={1} /> </div> <div id="containeras"> <label>length</label> <input type="text" className={errorCheckLenght} ref={elementLength} defaultValue={120} onChange={validateInput} /> </div> <div> <label>Width</label> <input type="text" className={errorCheckWidth} ref={elementWidth} defaultValue={80} onChange={validateInput} /> </div> <div> <label>Note</label> <input type="text" className="form-control note" ref={elementNote} /> </div> <div className="color_picker"> <label>Color</label> <input type="color" className="form-control form-control-color" defaultValue="#EEE8E8" ref={elementColor} /> </div> <div className="btn-group"> <button className="btn btn-outline-primary" onClick={createNewElement} > Create </button> <button className="btn btn-outline-danger" onClick={handleResetBtn} > Remove all goods </button> </div> </form> </div> <div></div> </div> <TruckBody divElement={divElement} /> </> ) } export default Control
/*********************************************** * stm32f446xx_spi_driver.h * * Created on: Nov 3, 2021 * Author: Jaime Arrocha ***********************************************/ #ifndef INC_STM32F446XX_SPI_DRIVER_H_ #define INC_STM32F446XX_SPI_DRIVER_H_ #include "stm32f446xx.h" /*********************************************** * Configuration structure for SPIx peripheral ***********************************************/ typedef struct { uint8_t SPI_DeviceMode; // Master or slave selection uint8_t SPI_BusConfig; // Communication type: Duplex, Half-Duplex, Simplex uint8_t SPI_Speed; // Baud rate uint8_t SPI_DFF; // Data frame format: 8-bit, 16-bit transmission/receival uint8_t SPI_CPOL; // Default value 0 uint8_t SPI_CPHA; // Default value 0 uint8_t SPI_SSM; // Slave-Select management } SPI_Config_t; /*********************************************** * Handle structure for SPIx peripheral ***********************************************/ typedef struct { SPI_RegDef_t* pSPIx; // Holds base address of peripheral SPI_Config_t SPIConfig; } SPI_Handle_t; /*********************************************** * SPI Configuration helpers ***********************************************/ #define SPI_DEVICE_MODE_SLAVE 0 #define SPI_DEVICE_MODE_MASTER 1 #define SPI_BUS_CFG_HALFD 0 #define SPI_BUS_CFG_FULLD 1 #define SPI_BUS_CFG_SIMPLEX_RX 2 #define SPI_CLK_SPEED_DIV2 0 #define SPI_CLK_SPEED_DIV4 1 #define SPI_CLK_SPEED_DIV8 2 #define SPI_CLK_SPEED_DIV16 3 #define SPI_CLK_SPEED_DIV32 4 #define SPI_CLK_SPEED_DIV64 5 #define SPI_CLK_SPEED_DIV128 6 #define SPI_CLK_SPEED_DIV256 7 #define SPI_DFF_MODE_8BIT 0 #define SPI_DFF_MODE_16BIT 1 #define SPI_CLKPOL_LOW 0 #define SPI_CLKPOL_HIGH 1 #define SPI_CLKPHA_LOW 0 #define SPI_CLKPHA_HIGH 1 #define SPI_SSM_DISABLE 0 #define SPI_SSM_ENABLE 1 /*********************************************** * SPI Control Registers 1, Bit Definitions ***********************************************/ #define SPI_CR1_CPHA 0 #define SPI_CR1_CPOL 1 #define SPI_CR1_MSTR 2 #define SPI_CR1_BR 3 #define SPI_CR1_SPE 6 #define SPI_CR1_LSBFIRST 7 #define SPI_CR1_SSI 8 #define SPI_CR1_SSM 9 #define SPI_CR1_RXONLY 10 #define SPI_CR1_DFF 11 #define SPI_CR1_CRCNEXT 12 #define SPI_CR1_CRCEN 13 #define SPI_CR1_BIDIOE 14 #define SPI_CR1_BIDIMODE 15 /*********************************************** * SPI Control Registers 2, Bit Definitions ***********************************************/ #define SPI_CR2_RXDMAEN 0 #define SPI_CR2_TXDMAEN 1 #define SPI_CR2_SSOE 2 #define SPI_CR2_FRF 4 #define SPI_CR2_ERRIE 5 #define SPI_CR2_RXNEIE 6 #define SPI_CR2_TXEIE 7 /*********************************************** * SPI Status Register, Bit Definitions ***********************************************/ #define SPI_SR_RXNE 0 #define SPI_SR_TXE 1 #define SPI_SR_CHSIDE 2 #define SPI_SR_UDR 3 #define SPI_SR_CRCERR 4 #define SPI_SR_MODF 5 #define SPI_SR_OVR 6 #define SPI_SR_BSY 7 #define SPI_SR_FRE 8 /*********************************************** * Peripheral Enable ***********************************************/ #define SPI1_DEV_EN() (SPI1->SPI_CR1 |= (1 << SPI_CR1_SPE)) #define SPI2_DEV_EN() (SPI2->SPI_CR1 |= (1 << SPI_CR1_SPE)) #define SPI3_DEV_EN() (SPI3->SPI_CR1 |= (1 << SPI_CR1_SPE)) #define SPI4_DEV_EN() (SPI4->SPI_CR1 |= (1 << SPI_CR1_SPE)) /*********************************************** * Peripheral Clock Setup ***********************************************/ int32_t SPI_PeriClockControl(SPI_RegDef_t* pSPIx, uint8_t enableState); /************************************************ * Init and reset GPIO port ************************************************/ int32_t SPI_Init(SPI_Handle_t* pSPIHandle); void SPI_DeInit(SPI_Handle_t* pSPIHandle); /************************************************ * SSI Handling ************************************************/ int32_t SPI_SSIConfig(SPI_RegDef_t* pSPIx, uint8_t enableState); // Controls the SSOE bit in SPI_CR2. This sets NSS output to enable/disable. int32_t SPI_SSOEConfig(SPI_RegDef_t* pSPIx, uint8_t enableState); /************************************************ * Data Send and Receive ************************************************/ // Synchronous send. Returns size of data send, -1 on error. int32_t SPI_SendData(SPI_RegDef_t* pSPIx, uint8_t *pTxBuffer, uint32_t len); // Synchronous receive. Returns size of recieved data. int32_t SPI_ReceiveData(SPI_RegDef_t* pSPIx, uint8_t *pRxBuffer, uint32_t len); /************************************************ * IRQ Configuration and ISR Handling ************************************************/ void SPI_IRQConfig(uint8_t IRQnumber, uint8_t enableState); void SPI_IRQPriorityConfig(uint8_t IRQnumber, uint32_t IRQPriority); void SPI_IRQHandle(SPI_Handle_t* pHandle); /************************************************ * Other Peripheral Control APIs ************************************************/ // Enables and disables SPI_CR1_SPE for peripheral enable/disable int32_t SPI_SetupDevice(SPI_RegDef_t* pSPIx, uint8_t enableState); #endif /* INC_STM32F446XX_SPI_DRIVER_H_ */
import { ErrorCode, ErrorProps, ErrorType } from 'types/errors'; export default class ApplicationError extends Error { code: ErrorCode; context: string | undefined; constructor(code: ErrorCode, message: string, context?: string, nativeError?: Error) { super(message || nativeError?.message); this.code = code; this.context = context; this.stack = nativeError?.stack; this.name = nativeError?.name || code.toString(); } getErrorProps(): ErrorProps { return { props: { error: this.toJson(), }, }; } toJson(): ErrorType { return { statusCode: this.code, message: this.message }; } }
package frc.robot.subsystems; import static frc.robot.Constants.DriveConstants.*; import static frc.robot.Constants.AutoConstants.*; import com.ctre.phoenix.sensors.Pigeon2; import com.pathplanner.lib.PathPlannerTrajectory; import com.pathplanner.lib.commands.PPSwerveControllerCommand; import edu.wpi.first.math.controller.PIDController; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.kinematics.SwerveDriveKinematics; import edu.wpi.first.math.kinematics.SwerveDriveOdometry; import edu.wpi.first.math.kinematics.SwerveModulePosition; import edu.wpi.first.math.kinematics.SwerveModuleState; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.SubsystemBase; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; public class WPI_Drivetrain extends SubsystemBase{ public double ypr[] = new double[3]; public Pigeon2 gyro = new Pigeon2(kIMUid); public WPI_SwerveModule[] modules = { LeftFrontWPI, RightFrontWPI, LeftRearWPI, RightRearWPI}; public SwerveModulePosition[] modulePositions = { modules[0].getSwerveModulePosition(), modules[1].getSwerveModulePosition(), modules[2].getSwerveModulePosition(), modules[3].getSwerveModulePosition() }; public final SwerveDriveOdometry odometer = new SwerveDriveOdometry(kDriveKinematics, new Rotation2d(0), modulePositions); public WPI_Drivetrain() { //waits for gyro to calibrate before zeroing it. //does this on a different thread as to not interupt current code. new Thread(() -> { try { Thread.sleep(1000); zeroHeading(); } catch (Exception e) { } }).start(); } //*zeros heading */ public void zeroHeading() { gyro.setYaw(0); } //*get heading of robot in degrees*/ public double getHeading() { return Math.IEEEremainder((gyro.getYaw()), 360); } public Rotation2d getHeadingRotation2d() { return Rotation2d.fromDegrees(getHeading()); } public Pose2d getPose() { return odometer.getPoseMeters(); } public void resetOdometry(Pose2d pose) { odometer.resetPosition(getHeadingRotation2d(), modulePositions, pose); } // public Command followTrajectoryCommand(PathPlannerTrajectory traj, boolean isFirstPath) { // return new SequentialCommandGroup( // new InstantCommand(() -> { // // Reset odometry for the first path you run during auto // if(isFirstPath){ // this.resetOdometry(traj.getInitialHolonomicPose()); // } // }), // new PPSwerveControllerCommand( // traj, // this::getPose, // Pose supplier // kDriveKinematics, // SwerveDriveKinematics // new PIDController(kAutoPositionPID[0], kAutoPositionPID[1], kAutoPositionPID[2]), // X controller. // new PIDController(kAutoPositionPID[0], kAutoPositionPID[1], kAutoPositionPID[2]), // Y controller. // new PIDController(kAutoHeadingPID[0], kAutoHeadingPID[1], kAutoHeadingPID[2]), // Rotation controller. // this::setModuleStates, // Module states consumer // true, // Should the path be automatically mirrored depending on alliance color. Optional, defaults to true // this // Requires this drive subsystem // ) // ); // } @Override public void periodic() { //update odo and swerve module data/positions for(int i = 0; i < modulePositions.length; i++) { modulePositions[i] = modules[i].getSwerveModulePosition(); } odometer.update(getHeadingRotation2d(), modulePositions); //System.out.println("Robot Position: (" + odometer.getPoseMeters().getX() + "," + odometer.getPoseMeters().getY() + ")"); SmartDashboard.putNumber("Robot Heading", getHeading()); SmartDashboard.putString("Robot Location", getPose().getTranslation().toString()); for(int i = 0; i < modules.length; i++) { SmartDashboard.putNumber("Wheel distance of module " + i, modules[i].getWheelPositionMeters()); SmartDashboard.putNumber("Drive Enc Reading of module " + i, modules[i].getDriveEncPosition()); } gyro.getYawPitchRoll(ypr); } public void stopModules() { LeftFrontWPI.stop(); RightFrontWPI.stop(); LeftRearWPI.stop(); RightRearWPI.stop(); } public void setModuleStates(SwerveModuleState[] desiredStates) { SwerveDriveKinematics.desaturateWheelSpeeds(desiredStates, kMaxDriveSpeed); LeftFrontWPI.setDesiredState(desiredStates[0]); RightFrontWPI.setDesiredState(desiredStates[1]); LeftRearWPI.setDesiredState(desiredStates[2]); RightRearWPI.setDesiredState(desiredStates[3]); } }
# Kubernetes Architecture - Cluster Architecture, Components & Main Objects Kubernetes is a cluster environment consist of several machine (called Nodes). Kubernetes consist of objects (such as the nodes) and several components and the kubernetes cluster is designed and architected in a specific way. This kubernetes cluster is known as a kubernetes architecture as this cluster have specific components, objects, and requirements. Each component is deployed in a specific way and perform a specific task. --- <p align="center"> <img src="images/IntroPic.png"> </p> --- ## Kubernetes Architecture - High-Level Kubernetes is a container orchestration platform, and with that being said, it points to the fact that kubernetes will have containers running on top of it as well as the fact that Kubernetes will provide orchestration, automation and further functionalities as explained in a previous [section](https://github.com/tahershaker/Learning-Kubernetes/tree/main/1.%20Introduction%20To%20Kubernetes#what-is-kubernetes---overview) such as Application deployment, Auto-Scaling, Self-Healing and much more. For containerized application to run on top of Kubernetes, compute resources (CPU & Memory) are required as well as several components providing the capability for running a container environment. Adding to this, for Kubernetes to be able to provide its added functionality (Application deployment, Auto-Scaling, Self-Healing, etc...), several more components are required to perform these functionality. The last, but not least, containerized applications requires some supporting function such as networking, security, monitoring, load balancing, DNS services, configuration management, and much more, thus, aside from the compute resources and components, several supporting tools, plugins, and 3rd party integrations are also required. > Kubernetes Cluster Kubernetes is a platform consisting of one or more compute resources called `Nodes` to provide the required compute resources to run containerized application. A kubernetes Node can be a physical server or virtual machine. These Nodes will be deployed in a `Cluster` form, and thus, Kubernetes is a `cluster` consisting of one or more node (physical server or virtual machine), hence, `Kubernetes Cluster` is always mentioned whenever kubernetes is discussed. Also, these Nodes will need an operating system, either Linux or Windows, to be installed. > Kubernetes Components On top of the Kubernetes Nodes, several components will be deployed to support running a container environment as well as the kubernetes functionalities. These components in Kubernetes are divided into 2, `Control Plan` Components and `Node` Components. The Control Plan components will be responsible of Managing, Monitoring, Orchestrating and Automating kubernetes functionality, and on the other hand, the Node components are responsible for providing the capability of running the containers on top of the Node. > Kubernetes Architecture Kubernetes give the ability to deploy all components on only one Node, however, in a Kubernetes Architecture and best practices, these components will be separated. The Control Plan components will be deployed in the same Node(s), these Nodes will be called `Master Nodes`. The Master Nodes will not host any containerized Workload applications, only the control plan components. Containerized Workloads will run on a separate type of Nodes called `Worker Nodes`, these nodes will host all containers running the business applications. The Kubernetes Node Components will run on all Nodes in the cluster - Master and Worker Nodes - as these components provide the capability to run containers on top of the Nodes. Kubernetes follows a client-server type of architecture in a cluster form with 2 type of nodes within this cluster `Master` and `Worker`. In a kubernetes cluster, and based on the kubernetes architecture and best practices, at least one Master Node and one or more Worker Node are required. In a highly available kubernetes cluster architecture 3 Master Nodes are required. > Kubernetes Objects Nearly everything deployed in a Kubernetes Cluster is referred to as a `Kubernetes Object`. A node is considered as an Object, there are several object in Kubernetes and each one of them will have a different `Kind`; (a Node is an Object with the Kind Node). There are a container object, networking object, security object and for each supporting function there will be an object with a Kind that support it's function. > _Reference_ > - _A Kubernetes cluster consists of a set of worker machines, called nodes, that run containerized applications. Every cluster has at least one worker node._<sup>Reference [1](#References)</sup> > - _The worker node(s) host the Pods that are the components of the application workload. The control plane manages the worker nodes and the Pods in the cluster. In production environments, the control plane usually runs across multiple computers and a cluster usually runs multiple nodes, providing fault-tolerance and high availability._<sup>Reference [1](#References)</sup> To summarize: - Kubernetes is a cluster consisting of one or more Node. - There are 2 types of Nodes, `Master Node` and `Worker Node`. - Several Components will be deployed on top of the Kubernetes cluster to achieve the required outcome. - Components are divided into 2 types, `Control Plan` Components and `Node` Components - Control Plan Components will be deployed on the Master Nodes, while Node Components will be deployed on all Nodes in the cluster. - Based on Kubernetes Architecture and best practices, One Master Node and one or more Worker Nodes are required. - In a highly available kubernetes cluster, 3 Master Nodes are required. - Anything deployed in a Kubernetes Cluster to run Containerized workload application is considered a Kubernetes Object. - Kubernetes Object have a `kind` which indicate the functionality of this Object. - Node is a type of Object with the kind Node. --- <p align="center"> <img src="images/KubernetesArchBasic.png"> </p> --- ## 2. Kubernetes Objects High-Level - Node, Namespace, Pods, Deployments & Services Kubernetes includes several object to perform it's desired outcome and give the ability to users to deploy and build containerized applications. There are several objects in kubernetes and each have a specific function or usability to perform. Different Object have different `kind`, and based on the kind of the object, the functionality is different. for example, a node is an object with the kind node, a pod is an object with the kind pod, and each one of them have different functionality. Some of the Kubernetes Object are listed below is a very high-level explanation and info. ### 2a. Kubernetes Node (high-level) A Kubernetes `Node` is considered as the first basic mandatory object. A Kubernetes Node is a a physical server or virtual machine running linux or windows operating system along with other kubernetes components and is responsible to providing compute resources to run containerized application on tpo of it. > _Reference_ > - _Kubernetes runs your workload by placing containers into Pods to run on Nodes. A node may be a virtual or physical machine, depending on the cluster. Each node is managed by the control plane and contains the services necessary to run Pods._<sup>Reference [3](#References)</sup> --- ### 2b. Kubernetes Namespace (high-level) As explained, Kubernetes is a cluster and is used by several users and developer. To be able to isolate the interaction and the containerized workload running on top of the cluster for each user, developer, team, or group, Kubernetes uses the concept of `Namespace`. Namespace a logical concept and is responsible of isolating resources for each user, or group within a single kubernetes cluster. Any object that is created in a namespace will have no relation to another object created in a different namespace. Once the kubernetes cluster is deployed, there is a default namespace created by default and will hold any object created by default. Kubernetes Cluster admin can then create other namespaces and give access to these namespaces to different users and groups to be able to deploy containerized application while maintain the isolation between them. > _Reference_ > - _In Kubernetes, namespaces provides a mechanism for isolating groups of resources within a single cluster. Names of resources need to be unique within a namespace, but not across namespaces. Namespace-based scoping is applicable only for namespaced objects (e.g. Deployments, Services, etc) and not for cluster-wide objects (e.g. StorageClass, Nodes, PersistentVolumes, etc)._<sup>Reference [4](#References)</sup> --- ### 2c. Kubernetes Pods (high-level) A Kubernetes Pod is the smallest kubernetes object that can be created in a kubernetes cluster. In kubernetes, containers runs inside a Pod object and not directly on the kubernetes infrastructure. A Kubernetes Pod is a way to provide Kubernetes tha ability to deploy, manage and maintain the container running in the environment. A Pod can run one or more container indie of it and it provides the networking and the storage required by this container(s). When ever we are talking about a Pod in Kubernetes, it is most likely referring to the container running inside of this Pod. > _Reference_ > - _Pods are the smallest deployable units of computing that you can create and manage in Kubernetes._<sup>Reference [5](#References)</sup> > - _A Pod (as in a pod of whales or pea pod) is a group of one or more containers, with shared storage and network resources, and a specification for how to run the containers. A Pod's contents are always co-located and co-scheduled, and run in a shared context. A Pod models an application-specific "logical host": it contains one or more application containers which are relatively tightly coupled._<sup>Reference [5](#References)</sup> --- ### 2d. Kubernetes Deployment (high-level) A containerized application may (in most cases) consists of several containers connected together in a specific way and are tightly dependant on each other. The containers of this application will run in separate Pods inside Kubernetes. A deployment is a kubernetes object that deploy the application as one bucket with all the Pods required to run this application. A deployment will give the user the ability to create the full application specification and desired state all in one go. In the YAML file used to deploy the Deployment Object, the user can specify the number of pods required (which is described in an object called ReplicaSet), which image to be used, the networking of each pod, and much more. With the Deployment, a user can update the full application using the YAML file used to deploy this Deployment. > _Reference_ > - _A Deployment provides declarative updates for Pods and ReplicaSets._<sup>Reference [6](#References)</sup> > - _You describe a desired state in a Deployment, and the Deployment Controller changes the actual state to the desired state at a controlled rate. You can define Deployments to create new ReplicaSets, or to remove existing Deployments and adopt all their resources with new Deployments._<sup>Reference [6](#References)</sup> --- ### 2e. Kubernetes Services (high-level) For a containerized application to work, some microservices that are running inside a Pod would need to communicate with each other or users need to reach this application. Services are a Kubernetes object handling the networking of the application running in the kubernetes cluster. The service is an abstraction that expose the application running inside a Pod. Each service have it's own IP address and this is the one used to reach the Pods. The kubernetes service also provide a service discovery functionality to the Pods running in the environment, As containers or Pod are ephemeral, they may die and another one is created with a different IP. Service takes care of this issue and serve the traffic to whatever container or Pod that is attached to it regardless of the Pod IP. The service do serve networking for a set of Pods attached to this service. There are different type of services which are going to be explained in details in a later section. > _Reference_ > - _In Kubernetes, a Service is a method for exposing a network application that is running as one or more Pods in your cluster._<sup>Reference [7](#References)</sup> > - _The Service API, part of Kubernetes, is an abstraction to help you expose groups of Pods over a network. Each Service object defines a logical set of endpoints (usually these endpoints are Pods) along with a policy about how to make those pods accessible._<sup>Reference [7](#References)</sup> > - _A key aim of Services in Kubernetes is that you don't need to modify your existing application to use an unfamiliar service discovery mechanism. You can run code in Pods, whether this is a code designed for a cloud-native world, or an older app you've containerized. You use a Service to make that set of Pods available on the network so that clients can interact with it._<sup>Reference [7](#References)</sup> --- ### 2f. How can an Object be Created or Deployed - YAML Manifest File When interacting with a Kubernetes cluster, the user uses a CLI tool called kubectl (which will be discussed in more details in a later section) or directly using API requests. To create an object in Kubernetes, the user must define the kind, specs, and desired state of this object. As an example, if a user wants to deploy a Pod, then the user my specify that the kind of this object is a Pod with the specification of the Pod such as the container image and other configuration of the Pod and then the desired state of this Pod such as having 2 replicas of this Pod. All of this information are defined in a manifest file. Normally this is done using a `YAML` formate file - `PS: JSON file can also be used but normally YAML files are most commonly used`. The user create the YAML file and defined all of these information inside this file and then send it to the kubernetes cluster using kubectl CLI or an API request with this file attached to it. Once the Manifest YAML file is sent to the kubernetes cluster, kubernetes will work on creating, Deploying, monitoring, and maintaining this object on the kubernetes cluster. > _Reference_ > - _A Kubernetes object is a `"record of intent"` --once you create the object, the Kubernetes system will constantly work to ensure that object exists. By creating an object, you're effectively telling the Kubernetes system what you want your cluster's workload to look like; this is your cluster's `desired state`._<sup>Reference [2](#References)</sup> > - _Almost every Kubernetes object includes two nested object fields that govern the object's configuration: the object spec and the object status. For objects that have a spec, you have to set this when you create the object, providing a description of the characteristics you want the resource to have: its `desired state`._<sup>Reference [2](#References)</sup> > - _The status describes the current state of the object, supplied and updated by the Kubernetes system and its components. The Kubernetes control plane continually and actively manages every object's `actual state` to match the `desired state` you supplied._<sup>Reference [2](#References)</sup> > - _When you create an object in Kubernetes, you must provide the object spec that describes its desired state, as well as some basic information about the object (such as a name). When you use the Kubernetes API to create the object (either directly or via kubectl), that API request must include that information as JSON in the request body. Most often, you provide the information to kubectl in file known as a `manifest`. By convention, manifests are YAML (you could also use JSON format). Tools such as kubectl convert the information from a manifest into JSON or another supported serialization format when making the API request over HTTP._<sup>Reference [2](#References)</sup> As a summary, once the kubernetes cluster is created, the user starts creating object `manifest` in the form of a `YAML` file which it will hold the object `spec` and the object `desired state` and then pass it to kubernetes using the CLI kubectl tool or directly using an API request. Kubernetes will make sure that this object is created based on the provided object spec and insure that the actual state of this object always match the defined desired state of this object. Below is an example of a manifest in YAML format the shows the required object spec for a kubernetes object called deployment. --- ```yaml apiVersion: apps/v1 # version number of the API kind: Deployment # Kubernetes object type metadata: name: nginx-deployment spec: # Specs of the object selector: matchLabels: app: nginx replicas: 2 # tells deployment to run 2 pods matching the template template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80 ``` --- <p align="center"> <img src="images/KubeObjects.png"> </p> --- ## 3. Kubernetes Components - (Control Plan & Nodes Components) Kubernetes is based on several components to provide it's desired outcomes, and each component have a specific task to perform. When talking about Kubernetes Components, 2 types of components will be discussed. `Control Plan` components and `Node` component. The Control Plan components are responsible for managing and maintaining the kubernetes cluster and the objects deployed within. The Control Plan components will be deployed on specific nodes and not all nodes in the kubernetes cluster. The nodes that will have the Control Plan components running on with be called `Master Nodes` and all other nodes will be called `Worker Nodes`. The Node components are responsible of the life-cycle and networking of the Pod running within the kubernetes cluster. The Node components will be deployed on every node in the kubernetes cluster. --- ### 3a. Control Plan Components `The control plane components is responsible for container orchestration and maintaining the desired state of the cluster.` The Control Plan components are responsible for interacting with the kubernetes cluster, monitoring and maintaining kubernetes cluster objects desired state and taking global actions when required to ensure desired state is met. By default, there are 4 main components in the control plan. In some situation, additional control plan component may exists, for example, if the kubernetes cluster deployed on a cloud provider (such as AWS, GCP, Azure or even VMware vSphere), there will be another 5th component that may be deployed to interact with the cloud provider. The Control Plan component may be deployed on any node in the kubernetes cluster, however, for architecture consistency, control plan components are deployed on one or three (in a highly available cluster) nodes and these nodes are called `Master Nodes`. When using scripts or deployment tools to deploy a Kubernetes Cluster (which is the majority of the cases), these scripts will install and deploy all control plan components on one or three nodes. The 4 main Control Plan components are API Server, Controller Manager, Scheduler, and etcd. > _Reference_ > - _The control plane's components make global decisions about the cluster (for example, scheduling), as well as detecting and responding to cluster events (for example, starting up a new pod when a deployment's replicas field is unsatisfied)._<sup>Reference [9](#References)</sup> > - _Control plane components can be run on any machine in the cluster. However, for simplicity, set up scripts typically start all control plane components on the same machine, and do not run user containers on this machine._<sup>Reference [9](#References)</sup> --- #### 3a-[i]. API Server `The API server expose the kubernetes cluster API and serve as the front-end of the kubernetes cluster making it the central hub of all communication.` The API Server component is responsible for communication and user interaction with the kubernetes cluster. Any request sent to a kubernetes cluster to perform any action will be sent to the API server component. The API Server component is also responsible for the internal components communication as well as the communication between the Control Plan and Kubernetes Node. If a 3rd part solution, plugin, or application is added to and integrated with the kubernetes cluster, communication will also direct to the API Server. User interaction with a kubernetes cluster is done using a CLI tool called `kubectl` or directly through API requests with the destination IP to be the API server IP. The user can use the kubectl or API to retrieve info from the kubernetes cluster or to create objects using the manifest YAML file. The communication between the user using the kubectl to the API server is done through HTTPS REST APIs, however, the internal communication between different components and the API server is done using [gRPC](https://grpc.io/docs/what-is-grpc/introduction/). Over TLS for more security. In summary - API Server is responsible for: - Exposing the Cluster API and handles all API requests - Authentication and Authorization - Processing API requests and validating data for the API objects like pods, services, etc. - Internal components communication - Communication between the Control Plan and the Node Components To learn more about the Kubernetes API into a more deep details such as specifications and versions, please refer to this [link](https://kubernetes.io/docs/concepts/overview/kubernetes-api/) > _Reference_ > - _The API server is a component of the Kubernetes control plane that exposes the Kubernetes API. The API server is the front end for the Kubernetes control plane._<sup>Reference [10](#References)</sup> > - _The main implementation of a Kubernetes API server is [kube-apiserver](https://kubernetes.io/docs/reference/generated/kube-apiserver/). kube-apiserver is designed to scale horizontally—that is, it scales by deploying more instances. You can run several instances of kube-apiserver and balance traffic between those instances._<sup>Reference [10](#References)</sup> --- #### 3a-[ii]. Controller Manager `The Controller Manager is responsible for running multiple controllers that maintain the desired state of the cluster.` The Controller Manager component is built out of several controllers all deployed and packaged in the Controller Manager component. The main responsibility of these controller is to maintain the desired state of the kubernetes cluster and all the objects deploy within. Controllers are programs that runs in a continuous loop and watches the current state of objects and make sure it matches the desired state the this object was created with. If the actual state and the desired state of an object does not match, controllers send requests to other components or take actions to make sure the desired state of this object is met. If a Deployment is created, using the manifest YAML file which includes the specs of this deployment and the desired state of it (for example 3 replicas of the Pod), one of the controllers in the Controller Manager components (called Deployment Controller) will monitor the Deployment (for ex the Pods), and ensure that this Deployment current state is the same as the desired state described in the manifest YAML file. For example, if a Pod died, the controller will get notified and will take action (utilizing other control plan components) to create a new Pod with the same specs as the one died to ensure the desired state is met. Each controller instance is responsible of a specific object/resource/task. Kubernetes objects (pods, namespaces, jobs, replicaSet, etc...) are managed by respective controllers. Controller manager is a component that manages all the Kubernetes controllers. Several controller are built in the controller-manager by default, more additional custom made controllers can be installed in addition to the existing ones, the additional controller as sometimes called `Operators`. Examples of the built in controllers are: - __Node Controller__: Responsible for managing Worker Nodes. It will monitor Nodes connecting to the cluster, validate the Node's health status, and update the Node's status field. - __Deployment Controller__: Responsible for managing Deployment objects and creating/modifying ReplicaSet objects. - __ReplicaSet Controller__: Responsible for creating/modifying Pods based on the ReplicaSet object configuration. - __Service Controller__: Responsible for configuring ClusterIP, NodePort, and LoadBalancer configuration based on Service objects. > _Reference_ > - _kube-controller-manager: - Control plane component that runs controller processes._<sup>Reference [12](#References)</sup> > - _Logically, each controller is a separate process, but to reduce complexity, they are all compiled into a single binary and run in a single process._<sup>Reference [12](#References)</sup> > - _In Kubernetes, controllers are control loops that watch the state of your cluster, then make or request changes where needed. Each controller tries to move the current cluster state closer to the desired state._<sup>Reference [13](#References)</sup> > - _There are many different types of controllers. Some examples of them are:_<sup>Reference [12](#References)</sup> >> - *__Node controller__: Responsible for noticing and responding when nodes go down.* >> - *__Job controller__: Watches for Job objects that represent one-off tasks, then creates Pods to run those tasks to completion.* >> - *__EndpointSlice controller__: Populates EndpointSlice objects (to provide a link between Services and Pods).* >> - *__ServiceAccount controller__: Create default ServiceAccounts for new namespaces.* >>> *- The above is not an exhaustive list.* --- #### 3a-[iii]. Scheduler `The Scheduler is responsible for scheduling Kubernetes pods on Worker Nodes by finding a suitable Worker Node to run newly created Pod(s).` Wether creating a Deployment, ReplicaSet, or a Pod, when a request to deploy a new Pod is received through the manifest YAML file, this file holds the Pod requirements such as the CPU, Memory, Networking, Storage, Affinity and much more. The scheduler is responsible to identify a suitable Worker Node to run this Pod on which satisfy all requirements of that Pod. The criteria that the scheduler use to chose the suitable node will not only be based on the required resources of the Pod but also will include additional criteria (if applicable) such as policies and affinity rules along with more criteria. The Scheduler is a controller that is managed by the Controller Manager and listens to pod creation events in the API server. The scheduler has two phases; `Scheduling cycle` (responsible for selecting a Worker Node) and the `Binding cycle` (Binds the selected Node to the newly created Pod and applies that change to the cluster). For the scheduler to choose the best node, it uses `filtering` and `scoring` operations. The scheduler filters that available nodes in the cluster and then apply a scoring to the filtered node to chose the best suitable node. In filtering, the scheduler finds the best-suited nodes where the pod can be scheduled. For example, if there are five worker nodes with resource availability to run the pod, it selects all five nodes. If there are no nodes, then the pod is unschedulable and moved to the scheduling queue. In the scoring phase, the scheduler ranks the nodes by assigning a score to the filtered worker nodes. The scheduler makes the scoring by calling multiple scheduling plugins. Finally, the worker node with the highest rank will be selected for scheduling the pod. If all the nodes have the same rank, a node will be selected at random. Pod have priorities, thus, the scheduler always places the high-priority pods ahead of the low-priority pods for scheduling. Also, in some cases, after the pod starts running in the selected node, the pod might get evicted or moved to other nodes. Custom schedulers can be created and multiple schedulers can run in a cluster along with the default scheduler controller. When a pod is deployed, custom scheduler can be specified in the pod manifest and the scheduling decisions will be taken based on the custom scheduler logic not the default scheduler controller. > _Reference_ > - _Control plane component that watches for newly created Pods with no assigned node, and selects a node for them to run on._<sup>Reference [14](#References)</sup> > - _Factors taken into account for scheduling decisions include: individual and collective resource requirements, hardware/software/policy constraints, affinity and anti-affinity specifications, data locality, inter-workload interference, and deadlines._<sup>Reference [14](#References)</sup> --- #### 3a-[iv]. etcd `etcd is considered to be the database of the kubernetes cluster which it will store all data of the cluster in a key-value store.` When creating a kubernetes cluster and objects within this cluster, all the data of the cluster and the objects must be stored somewhere. The etcd acts as the database of the kubernetes cluster and store the cluster configuration along with all data of all objects in a key-value store. etcd is an open-source strongly consistent, distributed key-value store that is used by kubernetes as well as it is used by other projects. etcd stores all configurations, states, and metadata of Kubernetes objects (pods, deployments, etc...) under the /registry directory key in key-value format. For example, information on a pod named Nginx in the default namespace can be found under /registry/pods/default/nginx. etcd characteristics can be defined as: - __Key Value Store:__ A nonrelational database that stores data as keys and values. It also exposes a key-value API. The datastore is built on top of BboltDB which is a fork of BoltDB. - __Distributed:__ etcd is designed to run on multiple nodes as a cluster without sacrificing consistency. - __Strongly consistent:__ If an update is made to a node, strong consistency will ensure it gets updated to all the other nodes in the cluster immediately. > _Reference_ > - _Consistent and highly-available key value store used as Kubernetes' backing store for all cluster data._<sup>Reference [15](#References)</sup> > - _If your Kubernetes cluster uses etcd as its backing store, make sure you have a back up plan for the data._<sup>Reference [15](#References)</sup> > _Reference_ > - _etcd is a strongly consistent, distributed key-value store that provides a reliable way to store data that needs to be accessed by a distributed system or cluster of machines._<sup>Reference [16](#References)</sup> --- ### 3b. Node Components `The Nodes components are responsible for running containerized applications. ` The Node Components is responsible of deploying, monitoring and maintaining the Pods running on the node, Provides Pod Networking connectivity and provide reporting about the Pod status to the control plan. The Node components will be running on all the nodes in the cluster Master Nodes or Worker Nodes. --- #### 3b-[i]. Kubelet `Kubelet is an agent running on each node responsible of running the containers inside Pods.` The Kubelet is an agent component running on every node in the cluster (Master and Worker Nodes). kubelet does not run as a container instead runs as a daemon, managed by systemd on each node. kubelet is responsible for registering Nodes with the API server (so kubernetes can keep track of the nodes) and building the containers inside Pods and monitor their status making sure that the container are in a healthy state. The state of containers are reported back to the control plan. If any container failed, it is the responsibility of the Kubelet to report the status and redeploy the container and Pod if required. Kubelet is responsible of the following: - Creating, modifying, and deleting containers for the pod. - Responsible for handling liveliness, readiness, and startup probes. - Responsible for Mounting volumes by reading pod configuration and creating respective directories on the host for the volume mount. - Collecting and reporting Node and pod status via calls to the API server with implementations like cAdvisor and CRI. Kubelet is also a controller that watches for pod changes and utilizes the node’s container runtime to pull images, run containers, etc. Couple of additional points regarding kubelet: - Kubelet uses the CRI (container runtime interface) gRPC interface to talk to the container runtime. - It also exposes an HTTP endpoint to stream logs and provides exec sessions for clients. - Uses the CSI (container storage interface) gRPC to configure block volumes. - It uses the CNI plugin configured in the cluster to allocate the pod IP address and set up any necessary network routes and firewall rules for the pod. In a later section, communication architecture between the control plan and the kubelet will be discussed in more details. > _Reference_ > - _An agent that runs on each node in the cluster. It makes sure that containers are running in a Pod._<sup>Reference [18](#References)</sup> > - _The kubelet takes a set of PodSpecs that are provided through various mechanisms and ensures that the containers described in those PodSpecs are running and healthy. The kubelet doesn't manage containers which were not created by Kubernetes._<sup>Reference [18](#References)</sup> --- #### 3b-[ii]. Kube-Proxy `Kube-Proxy is an instance or a process running on each node and is responsible of the basic networking for Pods.` Kube-Proxy is an daemon running on every node in the cluster (Master and Worker Nodes) as a DaemonSet (it can also run as a process running directly on the linux kernel) and is responsible for a subset of the networking framework in a kubernetes cluster. The kube-Proxy is not responsible for the full end-to-end networking in a Kubernetes cluster. In kubernetes, the networking is defined as a kubernetes object called `service`. As explained before, Service Service in Kubernetes is a way to expose a set of pods internally or to external traffic. Pods are ephemeral which means that Pod may die and recreated with a different IP. also Pod can have multiple replicas and each replica perform the same action and thus Pods need a load balancing mechanism as (in a normal situation) users will not use the Pods IP address directly. Kubernetes Service provide a solution for this matter. A Service is considered as a front-end networking for the back-end Pods (in this case we call Pods Service Endpoints). Each Pod or group of Pods will be associated with a Service Object. A Service have its own IP address which receive traffic and then forward/load balance it to the back-end Pods. The controllers in the control plan components will maintain a list of Pod IP and the associated Services with the Service IP. The responsibility of the Kube-Proxy is to implements the Kubernetes Services concept for pods. When a Pod is exposed using a Service, Kube-proxy listens to these changes and get information from the Control Plan and creates network rules (NATing. etc...) to send traffic destined to the Service IP to the back-end Pods (endpoints) associated with this Service object. Simply, the rules applied by the Kube-Proxy on the kernel level that are received from the Control Plan are simply mappings of Service IP to Pod IP. When a request is sent to a Service, it is redirected to a backend Pod based on these rules. All the Service networking, load balancing, and service discovery are handled by the Kube proxy. From a high-level, Kube-Proxy works as follows: - Kube proxy talks to the API server to get the details about the Service and respective Pod IPs & ports (endpoints). - It also monitors for changes in service and endpoints. - Kube-proxy then uses any one of the following modes to create/update rules for routing traffic to Pods behind a Service - _IPTables:_ It is the default mode. In IPTables mode, the traffic is handled by IPtable rules. This means that for each service, IPtable rules are created. These rules capture the traffic coming to the ClusterIP and then forward it to the backend pods. Also, In this mode, kube-proxy chooses the backend pod random for load balancing. Once the connection is established, the requests go to the same pod until the connection is terminated. - _IPVS:_ For clusters with services exceeding 1000, IPVS offers performance improvement. It supports the following load-balancing algorithms for the backend. - rr: round-robin : It is the default mode. - lc: least connection (smallest number of open connections) - dh: destination hashing - sh: source hashing - sed: shortest expected delay - nq: never queue - _Userspace:_ (legacy & not recommended) - _Kernelspace:_ This mode is only for Windows systems. > _Reference_ > - _kube-proxy is a network proxy that runs on each node in your cluster, implementing part of the Kubernetes Service concept._<sup>Reference [19](#References)</sup> > - _kube-proxy maintains network rules on nodes. These network rules allow network communication to your Pods from network sessions inside or outside of your cluster._<sup>Reference [19](#References)</sup> > - _kube-proxy uses the operating system packet filtering layer if there is one and it's available. Otherwise, kube-proxy forwards the traffic itself._<sup>Reference [19](#References)</sup> --- #### 3b-[iii]. Container Runtime `Container Runtime is responsible for the containerization process and running container on the nodes.` Container Runtime (also called Container Engine) is a software component that run on top of the operating system and is responsible for running the containers on top of the Nodes. The Container Runtime acts as the abstraction layer between the operating system kernel layer and the containers running on top. Container runtime runs on all the nodes in the Kubernetes cluster. It is responsible for pulling images from container registries, running containers, allocating and isolating resources for containers, and managing the entire lifecycle of a container on a host. Container runtime have 2 key concepts: - Container Runtime Interface (CRI): It is a set of APIs that allows Kubernetes to interact with different container runtime. It allows different container runtime to be used interchangeably with Kubernetes. The CRI defines the API for creating, starting, stopping, and deleting containers, as well as for managing images and container networks. - Open Container Initiative (OCI): It is a set of standards for container formats and runtime Kubernetes supports several Container Runtime that are all compliant with Container Runtime Interface (CRI), 2 of the most popular Container Runtime are Docker Engine, and Containerd. As explained in a previous section, Kubernetes Kubelet is the component responsible for managing container running on top of a kubernetes Node. Kubelet utilizes the Container Runtime to perform it's task. kubelet agent is responsible for interacting with the container runtime using CRI APIs to manage the lifecycle of a container. kubelet also gets all the container information from the container runtime and provides it to the control plane. The workflow of how Container Runtime works when creating a new Container is as follow: - When there is a new request for a pod from the API server, the kubelet talks to Container Runtime to launch the required containers via Kubernetes Container Runtime Interface. - Container Runtime checks and pulls the required container image from the configured container registry if required. - Container Runtime then generates OCI runtime specification (JSON) for a container. - Container Runtime then launches an OCI-compatible runtime (runc) to start the container process as per the runtime specification. > _Reference_ > - _A fundamental component that empowers Kubernetes to run containers effectively. It is responsible for managing the execution and lifecycle of containers within the Kubernetes environment._<sup>Reference [20](#References)</sup> > - _Kubernetes supports container runtime such as containerd, CRI-O, and any other implementation of the Kubernetes CRI (Container Runtime Interface)._<sup>Reference [20](#References)</sup> --- <p align="center"> <img src="images/KubeComponents.png"> </p> --- ## 4. Additional Kubernetes Components For a Kubernetes Cluster to be fully operational and provide full functionality, additional components aside from the core components can be added as an Add-On. Depending on the business requirement and the functionality required in the kubernetes cluster, the required add-on components can be installed on top of a kubernetes cluster. Add-On are not a must to install, however, some of them are a should to install. These Add-ons components can be - but not limited to - as follows: - CNI Plugin: Container Network Interface. Kubernetes by default to not provide extensible networking features and rather depend on 3rd party plugins to perform more advanced networking features. Kubernetes have created specifications for a networking plugin so that 3rd party must comply to when developing their plugins. Some of the most popular CNI Plugins are [Calico](https://www.tigera.io/project-calico/), [Flannel](https://github.com/flannel-io/flannel#deploying-flannel-manually), and [Cilium](https://github.com/cilium/cilium). - DNS Services: Kubernetes help microservices with the service discovery and by using DNS service in the kubernetes cluster, it enables the DNS-Based service discovery. Some of the most popular DNS service used with kubernetes is [CoreDNS](https://coredns.io/tags/documentation/) - Metrics Server: Kubernetes can provide Auto-Scaling feature to the running container, to perform this feature, metrics of nodes and Pods must be collected to be able to create rules of auto-scaling based on metrics. Metric Server is an open source metrics API implementation, created and maintained by the Kubernetes SIG. Main purpose of metrics-server is to help the Kubernetes Pod Autoscaler to automatically scale up or down Pods. > _Reference_ > - _While the other addons are not strictly required, all Kubernetes clusters should have cluster DNS, as many examples rely on it._<sup>Reference [23](#References)</sup> > - _Cluster DNS is a DNS server, in addition to the other DNS server(s) in your environment, which serves DNS records for Kubernetes services._<sup>Reference [23](#References)</sup> > - _Containers started by Kubernetes automatically include this DNS server in their DNS searches._<sup>Reference [23](#References)</sup> > _Reference_ > - _Network plugins are software components that implement the container network interface (CNI) specification. They are responsible for allocating IP addresses to pods and enabling them to communicate with each other within the cluster._<sup>Reference [26](#References)</sup> --- <p align="center"> <img src="images/KubeComponentsAddOns.png"> </p> --- ## Kubernetes Cluster Architecture - External etcd Topology So far in this document, the architecture discusses was pointing to the fact that all the Control Plan Components are deployed within Kubernetes Cluster and the etcd component is also deployed locally along with all other component. This topology is called a `Stacked etcd Cluster`. Their is another option to deploy the kubernetes cluster with the etcd deployed externally on a different external server, this is called `External etcd Cluster`. In some situations, running etcd outside the kubernetes cluster is required. One example is when running a Kubernetes cluster with no reliable disks to provide high availability to etcd data. Running etcd outside of the cluster is considered one of the high-availability topologies for a Kubernetes Cluster --- <p align="center"> <img src="images/ExternalEtcd.png"> </p> --- ## Kubernetes Cluster Architecture - High Availability For production environment, it is advisable to run a highly available kubernetes cluster. This can be achieved by first running the Cluster with an external etcd or running a stacked etcd topology with `3 Master Nodes` or a combination of both (external etcd with 3 Master nodes) In a high availability topology, using 3 Master Nodes, all the control plan components instance will be running an instance on each Node. In a Stacked etcd High Available Topology: - A minimum of three stacked control plane nodes for an HA cluster. - Each control plane node runs an instance of the kube-apiserver, kube-scheduler, and kube-controller-manager. The kube-apiserver is exposed to worker nodes using a load balancer. - Each control plane node creates a local etcd member and this etcd member communicates only with the kube-apiserver of this node. The same applies to the local kube-controller-manager and kube-scheduler instances. - A Load Balancer feature will be used to load balance external or internal traffic coming to the kubernetes cluster through the API server. --- <p align="center"> <img src="images/ClusterHA.png"> </p> --- In an External etcd High Available Topology: - A minimum of three hosts for control plane nodes and three hosts for etcd nodes are required for an HA cluster with this topology. - Each control plane node in an external etcd topology runs an instance of the kube-apiserver, kube-scheduler, and kube-controller-manager. And the kube-apiserver is exposed to worker nodes using a load balancer. However, etcd members run on separate hosts, and each etcd host communicates with the kube-apiserver of each control plane node. --- #### References - [[1] - Kubernetes Architecture](https://kubernetes.io/docs/concepts/architecture/) - [[2] - Kubernetes Objects](https://kubernetes.io/docs/concepts/overview/working-with-objects/) - [[3] - kubernetes Nodes](https://kubernetes.io/docs/concepts/architecture/nodes/) - [[4] - Kubernetes Namespaces](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/) - [[5] - Kubernetes Pod](https://kubernetes.io/docs/concepts/workloads/pods/) - [[6] - Kubernetes Deployment](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) - [[7] - Kubernetes Services](https://kubernetes.io/docs/concepts/services-networking/service/) - [[8] - Kubernetes Components](https://kubernetes.io/docs/concepts/overview/components/) - [[9] - Kubernetes Control Plan Components](https://kubernetes.io/docs/concepts/overview/components/#control-plane-components) - [[10] - Kubernetes Kube-ApiServer](https://kubernetes.io/docs/concepts/overview/components/#kube-apiserver) - [[11] - The Kubernetes API](https://kubernetes.io/docs/concepts/overview/kubernetes-api/) - [[12] - Kubernetes Controller Manager](https://kubernetes.io/docs/concepts/overview/components/#kube-controller-manager) - [[13] - Kubernetes Controllers](https://kubernetes.io/docs/concepts/architecture/controller/) - [[14] - Kubernetes Scheduler](https://kubernetes.io/docs/concepts/overview/components/#kube-scheduler) - [[15] - Kubernetes etcd](https://kubernetes.io/docs/concepts/overview/components/#etcd) - [[16] - etcd - Official Website](https://etcd.io/) - [[17] - Kubernetes Node Components](https://kubernetes.io/docs/concepts/overview/components/#node-components) - [[18] - Kubernetes Kubelet](https://kubernetes.io/docs/concepts/overview/components/#kubelet) - [[19] - Kubernetes Kube-Proxy](https://kubernetes.io/docs/concepts/overview/components/#kube-proxy) - [[20] - Kubernetes Container Runtime](https://kubernetes.io/docs/concepts/overview/components/#container-runtime) - [[21] - Kubernetes Addons](https://kubernetes.io/docs/concepts/overview/components/#addons) - [[22] - Installing Kubernetes Addons](https://kubernetes.io/docs/concepts/cluster-administration/addons/) - [[23] - Kubernetes DNS](https://kubernetes.io/docs/concepts/overview/components/#dns) - [[24] - Kubernetes CoreDNS](https://kubernetes.io/docs/tasks/administer-cluster/coredns/) - [[25] - CoreDNS](https://coredns.io/tags/documentation/) - [[26] - Kubernetes Network Plugin](https://kubernetes.io/docs/concepts/overview/components/#network-plugins) - [[27] - Kubernetes Metric Server](https://github.com/kubernetes-sigs/metrics-server) - [[28] - Kubernetes High Availability Topology](https://kubernetes.io/docs/setup/production-environment/tools/kubeadm/ha-topology/) --- > Next Step: [Building A Kubernetes Cluster](https://github.com/tahershaker/Learning-Kubernetes/tree/main/3.%20Building%20A%20Kubernetes%20Cluster)