text
stringlengths
184
4.48M
<template> <div class="grid grid-cols-1 md:grid-cols-2 gap-y-2 md:gap-x-8" :class="{ 'mx-6': this.$root.isMobile }" > <div class="flex flex-col justify-center w-full text-gray-700 md:px-8"> <h1 class="mb-6 text-xl font-medium md:text-3xl md:mb-11"> Tu auto en <span class="font-semibold text-nexcar-green">una sola<br> cuota mensual</span> </h1> <p class="mb-6 text-xs md:text-base md:mb-11"> Maneja el auto de tus sueños con todo incluido. <br v-if="!this.$root.isMobile"> Mantenciones, impuestos, seguros, patente <span class="font-medium text-nexcar-green">y mucho <br v-if="!this.$root.isMobile"> más</span> a cambio de una suscripción! </p> <a class="flex items-center justify-center w-40 px-2 py-1 text-base text-center text-white rounded-md md:px-9 md:py-2 md:w-60 mb-14 md:h-14 justify-self-center bg-nexcar-green md:text-lg lg:text-xl hover:bg-nexcar-dark-green" href="/cars" > Busca tu Nexcar </a> </div> <img v-if="this.$root.isMobile" src="../../../assets/images/one-quote-landing-with-car-mobile.svg" class="object-scale-down -mt-16" > <img v-else src="../../../assets/images/one-quote-landing-with-car.svg" class="max-w-xl" > <div class="px-8 py-8 mb-10 -mx-6 text-gray-700 bg-gray-100 md:mb-20 md:col-span-2 md:-mx-0"> <p class="text-xl font-medium md:texl-3xl mb-9"> ¿Por qué suscribirse? </p> <div class="flex flex-col mb-4 lg:flex-row"> <div class="flex p-4 mb-5 bg-white border rounded-md shadow-md lg:mr-10 lg:mb-0"> <img src="../../../assets/images/icons/simple-icon.svg" class="mr-4 w-7 h-7" > <div class="flex flex-col"> <p class="mb-4 text-lg font-medium lg:text-xl"> Simple </p> <p class="text-sm text-gray-500"> Tú solo te encargas de la bencina y el TAG. Nosotros nos encargamos del resto. </p> </div> </div> <div class="flex p-4 mb-5 bg-white border rounded-md shadow-md lg:mr-10 lg:mb-0"> <img src="../../../assets/images/icons/flexible-icon.svg" class="mr-4 w-9 h-7" > <div class="flex flex-col"> <p class="mb-4 text-lg font-medium lg:text-xl"> Flexible </p> <p class="text-sm text-gray-500"> Planes a tu medida con plazos de 12, 24, 36 y 48 meses, y kilometraje anual que elijas. </p> </div> </div> <div class="flex p-4 bg-white border rounded-md shadow-md lg:mb-0"> <img src="../../../assets/images/icons/convenient-icon.svg" class="w-8 h-8 mr-4" > <div class="flex flex-col"> <p class="mb-4 text-lg font-medium lg:text-xl"> Conveniente </p> <p class="text-sm text-gray-500"> Es la forma más económica de tener tu auto 0 Km. Si aún tienes dudas, escríbenos. </p> </div> </div> </div> </div> <h2 class="mb-5 text-xl font-medium text-gray-700 md:col-span-2 justify-self-center md:text-2xl lg:text-3xl"> Busca por tu marca favorita </h2> <div class="flex flex-wrap justify-center mb-9 md:mb-16 md:col-span-2"> <div v-for="(brand, index) in brands" :key="brand.id" class="flex md:mr-4 last:mr-0" > <img :src="brand.imageUrl" class="object-scale-down w-20 h-20 p-2 cursor-pointer md:mr-4 md:w-24 md:h-20 last:mr-0" @click="getCarsFiltered(brand)" > <div class="w-0.5 h-full bg-gray-200" v-if="!$root.isMobile && index != brands.length - 1" /> </div> </div> <div class="md:col-span-2 h-0.5 border-gray-200 border-b md:border-b-2 md:w-3/5 w-4/5 justify-self-center mb-10 md:mb-20" /> <div class="flex flex-col items-center mb-10 text-gray-700 md:col-span-2 md:mb-20"> <h2 class="mb-6 text-xl font-medium text-center md:text-2xl lg:text-3xl md:mb-9"> Súbete a tu nexcar en <span class="font-semibold text-nexcar-green">3</span> simples pasos </h2> <div class="flex flex-col items-center w-full mb-4 md:flex-row md:justify-around md:mb-10"> <div class="flex flex-col items-center max-w-xs p-3 mb-6 text-center border rounded-md shadow-md md:w-96 md:h-96 lg:w-auto md:py-5 md:mb-0"> <p class="mb-5 text-xl md:text-2xl md:mb-9"> Paso <span class="text-nexcar-green">1</span> </p> <img src="../../../assets/images/icons/first-step-icon.svg" class="w-10 h-12 mb-5 md:w-16 md:h-20 md:mb-9" > <p class="mb-5 font-semibold md:text-lg md:mb-7"> Elige el auto y el plan </p> <p class="text-sm md:text-base md:mb-5"> Selecciona el auto y plan que más te acomode y reserva online </p> </div> <img src="../../../assets/images/icons/next-step-arrow-icon.svg" class="mb-6 w-7 h-7 md:mb-0" :class="{ 'rotate-90 transition-transform duration-500 transform': this.$root.isMobile }" > <div class="flex flex-col items-center max-w-xs p-3 mb-6 text-center border rounded-md shadow-md md:h-96 md:w-96 lg:w-auto md:py-5 md:mb-0"> <p class="mb-5 text-xl md:text-2xl md:mb-9"> Paso <span class="text-nexcar-green">2</span> </p> <img src="../../../assets/images/icons/second-step-icon.svg" class="w-10 h-12 mb-5 md:w-16 md:h-20 md:mb-9" > <p class="mb-5 font-semibold md:text-lg md:mb-2"> Envíanos la documentación solicitada </p> <p class="text-sm md:text-base md:mb-5"> Te pediremos ciertos documentos para una evaluación comercial </p> </div> <img src="../../../assets/images/icons/next-step-arrow-icon.svg" class="mb-6 w-7 h-7 md:mb-0" :class="{ 'rotate-90 transition-transform duration-500 transform': this.$root.isMobile }" > <div class="flex flex-col items-center max-w-xs p-3 mb-6 text-center border rounded-md shadow-md md:h-96 md:py-5 md:w-96 lg:w-auto md:mb-0"> <p class="mb-5 text-xl md:text-2xl md:mb-9"> Paso <span class="text-nexcar-green">3</span> </p> <img src="../../../assets/images/icons/third-step-icon.svg" class="w-10 h-12 mb-5 md:w-16 md:h-20 md:mb-9" > <p class="mb-5 font-semibold md:text-lg md:mb-7"> Entrega del auto </p> <p class="text-sm md:text-base md:mb-5"> Te entregaremos tu auto donde tú quieras </p> </div> </div> <p class="mb-3 text-lg md:text-xl lg:text-2xl"> ¡Así de fácil! </p> <a class="flex items-center justify-center w-40 h-8 p-1 text-base text-white align-text-bottom rounded-md md:w-48 md:h-10 lg:w-60 md:p-2 lg:h-12 bg-nexcar-green md:text-xl hover:bg-nexcar-dark-green" href="/cars" > Busca tu Nexcar </a> </div> <div class="md:col-span-2 h-0.5 border-gray-200 border-b md:border-b-2 w-4/5 md:w-3/5 justify-self-center mb-10 md:mb-20" /> <price-comparison-grid class="mb-10 md:col-span-2 md:mb-14 lg:mb-16" /> <div class="flex flex-col items-center px-4 mb-10 -mx-6 text-gray-700 bg-gray-100 md:pt-20 md:pb-12 xl:px-40 md:col-span-2 lg:flex-row md:mb-20 py-7"> <div class="flex flex-col mb-7 lg:mb-0"> <p class="text-xl md:text-2xl mb-7 md:mb-16"> Ahorro por <span class="font-semibold text-nexcar-green">$2.1 millones vs la compra al contado</span> y más de <span class="font-semibold text-nexcar-green">$5.5 millones vs crédito</span> </p> <p class="mb-4 text-base md:text-lg"> ¿Todavía tienes dudas? </p> <a class="flex items-center justify-center h-8 p-1 text-sm text-white align-text-bottom rounded-md w-52 md:w-72 lg:w-80 md:h-10 md:p-2 lg:h-12 bg-nexcar-green md:text-xl hover:bg-nexcar-dark-green" href="/frequent_questions" > Ir a Preguntas frecuentes </a> </div> <img src="../../../assets/images/mazda-ford.svg" class="lg:order-first lg:mr-16" > </div> <div class="flex flex-col mb-10 text-gray-700 md:col-span-2 md:mb-20"> <h2 class="text-xl font-medium lg:text-center lg:text-3xl mb-7 md:mb-9"> Nexcar te ofrece <span class="text-nexcar-green">múltiples beneficios</span> </h2> <div class="grid grid-cols-1 mx-auto md:grid-cols-2 max-w-7xl gap-y-6 md:gap-y-9 md:gap-x-12"> <div class="flex items-center text-sm md:text-base"> <img src="../../../assets/images/icons/nexcar-includes-check.svg" class="w-4 h-4 mr-4 md:w-7 md:h-7 md:mr-6" > No más tramites ni preocupaciones </div> <div class="flex items-center text-sm md:text-base"> <img src="../../../assets/images/icons/nexcar-includes-check.svg" class="w-4 h-4 mr-4 md:w-7 md:h-7 md:mr-6" > Plan a tu medida, ¡Tú eliges plazo y kilometraje! </div> <div class="flex items-center text-sm md:text-base"> <img src="../../../assets/images/icons/nexcar-includes-check.svg" class="w-4 h-4 mr-4 md:w-7 md:h-7 md:mr-6" > Renueva constantemente tu auto de manera 100% digital. </div> <div class="flex items-center text-sm md:text-base"> <img src="../../../assets/images/icons/nexcar-includes-check.svg" class="w-4 h-4 mr-4 md:w-7 md:h-7 md:mr-6" > Sin gastos extras, ¡Tú solo pagas la bencina y el TAG! </div> <div class="flex items-center text-sm md:text-base"> <img src="../../../assets/images/icons/nexcar-includes-check.svg" class="w-4 h-4 mr-4 md:w-7 md:h-7 md:mr-6" > Sin grandes inversiones, ¡Mayor liquidez para tus cosas! </div> <div class="flex items-center text-sm md:text-base"> <img src="../../../assets/images/icons/nexcar-includes-check.svg" class="w-4 h-4 mr-4 md:w-7 md:h-7 md:mr-6" > Reduce carga impositiva para las empresas. </div> </div> </div> <div class="md:col-span-2 h-0.5 border-gray-200 border-b md:border-b-2 md:w-3/5 w-4/5 justify-self-center mb-10 md:mb-20" /> <h2 class="mb-5 text-xl font-medium text-center text-gray-700 md:col-span-2 justify-self-center md:text-3xl md:mb-12"> ¿Por qué Nexcar logra ser más conveniente? </h2> <div class="grid grid-cols-2 mx-auto mb-10 text-gray-700 md:mb-20 land-custom-grid max-w-7xl gap-x-2 md:gap-x-8 gap-y-2 md:gap-y-20 md:col-span-2"> <div class="w-20 justify-self-end"> <img src="../../../assets/images/icons/circle-money-symbol-icon.svg" class="self-end w-20 h-full p-3 bg-nexcar-second-light-green" :class="{ 'opacity-50': this.$root.isMobile && !this.circleMoneyIconSelected, 'cursor-pointer': this.$root.isMobile }" @click="setIcon('circleMoneyIconSelected')" > </div> <p class="col-span-2 mt-5 md:col-span-1 md:mt-0" :class="{ 'row-start-3 text-center': this.$root.isMobile && this.circleMoneyIconSelected }" v-if="!this.$root.isMobile || this.circleMoneyIconSelected" > <span class="font-medium">Consigue los mejores precios</span> <br> <span class="text-sm">Nos encargamos de buscar las mejores opciones de precio en</span> <span class="text-sm text-nexcar-green"> autos, seguros y mantenciones.</span> </p> <div class="w-20 md:justify-self-end"> <img src="../../../assets/images/icons/sell-buy-better-icon.svg" class="w-20 h-full p-3 bg-nexcar-second-light-green" :class="{ 'opacity-50': this.$root.isMobile && !this.sellBuyBetterIconSelected, 'cursor-pointer': this.$root.isMobile }" @click="setIcon('sellBuyBetterIconSelected')" > </div> <p class="col-span-2 mt-5 md:col-span-1 md:mt-0" :class="{ 'row-start-3 text-center': this.$root.isMobile && this.sellBuyBetterIconSelected }" v-if="!this.$root.isMobile || this.sellBuyBetterIconSelected" > <span class="font-medium">Compra/Vende mejor y más rápido</span> <br> <span class="text-sm">Sabemos como</span> <span class="text-sm text-nexcar-green">comprar, mantener y vender autos de manera eficiente.</span> <span class="text-sm"> Nunca más tendrás que preguntarte donde llevar tu auto.</span> </p> <div class="w-20 justify-self-end"> <img src="../../../assets/images/icons/tecnology-icon.svg" class="self-end w-20 h-full p-3 bg-nexcar-second-light-green" :class="{ 'opacity-50': this.$root.isMobile && !this.tecnologyIconSelected, 'cursor-pointer': this.$root.isMobile }" @click="setIcon('tecnologyIconSelected')" > </div> <p class="col-span-2 mt-5 md:col-span-1 md:mt-0" :class="{ 'row-start-3 text-center': this.$root.isMobile && this.tecnologyIconSelected }" v-if="!this.$root.isMobile || this.tecnologyIconSelected" > <span class="font-medium">Tecnología</span> <br> <span class="text-sm">Utilizamos</span> <span class="text-sm text-nexcar-green"> tecnología telemática y GPS</span> <span class="text-sm"> para rastrear los vehículos</span> <span class="text-sm text-nexcar-green"> con asistencia en ruta 24/7</span> <span class="text-sm"> disminuyendo el riesgo de robo.</span> </p> <div class="md:justify-self-end"> <img src="../../../assets/images/icons/access-icon.svg" class="w-20 h-full p-3 bg-nexcar-second-light-green" :class="{ 'opacity-50': this.$root.isMobile && !this.accessIconSelected, 'cursor-pointer': this.$root.isMobile }" @click="setIcon('accessIconSelected')" > </div> <p class="col-span-2 mt-5 md:col-span-1 md:mt-0" :class="{ 'row-start-3 text-center': this.$root.isMobile && this.accessIconSelected }" v-if="!this.$root.isMobile || this.accessIconSelected" > <span class="font-medium">Financiamiento y redes de beneficios</span> <br> <span class="text-sm">Accede a un</span> <span class="text-sm text-nexcar-green"> menor costo de financiamiento</span> <span class="text-sm"> con Nexcar. <br v-if="!this.$root.isMobile"> Obtén</span> <span class="text-sm text-nexcar-green"> múltiples beneficios</span> <span class="text-sm"> al ser parte de nuestra red.</span> </p> </div> <div class="md:col-span-2 h-0.5 border-gray-200 border-b md:border-b-2 md:w-3/5 w-4/5 justify-self-center mb-10 md:mb-20" /> <div class="grid mx-auto mb-10 text-gray-700 md:grid-cols-2 gap-y-2 md:col-span-2 md:gap-x-8 max-w-7xl"> <img src="../../../assets/images/iphone-mobile-view.svg" class="md:row-span-1 md:col-span-1 justify-self-center md:order-last" > <div class="flex flex-col"> <h2 class="mb-4 text-xl font-medium md:text-3xl md:mb-8"> ¿Qué incluye la cuota? </h2> <div class="flex flex-col justify-between md:h-2/3 h-52"> <div class="flex items-center"> <img src="../../../assets/images/icons/next-step-arrow-icon.svg" class="w-4 h-5 mr-4 md:w-4 md:h-6" > <p class="text-sm md:text-base"> Auto 0 km en la puerta de tu casa. </p> </div> <div class="flex items-center"> <img src="../../../assets/images/icons/next-step-arrow-icon.svg" class="w-4 h-5 mr-4 md:w-4 md:h-6" > <p class="text-sm md:text-base"> Mantenciones y revisión técnica a domicilio. </p> </div> <div class="flex items-center"> <img src="../../../assets/images/icons/next-step-arrow-icon.svg" class="w-4 h-5 mr-4 md:w-4 md:h-6" > <p class="text-sm md:text-base"> Acceso a auto de remplazo en caso de necesitarlo. </p> </div> <div class="flex items-center"> <img src="../../../assets/images/icons/next-step-arrow-icon.svg" class="w-4 h-5 mr-4 md:w-4 md:h-6" > <p class="text-sm md:text-base"> Seguros con asistencia en ruta 24/7. </p> </div> <div class="flex items-center"> <img src="../../../assets/images/icons/next-step-arrow-icon.svg" class="w-4 h-5 mr-4 md:w-4 md:h-6" > <p class="text-sm md:text-base"> Tu propia ejecutiva de contrato. </p> </div> <div class="flex items-center"> <img src="../../../assets/images/icons/next-step-arrow-icon.svg" class="w-4 h-5 mr-4 md:w-4 md:h-6" > <p class="text-sm md:text-base"> Acceso a beneficios Red Nexcar. </p> </div> <div class="flex items-center"> <img src="../../../assets/images/icons/next-step-arrow-icon.svg" class="w-4 h-5 mr-4 md:w-4 md:h-6" > <p class="text-sm md:text-base"> Y mucho más! </p> </div> </div> </div> </div> <div class="flex mb-10 -mx-6 bg-gray-100 md:col-span-2 md:mb-20"> <div class="flex flex-col justify-center flex-1 pl-5 md:pl-8 xl:pl-20 xs_padding"> <p class="mb-4 text-xl font-medium text-gray-700 xs_main_font_size md:text-2xl lg:text-3xl md:mb-6"> ¡Conoce más de Nexcar aquí! </p> <button class="flex items-center px-2 py-1 text-white rounded-md custom_video_button md:py-3 md:px-4 bg-nexcar-green hover:to-nexcar-dark-green md:text-2xl w-36 md:w-52 lg:rounded-lg" @click="showVideoModal" > <span class="mr-5 xs_buttom_margin">Ver video</span> <img src="../../../assets/images/icons/play-video-icon.svg" class="" > </button> </div> <img src="../../../assets/images/nexcar-video.svg" class="object-scale-down" :class="{ 'max-w-sm': this.$root.isMedium }" v-if="!this.$root.isMobile" > <img src="../../../assets/images/nexcar-video-mobile.svg" class="object-contain" v-else > </div> <div class="flex flex-col justify-between col-span-1 mb-10 -mx-6 md:mb-20 md:-mx-0 md:col-span-2"> <h2 class="px-2 mx-2 mb-6 text-xl text-gray-700 md:text-2xl lg:texl-3xl"> Conoce la experiencia de <span class="text-nexcar-green">nuestros clientes</span> </h2> <carousel :per-page-custom="[[0, 1], [768, 2], [1024, 3]]" :pagination-active-color="'#3F3F46'" class="w-full" > <slide v-for="recomendation in recomendations" :key="recomendation.completeName" > <recomendation :car-model="recomendation.carModel" :car-edition="''" :car-reviewer="recomendation.completeName" :date="recomendation.date" :comment="recomendation.comment" /> </slide> </carousel> </div> <find-your-nexcar /> </div> </template> <script> import Recomendation from './recomendation.vue'; import FindYourNexcar from '../shared/find-your-nexcar'; import VideoModal from './video-modal.vue'; import PriceComparisonGrid from './price-comparison-grid.vue'; import recomendations from './recomendations.json'; export default { components: { Recomendation, FindYourNexcar, PriceComparisonGrid, }, props: { brands: { type: Array, default() { return []; } }, }, data() { return { lastIconSelected: 'circleMoneyIconSelected', circleMoneyIconSelected: true, sellBuyBetterIconSelected: false, tecnologyIconSelected: false, accessIconSelected: false, recomendations: recomendations.recomendations, }; }, computed: { oneQuoteImagePath() { if (this.$root.isMobile) return '../../../assets/images/one-quote-landing-with-car-mobile.svg'; return '../../../assets/images/one-quote-landing-with-car.svg'; }, }, methods: { setIcon(iconName) { if (this.$root.isMobile) { this[this.lastIconSelected] = false; this[iconName] = true; this.lastIconSelected = iconName; } }, getCarsFiltered(brand) { window.location = `/cars?brand_id=${brand.id}`; }, showVideoModal() { this.$modal.show(VideoModal, {}, { width: '100%', maxWidth: this.$root.mdScreen, height: 'auto', adaptive: true, scrollable: true, name: 'video-modal', }); }, }, }; </script> <style lang="scss"> .land-custom-grid { @media (min-width: 768px) { grid-template-columns: repeat(2, min-content minmax(0, 1fr)); } } .custom_video_button { @media (max-width: 325px) { width: 120px; font-size: 14px; } } .xs_buttom_margin { @media (max-width: 325px) { margin-right: 4px; } } .xs_padding { @media (max-width: 325px) { padding-left: 8px; } } .xs_main_font_size { @media (max-width: 325px) { font-size: 16px; } } </style>
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; namespace Custom { /// <summary> /// A height map generator that simulates a designer following the planning policies. /// This is for testing the capabilities of the system when using ML Agents. /// In future, this would be generated by another agent. /// </summary> public class HeightMapGen { private Plot3D plot; private int width; private int depth; private float scale; private int minHeight; private int maxHeight; private int attractorsCount = 2; public int[,] heightMap; private List<Tuple<int, int, int>> attractors; /// <summary> /// Takes inputs to generate a heighmap that will dictate the skyline of the aggregation. /// </summary> /// <param name="plot">The plot where the heightmap is operating.</param> /// <param name="minHeight">The minimim height expected.</param> /// <param name="maxHeight">The minimim height expected.</param> /// <param name="attractorsCount">The number of attractors, these are created randomly. </param> public HeightMapGen(Plot3D plot, int minHeight, int maxHeight, int attractorsCount) { this.plot = plot; width = plot.width; depth = plot.depth; this.maxHeight = maxHeight < plot.height - 2 ? maxHeight : plot.height - 2; this.minHeight = minHeight; scale = plot.scale; heightMap = new int[width, depth]; this.attractorsCount = attractorsCount; attractors = new List<Tuple<int, int, int>>(); for (int x = 0; x < width; x++) { for (int z = 0; z < depth; z++) { heightMap[x, z] = minHeight; } } for (int i = 0; i < attractorsCount; i++) { AddAttractor(UnityEngine.Random.Range(0, width), UnityEngine.Random.Range(0, depth), UnityEngine.Random.Range(minHeight, maxHeight)); } GenerateMap(); } /// <summary> /// Adds one attractor to the list of attractors. /// </summary> /// <param name="attractorX">The x value to position the attractor.</param> /// <param name="attractorZ">The z value to position the attractor.</param> /// <param name="heightValue">Relative strength of the attractor.</param> public void AddAttractor(int attractorX, int attractorZ, int heightValue) { attractors.Add(new Tuple<int, int, int>(attractorX, attractorZ, heightValue)); } /// <summary> /// Adds one attractor to the list of attractors. /// </summary> /// <param name="attractor">A coordinate 2D to position the attractor.</param> /// <param name="heightValue">Relative strength of the attractor.</param> public void AddAttractor(Coordinate2D attractor, int heightValue) { attractors.Add(new Tuple<int, int, int>(attractor.X, attractor.Z, heightValue)); } /// <summary> /// Takes the attractors and generates a heightmap based on their relative strength. /// It provides a remapping to min and max values input by the user. /// </summary> public void GenerateMap() { float[,] distances = new float[width, depth]; float minDist = float.MaxValue; float maxDist = float.MinValue; for (int x = 0; x < width; x++) { for (int z = 0; z < depth; z++) { float value = 0; for (int i = 0; i < attractors.Count; i++) { float valueM = (float)(1 / (0.5 + (depth + width) + Mathf.Pow(CalculateManhattanDistance(x, attractors[i].Item1, z, attractors[i].Item2), 2))); float valueE = (float)(1 / (0.5 + (depth + width) + Mathf.Pow(CalculateEuclideanDistance(x, attractors[i].Item1, z, attractors[i].Item2), 2))); value += (attractors[i].Item3 * (valueM + valueE)); } if (value < minDist) minDist = value; if (value > maxDist) maxDist = value; distances[x, z] = value; } } for (int x = 0; x < width; x++) { for (int z = 0; z < depth; z++) { heightMap[x, z] = Mathf.RoundToInt(RemapFloats(distances[x, z], minDist, maxDist, minHeight, maxHeight)); } } } /// <summary> /// Takes inputs to generate a heighmap with 2 attractors that will dictate the skyline of the aggregation. /// </summary> /// <param name="plot">The plot where the heightmap is operating.</param> /// <param name="minHeight">The minimim height expected.</param> /// <param name="maxHeight">The minimim height expected.</param> /// <param name="attractorsCount">The number of attractors, these are created randomly. </param> /// <returns>A new heightmap</returns> public static int[,] GenerateFixedMap(Plot3D plot, int minHeight, int maxHeight) { int[,] heightMap = new int[plot.width, plot.depth]; float scale = plot.scale; List<Tuple<int, int, int>> attractors = new List<Tuple<int, int, int>>(); for (int x = 0; x < plot.width; x++) { for (int z = 0; z < plot.depth; z++) { heightMap[x, z] = minHeight; } } //hard coded attractors attractors.Add(new Tuple<int, int, int>(1, plot.depth - 4, 5)); attractors.Add(new Tuple<int, int, int>(plot.width - 2, 3, 7)); //generate map function float[,] distances = new float[plot.width, plot.depth]; float minDist = float.MaxValue; float maxDist = float.MinValue; for (int x = 0; x < plot.width; x++) { for (int z = 0; z < plot.depth; z++) { float value = 0; for (int i = 0; i < attractors.Count; i++) { float valueM = (float)(1 / (0.5 + (plot.depth + plot.width) + Mathf.Pow(CalculateManhattanDistance(x, attractors[i].Item1, z, attractors[i].Item2), 2))); float valueE = (float)(1 / (0.5 + (plot.depth + plot.width) + Mathf.Pow(CalculateEuclideanDistance(x, attractors[i].Item1, z, attractors[i].Item2), 2))); value += (attractors[i].Item3 * (valueM + valueE)); } if (value < minDist) minDist = value; if (value > maxDist) maxDist = value; distances[x, z] = value; } } for (int x = 0; x < plot.width; x++) { for (int z = 0; z < plot.depth; z++) { heightMap[x, z] = Mathf.RoundToInt(RemapFloats(distances[x, z], minDist, maxDist, minHeight, maxHeight)); } } return heightMap; } /// <summary> /// Calculates the Manhattan distance between the two points. /// From https://codereview.stackexchange.com/questions/120933/calculating-distance-with-euclidean-manhattan-and-chebyshev-in-c /// </summary> /// <param name="x1">The first x coordinate.</param> /// <param name="x2">The second x coordinate.</param> /// <param name="y1">The first y coordinate.</param> /// <param name="y2">The second y coordinate.</param> /// <returns>The Manhattan distance between (x1, y1) and (x2, y2)</returns> private static int CalculateManhattanDistance(int x1, int x2, int y1, int y2) { return Mathf.Abs(x1 - x2) + Mathf.Abs(y1 - y2); } /// <summary> /// Calculates linear distance between two points. /// </summary> /// <param name="x1">The first x coordinate.</param> /// <param name="x2">The second x coordinate.</param> /// <param name="y1">The first y coordinate.</param> /// <param name="y2">The second y coordinate.</param> /// <returns>The Euclidean distance between (x1, y1) and (x2, y2)</returns> private static int CalculateEuclideanDistance(int x1, int x2, int y1, int y2) { return (int)Mathf.Sqrt(Mathf.Pow(x1 - x2, 2) + Mathf.Pow(y1 - y2, 2)); } /// <summary> /// The methods provides remapping for a value. /// </summary> /// <param name="value">The value to be remapped.</param> /// <param name="oldMin">The origin lower bound.</param> /// <param name="oldMax">The origin upper bound.</param> /// <param name="newLow">The target lower bound.</param> /// <param name="newMax">The target upper bound.</param> /// <returns>The remapped float value given the origin and target bounds.</returns> private static float RemapFloats(float value, float oldMin, float oldMax, float newLow, float newMax) { return newLow + (value - oldMin) * (newMax - newLow) / (oldMax - oldMin); } /// <summary> /// The methods provides remapping for a value. /// </summary> /// <param name="value">The value to be remapped.</param> /// <param name="oldMin">The origin lower bound.</param> /// <param name="oldMax">The origin upper bound.</param> /// <param name="newLow">The target lower bound.</param> /// <param name="newMax">The target upper bound.</param> /// <returns>The remapped integer value given the origin and target bounds.</returns> private static float RemapInt(int value, int oldMin, int oldMax, int newLow, int newMax) { return Mathf.FloorToInt(newLow + (value - oldMin) * (newMax - newLow) / (float)(oldMax - oldMin)); } } }
import { createContext, useEffect, useState } from 'react'; import { Container, createTheme, CssBaseline, ThemeProvider, Typography } from '@mui/material'; import Footer from './components/footer/footer'; import Rankings from './components/rankings/rankings'; const darkTheme = createTheme({ palette: { mode: 'dark', }, }) export const RankingContext = createContext(null as any) export default function MyApp() { const [rankings, setRankings] = useState([] as any) const [aocRankings, setAocRankings] = useState({} as any) useEffect(() => { fetch('https://advent-of-code.s3.eu-west-1.amazonaws.com/leaderboard.json') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { setAocRankings(data); }) .catch(error => { console.error('There was a problem with the fetch operation:', error); }); }, []) useEffect(() => { // fetch rankings if (!aocRankings.members) return const members = Object.values(aocRankings.members).filter((m: any) => m.local_score > 0); const problems: any = members.reduce((acc: any, m: any) => { Object.keys(m.completion_day_level).forEach((day: any) => { Object.keys(m.completion_day_level[day]).forEach((part: any) => { if (!acc[`${day}-${part}`]) { acc[`${day}-${part}`] = [] } acc[`${day}-${part}`].push({ 'member': m, 'timestamp': m.completion_day_level[day][part].get_star_ts, }) }) }) return acc }, {} as any) const rankedProblems = Object.keys(problems).map((key: any) => { return problems[key].sort((a: any, b: any) => a.timestamp - b.timestamp) }) const trophiesById: any = members.reduce((acc: any, m: any) => { return { ...acc, [m.id]: { 'gold': 0, 'silver': 0, 'bronze': 0, } } }, {}) rankedProblems.forEach((problem: any) => { if (problem.length > 0) { trophiesById[problem[0].member.id]['gold'] += 1 } if (problem.length > 1) { trophiesById[problem[1].member.id]['silver'] += 1 } if (problem.length > 2) { trophiesById[problem[2].member.id]['bronze'] += 1 } }) members.sort((a: any, b: any) => b.local_score - a.local_score) members.forEach((m: any, index: number) => { m['trophies'] = trophiesById[m.id] }) setRankings(members) }, [aocRankings]) return ( <ThemeProvider theme={darkTheme}> <CssBaseline /> <RankingContext.Provider value={{ rankings, setRankings }}> <Typography variant="h2" component="h2" align="center" sx={{ margin: "50px 0" }}> Advent of Code 2023 </Typography> <Container sx={{ flexGrow: 1, marginBottom: "75px" }}> <Rankings /> </Container> <Footer /> </RankingContext.Provider> </ThemeProvider> ); }
import 'package:flutter/material.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:get/get.dart'; import 'package:outlet_insight/controllers/binder.dart'; import 'package:outlet_insight/controllers/home_page_controller.dart'; import 'package:outlet_insight/controllers/shared_preference_controller.dart'; import 'package:outlet_insight/pages/login_page.dart'; import 'pages/outlet_page.dart'; void main() { runApp(const MyApp()); } final navigatorKey = GlobalKey<NavigatorState>(); class MyApp extends StatelessWidget { const MyApp({super.key}); // This widget is the root of your application. @override Widget build(BuildContext context) { return GetMaterialApp( navigatorKey: navigatorKey, initialBinding: DependencyBinder(), title: 'Outlet Insight App', theme: ThemeData( fontFamily: 'Nunito', textTheme: const TextTheme( bodyMedium: TextStyle(fontWeight: FontWeight.w400), // Regular displayLarge: TextStyle(fontWeight: FontWeight.w700), // Bold ), colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), debugShowCheckedModeBanner: false, home: MyHomePage(), ); } } class MyHomePage extends StatelessWidget { final HomePageController homePageController = Get.put(HomePageController()); MyHomePage({super.key}); @override Widget build(BuildContext context) { ScreenUtil.init(context, designSize: const Size(360, 800)); return GetBuilder<SharedPreferenceController>( builder: (cache) { return cache.authState == true ? const OutletPage() : const LoginPage(); }, ); } }
// // ContentView.swift // CountirsUsingGraphQl // // Created by NourAllah Ahmed on 24/01/2023. // import SwiftUI struct ContentView: View { @State var countries :[AllCountriesQuery.Data.Country] = [] var body: some View { NavigationView{ List( countries, id: \.code ){ country in NavigationLink (destination: DetailsScreen(countryCode: country.code ), label: { HStack{ Text(country.emoji) .fontWeight(Font.Weight.regular) .font(.system(size: 35)) Text(country.name) .fontWeight(Font.Weight.regular) .font(.system(size: 25)) }}) } .listStyle(.plain) .navigationTitle("Countries") }.onAppear(perform: { Network.shared.apollo.fetch( query: AllCountriesQuery() ){ result in switch result{ case .success(let graphQlResult): if ((graphQlResult.data?.countries) != nil) { DispatchQueue.main.async { self.countries = graphQlResult.data?.countries ?? [] } } case .failure(let error): print(error) } }} ) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
import { yupResolver } from "@hookform/resolvers/yup"; import * as Location from "expo-location"; import React, { useEffect, useState } from "react"; import { Controller, useForm } from "react-hook-form"; import { RegisterStepFinalFormValues, registerStepFinalSchema, } from "./registerValidationSchemas"; import Button from "../../atoms/Button"; import InputGroup from "../../molecules/InputGroup"; import Spacer from "../../atoms/Spacer"; import Alert from "../../atoms/Alert"; import AsyncStorage from "@react-native-async-storage/async-storage"; import fetchRegisterUser from "../../../common/api/requests/auth/fetchRegisterUser"; import { useNavigation } from "@react-navigation/native"; import { StackNavigationProp } from "@react-navigation/stack"; import { StackParamList } from "../../../navigation/StackNavigationParams"; import Toast from "react-native-toast-message"; import type { LocationObject } from "expo-location"; import { Text } from "../../atoms/Text"; import { StatusCode } from "../../../common/api/interfaces/StatusCode.enum"; export default function RegisterStepFinal() { const navigation = useNavigation<StackNavigationProp<StackParamList>>(); const [location, setLocation] = useState<LocationObject | null>(null); const [isEmailAlreadyExist, setIsEmailAlreadyExist] = useState<boolean>(false); const { control, handleSubmit } = useForm<RegisterStepFinalFormValues>({ defaultValues: { address: "", }, mode: "onBlur", resolver: yupResolver(registerStepFinalSchema), }); useEffect(() => { const getLocationPermission = async () => { const { status } = await Location.requestForegroundPermissionsAsync(); if (status !== "granted") return null; const currentLocation = await Location.getCurrentPositionAsync({}); setLocation(currentLocation); }; getLocationPermission(); }, []); const registerErrorToast = () => Toast.show({ type: "error", props: { title: "Oups", text: `Il semblerait que nous ayons rencontré un problème.`, }, }); async function onSubmit(data: RegisterStepFinalFormValues) { const body = { address: data.address, longitude: location?.coords.longitude, latitude: location?.coords.latitude, cp: 93310, }; await AsyncStorage.mergeItem?.("userFormData", JSON.stringify(body)); const userData = (await AsyncStorage.getItem("userFormData")) || ""; await fetchRegisterUser({ user: JSON.parse(userData) }) .then((res) => { if (res.status === StatusCode.CREATED) { navigation.navigate("Se connecter"); } else if (res.status === StatusCode.CONFLICT) { setIsEmailAlreadyExist(true); } else { registerErrorToast(); } }) .catch((err) => console.error(err)); } return ( <> {isEmailAlreadyExist && ( <> <Text>Ravis de te revoir !</Text> <Spacer axis="vertical" size={3} /> <Text>Il semblerait que tu aies déjà un compte chez nous.</Text> <Spacer axis="vertical" size={3} /> <Button handlePress={() => navigation.navigate("Se connecter")}> Je me connecte </Button> </> )} {!isEmailAlreadyExist && ( <> <Alert type="info"> Totoro est une application de proximité, votre adresse de résidence nous permet de séléctionner les meilleurs missions près de chez vous. </Alert> <Spacer axis="vertical" size={3} /> <Controller name="address" control={control} render={({ field: { onChange, onBlur, value }, fieldState: { error }, }) => ( <InputGroup label="Adresse de résidence" onBlur={onBlur} onChangeText={onChange} value={value} placeholder="8 rue de la résidence des ploucs" error={error} /> )} /> <Spacer axis="vertical" size={3} /> <Button handlePress={handleSubmit(onSubmit)}>Je m'inscris !</Button> </> )} </> ); }
import type { ViewFieldBooleanMetadata, ViewFieldChipMetadata, ViewFieldDateMetadata, ViewFieldMetadata, ViewFieldMoneyMetadata, ViewFieldNumberMetadata, ViewFieldRelationMetadata, ViewFieldTextMetadata, ViewFieldURLMetadata, } from '@/ui/editable-field/types/ViewField'; import { IconBrandLinkedin, IconBrandX, IconBuildingSkyscraper, IconCalendarEvent, IconLink, IconMap, IconMoneybag, IconTarget, IconUserCircle, IconUsers, } from '@/ui/icon/index'; import { Entity } from '@/ui/input/relation-picker/types/EntityTypeForSelect'; import type { ColumnDefinition } from '@/ui/table/types/ColumnDefinition'; export const companiesAvailableColumnDefinitions: ColumnDefinition<ViewFieldMetadata>[] = [ { id: 'name', label: 'Name', icon: <IconBuildingSkyscraper />, size: 180, order: 1, metadata: { type: 'chip', urlFieldName: 'domainName', contentFieldName: 'name', relationType: Entity.Company, }, isVisible: true, } as ColumnDefinition<ViewFieldChipMetadata>, { id: 'domainName', label: 'URL', icon: <IconLink />, size: 100, order: 2, metadata: { type: 'url', fieldName: 'domainName', placeHolder: 'example.com', }, isVisible: true, } as ColumnDefinition<ViewFieldURLMetadata>, { id: 'accountOwner', label: 'Account Owner', icon: <IconUserCircle />, size: 150, order: 3, metadata: { type: 'relation', fieldName: 'accountOwner', relationType: Entity.User, }, isVisible: true, } satisfies ColumnDefinition<ViewFieldRelationMetadata>, { id: 'createdAt', label: 'Creation', icon: <IconCalendarEvent />, size: 150, order: 4, metadata: { type: 'date', fieldName: 'createdAt', }, isVisible: true, } satisfies ColumnDefinition<ViewFieldDateMetadata>, { id: 'employees', label: 'Employees', icon: <IconUsers />, size: 150, order: 5, metadata: { type: 'number', fieldName: 'employees', isPositive: true, }, isVisible: true, } satisfies ColumnDefinition<ViewFieldNumberMetadata>, { id: 'linkedin', label: 'LinkedIn', icon: <IconBrandLinkedin />, size: 170, order: 6, metadata: { type: 'url', fieldName: 'linkedinUrl', placeHolder: 'LinkedIn URL', }, isVisible: true, } satisfies ColumnDefinition<ViewFieldURLMetadata>, { id: 'address', label: 'Address', icon: <IconMap />, size: 170, order: 7, metadata: { type: 'text', fieldName: 'address', placeHolder: 'Addre​ss', // Hack: Fake character to prevent password-manager from filling the field }, isVisible: true, } satisfies ColumnDefinition<ViewFieldTextMetadata>, { id: 'idealCustomerProfile', label: 'ICP', icon: <IconTarget />, size: 150, order: 8, metadata: { type: 'boolean', fieldName: 'idealCustomerProfile', }, isVisible: false, } satisfies ColumnDefinition<ViewFieldBooleanMetadata>, { id: 'annualRecurringRevenue', label: 'ARR', icon: <IconMoneybag />, size: 150, order: 8, metadata: { type: 'moneyAmount', fieldName: 'annualRecurringRevenue', }, } satisfies ColumnDefinition<ViewFieldMoneyMetadata>, { id: 'xUrl', label: 'Twitter', icon: <IconBrandX />, size: 150, order: 8, metadata: { type: 'url', fieldName: 'xUrl', placeHolder: 'X', }, isVisible: false, } satisfies ColumnDefinition<ViewFieldURLMetadata>, ];
package com.example.aswe.demo.controllers; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.crossstore.ChangeSetPersister.NotFoundException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.example.aswe.demo.models.Cart; import com.example.aswe.demo.models.Course; import com.example.aswe.demo.models.Enrollment; import com.example.aswe.demo.models.User; import com.example.aswe.demo.repository.CartRepository; import com.example.aswe.demo.repository.CourseRepository; import com.example.aswe.demo.repository.EnrollmentRepository; import com.example.aswe.demo.repository.UserRepository; import com.example.aswe.demo.service.CourseService; @CrossOrigin(origins = "http://localhost:3000") @RestController @RequestMapping("api/student") public class StudentController { @Autowired private CartRepository cartRepository; @Autowired private UserRepository userRepository; @Autowired private CourseRepository courseRepository; @Autowired private EnrollmentRepository enrollmentRepository; @Autowired private CourseService courseService; // Get all cart items by user id @GetMapping("/cart/{userId}") public ResponseEntity<List<Cart>> getAllCartItemsByUserId(@PathVariable Long userId) { try { List<Cart> cartItems = cartRepository.findByUserId(userId); return ResponseEntity.ok(cartItems); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } } @GetMapping("/search") public List<Course> searchCoursesByTitle(@RequestParam String title) { return courseRepository.findByTitleContainingIgnoreCase(title); } @GetMapping("course/{id}") public Course getCourseById(@PathVariable("id") Long id) { return courseService.getPost(id); } @PostMapping("/cart/addcourse/{userId}/{courseId}") public ResponseEntity<String> addCourseToCartByUserId(@PathVariable Long userId, @PathVariable Long courseId) { Optional<User> userOptional = userRepository.findById(userId); Optional<Course> courseOptional = courseRepository.findById(courseId); if (userOptional.isPresent() && courseOptional.isPresent()) { User user = userOptional.get(); Course course = courseOptional.get(); if (checkCourseInCart(userId, courseId)) return ResponseEntity.status(HttpStatus.CONFLICT).body("Course already in the cart."); Cart cart = new Cart(); cart.setUser(user); cart.setCourse(course); cartRepository.save(cart); return ResponseEntity.ok("Course added to the cart successfully."); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body("User with ID " + userId + " or Course with Id" + courseId + " not found."); } } public Boolean checkCourseInCart(Long userId, Long courseId) { Optional<Cart> cart = cartRepository.findByUserIdAndCourseId(userId, courseId); return cart.isPresent(); } @DeleteMapping("/cart/delete/{cartItemId}") public ResponseEntity<?> deleteCartItem(@PathVariable Long cartItemId) { Optional<Cart> cartItemOptional = cartRepository.findById(cartItemId); if (cartItemOptional.isPresent()) { Cart cartItem = cartItemOptional.get(); cartRepository.delete(cartItem); return ResponseEntity.ok().build(); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } } @PostMapping("/enroll/{userId}/{courseId}") public ResponseEntity<String> enrollToCourse(@PathVariable Long userId, @PathVariable Long courseId) { Optional<User> userOptional = userRepository.findById(userId); Optional<Course> courseOptional = courseRepository.findById(courseId); if (userOptional.isPresent() && courseOptional.isPresent()) { User user = userOptional.get(); Course course = courseOptional.get(); if (!enrollmentRepository.existsByUserAndCourse(user, course)) { Enrollment enrollment = new Enrollment(); enrollment.setUser(user); enrollment.setCourse(course); enrollment.setEnrollmentDate(new Date()); enrollmentRepository.save(enrollment); return ResponseEntity.ok("Enrolled to course successfully."); } else { return ResponseEntity.status(HttpStatus.CONFLICT).body("Already enrolled to this course."); } } else { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body("User with ID " + userId + " or Course with ID " + courseId + " not found."); } } @GetMapping("/courses/enrolled/{userId}") public ResponseEntity<?> getCoursesEnrolledByUser(@PathVariable Long userId) { Optional<User> userOptional = userRepository.findById(userId); if (userOptional.isPresent()) { User user = userOptional.get(); List<Enrollment> enrollments = enrollmentRepository.findByUser(user); List<Course> enrolledCourses = enrollments.stream().map(Enrollment::getCourse).collect(Collectors.toList()); return ResponseEntity.ok(enrolledCourses); } else { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body("User with ID " + userId + " not found."); } } @GetMapping("/enrollment/{userId}/{courseId}/check") public boolean checkEnrollment(@PathVariable Long userId, @PathVariable Long courseId) { Optional<User> userOptional = userRepository.findById(userId); Optional<Course> courseOptional = courseRepository.findById(courseId); if (userOptional.isPresent() && courseOptional.isPresent()) { User user = userOptional.get(); Course course = courseOptional.get(); return enrollmentRepository.existsByUserAndCourse(user, course); } else { return false; } } }
// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import fs = require('fs'); import path = require('path'); import * as vscode from 'vscode'; import * as commands from './config/commands'; import { SnippetsManager } from './snippet/snippetsManager'; // 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('Congratulations, your extension "simple-snippets" is now active!'); let snippetsFolder = vscode.workspace.getConfiguration('simple-snippets').get('saveFolder'); if (snippetsFolder === undefined || snippetsFolder === null || snippetsFolder === '') { let userFolder = context.globalStorageUri.path.split('globalStorage')[0]; if (userFolder.substring(0, 3) === '/C:') { userFolder = userFolder.substring(1, userFolder.length); } snippetsFolder = path.join(userFolder, 'snippets'); } if (snippetsFolder === undefined || snippetsFolder === null || !fs.existsSync(snippetsFolder as string)) { vscode.window.showWarningMessage('Snippets saved folder is not exists!'); return; } // 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 let snippetsManager = new SnippetsManager(snippetsFolder as string); let disposable = vscode.commands.registerCommand(commands.CommandsConsts.addSnippet, () => {commands.saveAsSnippet(snippetsManager)}); context.subscriptions.push(disposable); } // This method is called when your extension is deactivated export function deactivate() {}
/** * Copyright (C) 24/01/2015 Patrick * * 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 com.twistedequations.rotor; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.media.MediaDescription; import android.net.Uri; import android.os.Build; import android.os.Parcel; import android.os.Parcelable; /** * Short description of the {@link com.twistedequations.rotor.MediaMetadataCompat}. */ public class MediaDescriptionCompat implements Parcelable { public String mediaID; public CharSequence title; public CharSequence subtitle; public CharSequence description; public Bitmap icon; public Uri iconUri; @TargetApi(Build.VERSION_CODES.LOLLIPOP) public MediaDescription getDescription() { MediaDescription description = new MediaDescription.Builder() .setDescription(this.description) .setIconBitmap(icon) .setIconUri(iconUri) .setMediaId(mediaID) .setTitle(title) .setSubtitle(subtitle) .build(); return description; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeString(mediaID); parcel.writeString(title.toString()); parcel.writeString(subtitle.toString()); parcel.writeString(description.toString()); parcel.writeParcelable(icon, i); parcel.writeString(iconUri.toString()); } public static final Creator<MediaDescriptionCompat> CREATOR = new Creator<MediaDescriptionCompat>() { @Override public MediaDescriptionCompat createFromParcel(Parcel parcel) { MediaDescriptionCompat description = new MediaDescriptionCompat(); description.mediaID = parcel.readString(); description.title = parcel.readString(); description.subtitle = parcel.readString(); description.icon = parcel.readParcelable(Bitmap.class.getClassLoader()); description.iconUri = Uri.parse(parcel.readString()); return description; } @Override public MediaDescriptionCompat[] newArray(int size) { return new MediaDescriptionCompat[size]; } }; }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>图片懒加载</title> <style> div,ul,li,img{margin:0; padding:0; list-style:none;} li{ width:640px; height:480px; background:url(../../image/7.gif) center center no-repeat; background-size:442px 244px;} img{ width:100%; } </style> </head> <body> <h1>图片懒加载、延迟加载:延迟加载图片或触发、符合某些条件时才加载某些图片</h1> <p>obj.offsetTop当前对象距离页面顶端的距离小于滚动距离加窗口高度,即显示区域及以上的内容全部加载</p> <div> <ul> <li data-src="../../image/l1.jpg"></li> <li data-src="../../image/l2.jpg"></li> <li data-src="../../image/l3.jpg"></li> <li data-src="../../image/l4.jpg"></li> <li data-src="../../image/l5.jpg"></li> <li data-src="../../image/l6.jpg"></li> <li data-src="../../image/l7.jpg"></li> <li data-src="../../image/l8.jpg"></li> <li data-src="../../image/l9.jpg"></li> <li data-src="../../image/l10.jpg"></li> <li data-src="../../image/l11.jpg"></li> <li data-src="../../image/l12.jpg"></li> <li data-src="../../image/l13.jpg"></li> <li data-src="../../image/l14.jpg"></li> </ul> </div> <script> function setImg(index){ var oDiv=document.getElementsByTagName("div")[0]; var oUl=oDiv.children[0]; var aLi=oUl.children; if (aLi[index].dataset) { var src=aLi[index].dataset.src; } else{ var src=aLi[index].getAttribute('data-src'); } var oImg=document.createElement('img'); oImg.src=src; if (aLi[index].children.length==0) { aLi[index].appendChild(oImg); } } //获得当前对象距离页面顶端的距离 function getH(obj) { // return obj.offsetTop; var h = 0; while (obj) { h += obj.offsetTop; obj = obj.offsetParent; //寻找某一元素用来定位的父级元素 } return h; } //当网页滚动时判断当前li的位置 window.onscroll = function () { var oDiv=document.getElementsByTagName("div")[0]; var oUl=oDiv.children[0]; var aLi=oUl.children; for (var i = 0, l = aLi.length; i < l; i++) { var oLi = aLi[i]; //检查oLi是否在可视区域 var t = document.documentElement.clientHeight + (document.documentElement.scrollTop || document.body.scrollTop); var h = getH(oLi); if (h < t) { setTimeout("setImg(" + i + ")", 500); } } }; window.onload=function(){ window.onscroll(); } </script> </body> </html>
function Inrg = getRhoFDM (Inrg,T) % < Description > % % Inrg = getRhoFDM (Inrg,T) % % Construct the full density matrix (FDM) in the basis of both discarded % and kept states, for given temperature T. % % < Input > % Inrg : [struct] NRG information obtained after running NRG_1channel. % T : [number] Temperature. Here we set \hbar = k_B = 1. % % < Ouput > % Inrg : [struct] NRG result. It keeps the result of NRG_1channel. In % addition to the result, this function adds two more fields to Inrg: % .RD, .RK : [cell] Full density matrix in the discarded and kept state % basis, respectively. Each cell element Inrg.RD{n} is a column % vector whose elements are the density matrix elements associated % with the discarded energy eigenstates at the iteration n-1. (Note % that s00 for n = 1 is for the iteration diagonalizing K00 basis.) % Inrg.RK{n} is a matrix in the basis of the kept energy eigenstates % at the iteration n-1. % % Written by S.Lee (May 22,2017) % Updated by S.Lee (May 12,2019): Revised for SoSe 2019. % Updated by S.Lee (Jun.20,2020): Revised for SoSe 2020. % Updated by J.Shim (Jul.07.2022): Revised for SoSe 2022. tobj = tic2; disptime(['Construct full density matrix @ T = ',sprintf('%.4g',T),' ...']); L = numel(Inrg.E0); % extract the local space dimension from ket tensors locdim = zeros(L,1); for itL = (1:L) if ~isempty(Inrg.AK{itL}) locdim(itL) = size(Inrg.AK{itL},2); else locdim(itL) = size(Inrg.AD{itL},2); end end % the shift of energy in each shell measured from the lowest-energy of the % last iteration E0r = [Inrg.EScale(2:end).*Inrg.E0(2:end),0]; E0r = fliplr(cumsum(fliplr(E0r))); RD = cell(1,L); % FDM in the discarded state basis; row vector RK = cell(1,L); % FDM in the kept state basis; matrix RDsum = zeros(1,L); % sum of Boltzmann weights % obtain the Boltzamann weights for itL = (1:L) % Obtain the column vector RD{itL} whose elements are the Boltzmann % weights RD{itL} = exp(-(Inrg.ED{itL}*Inrg.EScale(itL)-E0r(itL))/T)*prod(locdim(itL+1:end)); RDsum(itL) = sum(RD{itL}); end RDsum = sum(RDsum); % normalize the Boltzmann weights to get the elements of the density matrix % in the discarded basis for itL = (1:L) RD{itL} = RD{itL}/RDsum; end % update the FDM in the kept basis for itL = (L:-1:2) % Construct RK{itL-1} as the sum of RD{itL} and RK{itL}, with the local % Hilbert space for the site s(itL-1). (Note that s00 for itL = 1, s01 % for itL = 2, etc.) % Hint: one may utilize updateLeft, after permuting the legs of % Inrg.AD{itL} and Inrg.AK{itL}. % to utilize updateLeft for contracting AD with RD, and AK with RK, % permute the legs of AD and AK (left <-> right) AD2 = permute(Inrg.AD{itL},[3 2 1]); AK2 = permute(Inrg.AK{itL},[3 2 1]); RK{itL-1} = updateLeft(diag(RD{itL}),2,AD2,[],[],AD2) ... + updateLeft(RK{itL},2,AK2,[],[],AK2); % NOTE: AK and AD are in left-canonical form, not right-canonical. end if sum(RD{end}) > 1e-2 disptime('WRN: sum(Inrg.RD{end}) > 1e-2 ; chain length is not enough'); end Inrg.RK = RK; Inrg.RD = RD; toc2(tobj,'-v'); end
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:task_back4app/components/loader_dialog.dart'; import 'package:task_back4app/components/text_form_field.dart'; import 'package:task_back4app/providers/user_provider.dart'; class SignupPage extends StatefulWidget { final VoidCallback toggleIsSigningUp; const SignupPage({super.key, required this.toggleIsSigningUp}); @override State<SignupPage> createState() => _SignupPageState(); } class _SignupPageState extends State<SignupPage> { final _formKey = GlobalKey<FormState>(); TextEditingController usernameController = TextEditingController(); TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); TextEditingController confirmPasswordController = TextEditingController(); var isObscure = true; var isConfirmPasswordObscure = true; void handleSignupTap(UserProvider userContext) async { final isFormValid = _formKey.currentState!.validate(); if (isFormValid) { showLoaderDialog(context, "Signing up..."); final response = await userContext.signup( usernameController.text.trim(), passwordController.text.trim(), emailController.text.trim(), ); if (context.mounted) { Navigator.of(context).pop(); if (!response.success) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( duration: const Duration(seconds: 1), content: Text( response.error!.message, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold), ), backgroundColor: Theme.of(context).colorScheme.error, ), ); } else { usernameController.clear(); emailController.clear(); passwordController.clear(); confirmPasswordController.clear(); } } } } @override Widget build(BuildContext context) { return Consumer<UserProvider>( builder: (context, userContext, child) => Scaffold( body: SingleChildScrollView( child: Form( key: _formKey, child: Column( children: [ Container( height: 250, width: double.infinity, padding: const EdgeInsets.all(20), decoration: const BoxDecoration( gradient: LinearGradient( colors: [ Color(0xff1E2E3D), Color(0xff152534), Color(0xff0C1C2E), ], ), ), child: Padding( padding: EdgeInsets.only( top: MediaQuery.of(context).padding.top), child: const Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Tasks Management', style: TextStyle( color: Colors.white, fontSize: 38, fontWeight: FontWeight.bold), ), Text( 'Sign up for a new\nAccount', style: TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.bold), ), SizedBox( height: 6, ), Text( 'Enter Account Details', style: TextStyle( color: Colors.white, fontSize: 14, ), ), ], ), ), ), Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30), child: Column( crossAxisAlignment: CrossAxisAlignment.end, mainAxisSize: MainAxisSize.min, children: [ CustomTextFormField( labelText: 'Username', keyboardType: TextInputType.emailAddress, textInputAction: TextInputAction.next, validator: (value) { if (value!.isEmpty) { return "Please enter username."; } return null; }, controller: usernameController, ), CustomTextFormField( labelText: 'Email', keyboardType: TextInputType.emailAddress, textInputAction: TextInputAction.next, validator: (value) { if (value!.isEmpty) { return "Please enter a valid Email."; } return null; }, controller: emailController, ), CustomTextFormField( labelText: 'Password', keyboardType: TextInputType.visiblePassword, textInputAction: TextInputAction.next, validator: (value) { if (value!.isEmpty) { return "Please enter password."; } else if (value.length < 8) { return "Password length must be atleast 8 chars."; } return null; }, controller: passwordController, obscureText: isObscure, maxLines: 1, suffixIcon: Padding( padding: const EdgeInsets.only(right: 15), child: IconButton( onPressed: () { setState(() { isObscure = !isObscure; }); }, style: ButtonStyle( minimumSize: MaterialStateProperty.all( const Size(48, 48), ), ), icon: Icon( isObscure ? Icons.visibility_off_outlined : Icons.visibility_outlined, color: Colors.black, ), ), ), ), CustomTextFormField( labelText: 'Confirm Password', keyboardType: TextInputType.visiblePassword, textInputAction: TextInputAction.done, validator: (value) { if (value!.isEmpty || value != passwordController.value.text) { return "Passwords do not match."; } return null; }, controller: confirmPasswordController, obscureText: isConfirmPasswordObscure, maxLines: 1, suffixIcon: Padding( padding: const EdgeInsets.only(right: 15), child: IconButton( onPressed: () { setState(() { isConfirmPasswordObscure = !isConfirmPasswordObscure; }); }, style: ButtonStyle( minimumSize: MaterialStateProperty.all( const Size(48, 48), ), ), icon: Icon( isConfirmPasswordObscure ? Icons.visibility_off_outlined : Icons.visibility_outlined, color: Colors.black, ), ), ), ), const SizedBox( height: 15, ), SizedBox( width: double.infinity, child: FilledButton( onPressed: () => handleSignupTap(userContext), style: const ButtonStyle().copyWith( backgroundColor: MaterialStateProperty.all( const Color(0xff1E2E3D)), ), child: const Text('Signup'), ), ), ], ), ), Padding( padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 25), child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "Already have an account?", style: Theme.of(context) .textTheme .bodySmall ?.copyWith(color: Colors.black), ), Padding( padding: const EdgeInsets.only(left: 4), child: TextButton( onPressed: widget.toggleIsSigningUp, style: Theme.of(context).textButtonTheme.style, child: Text( 'Login', style: Theme.of(context).textTheme.bodySmall?.copyWith( color: const Color(0xff1E2E3D), fontWeight: FontWeight.bold, ), ), ), ), ], ), ), ], ), ), ), ), ); } }
import { DirectiveLocation as GraphQLDirectiveLocation, DirectiveLocationEnum, } from "graphql"; import { isSpecifiedScalarType } from "./resolvers"; import { TypeName, TypeReference, typeNameFromReference } from "./reference"; // Perf: const enums are inlined in the build (+small integers are stored on the stack in v8) // IMPORTANT: const enums MUST NOT be exported, otherwise esbuild struggles to inline them: use exported functions const enum TypeKind { SCALAR = 1, OBJECT = 2, INTERFACE = 3, UNION = 4, ENUM = 5, INPUT = 6, } export type ScalarTypeDefinitionTuple = [ kind: TypeKind.SCALAR, // directives?: DirectiveTuple[], // TODO ? ]; export type ObjectTypeDefinitionTuple = [ kind: TypeKind.OBJECT, fields: FieldDefinitionRecord, interfaces?: TypeName[], // directives?: DirectiveTuple[], ]; const enum ObjectKeys { fields = 1, interfaces = 2, } export type InterfaceTypeDefinitionTuple = [ kind: TypeKind.INTERFACE, fields: FieldDefinitionRecord, interfaces?: TypeName[], // directives?: DirectiveTuple[], ]; const enum InterfaceKeys { fields = 1, interfaces = 2, } export type UnionTypeDefinitionTuple = [ kind: TypeKind.UNION, types: TypeName[], // directives?: DirectiveTuple[], ]; const enum UnionKeys { types = 1, } export type EnumTypeDefinitionTuple = [ kind: TypeKind.ENUM, values: string[], // directives?: DirectiveTuple[], ]; const enum EnumKeys { values = 1, } export type InputObjectTypeDefinitionTuple = [ kind: TypeKind.INPUT, fields: InputValueDefinitionRecord, // directives?: DirectiveTuple[], ]; const enum InputObjectKeys { fields = 1, } export type TypeDefinitionTuple = | ScalarTypeDefinitionTuple | ObjectTypeDefinitionTuple | InterfaceTypeDefinitionTuple | UnionTypeDefinitionTuple | EnumTypeDefinitionTuple | InputObjectTypeDefinitionTuple; export type CompositeTypeTuple = | ObjectTypeDefinitionTuple | InterfaceTypeDefinitionTuple | UnionTypeDefinitionTuple; export type FieldDefinitionTuple = [ type: TypeReference, arguments: InputValueDefinitionRecord, // directives?: DirectiveTuple[], ]; const enum FieldKeys { type = 0, arguments = 1, } export type FieldDefinition = TypeReference | FieldDefinitionTuple; export type FieldDefinitionRecord = Record<string, FieldDefinition>; export type InputValueDefinitionTuple = [ type: TypeReference, defaultValue: unknown, // directives?: DirectiveTuple[], ]; const enum InputValueKeys { type = 0, defaultValue = 1, } export type InputValueDefinition = TypeReference | InputValueDefinitionTuple; export type InputValueDefinitionRecord = Record<string, InputValueDefinition>; const DirectiveLocation = { QUERY: 1, MUTATION: 2, SUBSCRIPTION: 3, FIELD: 4, FRAGMENT_DEFINITION: 5, FRAGMENT_SPREAD: 6, INLINE_FRAGMENT: 7, VARIABLE_DEFINITION: 8, /** Type System Definitions */ SCHEMA: 9, SCALAR: 10, OBJECT: 11, FIELD_DEFINITION: 12, ARGUMENT_DEFINITION: 13, INTERFACE: 14, UNION: 15, ENUM: 16, ENUM_VALUE: 17, INPUT_OBJECT: 18, INPUT_FIELD_DEFINITION: 19, } as const; type DirectiveLocation = (typeof DirectiveLocation)[keyof typeof DirectiveLocation]; const DirectiveLocationToGraphQL = { 1: GraphQLDirectiveLocation.QUERY, 2: GraphQLDirectiveLocation.MUTATION, 3: GraphQLDirectiveLocation.SUBSCRIPTION, 4: GraphQLDirectiveLocation.FIELD, 5: GraphQLDirectiveLocation.FRAGMENT_DEFINITION, 6: GraphQLDirectiveLocation.FRAGMENT_SPREAD, 7: GraphQLDirectiveLocation.INLINE_FRAGMENT, 8: GraphQLDirectiveLocation.VARIABLE_DEFINITION, /** Type System Definitions */ 9: GraphQLDirectiveLocation.SCHEMA, 10: GraphQLDirectiveLocation.SCALAR, 11: GraphQLDirectiveLocation.OBJECT, 12: GraphQLDirectiveLocation.FIELD_DEFINITION, 13: GraphQLDirectiveLocation.ARGUMENT_DEFINITION, 14: GraphQLDirectiveLocation.INTERFACE, 15: GraphQLDirectiveLocation.UNION, 16: GraphQLDirectiveLocation.ENUM, 17: GraphQLDirectiveLocation.ENUM_VALUE, 18: GraphQLDirectiveLocation.INPUT_OBJECT, 19: GraphQLDirectiveLocation.INPUT_FIELD_DEFINITION, } as const; export type DirectiveName = string; export type DirectiveTuple = [ name: DirectiveName, arguments: Record<string, unknown>, // JS values (cannot be a variable inside schema definition, so it is fine) ]; export type DirectiveDefinitionTuple = [ name: DirectiveName, locations: DirectiveLocation[], arguments?: InputValueDefinitionRecord, ]; const enum DirectiveKeys { name = 0, locations = 1, arguments = 2, } export type TypeDefinitionsRecord = Record<TypeName, TypeDefinitionTuple>; export type InterfaceImplementationsRecord = Record<TypeName, TypeName[]>; export type OperationTypes = { query?: TypeName; mutation?: TypeName; subscription?: TypeName; }; export type SchemaDefinitions = { types: TypeDefinitionsRecord; directives?: DirectiveDefinitionTuple[]; // implementations?: InterfaceImplementationsRecord; // TODO? }; const typeNameMetaFieldDef: FieldDefinition = "String"; const specifiedScalarDefinition: ScalarTypeDefinitionTuple = [TypeKind.SCALAR]; export function findObjectType( defs: SchemaDefinitions, typeName: TypeName, ): ObjectTypeDefinitionTuple | undefined { const type = defs.types[typeName]; return type?.[0] === TypeKind.OBJECT ? type : undefined; } export function getObjectFields( def: ObjectTypeDefinitionTuple, ): FieldDefinitionRecord { return def[ObjectKeys.fields]; } export function addInterfaceImplementation( defs: SchemaDefinitions, interfaceType: TypeName, objectType: TypeName, ) { const iface = getInterfaceType(defs, interfaceType); const type = defs.types[objectType]; if (!iface) { throw new Error( `Type ${interfaceType} either doesn't exist or is not an interface`, ); } if (type && !isObjectTypeDefinition(type)) { throw new Error(`Type ${objectType} is not an object type`); } if (!type) { defs.types[objectType] = [ TypeKind.OBJECT, Object.create(null), [interfaceType], ]; return; } let knownInterfaces = type[ObjectKeys.interfaces]; if (!knownInterfaces) { knownInterfaces = []; type[ObjectKeys.interfaces] = knownInterfaces; } if (!knownInterfaces.includes(interfaceType)) { knownInterfaces.push(interfaceType); } } export function getField( defs: SchemaDefinitions, typeName: TypeName, fieldName: string, ) { if (fieldName === "__typename") { return typeNameMetaFieldDef; } return ( getOwnField(defs, typeName, fieldName) ?? findInterfaceField(defs, typeName, fieldName) ); } function getOwnField( defs: SchemaDefinitions, typeName: TypeName, fieldName: string, ): FieldDefinition | undefined { const type = defs.types[typeName]; if (!type) { return undefined; } if (type[0] === TypeKind.OBJECT) { return type[ObjectKeys.fields]?.[fieldName]; } if (type[0] === TypeKind.INTERFACE) { return type[InterfaceKeys.fields]?.[fieldName]; } return undefined; } function findInterfaceField( defs: SchemaDefinitions, typeName: TypeName, fieldName: string, ) { const type = defs.types[typeName]; if (!type) { return undefined; } if (type[0] === TypeKind.OBJECT && type[ObjectKeys.interfaces]) { return findField(defs, type[ObjectKeys.interfaces], fieldName); } if (type[0] === TypeKind.INTERFACE && type[InterfaceKeys.interfaces]) { return findField(defs, type[InterfaceKeys.interfaces], fieldName); } return undefined; } function findField( defs: SchemaDefinitions, interfaceTypes: TypeName[], fieldName: string, ) { // TODO: merge field definition from all interface types to ensure all necessary arguments are present // (or maybe instead always encode all arguments in the schema fragment for simplicity?) for (const interfaceName of interfaceTypes) { const ownField = getOwnField(defs, interfaceName, fieldName); if (ownField !== undefined) { return ownField; } } return undefined; } export function getInputObjectType( defs: SchemaDefinitions, typeRef: TypeReference, ): InputObjectTypeDefinitionTuple | undefined { const type = defs.types[typeNameFromReference(typeRef)]; return type?.[0] === TypeKind.INPUT ? type : undefined; } export function getLeafType( defs: SchemaDefinitions, typeRef: TypeReference, ): EnumTypeDefinitionTuple | ScalarTypeDefinitionTuple | undefined { const typeName = typeNameFromReference(typeRef); if (isSpecifiedScalarType(typeName)) { return specifiedScalarDefinition; } const type = defs.types[typeName]; if (type?.[0] !== TypeKind.ENUM && type?.[0] !== TypeKind.SCALAR) { return undefined; } return type; } export function isDefined( defs: SchemaDefinitions, typeRef: TypeReference, ): boolean { if (typeof typeRef === "number") { // Fast-path: spec type return true; } const types = defs.types; const typeName = typeNameFromReference(typeRef); return !!types[typeName] || isSpecifiedScalarType(typeName); } export function isInputType( defs: SchemaDefinitions, typeRef: TypeReference, ): boolean { if (typeof typeRef === "number") { // Fast-path: all spec types are input types return true; } const typeName = typeNameFromReference(typeRef); const kind = defs.types[typeName]?.[0]; return ( isSpecifiedScalarType(typeName) || kind === TypeKind.ENUM || kind === TypeKind.INPUT || kind === TypeKind.SCALAR ); } export function isObjectType( defs: SchemaDefinitions, typeRef: TypeReference, ): boolean { if (typeof typeRef === "number") { // Fast-path: all spec types are scalars return false; } const types = defs.types; const type = types[typeRef] ?? types[typeNameFromReference(typeRef)]; return type?.[0] === TypeKind.OBJECT; } export function isAbstractType( defs: SchemaDefinitions, typeRef: TypeReference, ): boolean { if (typeof typeRef === "number") { // Fast-path: all spec types are scalars return false; } const type = defs.types[typeRef] ?? defs.types[typeNameFromReference(typeRef)]; return type?.[0] === TypeKind.UNION || type?.[0] === TypeKind.INTERFACE; } export function getUnionType( defs: SchemaDefinitions, typeRef: TypeReference, ): UnionTypeDefinitionTuple | undefined { const types = defs.types; const type = types[typeRef] ?? types[typeNameFromReference(typeRef)]; return type?.[0] === TypeKind.UNION ? type : undefined; } export function getInterfaceType( defs: SchemaDefinitions, typeRef: TypeReference, ): InterfaceTypeDefinitionTuple | undefined { const types = defs.types; const type = types[typeRef] ?? types[typeNameFromReference(typeRef)]; return type?.[0] === TypeKind.INTERFACE ? type : undefined; } export function isSubType( defs: SchemaDefinitions, abstractTypeName: TypeName, maybeSubTypeName: TypeName, ): boolean { const union = getUnionType(defs, abstractTypeName); if (union) { return union[UnionKeys.types].includes(maybeSubTypeName); } const object = findObjectType(defs, maybeSubTypeName); if (object) { return !!object[ObjectKeys.interfaces]?.includes(abstractTypeName); } const iface = getInterfaceType(defs, maybeSubTypeName); if (iface) { return !!iface[InterfaceKeys.interfaces]?.includes(abstractTypeName); } return false; } export function getDirectiveName(tuple: DirectiveDefinitionTuple): string { return tuple[DirectiveKeys.name]; } export function getDirectiveLocations( tuple: DirectiveDefinitionTuple, ): DirectiveLocation[] { return tuple[DirectiveKeys.locations]; } export function encodeDirectiveLocation( location: DirectiveLocationEnum, ): DirectiveLocation { return DirectiveLocation[location]; } export function decodeDirectiveLocation( location: DirectiveLocation, ): DirectiveLocationEnum { return DirectiveLocationToGraphQL[location]; } export function isObjectTypeDefinition( type: TypeDefinitionTuple, ): type is ObjectTypeDefinitionTuple { return type[0] === TypeKind.OBJECT; } export function isUnionTypeDefinition( type: TypeDefinitionTuple, ): type is UnionTypeDefinitionTuple { return type[0] === TypeKind.UNION; } export function isInterfaceTypeDefinition( type: TypeDefinitionTuple, ): type is InterfaceTypeDefinitionTuple { return type[0] === TypeKind.INTERFACE; } export function isEnumTypeDefinition( type: TypeDefinitionTuple, ): type is EnumTypeDefinitionTuple { return type[0] === TypeKind.ENUM; } export function isScalarTypeDefinition( type: TypeDefinitionTuple, ): type is ScalarTypeDefinitionTuple { return type[0] === TypeKind.SCALAR; } export function isInputObjectTypeDefinition( type: TypeDefinitionTuple, ): type is InputObjectTypeDefinitionTuple { return type[0] === TypeKind.INPUT; } export function getInputValueTypeReference( inputValue: InputValueDefinition, ): TypeReference { return Array.isArray(inputValue) ? inputValue[InputValueKeys.type] : inputValue; } export function getInputObjectFields( obj: InputObjectTypeDefinitionTuple, ): InputValueDefinitionRecord { return obj[InputObjectKeys.fields]; } export function getInputDefaultValue( inputValue: InputValueDefinition, ): unknown | undefined { return Array.isArray(inputValue) ? inputValue[InputValueKeys.defaultValue] : undefined; } export function getFields( def: ObjectTypeDefinitionTuple | InterfaceTypeDefinitionTuple, ): FieldDefinitionRecord { return def[0] === TypeKind.OBJECT ? def[ObjectKeys.fields] : def[InterfaceKeys.fields]; } export function getFieldTypeReference(field: FieldDefinition): TypeReference { return Array.isArray(field) ? field[FieldKeys.type] : field; } export function getFieldArgs( field: FieldDefinition, ): InputValueDefinitionRecord | undefined { return Array.isArray(field) ? field[FieldKeys.arguments] : undefined; } export function setFieldArgs( field: FieldDefinitionTuple, args: InputValueDefinitionRecord, ): InputValueDefinitionRecord { field[FieldKeys.arguments] = args; return args; } export function getEnumValues(tuple: EnumTypeDefinitionTuple): string[] { return tuple[EnumKeys.values]; } export function getDirectiveDefinitionArgs( directive: DirectiveDefinitionTuple, ): InputValueDefinitionRecord | undefined { return directive[DirectiveKeys.arguments]; } export function setDirectiveDefinitionArgs( directive: DirectiveDefinitionTuple, args: InputValueDefinitionRecord, ): InputValueDefinitionRecord { directive[DirectiveKeys.arguments] = args; return args; } export function createUnionTypeDefinition( types: TypeName[], ): UnionTypeDefinitionTuple { return [TypeKind.UNION, types]; } export function createInterfaceTypeDefinition( fields: FieldDefinitionRecord, interfaces?: TypeName[], ): InterfaceTypeDefinitionTuple { return interfaces?.length ? [TypeKind.INTERFACE, fields, interfaces] : [TypeKind.INTERFACE, fields]; } export function createObjectTypeDefinition( fields: FieldDefinitionRecord, interfaces?: TypeName[], ): ObjectTypeDefinitionTuple { return interfaces?.length ? [TypeKind.OBJECT, fields, interfaces] : [TypeKind.OBJECT, fields]; } export function createInputObjectTypeDefinition( fields: InputValueDefinitionRecord, ): InputObjectTypeDefinitionTuple { return [TypeKind.INPUT, fields]; } export function createEnumTypeDefinition( values: string[], ): EnumTypeDefinitionTuple { return [TypeKind.ENUM, values]; } export function createScalarTypeDefinition(): ScalarTypeDefinitionTuple { return [TypeKind.SCALAR]; } export function getObjectTypeInterfaces( def: ObjectTypeDefinitionTuple, ): TypeName[] { return def[ObjectKeys.interfaces] ?? []; } export function getInterfaceTypeInterfaces( def: InterfaceTypeDefinitionTuple, ): TypeName[] { return def[InterfaceKeys.interfaces] ?? []; } export function getUnionTypeMembers( tuple: UnionTypeDefinitionTuple, ): TypeName[] { return tuple[UnionKeys.types]; } export function getFieldArguments( def: FieldDefinition, ): InputValueDefinitionRecord | undefined { return Array.isArray(def) ? def[FieldKeys.arguments] : undefined; } export function getDirectiveArguments( def: DirectiveDefinitionTuple, ): InputValueDefinitionRecord | undefined { return Array.isArray(def) ? def[DirectiveKeys.arguments] : undefined; }
import hou import viewerstate.utils as su import json import time class AnimationHelper: def __init__(self, tick_callback=None): self.animation_duration = 0.3 self.wait_time = 1.0 self.data = {} self.tick_callback = tick_callback for c in hou.ui.eventLoopCallbacks(): hou.ui.removeEventLoopCallback(c) hou.ui.addEventLoopCallback(self.tick) def add_animation(self, index): if not self.is_clickable(index): return self.data[index] = {'ratio': 0, 'wait_time': self.wait_time, 'active': True} def set_finished(self, index, last_index): print('set_finished:%d, %d' % (index, last_index)) self.data[index]['active'] = False self.data[last_index]['active'] = False def is_clickable(self, index): if index == -1: return False if index not in self.data: return True if not self.data[index]['active']: return False if self.data[index]['ratio'] == 0: return True def is_in_waiting(self, index): if index not in self.data: return False if self.data[index]['wait_time'] > 0 and self.data[index]['ratio'] == 1: return True def tick(self): ratio_step = 0.05 / self.animation_duration # EventLoopCallback间隙为50ms for index, value in self.data.items(): if value['wait_time'] > 0: # 翻出来阶段 if value['ratio'] < 1: # 正在播放翻出动画阶段 value['ratio'] = hou.hmath.clamp(value['ratio'] + ratio_step, 0, 1) else: # 卡片完全翻转之后等待时长开始递减 value['wait_time'] = hou.hmath.clamp(value['wait_time'] - 0.05, 0, self.wait_time) elif value['active']: # 翻回动画只在卡片还在激活状态下才可能触发 value['ratio'] = hou.hmath.clamp(value['ratio'] - ratio_step, 0, 1) if self.tick_callback: self.tick_callback(self.data) def close(self): hou.ui.removeEventLoopCallback(self.tick) class State(object): def __init__(self, state_name, scene_viewer): self.state_name = state_name self.scene_viewer = scene_viewer self.last_click = None self.finished_count = 0 def onEnter(self, kwargs): self.node: hou.Node = kwargs["node"] self.geo: hou.Geometry = self.node.node('OutGrid').geometry() self.game_start_time = time.time() self.node.parm('RandomSeed').pressButton() self.animation = AnimationHelper(tick_callback = self.update_animation_parm) def onExit(self, kwargs): self.animation.close() with hou.undos.disabler(): self.node.parm('HoverIndex').set(-1) self.node.parm('AnimationData').set('{}') def onMouseEvent(self, kwargs): ui_event = kwargs["ui_event"] origin, direction = ui_event.ray() gi = su.GeometryIntersector(self.geo, self.scene_viewer) gi.intersect(origin, direction) click_index = gi.prim_num if self.node.parm('HoverIndex').evalAsInt() != click_index: with hou.undos.disabler(): self.node.parm('HoverIndex').set(click_index) reason = ui_event.reason() if reason in [hou.uiEventReason.Picked, hou.uiEventReason.Start]: if self.animation.is_clickable(click_index): self.animation.add_animation(click_index) # print('click:%s' % click_index) if self.is_same_type_with_last(click_index) and self.animation.is_in_waiting(self.last_click): self.animation.set_finished(click_index, self.last_click) self.finished_count += 2 self.check_end_game() self.last_click = click_index return False def update_animation_parm(self, data): with hou.undos.disabler(): js = json.dumps(data) if js != self.node.parm('AnimationData').evalAsString(): self.node.parm('AnimationData').set(js) def get_type_id(self, index): if index is None: return -1 print('click:%s' % index) return self.geo.point(index).intAttribValue('Type') def is_same_type_with_last(self, index): if self.last_click is None or index is None: return False return self.get_type_id(index) == self.get_type_id(self.last_click) def check_end_game(self): if self.finished_count == len(self.geo.iterPoints()): hou.ui.displayMessage("挑战成功!用时:%ds" % round(time.time() - self.game_start_time, 0)) def createViewerStateTemplate(): """ Mandatory entry point to create and return the viewer state template to register. """ state_typename = kwargs["type"].definition().sections()["DefaultState"].contents() state_label = "ViewerStateCardGame" state_cat = hou.sopNodeTypeCategory() template = hou.ViewerStateTemplate(state_typename, state_label, state_cat) template.bindFactory(State) template.bindIcon(kwargs["type"].icon()) return template
#include "result.h" #include <font.h> #include <glm/gtc/matrix_transform.hpp> namespace game { Result::Result(int height, SDL_Window *window, game::Background &background, engine::Font &font) : Scene(height, window), background{background}, font(font) {} void Result::startup(Fight::Winner new_winner, int new_losses) { winner = new_winner; losses = new_losses; alpha = 0.0f; state = State::FADE_IN; } void Result::on_loop(float delta_time) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); font.clear(); if (state == State::FADE_IN) { alpha += delta_time * 0.001f; if (alpha > 0.9f) { alpha = 1.0f; state = State::PRESENTING; } } else if (state == State::FADE_OUT) { alpha -= delta_time * 0.001f; if (alpha < 0.1f) { alpha = 0.0f; exit(); } } std::string message; glm::mat4 model(1.0f); switch (winner) { case Fight::Winner::UNDECIDED: case Fight::Winner::NOBODY: model = glm::translate(model, glm::vec3(250.0f, 300.0f, 0.0f)); message = "Draw"; break; case Fight::Winner::TEAM1: model = glm::translate(model, glm::vec3(275.0f, 300.0f, 0.0f)); message = "Win!"; break; case Fight::Winner::TEAM2: model = glm::translate(model, glm::vec3(200.0f, 300.0f, 0.0f)); message = "Loose!"; break; } model = glm::scale(model, glm::vec3(90.0f, 120.0f, 1.0f)); font.write(model, glm::vec4(1.0f, 1.0f, 1.0f, alpha), message.c_str()); model = glm::mat4(1.0f); if (losses == 1) { model = glm::translate(model, glm::vec3(200.0f, 200.0f, 0.0f)); model = glm::scale(model, glm::vec3(40.0f, 50.0f, 1.0f)); message = "You lost once."; } else { model = glm::translate(model, glm::vec3(150.0f, 200.0f, 0.0f)); model = glm::scale(model, glm::vec3(40.0f, 50.0f, 1.0f)); message = std::string("You lost ") + std::to_string(losses) + " times."; } font.write(model, glm::vec4(1.0f, 1.0f, 1.0f, alpha), message.c_str()); background.draw(alpha); font.draw(); } void Result::on_mouse_button_up(int x, int y) { state = State::FADE_OUT; alpha = 1.0f; } } // namespace game
<!doctype html> <html lang=""> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>web-tour Demo</title> <script src="../webcomponentsjs/webcomponents.min.js"></script> <link rel="import" href="web-tour.html"> <style type="text/css"> body, html { width: 100%; height: 100%; margin: 0; padding: 0; } h1 { margin-top: 0; padding-left: 20px; padding-top: 20px; } button { margin-left: 20px; } .container { background-color: #eee; border: 2px solid #444; margin: 20px; height: 250px; } .container .example { float: left; margin-top: 40px; margin-left: 11%; margin-right: 11%; width: 11%; height: 150px; } #example1 { background-color: red; border-radius: 150px; } #example2 { background-color: green; border-radius: 150px; } #example3 { background-color: blue; border-radius: 150px; } </style> </head> <body unresolved> <template is="auto-binding" id="template"> <h1>Demo of the `web-tour` component</h1> <button on-click="{{startTour}}">Start tour</button> <div class="container"> <div id="example1" class="example"></div> <div id="example2" class="example"></div> <div id="example3" class="example"></div> </div> <web-tour id="tour" texts="{{tourTexts}}" host="{{tourHost}}"> <web-tour-step heading="Red spot" target="{{step1Target}}" backdropOffset="{{step1Offset}}"> <p> The component atomatically hilights the target element and positions the dialog. An offset could be configured around the target element to be more flexible in hilihting. </p> </web-tour-step> <web-tour-step heading="Green spot" targetSelector="#example2" backdrop="false"> <p>The backdrop could be easily disabled. By using the targetSelector attribute, the target element could be directly defined.</p> <p><b>The tour is paused for two seconds when pressing GO ON.</b></p> </web-tour-step> <web-tour-step empty delay="2000"></web-tour-step> <web-tour-step heading="Blue spot" target="{{step3Target}}" moreInfosAvailable on-info-request="{{showMoreInfos}}"> <p>Now the dialog moved to the left side of the target, because there is more room available.</p> </web-tour-step> <web-tour-step heading="Final step"> <p> This step is configured without a target. Because it is the last step, the button text at the bottom right changed to 'Finish'. </p> </web-tour-step> </web-tour> </template> <script type="text/javascript"> (function(window, document, undefined) { var template = document.querySelector('#template'); template.startTour = function() { template.tourTexts.next = 'Go on'; template.tourHost = document.querySelector('.container'); template.step1Target = document.querySelector('#example1'); template.step1Offset = {left: 10, right: 10, top: 10, bottom: 10}; template.step3Target = document.querySelector('#example3'); var tour = document.querySelector('#tour'); tour.start(); }; template.showMoreInfos = function() { window.open('http://webcomponents.org/', '_blank'); }; })(window, document); </script> </body> </html>
// Copyright 2024 The MediaPipe 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. #include "mediapipe/tasks/cc/genai/inference/utils/xnn_utils/llm_weights.h" #include <sys/stat.h> #include <cstddef> #include <memory> #include <optional> #include <utility> #include "absl/log/absl_check.h" #include "absl/log/absl_log.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" #include "absl/strings/string_view.h" #include "mediapipe/framework/deps/file_path.h" #include "mediapipe/framework/port/file_helpers.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/port/status_macros.h" #include "mediapipe/tasks/cc/genai/inference/proto/transformer_params.pb.h" #include "mediapipe/tasks/cc/genai/inference/utils/xnn_utils/pack_weights_cache.h" #include "mediapipe/tasks/cc/genai/inference/utils/xnn_utils/tflite_weight_accessor.h" #include "mediapipe/tasks/cc/genai/inference/utils/xnn_utils/utils.h" #include "mediapipe/tasks/cc/genai/inference/utils/xnn_utils/xnn_tensor.h" namespace mediapipe::tasks::genai::xnn_utils { namespace { using FeedForwardWeights = LlmWeights::FeedForwardWeights; using SelfAttentionWeights = LlmWeights::SelfAttentionWeights; using TransformerParameters = odml::infra::proto::TransformerParameters; LlmParams::Norm TransformerParametersProtoNormTypeToLlmParamsNormType( TransformerParameters::Norm norm_type) { switch (norm_type) { case TransformerParameters::NORM_UNSPECIFIED: ABSL_LOG(DFATAL) << "Unspecified norm type."; return LlmParams::Norm::UNSPECIFIED; case TransformerParameters::NO_NORM: return LlmParams::Norm::NO_NORM; case TransformerParameters::RMS_NORM: return LlmParams::Norm::RMS_NORM; case TransformerParameters::LAYER_NORM: return LlmParams::Norm::LAYER_NORM; default: ABSL_LOG(DFATAL) << "Unknown norm type: " << norm_type; } return LlmParams::Norm::UNSPECIFIED; } // According to norm_type, load necessary weights with given basename. absl::StatusOr<std::optional<LlmWeights::NormWeights>> LoadNormWeights( LlmParams::Norm norm_type, const LlmParams& params, absl::string_view basename, WeightAccessor& weight_accessor) { switch (norm_type) { case LlmParams::Norm::UNSPECIFIED: break; case LlmParams::Norm::NO_NORM: break; case LlmParams::Norm::RMS_NORM: { auto rms_norm_weights = RMSNormWeights(); MP_ASSIGN_OR_RETURN( rms_norm_weights.norm_weight, weight_accessor.LoadWeight(absl::StrCat(basename, ".scale"), {params.model_dim_D})); return rms_norm_weights; } case LlmParams::Norm::LAYER_NORM: { auto layer_norm_weights = LayerNormWeights(); MP_ASSIGN_OR_RETURN( layer_norm_weights.beta, weight_accessor.LoadWeight(absl::StrCat(basename, ".bias"), {1, 1, params.model_dim_D})); MP_ASSIGN_OR_RETURN( layer_norm_weights.gamma, weight_accessor.LoadWeight(absl::StrCat(basename, ".scale"), {1, 1, params.model_dim_D})); return layer_norm_weights; } default: break; } return std::nullopt; } } // namespace LlmParams LlmParams::FromLLMParametersProto( const odml::infra::proto::LlmParameters& llm_params) { const auto& transformer_params = llm_params.transformer_parameters(); LlmParams params = { .num_transformer_M = static_cast<size_t>(transformer_params.num_stacks()), .batch_size_B = static_cast<size_t>(transformer_params.batch_size()), .seq_size_T = static_cast<size_t>(transformer_params.max_seq_length()), .model_dim_D = static_cast<size_t>(transformer_params.embedding_dim()), .hidden_dim_HD = static_cast<size_t>(transformer_params.hidden_dimension()), .head_dim_H = static_cast<size_t>(transformer_params.head_dimension()), .n_heads_N = static_cast<size_t>(transformer_params.num_heads()), .voc_size_V = static_cast<size_t>(llm_params.vocab_size()), .num_kv_heads = static_cast<size_t>(transformer_params.num_kv_heads() == 0 ? transformer_params.num_heads() : transformer_params.num_kv_heads()), .enable_kv_cache = true, .enable_dynamic_shape = false}; switch ( transformer_params.self_attention_parameters().attention_mask_type()) { case TransformerParameters::UNSPECIFIED: ABSL_LOG(DFATAL) << "Unspecified attention_mask_type, assuming causal"; params.model_type = LlmParams::ModelType::UNSPECIFIED; break; case TransformerParameters::CAUSAL: params.model_type = LlmParams::ModelType::CAUSAL; break; case TransformerParameters::PREFIX: params.model_type = LlmParams::ModelType::PREFIX; break; default: ABSL_LOG(DFATAL) << "Unknown attention_mask_type: " << transformer_params.self_attention_parameters() .attention_mask_type(); } params.ff_params = LlmParams::FeedForwardParams{ .no_bias = transformer_params.feed_forward_parameters().no_bias(), }; params.final_proj_params = LlmParams::FinalProjectParams{ .no_bias = transformer_params.final_project_parameters().no_bias(), }; switch (transformer_params.feed_forward_parameters().activation()) { case TransformerParameters::ACTIVATION_UNSPECIFIED: ABSL_LOG(DFATAL) << "Unspecified feed_forward_parameters.activation."; params.ff_params.activation = LlmParams::Activation::UNSPECIFIED; break; case TransformerParameters::GELU: params.ff_params.activation = LlmParams::Activation::GELU; break; case TransformerParameters::SILU: params.ff_params.activation = LlmParams::Activation::SILU; break; case TransformerParameters::RELU: params.ff_params.activation = LlmParams::Activation::RELU; break; default: ABSL_LOG(DFATAL) << "Unknown feed_forward_parameters.activation: " << transformer_params.feed_forward_parameters().activation(); } params.sa_params.qkv_no_bias = transformer_params.self_attention_parameters().qkv_no_bias(); params.sa_params.post_proj_no_bias = transformer_params.self_attention_parameters().post_proj_no_bias(); params.sa_params.pre_norm = TransformerParametersProtoNormTypeToLlmParamsNormType( transformer_params.pre_norm()); params.sa_params.post_norm = TransformerParametersProtoNormTypeToLlmParamsNormType( transformer_params.post_norm()); params.sa_params.soft_cap_value = transformer_params.self_attention_parameters().soft_cap_value(); params.ff_params.pre_norm = TransformerParametersProtoNormTypeToLlmParamsNormType( transformer_params.feed_forward_parameters().pre_norm()); params.ff_params.post_norm = TransformerParametersProtoNormTypeToLlmParamsNormType( transformer_params.feed_forward_parameters().post_norm()); params.final_norm = TransformerParametersProtoNormTypeToLlmParamsNormType( transformer_params.final_norm()); params.skip_absolute_positional_embeddings = transformer_params.skip_absolute_positional_embeddings(); if (transformer_params.self_attention_parameters() .has_attention_scale_type()) { switch ( transformer_params.self_attention_parameters().attention_scale_type()) { case TransformerParameters::SCALE_TYPE_UNSPECIFIED: ABSL_LOG(DFATAL) << "Unspecified attention_scale_type."; params.sa_params.attention_scale_type = LlmParams::AttentionScaleType::UNSPECIFIED; break; case TransformerParameters::SCALE_TYPE_PER_DIM_SCALE: params.sa_params.attention_scale_type = LlmParams::AttentionScaleType::PER_DIM_SCALE; break; case TransformerParameters::SCALE_TYPE_INV_SQRT_HEAD_DIM: params.sa_params.attention_scale_type = LlmParams::AttentionScaleType::INV_SQRT_HEAD_DIM; break; default: ABSL_LOG(DFATAL) << "Unknown attention_scale_type: " << transformer_params.self_attention_parameters() .attention_scale_type(); } } else { if (transformer_params.num_kv_heads() == 0 || transformer_params.num_heads() == transformer_params.num_kv_heads()) { // If MHA, PER_DIM_SCALE is used. params.sa_params.attention_scale_type = LlmParams::AttentionScaleType::PER_DIM_SCALE; } else { // If MQA or GQA, INV_SQRT_HEAD_DIM is used. params.sa_params.attention_scale_type = LlmParams::AttentionScaleType::INV_SQRT_HEAD_DIM; } } return params; } absl::StatusOr<std::shared_ptr<Tensor>> LlmWeightsLoader::TryCacheThenLoadSelfAttention( absl::string_view filename_prefix, absl::string_view alt_filename_prefix, bool is_query) { std::shared_ptr<Tensor> r; if (!is_query) { MP_ASSIGN_OR_RETURN( r, weight_accessor_->LoadTransposedWeight( filename_prefix, {params_.model_dim_D, params_.num_kv_heads * params_.head_dim_H}, 1)); if (!r) { MP_ASSIGN_OR_RETURN(r, weight_accessor_->LoadTransposedWeight( alt_filename_prefix, {params_.model_dim_D, params_.num_kv_heads * params_.head_dim_H}, 1)); } RET_CHECK(r) << "Could not load " << filename_prefix << " (or " << alt_filename_prefix << ")"; r->SetMetadata(xnn_utils::kKeySelfAttentionReshapedWeight, params_.num_kv_heads); } else { MP_ASSIGN_OR_RETURN( r, weight_accessor_->LoadTransposedWeight( filename_prefix, {params_.model_dim_D, params_.n_heads_N * params_.head_dim_H}, 1)); if (!r) { MP_ASSIGN_OR_RETURN( r, weight_accessor_->LoadTransposedWeight( alt_filename_prefix, {params_.model_dim_D, params_.n_heads_N * params_.head_dim_H}, 1)); } RET_CHECK(r) << "Could not load " << filename_prefix << " (or " << alt_filename_prefix << ")"; r->SetMetadata(xnn_utils::kKeySelfAttentionReshapedWeight, params_.n_heads_N); } r->SetMetadata(kKeyInDimLastInWeight, 1); return r; } absl::StatusOr<FeedForwardWeights> LlmWeightsLoader::LoadFeedForward( int layer_id) { const auto& params = params_; auto ff_file_prefix = absl::StrCat(kTransformerWeightPrefix, layer_id, ".ff_layer."); FeedForwardWeights feed_forward; MP_ASSIGN_OR_RETURN( feed_forward.pre_norm_weight, LoadNormWeights(params.ff_params.pre_norm, params, absl::StrCat(ff_file_prefix, "pre_layer_norm"), *weight_accessor_)); MP_ASSIGN_OR_RETURN( feed_forward.post_norm_weight, LoadNormWeights(params.ff_params.post_norm, params, absl::StrCat(ff_file_prefix, "post_layer_norm"), *weight_accessor_)); MP_ASSIGN_OR_RETURN(feed_forward.layer_1_weight, weight_accessor_->LoadTransposedWeight( absl::StrCat(ff_file_prefix, "ffn_layer1.w"), {params.model_dim_D, params.hidden_dim_HD}, /*original_dim_scale=*/1)); if (!feed_forward.layer_1_weight) { MP_ASSIGN_OR_RETURN(feed_forward.layer_1_weight, weight_accessor_->LoadTransposedWeight( absl::StrCat(ff_file_prefix, "ffn_layer1.linear.w"), {params.model_dim_D, params.hidden_dim_HD}, /*original_dim_scale=*/1)); } MP_ASSIGN_OR_RETURN(feed_forward.layer_1_gate_weight, weight_accessor_->LoadTransposedWeight( absl::StrCat(ff_file_prefix, "ffn_layer1_gate.w"), {params.model_dim_D, params.hidden_dim_HD}, /*original_dim_scale=*/1)); if (!feed_forward.layer_1_gate_weight) { MP_ASSIGN_OR_RETURN( feed_forward.layer_1_gate_weight, weight_accessor_->LoadTransposedWeight( absl::StrCat(ff_file_prefix, "ffn_layer1_gate.linear.w"), {params.model_dim_D, params.hidden_dim_HD}, /*original_dim_scale=*/1)); } MP_ASSIGN_OR_RETURN( feed_forward.layer_2_weight, weight_accessor_->LoadTransposedWeight( absl::StrCat(ff_file_prefix, "ffn_layer2.w"), Tensor::DimsType{params.hidden_dim_HD, params.model_dim_D}, /*original_dim_scale=*/1)); if (!feed_forward.layer_2_weight) { MP_ASSIGN_OR_RETURN( feed_forward.layer_2_weight, weight_accessor_->LoadTransposedWeight( absl::StrCat(ff_file_prefix, "ffn_layer2.linear.w"), Tensor::DimsType{params.hidden_dim_HD, params.model_dim_D}, /*original_dim_scale=*/1)); } if (!params.ff_params.no_bias) { MP_ASSIGN_OR_RETURN(feed_forward.layer_1_bias, weight_accessor_->LoadWeight( absl::StrCat(ff_file_prefix, "ffn_layer1.bias.b"), {params.hidden_dim_HD})); MP_ASSIGN_OR_RETURN( feed_forward.layer_1_gate_bias, weight_accessor_->LoadWeight( absl::StrCat(ff_file_prefix, "ffn_layer1_gate.bias.b"), {params.hidden_dim_HD})); MP_ASSIGN_OR_RETURN(feed_forward.layer_2_bias, weight_accessor_->LoadWeight( absl::StrCat(ff_file_prefix, "ffn_layer2.bias.b"), {params.model_dim_D})); } return feed_forward; } absl::StatusOr<SelfAttentionWeights> LlmWeightsLoader::LoadSelfAttention( int layer_id) { const auto& params = params_; SelfAttentionWeights self_attention; auto sa_file_prefix = absl::StrCat(kTransformerWeightPrefix, layer_id); MP_ASSIGN_OR_RETURN( self_attention.pre_norm_weight, LoadNormWeights(params.sa_params.pre_norm, params, absl::StrCat(sa_file_prefix, ".pre_layer_norm"), *weight_accessor_)); MP_ASSIGN_OR_RETURN( self_attention.post_norm_weight, LoadNormWeights(params.sa_params.post_norm, params, absl::StrCat(sa_file_prefix, ".post_layer_norm"), *weight_accessor_)); absl::StrAppend(&sa_file_prefix, ".self_attention."); MP_ASSIGN_OR_RETURN( self_attention.k_weight, TryCacheThenLoadSelfAttention(absl::StrCat(sa_file_prefix, "k.w"), absl::StrCat(sa_file_prefix, "k.linear.w"), /*is_query=*/false)); MP_ASSIGN_OR_RETURN( self_attention.q_weight, TryCacheThenLoadSelfAttention(absl::StrCat(sa_file_prefix, "q.w"), absl::StrCat(sa_file_prefix, "q.linear.w"), /*is_query=*/true)); MP_ASSIGN_OR_RETURN( self_attention.v_weight, TryCacheThenLoadSelfAttention(absl::StrCat(sa_file_prefix, "v.w"), absl::StrCat(sa_file_prefix, "v.linear.w"), /*is_query=*/false)); if (!params.sa_params.qkv_no_bias) { MP_ASSIGN_OR_RETURN( self_attention.q_bias, weight_accessor_->LoadWeight(absl::StrCat(sa_file_prefix, "q.bias.b"), {params.n_heads_N * params.head_dim_H})); MP_ASSIGN_OR_RETURN( self_attention.k_bias, weight_accessor_->LoadWeight(absl::StrCat(sa_file_prefix, "k.bias.b"), {params.n_heads_N * params.head_dim_H})); MP_ASSIGN_OR_RETURN( self_attention.v_bias, weight_accessor_->LoadWeight(absl::StrCat(sa_file_prefix, "v.bias.b"), {params.n_heads_N * params.head_dim_H})); } MP_ASSIGN_OR_RETURN( self_attention.per_dim_scale, weight_accessor_->LoadWeight( absl::StrCat(sa_file_prefix, "per_dim_scale.per_dim_scale"), {params.head_dim_H})); MP_ASSIGN_OR_RETURN( self_attention.post_proj_weight, weight_accessor_->LoadWeight( absl::StrCat(sa_file_prefix, "post.w"), {params.model_dim_D, params.n_heads_N * params.head_dim_H}, /*dim_scale_if_any=*/0)); if (!self_attention.post_proj_weight) { MP_ASSIGN_OR_RETURN( self_attention.post_proj_weight, weight_accessor_->LoadWeight( absl::StrCat(sa_file_prefix, "post.linear.w"), {params.model_dim_D, params.n_heads_N * params.head_dim_H}, /*dim_scale_if_any=*/0)); } if (!params.sa_params.post_proj_no_bias) { MP_ASSIGN_OR_RETURN( self_attention.post_proj_bias, weight_accessor_->LoadWeight( absl::StrCat(sa_file_prefix, "post.bias.b"), {params.model_dim_D})); } return self_attention; } absl::StatusOr<LlmWeights> LlmWeightsLoader::LoadWeights() { RET_CHECK(weight_accessor_); LlmWeights result; for (int layer_id = 0; layer_id < params_.num_transformer_M; ++layer_id) { MP_ASSIGN_OR_RETURN(auto ff, LoadFeedForward(layer_id)); result.ffs.push_back(std::move(ff)); MP_ASSIGN_OR_RETURN(auto sa, LoadSelfAttention(layer_id)); result.sas.push_back(std::move(sa)); } MP_ASSIGN_OR_RETURN(result.final_norm_weight, LoadNormWeights(params_.final_norm, params_, "params.lm.final_ln", *weight_accessor_)); MP_ASSIGN_OR_RETURN( result.softmax_linear, weight_accessor_->LoadTransposedWeight( absl::StrReplaceAll(kLogitsFfnWeightFilename, {{".linear.", "."}}), {params_.model_dim_D, params_.voc_size_V}, 1)); if (!result.softmax_linear) { MP_ASSIGN_OR_RETURN(result.softmax_linear, weight_accessor_->LoadTransposedWeight( kLogitsFfnWeightFilename, {params_.model_dim_D, params_.voc_size_V}, 1)); } if (!params_.final_proj_params.no_bias) { MP_ASSIGN_OR_RETURN(result.softmax_bias, weight_accessor_->LoadWeight(kLogitsFfnBiasFilename, {params_.voc_size_V})); } RET_CHECK(result.softmax_linear) << kLogitsFfnWeightFilename; MP_ASSIGN_OR_RETURN( result.token_embedding, weight_accessor_->LoadWeight(kTokenEmbedding, {params_.voc_size_V, params_.model_dim_D}, /*dim_scale_if_any=*/0)); return result; } DefaultLlmWeightsLoader::DefaultLlmWeightsLoader(absl::string_view weight_path, const LlmParams& params) : LlmWeightsLoader(nullptr, params) { xnn_weights_cache_ = std::make_shared<PackWeightsCache>( params.cache_dir.empty() ? absl::StrCat(weight_path, ".cache") : mediapipe::file::JoinPath( params.cache_dir, absl::StrCat(mediapipe::file::Basename(weight_path), ".cache"))); ABSL_CHECK_OK(xnn_weights_cache_->Initialize()); weight_accessor_ = std::make_unique<WeightAccessorCompositeWithCache>( std::make_shared<TfLiteWeightAccessor>(weight_path), xnn_weights_cache_.get()); } } // namespace mediapipe::tasks::genai::xnn_utils
1.关系型数据库: 建立在关系模型基础上,由多张相互连接的二维表组成的数据库 优点:使用表存储数据,格式统一,便于维护 使用sql语言操作,标准统一,使用方便 2.SQL: 1.sql语句不区分大小写 2.单行注释:—或者#,多行注释:/**/ 3.sql语句分类: 1.DDL语句:数据定义语言,用来定义数据库对象(数据库,表,字段) 2.DML语句:数据操作语言,用来对数据表中的对象进行增删改 3.DQL语句;数据查询语句,用来查询数据表中的记录 4.DCL语句:数据控制语句,用来创建数据库用户,控制数据库的访问权限 4.DDL语句学习: 1.查询所有数据库:SHOW DATABASE 2.查询当前数据库:SELECT DATABASE 3.创建数据库:CREATE [IF NOT EXISTS]数据库名[DEFAULT CHAERSET字符集][COLIATC排序规则] 4.删除:DROP DATABASE[IF EXISTS]数据库名 5.使用:USE[ 数据库名] 4.DDL表操作-查询: 1.查询当前数据库所有表:SHOW TABLES; 2.查询表结构:DESC 表名; 3.查询指定表的建表语句:SHOW CREATE TABLE 表名; 5.DDL表操作-创建 1.CREATE TABLE 表名( 字段1 字段1类型[COMMENT 字段1注释] 字段2 字段2类型[COMMENT 字段2注释] 字段3 字段3类型[COMMENT 字段3注释] 字段4 字段4类型[COMMENT 字段4注释] )[表注释]; 具体操作: CREATE TABLE USER( Id int comment’编号’, Name varchar(50) comment’姓名’, Age int comment ‘年龄’, Gender varchar(1)comment ‘性别’)commen‘’; DESC USER SHOW CREATE TABLE USER 6.数据库的数据类型: 1.TINYINT ,SMALLINT,MEDIUMINT,INT or INTEGER,BIGINT,FLOAT,DOUBLE,DECIMAL(指定精度和标度) 案例:age -> TINYINT(UNSIGNED) score -> double(4,1) 2.字符串类型:CHAR(定长字符串),VARCHAR,(变长字符串)TINYBLOB,TINYTEXT,BLOB,TEXT,MEDIUMBLOB,MEDIUMTEXT,LONGBLOB,LONGTEXT 带blob存储二进制数据(使用不多) 案例:用户名->varchar name->char 3.日期类型:DATE,TIME,YEAR,DATETIME,TIMESTAMP, 7.根据需求创建表(员工信息,编号(纯数字),工号,姓名,性别,年龄,身份证号,入职时间): create table emp( id int comment‘’ workno varchar(10) comment’’, Name varchar(10) comment’’, Gender char(1) comment’’, Age tinyint unsigned comment’’, Idcard char(10) comment’’, Entrydate date comment’’ )comment’’; 8.DDL-表操作-修改 1.向表结构中添加字段:ALTER TABLE 表名 ADD 字段名 类型( 长度)[comment注释][约束],例:alter table emp add nickname varchar(20); 2.修改字段:修改数据类型:alter table 表名 modify 字段名 新数据类型[长度],修改字段名和数据类型:alter table 表名 change 旧字段名 新字段名 类型(长度)[comment注释][约束],例: alter table emp change nickname username varchar(10) 3.删除字段:alter table emp drop username 4.修改表名:alter table emp rename to employee 5.删除表:drop table emp || truncate table emp(删除指定表,并重新创建该表,会删除数据) 8.DML语句-数据操作语言,对表中数据进行增删改操作 1.指定字段添加数据(INSERT):INSERT INTO 表名(字段名1,字段名2,….)values(值1,值2,….); 2.给全部字段添加数据:insert into 表名 values(值1,值2) 3.批量添加数据:INSERT INTO 表名(字段名1,字段名2,….)values(值1,值2,….)()();或者insert into 表名values()() 4.修改数据:update 表名 set 字段名1=值1,字段名2=值2,…[where条件] 5.删除数据:delete from 表名 where 条件:delete from emp where gender = ‘女’ 或者delete from 表名(删除所有数据) 9.DQL查询数据:(以下为编写顺序) select 字段列表 from表名列表 where 条件列表 (条件可以加比较运算符或between and,in(),like,is null,逻辑运算符:and,or,not) group by 分组字段列表 having 分组后条件列表 order by 排序字段列表 limit分页参数 查询多个字段:select 字段1,字段2from表名 查询所有字段:select * from 表名 设置别名:select 字段名1 as别名,字段2as别名from表名 去除重复记录:select distinct 字段列表from表名 例子:select name,workno,age from emp; select *(尽量不要写*) from emp; select workaddress as ’工作地址‘ from emp; select distinct workadd ress from emp;(去重操作) select * from emp where age=1; select * from emp where age<20; select * from emp where idcard is null; select * from emp where idcard is not null; select * from emp where age !=(<>)88; select * from emp where age >= 15 and(&&) age<+25; Select * from emp where age between 15 and 20; Select * from emp where gender = ‘女’ and age<25; Select * from emp where age = 18 or age = 20 or age = 40; Select * from emp where age in(18,20,40); Select * from emp where name like__(模糊匹配:_占位符,%任意长度字符) select * from emp where idcard like’%x‘; select * from emp where idcard like’______________x’; 聚合函数:select聚合函数(字段列表)from count:统计数量; max:最大值 min:最小值 avg:平均值 sum:求和 例子: select count(*)from emp;(不计算null值) select count(idcard) from emp; select avg(age) from emp; Select Max(age) from emp; Select sum(age) from emp Where WorkAddress = ‘西安’; 分组查询: select 字段列表from表名 group by 分组字段名[having分组后过滤条件]; where和having区别: 1.执行时机:where分组前进行过滤,不满足where条件不参与分组,而having是分组之后对结果进行过滤。 2.判断条件不同:where不能对复合函数进行判断,而having可以 例子:select gender,count(*) from emp group by gender; Select gender,avg(age) from group by gender; Select count(*) from emp where age <45 group by workAddress; Select workaddress ,count(*) from emp where age<45 group by workaddress having count(*)>=3; 排序查询: select 字段列表 from 表名 order by 字段1 排序方式1,字段2 排序方式2; 排序方式: 1.asc:升序(默认值)2.desc:降序 例:select * from emp order by age asc; Select * from emp order by age desc; Select * from emp order by entrytime desc; Select * from emp order by age asc,entrytime desc; 分页查询: select 字段列表 from 表名 limit起始索引,查询记录数; 起始索引从0开始,起始索引 = (查询页码-1)*每页显示记录数 分页查询是数据库的放呀,不同的数据库有不同的实现,mysql是limit 如果查询的是第一页数据,起始索引可以省略,直接简写为limit10; 例子: select * from emp Limit 0,10; Select * from emp limit 10,10; 10.DQL查询实例: select * from where gender = ‘女’ age in (20,21,22,23,24); Select * from where gender = ‘男’ and age between 20 and 40 and name like ‘___’; Select gender count(*) from emp where age<60 group by gender; Select name,age from emp where age<=35 order by age asc,entrydate desc; Select * from emp where gender = ‘男’ and age between 20 and 40 order by age asc, entrydate asc limit 5 ; 11.DQL语句的执行顺序: 1.from 2.where 3.groupby 4. select 5. order by6.limit 例子:select name,age from emp where age>=25 order by age asc; 12.DCL-用来管理数据库的用户,控制数据库的访问权限 1.查询用户:USE mysql;select*from user; 2.创建用户:create user ’用户名‘@’主机名‘identified by ’密码‘; 3.修改用户密码:alter user ’用户名‘@’主机名‘ identified with mysql_native_password by ’新密码‘; 4.删除用户: drop user’用户名‘@’主机名‘; 5.权限控制:ALL或者ALL PRIVILEGES(所有权限) SELECT 查询 insert 插入数据 update 修改数据 delete 删除数据 alter 修改表 drop 删除数据库/表/视图 create 创建数据库/表 查询权限:show grants for ’用户名‘@’主机名‘ 授予权限:grant 权限列表 on 数据库名,表名 to ‘用户名’@‘主机名’; 撤销权限:revoke 权限列表 on 数据库名,表名 from ‘用户名’@‘主机名’; 13.函数(可以直接被调用的程序或者代码): 1.字符串函数:CONCOT(s1,s2),字符串拼接 2.lower,upper,将字符串全部转写为(小写,大写); 3.LPAD,RPAD(str,n,pad),左/右填充用字符串pad对str左/右进行填充直到达到n个字符串长度 4.trim(str)去掉字符串头部和尾部的空格 5.SUBSTRING(str,start,len):截取字符串,start开始,长度为len 例:select concot(‘hello’,’mysql’); Select lower(‘hello’); Select upper(‘hello’); Select lpad(‘01’,5,’-’); Select rpad(‘01’,5,’-’); Select trim(‘ hello mysql ’); Substring(‘mysql’,1,5); 实例: Update emp set workno = lpad(workno,5,’0’); 6.数值函数: Ceil()向上取整,floor()向下取整,mod(x,y)返回x/y的模,rand()返回0-1内的随机数,round(x,y)求参数的四舍五入的值,保留y位小数 例:select ceil(1.9); 例子:生成一个随机六位数的验证码:select lpad(round(rand()*1000000,0),6,’0’); 7.日期函数: curdate返回当前日期,curdate返回当前日期,now返回当前日期和时间,year(date)获取指定date的年份,month(date)获取指定date的月份,day(date)获取指定date的日期,DATE_ADD(date,interval expr type)返回一个日期/时间值加上一个时间间隔expr后的时间值,DATEDIFF(date1,date2)返回起始时间date1和结束时间date2之间的天数 例子:select curdate() Select curtime() Select now() Select year(now()) 例子:查询所有员工的入职天数,并根据入职天数倒序排序: Select name,DATEDIFF(curdate(),entrydate) as ‘entrydays’from emp order by entrydays desc; 8.流程控制函数:if,IFNULL(value1,value2)value1不为空,返回value1否则返回value2,case when[val1]then [res1]else[default]end如果val1为true,返回res1,否则返回deault默认值,CASE[expr]when[val1]then[res1]….else[default]end 如果expr的值等于val1,返回res1,…否则返回default默认值。 14.约束:作用于表中字段上的规则,用于限制存储在表中的数据,保证数据库中数据的正确,有效性和完整性 分类:非空约束(not null),唯一约束(unique),主键约束(primary key),默认约束(default),检查约束(check),外键约束(用来让两张表的数据进行连接保证数据的一致性和完整性foreign key)。 例子: Create table user( Id int primary auto_increment comment’’, Name varchar(10) not null unique comment’’, Age int check(age>0 and age<120))comment ‘’, Status char(1) default ‘1’ comment’’, Gender char(1) comment’’)comment’’; 外键约束:通过外键将两张表连接起来,有外键的称之为子表,建立外键关联: 添加外键: alter table 表名 add constraint 外键名称 foreign key (外键字段名)references 主表(主表列名); 具体:alter table emp add constraint fk_emp_deft_id foreign key(dept-id) reference dept(id); 15.多表关系:一对多多对一(在多的一方建立外键,) 多对多:建立第三张中间表,中间表至少包含两个外键,分别关联两方主键; 一对一:多用于单表拆分,将一张表的基础字段放在一张表中,其他详情字段放在另一张表中,以提升操作效率。 16.多表查询:笛卡尔积,在多表查询是要消除无效笛卡尔积,(select * from emp dept); 解决方法:select * from emp,dept where emp.dept_id = dept.id; 1.内连接:相当于查询A,B交集部分数据 隐式内连接:select 字段列表 from 表1,表2 where 条件…;通常使用起别名的方式进行书写,起了别名之后就不能用远名字编写了 显式内连接:select 字段列表 from 表1[inner] join 表2 on 连接条件..;inner关键字可以省略 2.外连接: 左连接(查询左表所有数据以及两张表交集部分数据), select字段列表 from 表1 left [outer] join 表2 on 条件 右连接(查询右表所有数据以及两张表交集部分数据) select字段列表 from 表1 right [outer] join 表2 on 条件 3.自连接:当前表与自身的连接查询,自连接必须使用表别名 Select 字段列表 from 表a 别名a join 表a 别名b on 条件..; 例子:select a.name,b.name from emp a,emp b,where a.managerid = b.id; 4.联合查询:union,union all对于联合查询的多张表的列数必须保持一致,字段类型也需要保持一致 select 字段列表 from 表a union [all] select 字段列表 from 表b;如果有all的话是直接拼接结果,而没有的话是会去重的。 例子:select * from emp Where salary <5000 union (all) select * from emp where age > 50; 5.子查询:sql语句中嵌套select语句,也称为子查询 select * from t1 where column = (select column from t2 ) 标量子查询(子查询结果为单个值) select * from emp where dept_id = (select id from dept where name = ‘销售部’); 列子查询(子查询的结果为一列)常用:in(在指定的范围之内多选一),not in(不在指定的集合范围之内),any(子查询返回列表中,有任意一个满足即可),some(与 any同等,使用some的地方都可以用any),all(子查询返回列表中的所有值必须都满足) Select id from dept where name = ‘销售部’ or name = ‘市场部’; Select * from emp where dept_id in(Select id from dept where name = ‘销售部’ or name = ‘市场部’); Select * from emp where salary > all (select salary from emp where dept_id = (select id from dept where name = ‘财务部’)) 行子查询(查询结果为一行):子查询返回结果是一行常用:in,not in,=,<> Select * from emp where (salary,managerid) = (select salary,managerid from emp where name = ‘张无忌’); 表子查询(子查询结果为多行多列)常用in select * from emp where (job,salary) in (select job,salary from emp where name = ‘鹿杖客’ or name = ‘宋远桥’) 16.事务:一组操作的集合,他是一个不可分割的工作单位,事务会把所有的操作作为一个整体一起向系统提交或者撤销操作请求,即这些操作要么同时成功,要不同时失败 事务操作: 事务四大特性: 并发事务问题: 事务隔离级别:
import { Avatar, Headline, List, Text, Title, useTheme } from "react-native-paper"; import { Platform, StyleSheet, View } from "react-native"; import BottomSheet from "../components/bottomSheet"; import { GradeItem } from "../components/content/gradeItem"; import { Ionicons } from "@expo/vector-icons"; import { LaCard } from "../components/content/laCard"; import React from "react"; import { RestrictedWrapper } from "../components/restrictedWrapper"; import { ScreenContainer } from "../components/screenContainer"; import { fetchGrades } from "../utils/api/apiUtils"; import { useBlueboardClient } from "blueboard-client-react"; import { useLoading } from "../hooks/useLoading"; import { usePermissions } from "../hooks/controlHooks"; import { useSelector } from "react-redux"; import { getOffset } from "../utils/misc/offsetUtils"; export const KretaScreen = () => { const [currentSubjectData, setCurrentSubjectData] = React.useState(null); const [showSubjects, setShowSubjects] = React.useState(true); const [currentGrade, setCurrentGrade] = React.useState(null); const bottomSheetRef = React.useRef(null); const theme = useTheme(); const loading = useLoading(); const permissions = usePermissions(); const gradesData = useSelector((state) => state.kreta.gradesValue); const client = useBlueboardClient(); const styles = StyleSheet.create({ sheetContainer: { flex: 1, padding: 20, }, dataContainer: { flexDirection: "row", justifyContent: "space-between", }, title: { paddingTop: 8, }, subTitle: { paddingBottom: 8, }, subjectItem: { padding: 0, marginVertical: 5, borderRadius: theme.roundness, }, noPremContainer: { justifyContent: "center", flex: 1, }, space: { height: 50, }, }); const colors = { 1: "#f44336", // orange: 2: "#ff9800", // yellow 3: "#ffeb3b", // light green 4: "#8bc34a", // dark green 5: "#4caf50", }; const getSubjects = () => { return gradesData?.map((item) => ( <List.Item key={item.subject} title={item.subject} style={styles.subjectItem} right={() => ( <Ionicons name="chevron-forward-outline" size={24} color={theme.colors.text} /> )} onPress={() => { setCurrentSubjectData(item); setShowSubjects(false); }} /> )); }; const getGrades = () => { return currentSubjectData?.grades.map((item) => ( <GradeItem key={item.id} data={item} minimal={true} onPress={() => openSheet(item)} /> )); }; const openSheet = (grade) => { setCurrentGrade(grade); bottomSheetRef.current.show(); }; const tryAgain = async () => { loading(true); try { await fetchGrades(client); } catch (err) { console.log(err); } loading(false); }; const calculateAverage = () => { var res = 0; for (const grade of currentSubjectData.grades) { res += grade.grade; } return Number(res / currentSubjectData.grades.length).toFixed(2); }; return ( <ScreenContainer scrollable={permissions.includes("General::Grades")}> <Headline>Kréta</Headline> <RestrictedWrapper permission="General::Grades" fallback={ <View style={styles.noPremContainer}> <Text style={{ textAlign: "center" }}>Nincs hozzáférésed ehhez az oldalhoz</Text> </View> }> {showSubjects ? ( <LaCard title="Tantárgyak" error={gradesData === null} retry={() => tryAgain()}> <View style={{ paddingTop: 5 }}>{getSubjects()}</View> </LaCard> ) : ( <LaCard title={`${currentSubjectData.subject} - ${calculateAverage()}`} actionIcon="arrow-back" onPress={() => setShowSubjects(true)}> <View style={{ paddingTop: 5 }}>{getGrades()}</View> </LaCard> )} <View style={styles.space} /> <BottomSheet backgroundColor={theme.colors.backdrop} sheetBackgroundColor={theme.dark ? "#1e1e1e" : theme.colors.surface} radius={theme.roundness} ref={bottomSheetRef} height={220}> <View style={styles.sheetContainer}> <View style={styles.dataContainer}> <View style={{ width: "80%" }}> <Title style={styles.title} numberOfLines={1}> {currentGrade?.type} </Title> <Text style={styles.subTitle} numberOfLines={1}> {currentGrade?.name} </Text> </View> <Avatar.Text style={{ backgroundColor: colors[currentGrade?.grade], margin: 8 }} size={56} labelStyle={ Platform.OS !== "ios" ? { marginTop: getOffset(12), flex: 1, alignSelf: "center" } : {} } color="#000000" label={currentGrade?.grade === 0 ? "-" : currentGrade?.grade} /> </View> <View style={{ ...styles.dataContainer, paddingTop: 4 }}> <Text>Tantárgy:</Text> <Text>{currentGrade?.subject}</Text> </View> <View style={styles.dataContainer}> <Text>Tanár:</Text> <Text>{currentGrade?.teacher}</Text> </View> <View style={styles.dataContainer}> <Text>Dátum:</Text> <Text> { // Budget inline formatting let's go currentGrade?.date .replace("-", ". ") .replace("-", ". ") .replace("T", ". ") .replace("Z", "") } </Text> </View> <View style={styles.dataContainer}> <Text>Súly:</Text> <Text>{currentGrade?.weight}%</Text> </View> </View> </BottomSheet> </RestrictedWrapper> </ScreenContainer> ); };
import 'package:flutter/material.dart'; import '../widgets//player.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), useMaterial3: true, ), home: Stack( children: [ PageView( scrollDirection: Axis.vertical, children: [ ShortPage( accountName: 'Workshop Web', subscriber: '2M', price: '100.000', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', likeCount: '1k', commentCount: '342', imageProfile: 'https://source.unsplash.com/random/200x200?sig=1', imagePost: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT-aU6V45T4TEEDoj4xfR0kWCpTMLFqpZQb3TOQbUIJyQ&s', ), ShortPage( accountName: 'Agile', subscriber: '1M', price: '30.000', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', likeCount: '2k', commentCount: '327', imageProfile: 'https://source.unsplash.com/random/200x200?sig=1', imagePost: 'https://ih1.redbubble.net/image.1702773716.8569/flat,750x,075,f-pad,750x1000,f8f8f8.u1.jpg', ), ShortPage( accountName: 'AWS', subscriber: '2M', price: '100.000', description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', likeCount: '2k', commentCount: '877', imageProfile: 'https://source.unsplash.com/random/200x200?sig=1', imagePost: 'https://m.media-amazon.com/images/I/51NXb-EodmL.jpg', ), ], ), Positioned( top: 35, width: MediaQuery.of(context).size.width, child: Row( children: [ const Spacer(), Container( decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.2), spreadRadius: 4, blurRadius: 20, offset: const Offset(0, 3), // changes position of shadow ), ], ), child: IconButton( icon: const Icon(Icons.search), iconSize: 30, color: Colors.white, onPressed: () {}, ), ), const SizedBox(width: 4), Container( decoration: BoxDecoration( boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.2), spreadRadius: 4, blurRadius: 20, offset: const Offset(0, 3), // changes position of shadow ), ], ), child: IconButton( icon: const Icon(Icons.more_vert), iconSize: 30, color: Colors.white, onPressed: () {}, ), ), const SizedBox(width: 8), ], ), ), ], ), ); } }
package ru.yandex.practicum.filmorate; import lombok.RequiredArgsConstructor; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase; import org.springframework.boot.test.context.SpringBootTest; import ru.yandex.practicum.filmorate.exception.FilmNotFoundException; import ru.yandex.practicum.filmorate.model.Film; import ru.yandex.practicum.filmorate.model.Genre; import ru.yandex.practicum.filmorate.model.Mpa; import ru.yandex.practicum.filmorate.model.User; import ru.yandex.practicum.filmorate.service.FilmService; import ru.yandex.practicum.filmorate.service.UserService; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest @AutoConfigureTestDatabase @RequiredArgsConstructor(onConstructor_ = @Autowired) class FilmServiceTest { private final FilmService filmService; private final UserService userService; Film film = Film.builder() .id(-1) .name("Name") .description("Desc") .releaseDate(LocalDate.now()) .duration(120) .mpa(Mpa.builder().id(1).build()) .build(); @Test public void testCreateFilmMustReturnUserWithNewId() { film.setName("testCreateFilmMustReturnUserWithNewId"); film = filmService.addFilm(film); assertNotEquals(-1, (int) film.getId(), "Фильм не записан в базу, не присвоен id."); } @Test public void testGetFilmsWithNotEmptyBase() { film.setName("testGetFilmsWithNotEmptyBase"); filmService.addFilm(film); List<Film> films = filmService.getFilms(); assertFalse(films.isEmpty(), "Возвращен пустой список фильмов, после добавления."); } @Test public void testFindUserByNormalId() { film.setName("testFindUserByNormalId"); Film expectedFilm = filmService.addFilm(film); assertEquals(expectedFilm.getName(), film.getName(), "Фильм некорректно записан в базу. Ошибка в name"); assertEquals(expectedFilm.getDescription(), film.getDescription(), "Фильм некорректно записан в" + "базу. Ошибка в description"); } @Test public void testFindUserByWrongId() { final FilmNotFoundException exception = assertThrows( FilmNotFoundException.class, () -> filmService.getFilmById(-1) ); assertEquals("Фильм с идентификатором -1 не найден.", exception.getMessage()); } @Test public void testUpdateFilmId() { film.setName("testUpdateFilmNormalId"); film = filmService.addFilm(film); List<Genre> genres = new ArrayList<>(); genres.add(Genre.builder().id(1).build()); genres.add(Genre.builder().id(3).build()); film.setMpa(Mpa.builder().id(2).build()); film.setGenres(genres); filmService.addFilm(film); Film expectedFilm = filmService.getFilmById(film.getId()); assertEquals(2, expectedFilm.getMpa().getId(), "Не выполнено обновления фильма. Не записан рейтинг."); assertEquals(2, expectedFilm.getGenres().size(), "Не выполнено обновления фильма. Не записаны жанры."); } @Test void testAddLike() { film.setName("testForAddLIke"); film = filmService.addFilm(film); User userTest = User.builder() .login("testAddLike") .email("testCreate@ya.ru") .birthday(LocalDate.now()) .build(); userTest = userService.addUser(userTest); filmService.addLike(film.getId(), userTest.getId()); film = filmService.getFilmById(film.getId()); assertEquals(1, film.getLikes().size(), "Лайк фильму не поставлен."); } @Test void testDeleteLike() { film.setName("testDeleteLike"); film = filmService.addFilm(film); User userTest = User.builder() .login("testDeleteLike") .email("testCreate@ya.ru") .birthday(LocalDate.now()) .build(); userTest = userService.addUser(userTest); filmService.addLike(film.getId(), userTest.getId()); filmService.deleteLike(film.getId(), userTest.getId()); film = filmService.getFilmById(film.getId()); assertTrue(film.getLikes().isEmpty(), "Лайк фильму не удален."); } @Test void testGetPopularFilms() { film = filmService.addFilm(film); User userTest = User.builder() .login("testLogin") .email("testCreate@ya.ru") .birthday(LocalDate.now()) .build(); userTest = userService.addUser(userTest); filmService.addLike(film.getId(), userTest.getId()); film.setId(-1); film.setName("Name2"); filmService.addFilm(film); List<Film> films = filmService.getPopularFilms(2); assertEquals(2, films.size(), "Неправильно выдает популярные фильмы"); } }
/** * Select an option of a select element * @param {String} selectionType Type of method to select by (name, value or * text) * @param {String} selectionValue Value to select by * @param {String} selectElem Element selector */ module.exports = (selectionType, selectionValue, selectElem) => { /** * Arguments to pass to the selection method * @type {Array} */ const commandArguments = [ selectElem, selectionValue, ]; /** * The method to use for selecting the option * @type {String} */ let command = ''; switch (selectionType) { case 'name': { command = 'selectByAttribute'; // The selectByAttribute command expects the attribute name as it // second argument so let's add it commandArguments.splice(1, 0, 'name'); break; } case 'value': { command = 'selectByValue'; break; } case 'text': { command = 'selectByVisibleText'; break; } default: { throw new Error(`Unknown selection type "${selectionType}"`); } } browser[command](...commandArguments); };
****premutations**** // Given a permutation length, what is the ith permutation? vector<ll> nthPerm(ll len, ll nth) { vector<ll> identity(len), perm(len); lp(i, len) identity[i] = i; for (int i = len - 1; i >= 0; --i) { ll p = nth / Fact[i]; perm[len - 1 - i] = identity[p]; identity.erase(identity.begin() + p); nth %= Fact[i]; } return perm; } // Given a permutation, what is its index? ll PermToIndex(vector<int> perm) { ll idx = 0; int n = sz(perm); for (int i = 0; i < n; ++i) { // Remove first, and Renumber the remaining elements to remove gaps idx += Fact[n-i-1] * perm[i]; for(int j = i+1; j < n; j++) perm[j] -= perm[j] > perm[i]; } return idx; } *************( Permutations Application: Say we have a permutation: 2 0 1 3 Applying a permutation on other, aka multiplication, means to map its values according to the permutation. So 2 0 1 3 MEANS: 0 -map-> 2 1 -map-> 0 2 -map-> 1 3 -map-> 3 Then (0 1 2 3) * (2 0 1 3) = 2 0 1 3 (2 3 1 0) * (2 0 1 3) = 1 3 0 2 (3 2 0 1) * (2 0 1 3) = 3 1 2 0 (3 2 0 1) * (2 0 1 3) * (2 0 1 3) = (3 1 2 0) * (2 0 1 3) = 3 0 1 2 Permutation Multiplication is associative, like numbers Multiplication, e.g. doesn't matter what to apply first For Numbers: 3 * 5 * 7 = (3 * 5) * 7 = 3 * (5 * 7) Then for Some Permutations: P1 * p2 * p3 * p4 = P1 * (p2 * p3 * p4) = (P1 * p2) * (p3 * p4) and so on. Permutation Multiplication is NOT Commutative, like numbers subtraction, e.g. order matter For numbers: 3-5 ~= 5-3 Then for Permutations = (0 1 2 3) * (2 0 1 3) ~= (2 0 1 3) * (0 1 2 3) P^k means apply Permutation k times, e.g. (3 2 0 1) * (2 0 1 3) * (2 0 1 3) is written as: p1 * p2^2 Say we are given P1 and P2, and we would like to evaluate p1 * p2^k, where k = 10^9?!! Check above, Permutation is similar in that for Numbers. E.g. how do you calculate a^16? we use divide and conquer: a^16 = a^8 * a^8. Calculate a^8 and square it! SAME for Permutation typedef vector<int> perm; perm pow(perm inp, perm apply, int k) { if(k == 0) // won't apply permutation, so same as input return inp; if(k == 1) return applyPerm(inp, apply); // implement: (0 1 2 3) * (2 0 1 3) = 2 0 1 3 perm = pow(inp, apply, k/2); cur = applyPerm(cur, cur); if(k%2 == 1) // we have odd power cur = applyPerm(cur, perm); return cur; } Order? N for applyPerm * logk for depth -> O(nlogk) Could we do better? YES, a bit more code, but we can do it! Using Permutation Cycle Notation Permutation Cycle Notation From Abstract Algebra, we know that Permutation is set of dis-joint cycles. How In other words, if you followed which value replace other, you create a cycle. Let Say we have permutation p: 1 2 3 0 0 -> 1 1 -> 2 2 -> 3 3 -> 0 // End of Cycle What about 3 2 1 0 4 0 -> 3 3 -> 0 // End of Even Cycle 1 -> 2 2 -> 1 // End of Even Cycle 4 -> 4 // End of ODD Cycle, with one element What about 2 0 1 4 3 0 -> 2 2 -> 1 1 -> 0 // End of ODD Cycle 3 -> 4 4 -> 3 // End of Even Cycle Then, any permutation is set of cycles -> this is CLUE for many permutation problems Let's pick a one cycle permutation, and see its application: 3 0 1 2 0 -> 3 3 -> 2 2 -> 1 1 -> 0 let's apply it many times over a perm p: 0 1 2 3 (0 1 2 3) * (3 0 1 2)^1 = 3 0 1 2 (0 1 2 3) * (3 0 1 2)^2 = 2 3 0 1 Notice, the rotation of the cycle (0 1 2 3) * (3 0 1 2)^3 = 1 2 3 0 (0 1 2 3) * (3 0 1 2)^3 = 0 1 2 3 We backed again! Think in that, a cycle of length N, if applied N times, it backs to is origin! And applying a cycle N+1 = 1 time N+2 = 2 times 2N+1 = 1 time M = M%N time Let's think again in our problem: how to solve p1 * p2^k and k = 10^9? Simply, 1) Generate Permutation Cycles (aka disjoint cycle decomposition) -> O(n) 2) For each cycle length M, apply cycle M%N times, which is just a rotation 3) Cleverly, implement all in O(n) )**********
<template> <div class="mdl-grid textfieldCorrection newwordnote"> <p class="mdl-cell mdl-cell--12-col" v-on:click="jumpMarkText">{{selectedtext}}</p> <form class="mdl-cell mdl-cell--8-col"> <div class="mdl-textfield mdl-js-textfield textfieldCorrection"> <component is="autotextarea" class="mdl-textfield__input inputFieldNote contentColor" v-bind:inputtext="newnote" v-bind:submitit="submitit" v-on:submitit="save($event)" > </component> </div> </form> <div class="mdl-cell mdl-cell--4-col"> <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" v-on:click="save2"> <i class="material-icons">done</i> </button> <button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" v-on:click="back"> <i class="material-icons">clear</i> </button> </div> </div> </template> <script> import getselectedtext from './mixins/analysis/gettokensofselectedtext.js'; import autotextarea from './components/global/autosizingtextarea.vue'; export default { mixins: [getselectedtext], components: { autotextarea }, props: { serverip: { type: String, default : ''}, selectedindexes: { type: Object, default: null }, docid: { type: Number, default: -1 }, newnote: { type: String, default: "" }, wordnotedb: { type: Object, default: null }, tokens: { type: Array, default: function () { return [] }}, }, data: function () { return { selectedtext: '', submitit: false } }, methods: { back: function () { this.$emit('back', [-10, -10, -10]); }, save: function (newnote) { //console.log('DOCID: ' + this.docid + ' : ' + this.selectedindexes); if (typeof this.selectedindexes !== 'undefined' && this.selectedindexes.start !== -1 && this.selectedindexes.end !== -1) { let socket = io(this.serverip+':8080'); if (typeof this.wordnotedb === 'undefined') { socket.emit('savewordnote', newnote, this.docid, this.selectedindexes); //TODO: get noteID from DB in callback and correct it while/after render in the background let tempNote = { docID: this.docid, noteID: -1, content: newnote, textIndex1: this.selectedindexes.start, textIndex2: this.selectedindexes.end }; this.newnote = ''; this.selectedindexes = {}; this.$emit('back', [-1, 1, tempNote]); } else { socket.emit('updatewordnote', this.wordnotedb.noteID, newnote); this.wordnotedb.content = newnote; this.selectedtext = ''; this.$emit('back', [this.wordnotedb.noteID, 2, this.wordnotedb]); } } this.submitit = false; }, save2:function () { this.submitit = true; }, deleting: function () { if (typeof this.selectedindexes !== 'undefined' && this.selectedindexes.start !== -1 && this.selectedindexes.end !== -1) { let socket = io(this.serverip+':8080'); socket.emit('deletenote', this.wordnotedb.noteID); this.$emit('back', this.wordnotedb.nodeID, 0); } }, jumpMarkText: function () { //href bahavior for #selectedindexes.start } }, watch: { selectedindexes: { handler: function (newSelectedIndexes) { if (newSelectedIndexes.start !== -1 && newSelectedIndexes.end !== -1) { this.selectedtext = this.generateText(this.gettokensofselectedtext(this.tokens, newSelectedIndexes)); } }, deep: true }, } } </script>
--- layout: post title: Column menu in Vue Grid component | Syncfusion description: Learn here all about Column menu in Syncfusion Vue Grid component of Syncfusion Essential JS 2 and more. control: Column menu platform: ej2-vue documentation: ug domainurl: ##DomainURL## --- # Column menu in Vue Grid component The column menu has options to integrate features like sorting, grouping, filtering, column chooser, and autofit. It will show a menu with the integrated feature when users click on multiple icon of the column. To enable column menu, you need to define the [`showColumnMenu`](https://ej2.syncfusion.com/vue/documentation/api/grid/#showcolumnmenu) property as true. To use the column menu, inject the `ColumnMenu` in the `provide` section. The default items are displayed in following table. | Item | Description | |-----|-----| | `SortAscending` | Sort the current column in ascending order. | | `SortDescending` | Sort the current column in descending order. | | `Group` | Group the current column. | | `Ungroup` | Ungroup the current column. | | `AutoFit` | Auto fit the current column. | | `AutoFitAll` | Auto fit all columns. | | `ColumnChooser` | Choose the column visibility. | | `Filter` | Show the filter option as given in `filterSettings.type` | {% tabs %} {% highlight html tabtitle="app.vue" %} {% include code-snippet/grid/column/default-cs7/app.vue %} {% endhighlight %} {% endtabs %} {% previewsample "page.domainurl/code-snippet/grid/column/default-cs7" %} > You can disable column menu for a particular column by defining the [`columns.showColumnMenu`](https://ej2.syncfusion.com/vue/documentation/api/grid/column/#showcolumnmenu) as false. > You can customize the default items by defining the [`columnMenuItems`](https://ej2.syncfusion.com/vue/documentation/api/grid/#columnmenuitems) with required items. ## Column menu events During the resizing action, the grid component triggers the below two events. 1. The `columnMenuOpen` event triggers before the column menu opens. 2. The `columnMenuClick` event triggers when the user clicks the column menu of the grid. {% tabs %} {% highlight html tabtitle="app.vue" %} {% include code-snippet/grid/column/default-cs8/app.vue %} {% endhighlight %} {% endtabs %} {% previewsample "page.domainurl/code-snippet/grid/column/default-cs8" %} ## Custom column menu item Custom column menu items can be added by defining the [`columnMenuItems`](https://ej2.syncfusion.com/vue/documentation/api/grid/#columnmenuitems) as collection of the [`columnMenuItemModel`](https://ej2.syncfusion.com/vue/documentation/api/grid/columnMenuItemModel/). Actions for this customized items can be defined in the [`columnMenuClick`](https://ej2.syncfusion.com/vue/documentation/api/grid/#columnmenuclick) event. {% tabs %} {% highlight html tabtitle="app.vue" %} {% include code-snippet/grid/column/default-cs9/app.vue %} {% endhighlight %} {% endtabs %} {% previewsample "page.domainurl/code-snippet/grid/column/default-cs9" %} ## Customize menu items for particular columns Sometimes, you have a scenario that to hide an item from column menu for particular columns. In that case, you need to define the [`columnMenuOpenEventArgs.hide`](https://ej2.syncfusion.com/vue/documentation/api/grid/columnMenuOpenEventArgs/) as true in the [`columnMenuOpen`](https://ej2.syncfusion.com/vue/documentation/api/grid/#columnmenuopen) event. The following sample, `Filter` item was hidden in column menu when opens for the `OrderID` column. {% tabs %} {% highlight html tabtitle="app.vue" %} {% include code-snippet/grid/column/default-cs10/app.vue %} {% endhighlight %} {% endtabs %} {% previewsample "page.domainurl/code-snippet/grid/column/default-cs10" %} ## Customize the icon of column menu You can customize the column menu icon by overriding the default grid class `.e-icons.e-columnmenu` with a custom property `content` as mentioned below, ``` .e-grid .e-columnheader .e-icons.e-columnmenu::before { content: "\e941"; } ``` In the below sample, grid is rendered with a customized column menu icon. {% tabs %} {% highlight html tabtitle="app.vue" %} {% include code-snippet/grid/how-to/default-cs1/app.vue %} {% endhighlight %} {% endtabs %} {% previewsample "page.domainurl/code-snippet/grid/how-to/default-cs1" %}
#include <iostream> #include "../color.h" #include "../vec3.h" #include "../ray.h" #include <iostream> color ray_color(const ray& r){ vec3 unit_direction = unit_vector(r.direction()); auto a = 0.5 * (unit_direction.y() + 1.0); return (1.0 - a) * color(1.0, 1.0, 1.0) + a*color(0.5, 0.7, 1.0); } int main() { double aspect_ratio = 16.0 / 9.0; int image_width = 400; int image_height = static_cast<int>(image_width / aspect_ratio); image_height = image_height == 0 ? 1 : image_height; // Camera double focal_length = 1.0; double viewport_height = 2.0; double viewport_width = viewport_height * (static_cast<double>(image_width)/image_height); point3 camera_center = point3(0, 0, 0); // Calculating horizontal and vertical vectors vec3 viewport_u = vec3(viewport_width, 0, 0); vec3 viewport_v = vec3(0, -viewport_height, 0); // Calculating delta vectors vec3 delta_u = viewport_u / image_width; vec3 delta_v = viewport_v / image_height; // Calculate the location of the upper left pixel vec3 viewport_upper_left = camera_center - vec3(0, 0, focal_length) - viewport_u/2 - viewport_v/2; vec3 pixel00_loc = viewport_upper_left + 0.5 * (delta_u + delta_v); std::cout << "P3\n" << image_width << " " << image_height << "\n255\n"; for (int i = 0; i < image_height; ++i){ std::clog << "\rScanlines remaining: " << (image_height - i) << " " << std::flush; for (int j = 0; j < image_width; ++j){ vec3 pixel_center = pixel00_loc + (i * delta_u) + (j * delta_v); vec3 ray_direction = pixel_center - camera_center; ray r(camera_center, ray_direction); color pixel_color = ray_color(r); write_color(std::cout, pixel_color); } } }
#include <iostream> #include <sstream> #ifndef USE_MPI #define BOOST_TEST_MODULE testDemandSDDP #endif #define BOOST_TEST_DYN_LINK #ifdef USE_MPI #include <boost/mpi.hpp> #endif #define _USE_MATH_DEFINES #include <math.h> #include <boost/test/unit_test.hpp> #include <Eigen/Dense> #include "reflow/core/grids/OneDimRegularSpaceGrid.h" #include "reflow/core/grids/OneDimData.h" #include "reflow/sddp/LocalLinearRegressionForSDDPGeners.h" #include "reflow/sddp/LocalConstRegressionForSDDPGeners.h" #include "reflow/sddp/SDDPFinalCut.h" #include "reflow/sddp/SDDPLocalCut.h" #include "reflow/sddp/backwardForwardSDDP.h" #include "test/c++/tools/simulators/SimulatorGaussianSDDP.h" #include "test/c++/tools/sddp/OptimizeDemandSDDP.h" using namespace std; using namespace Eigen ; using namespace reflow; #if defined __linux #include <fenv.h> #define enable_abort_on_floating_point_exception() feenableexcept(FE_DIVBYZERO | FE_INVALID) #endif double accuracyClose = 1.; /// fake optimization (see OptimizeDemandSDDP.h) /// only calculate the expectancy of demand. template< class LocalRegressionForSDDP > void testDemandSDDP(const double &p_sigD, const int &p_sampleOptim, const int &p_sampleCheckSimul) { #ifdef USE_MPI boost::mpi::communicator world; #endif double maturity = 40; int nstep = 40; // optimizer //************ double sigD = p_sigD ; //volatility for inflows double kappaD = 0.2; double spot = 3 ; // define a a time grid shared_ptr<OneDimRegularSpaceGrid> timeGrid(new OneDimRegularSpaceGrid(0., maturity / nstep, nstep)); // periodicity factor int iPeriod = 52; // define average demand shared_ptr<vector< double > > demandValues(new vector<double>(nstep + 1)); for (int i = 0; i < nstep + 1; ++i) (*demandValues)[i] = (2. + 0.4 * cos((M_PI * i * iPeriod) / nstep)) ; shared_ptr<OneDimData<OneDimRegularSpaceGrid, double> > demand(new OneDimData< OneDimRegularSpaceGrid, double> (timeGrid, demandValues)); // initial state ArrayXd initialState = ArrayXd::Constant(1, demand->get(0)); /// final cut ArrayXXd finalCut = ArrayXXd::Zero(2, 1); SDDPFinalCut finCut(finalCut); // no regression here ArrayXi nbMesh; // number of samples in optimisation and simulation int sampleOptim = p_sampleOptim ; // at each time step, each state, number do samples used (optimization) int sampleCheckSimul = p_sampleCheckSimul ; // number of simulation to check convergence // backward and forward simulator ( one uncertainty times nbsimul ) int nbUncertainties = 1; shared_ptr<SimulatorGaussianSDDP> backSimulator = make_shared<SimulatorGaussianSDDP>(nbUncertainties, sampleOptim); shared_ptr<SimulatorGaussianSDDP> forSimulator = make_shared<SimulatorGaussianSDDP>(nbUncertainties); // define the storage shared_ptr<OptimizerSDDPBase > optimizer = make_shared<OptimizeDemandSDDP<SimulatorGaussianSDDP> > (sigD, kappaD, demand, spot, backSimulator, forSimulator); // optimisation dates ArrayXd dates = ArrayXd::LinSpaced(nstep + 1, 0., maturity); // names for archive string nameRegressor = "RegressorDemand"; string nameCut = "CutDemand"; string nameVisitedStates = "VisitedStateDemand"; // precision parameter int nIterMax = 40; double accuracy = accuracyClose / 100; int nstepIterations = 4; // check for convergence between nstepIterations step ostringstream stringStream; // store intermediate results pair<double, double> values = backwardForwardSDDP<LocalRegressionForSDDP>(optimizer, sampleCheckSimul, initialState, finCut, dates, nbMesh, nameRegressor, nameCut, nameVisitedStates, nIterMax, accuracy, nstepIterations, stringStream #ifdef USE_MPI , world #endif ); #ifdef USE_MPI if (world.rank() == 0) #endif { cout << stringStream.str() << endl ; cout << " Value Optim " << values.first << " and Simulation " << values.second << " Iteration " << nIterMax << endl ; BOOST_CHECK_CLOSE(values.first, values.second, accuracyClose); } } BOOST_AUTO_TEST_CASE(testDemandSDDP1DDeterministic) { double sig = 0. ; int sampleOptim = 1; int sampleCheckSimul = 1; testDemandSDDP<LocalLinearRegressionForSDDP>(sig, sampleOptim, sampleCheckSimul); testDemandSDDP<LocalConstRegressionForSDDP>(sig, sampleOptim, sampleCheckSimul); } BOOST_AUTO_TEST_CASE(testDemandSDDP1D) { double sig = 0.6 ; int sampleOptim = 500; int sampleCheckSimul = 1000; testDemandSDDP<LocalLinearRegressionForSDDP>(sig, sampleOptim, sampleCheckSimul); testDemandSDDP<LocalConstRegressionForSDDP>(sig, sampleOptim, sampleCheckSimul); } #ifdef USE_MPI // (empty) Initialization function. Can't use testing tools here. bool init_function() { return true; } int main(int argc, char *argv[]) { #if defined __linux enable_abort_on_floating_point_exception(); #endif boost::mpi::environment env(argc, argv); return ::boost::unit_test::unit_test_main(&init_function, argc, argv); } #endif
import { IconType } from 'react-icons' import clsx from 'clsx' import { Anchor, AnchorProps } from '~/components/anchor' type InheritFromAnchorProps = Omit<Omit<AnchorProps, 'children'>, 'underline'> export interface SocialLinkCardProps extends InheritFromAnchorProps { icon: IconType title: string social: 'twitter' | 'github' | 'instagram' | 'linkedin' | 'twitch' | 'email' asFootnote?: boolean } export const SocialLinkCard = ({ icon: Icon, title, href, className, social, asFootnote = false, }: SocialLinkCardProps) => { return ( <Anchor href={href} external className={clsx( className, { 'bg-twitter-transparent hover:bg-twitter-brand text-twitter-brand hover:text-white': social === 'twitter', 'bg-github-transparent hover:bg-github-brand text-gray-800 dark:text-gray-400 dark:hover:text-white hover:text-white': social === 'github', 'bg-twitch-transparent hover:bg-twitch-brand text-twitch-brand hover:text-white': social === 'twitch', 'bg-linkedin-transparent hover:bg-linkedin-brand text-linkedin-brand hover:text-white': social === 'linkedin', 'bg-gray-700 hover:bg-gray-600 text-gray-800 hover:text-white': social === 'email', }, 'flex flex-col items-center justify-between group rounded-lg transition-colors duration-200', 'hover:scale-110 transition-transform hover:shadow-md', { 'w-auto h-auto lg:w-36 lg:h-36 p-8': !asFootnote, 'p-4': asFootnote, }, )} underline={false} > <Icon className={clsx('transition-colors', { 'text-twitter-brand group-hover:text-white': social === 'twitter', 'text-gray-700 dark:text-gray-500 group-hover:text-white': social === 'github', 'text-linkedin-brand group-hover:text-white': social === 'linkedin', 'text-twitch-brand group-hover:text-white': social === 'twitch', 'text-gray-800 group-hover:text-gray-200': social === 'email', 'text-lg lg:text-2xl': asFootnote, 'text-[32px]': !asFootnote, })} /> {!asFootnote && <p className="mt-5 text-lg font-bold">{title}</p>} </Anchor> ) }
(function(factory) { if (typeof define === 'function' && define.amd) { define(['underscore', 'blockly-bq', 'blockly.blocks'], factory); } else { factory(_, window.Blockly, window.Blocks); } }(function(_, Blockly, Blocks) { var load = function(options) { if (window.FacilinoAdvanced===true) { Blockly.Arduino.button = function() { var pin = Blockly.Arduino.valueToCode(this, 'PIN', Blockly.Arduino.ORDER_NONE); var code = ''; if (Facilino.isVariable(pin)) { code += 'pinMode(' +pin+',INPUT);\n'; } else { Blockly.Arduino.setups_['setup_button_' + pin] = 'pinMode(' +pin+',INPUT);\n'; } code += 'digitalRead(' +pin+')'; // console.log('code',code); return [code, Blockly.Arduino.ORDER_ATOMIC]; }; Blockly.Blocks.button = { category: Facilino.locales.getKey('LANG_CATEGORY_ADVANCED'), subcategory: Facilino.locales.getKey('LANG_SUBCATEGORY_BUTTON'), tags: ['input','output','button'], helpUrl: Facilino.getHelpUrl('button'), examples: ['button_example.bly'], category_colour: Facilino.LANG_COLOUR_ADVANCED, colour: Facilino.LANG_COLOUR_ADVANCED_BUTTON, keys: ['LANG_BQ_BUTTON_NAME','LANG_BQ_BUTTON','LANG_BQ_BUTTON_TOOLTIP'], name: Facilino.locales.getKey('LANG_BQ_BUTTON_NAME'), inputs: [Facilino.locales.getKey('LANG_BQ_BUTTON_PIN')], output: Facilino.locales.getKey('LANG_BQ_BUTTON_OUTPUT'), init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_BUTTON); this.appendValueInput('PIN').appendField(Facilino.locales.getKey('LANG_BQ_BUTTON')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/pushbutton.png', 52*options.zoom, 24*options.zoom)).setCheck(['DigitalPin',Number]).appendField(Facilino.locales.getKey('LANG_BQ_BUTTON_PIN')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/digital_signal.svg', 22*options.zoom, 22*options.zoom)).setAlign(Blockly.ALIGN_RIGHT).setCheck('DigitalPin'); this.setOutput(true,Boolean); this.setTooltip(Facilino.locales.getKey('LANG_BQ_BUTTON_TOOLTIP')); }, default_inputs: function() { var xml=''; xml+='<value name="PIN"><shadow type="pin_digital"></shadow></value>'; return xml; } }; Blockly.Arduino.button_case = function() { var pin = Blockly.Arduino.valueToCode(this, 'PIN', Blockly.Arduino.ORDER_NONE); var code = ''; if (Facilino.isVariable(pin)) { code += 'pinMode(' +pin+',INPUT);\n'; } else { Blockly.Arduino.setups_['setup_button_' + pin] = 'pinMode(' +pin+',INPUT);\n'; } var code_pressed = ''; var code_not_pressed = ''; code_pressed += Blockly.Arduino.statementToCode(this, 'PRESSED'); code_not_pressed += Blockly.Arduino.statementToCode(this, 'NOT_PRESSED'); code_pressed = code_pressed.replace(/&quot;/g, '"'); code_not_pressed = code_not_pressed.replace(/&quot;/g, '"'); code += 'if ('+'digitalRead(' +pin+')==LOW){\n'+code_pressed+'\n}\nelse{\n'+code_not_pressed+'\n}\n'; // console.log('code',code); return code; }; Blockly.Blocks.button_case = { category: Facilino.locales.getKey('LANG_CATEGORY_ADVANCED'), subcategory: Facilino.locales.getKey('LANG_SUBCATEGORY_BUTTON'), tags: ['input','output','button'], helpUrl: Facilino.getHelpUrl('button_case'), examples: ['button_case_example.bly'], category_colour: Facilino.LANG_COLOUR_ADVANCED, colour: Facilino.LANG_COLOUR_ADVANCED_BUTTON, keys: ['LANG_BQ_BUTTON_CASE_NAME','LANG_BQ_BUTTON','LANG_BQ_BUTTON_PIN','LANG_BUTTON_PRESSED','LANG_BUTTON_NOT_PRESSED','LANG_BQ_BUTTON_CASE_TOOLTIP'], name: Facilino.locales.getKey('LANG_BQ_BUTTON_CASE_NAME'), //bq_button initialization init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_BUTTON); this.appendValueInput('PIN').appendField(Facilino.locales.getKey('LANG_BQ_BUTTON')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/pushbutton.png', 52*options.zoom, 24*options.zoom)).setCheck(['DigitalPin',Number]).appendField(Facilino.locales.getKey('LANG_BQ_BUTTON_PIN')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/digital_signal.svg', 22*options.zoom, 22*options.zoom)).setAlign(Blockly.ALIGN_RIGHT).setCheck('DigitalPin'); this.setOutput(false); this.appendStatementInput('PRESSED') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Facilino.locales.getKey('LANG_BUTTON_PRESSED')); this.appendStatementInput('NOT_PRESSED') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Facilino.locales.getKey('LANG_BUTTON_NOT_PRESSED')); this.setPreviousStatement(true,'code'); this.setNextStatement(true,'code'); this.setTooltip(Facilino.locales.getKey('LANG_BQ_BUTTON_CASE_TOOLTIP')); }, default_inputs: function() { var xml=''; xml+='<value name="PIN"><shadow type="pin_digital"></shadow></value>'; return xml; } }; Blockly.Arduino.button_long_short = function() { var pin = Blockly.Arduino.valueToCode(this, 'PIN', Blockly.Arduino.ORDER_NONE); var code = ''; if (Facilino.isVariable(pin)) { code += 'pinMode(' +pin+',INPUT);\n'; } else { Blockly.Arduino.setups_['setup_button_' + pin] = 'pinMode(' +pin+',INPUT);\n'; } Blockly.Arduino.definitions_['declare_var_button_active_'+pin]='boolean _buttonActive_'+pin+'=false;\n'; Blockly.Arduino.definitions_['declare_var_long_press_active_'+pin]='boolean _longPressActive_'+pin+'=false;\n'; Blockly.Arduino.definitions_['declare_var_button_timer_'+pin]='long _buttonTimer_'+pin+'=0;\n'; var code_long_pressed = ''; var code_short_pressed = ''; code_long_pressed += Blockly.Arduino.statementToCode(this, 'LONG_PRESSED'); code_short_pressed += Blockly.Arduino.statementToCode(this, 'SHORT_PRESSED'); code_long_pressed = code_long_pressed.replace(/&quot;/g, '"'); code_short_pressed = code_short_pressed.replace(/&quot;/g, '"'); var block =this.getParent(); var in_interrupt_instruction=false; while(block!==null) { if (block.type==='attachInterrupt') { in_interrupt_instruction=true; break; } block=block.getParent(); } if (in_interrupt_instruction===true) { if (Facilino.profiles['processor']==='ESP32') { Blockly.Arduino.definitions_['declare_var_ui_timer_'+pin]='hw_timer_t* _uiTimer_'+pin+'=NULL;\n'; Blockly.Arduino.setups_['setup_button_timer_' + pin] = '_uiTimer_'+pin+'=timerBegin(1,80,true);\n timerAttachInterrupt(_uiTimer_'+pin+',&_uiTimerInterrupt_'+pin+', true);\n timerAlarmWrite(_uiTimer_'+pin+',('+this.getFieldValue('TIME')+')*1000,true);\n timerAlarmEnable(_uiTimer_'+pin+');\n timerStop(_uiTimer_'+pin+');\n'; Blockly.Arduino.definitions_['define_isr_timer_'+pin]='void IRAM_ATTR _uiTimerInterrupt_'+pin+'(){\n if (_buttonActive_'+pin+'==true){\n _longPressActive_'+pin+'=true;\n'+code_long_pressed+' }\n timerStop(_uiTimer_'+pin+');\n }\n'; code+='if (digitalRead('+pin+')==LOW) {\n if (_buttonActive_'+pin+'==false) {\n _buttonActive_'+pin+'=true;\n timerStart(_uiTimer_'+pin+');\n _buttonTimer_'+pin+'=millis();\n }\n }\n else {\n if (_buttonActive_'+pin+'== true){\n if (_longPressActive_'+pin+'==true){\n _longPressActive_'+pin+'=false;\n }\n else if ((millis()-_buttonTimer_'+pin+')>100){\n'+code_short_pressed+'\n }\n }\n _buttonActive_'+pin+'=false;\n }\n'; } else { code+='if (digitalRead('+pin+')==LOW) {\n if (_buttonActive_'+pin+'==false) {\n _buttonActive_'+pin+'=true;\n _buttonTimer_'+pin+'=millis();\n }\n else {\n if (_buttonActive_'+pin+'== true){\n if ((millis()-_buttonTimer_'+pin+')>'+this.getFieldValue('TIME')+'){\n'+code_long_pressed+'\n }\n else if ((millis()-_buttonTimer_'+pin+')>100){\n'+code_short_pressed+'\n }\n _buttonActive_'+pin+'=false;\n }\n }\n'; } } else { code+='if (digitalRead('+pin+')==LOW) {\n if (_buttonActive_'+pin+'==false) {\n _buttonActive_'+pin+'=true;\n _buttonTimer_'+pin+'=millis();\n }\n if (((millis()-_buttonTimer_'+pin+'>'+this.getFieldValue('TIME')+'))&&(_longPressActive_'+pin+'==false)){\n _longPressActive_'+pin+'=true;\n'+code_long_pressed+'\n}\n }\n else {\n if (_buttonActive_'+pin+'== true){\n if (_longPressActive_'+pin+'==true){\n _longPressActive_'+pin+'=false;\n }\n else if ((millis()-_buttonTimer_'+pin+')>100){\n'+code_short_pressed+'\n}\n _buttonActive_'+pin+'=false;\n }\n }\n'; } return code; }; Blockly.Blocks.button_long_short = { category: Facilino.locales.getKey('LANG_CATEGORY_ADVANCED'), subcategory: Facilino.locales.getKey('LANG_SUBCATEGORY_BUTTON'), tags: ['input','output','button'], helpUrl: Facilino.getHelpUrl('button_long_short'), examples: ['button_case_example.bly'], category_colour: Facilino.LANG_COLOUR_ADVANCED, colour: Facilino.LANG_COLOUR_ADVANCED_BUTTON, keys: ['LANG_BQ_BUTTON_LONG_SHORT_NAME','LANG_BQ_BUTTON','LANG_BQ_BUTTON_PIN','LANG_BUTTON_LONG_PRESSED','LANG_BUTTON_SHORT_PRESSED','LANG_BQ_BUTTON_LONG_SHORT_TOOLTIP'], name: Facilino.locales.getKey('LANG_BQ_BUTTON_LONG_SHORT_NAME'), //bq_button initialization init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_BUTTON); this.appendValueInput('PIN').appendField(Facilino.locales.getKey('LANG_BQ_BUTTON')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/pushbutton.png', 52*options.zoom, 24*options.zoom)).setCheck(['DigitalPin',Number]).appendField(Facilino.locales.getKey('LANG_BQ_BUTTON_PIN')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/digital_signal.svg', 22*options.zoom, 22*options.zoom)).setAlign(Blockly.ALIGN_RIGHT).setCheck('DigitalPin'); this.appendDummyInput('').appendField(Facilino.locales.getKey('LANG_BQ_BUTTON_TIME')).appendField(new Blockly.FieldNumber('1000','200','5000'),'TIME').setAlign(Blockly.ALIGN_RIGHT); this.setOutput(false); this.appendStatementInput('LONG_PRESSED') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Facilino.locales.getKey('LANG_BUTTON_LONG_PRESSED')); this.appendStatementInput('SHORT_PRESSED') .setAlign(Blockly.ALIGN_RIGHT) .appendField(Facilino.locales.getKey('LANG_BUTTON_SHORT_PRESSED')); this.setPreviousStatement(true,'code'); this.setInputsInline(false); this.setNextStatement(true,'code'); this.setTooltip(Facilino.locales.getKey('LANG_BQ_BUTTON_LONG_SHORT_TOOLTIP')); }, default_inputs: function() { var xml=''; xml+='<value name="PIN"><shadow type="pin_digital"></shadow></value>'; return xml; } }; Blockly.Arduino.zum_button = function() { var pin = Blockly.Arduino.valueToCode(this, 'PIN', Blockly.Arduino.ORDER_NONE); var code = ''; pullup='INPUT_PULLUP'; if (Facilino.isVariable(pin)) { code += 'pinMode(' +pin+',INPUT_PULLUP);\n'; } else { Blockly.Arduino.setups_['setup_button_' + pin] = 'pinMode(' +pin+',INPUT_PULLUP);\n'; } code += 'digitalRead(' +pin+')' return [code, Blockly.Arduino.ORDER_ATOMIC]; }; Blockly.Blocks.zum_button = { category: Facilino.locales.getKey('LANG_CATEGORY_ADVANCED'), subcategory: Facilino.locales.getKey('LANG_SUBCATEGORY_BUTTON'), tags: ['input','output','button'], helpUrl: Facilino.getHelpUrl('zum_button'), examples: ['zum_button_example.bly'], category_colour: Facilino.LANG_COLOUR_ADVANCED, colour: Facilino.LANG_COLOUR_ADVANCED_BUTTON, keys: ['LANG_ZUM_BUTTON','LANG_ZUM_BUTTON_PIN','LANG_ZUM_BUTTON_TOOLTIP'], name: Facilino.locales.getKey('LANG_ZUM_BUTTON_NAME'), init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_BUTTON); this.appendValueInput('PIN').appendField(Facilino.locales.getKey('LANG_ZUM_BUTTON')).appendField(Facilino.locales.getKey('LANG_ZUM_BUTTON_PIN')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/digital_signal.svg', 22*options.zoom, 22*options.zoom)).setCheck(['DigitalPin',Number]); this.appendDummyInput().appendField('pull-up?').appendField(new Blockly.FieldCheckbox('FALSE'), 'PULLUP').setAlign(Blockly.ALIGN_RIGHT); this.setOutput(true,Boolean); this.setTooltip(Facilino.locales.getKey('LANG_ZUM_BUTTON_TOOLTIP')); this.setInputsInline(false); }, default_inputs: function() { var xml=''; xml+='<value name="PIN"><shadow type="pin_digital"></shadow></value>'; return xml; } }; Blockly.Arduino.two_buttons_ui = function() { var select_pin = Blockly.Arduino.valueToCode(this, 'PIN_SELECT', Blockly.Arduino.ORDER_NONE); var cancel_pin = Blockly.Arduino.valueToCode(this, 'PIN_CANCEL', Blockly.Arduino.ORDER_NONE); var code = ''; Blockly.Arduino.setups_['inout_digital_input' + select_pin] = JST['inout_digital_input']({'pin': select_pin}); Blockly.Arduino.setups_['inout_digital_input' + cancel_pin] = JST['inout_digital_input']({'pin': cancel_pin}); Blockly.Arduino.definitions_['declare_var_button_active_'+select_pin]='boolean _buttonActive_'+select_pin+'=false;\n'; Blockly.Arduino.definitions_['declare_var_long_press_active_'+select_pin]='boolean _longPressActive_'+select_pin+'=false;\n'; Blockly.Arduino.definitions_['declare_var_button_timer_'+select_pin]='long _buttonTimer_'+select_pin+'=0;\n'; Blockly.Arduino.definitions_['declare_var_button_active_'+cancel_pin]='boolean _buttonActive_'+cancel_pin+'=false;\n'; Blockly.Arduino.definitions_['declare_var_button_timer_'+cancel_pin]='long _buttonTimer_'+cancel_pin+'=0;\n'; Blockly.Arduino.definitions_['declare_var_button_updateUI_'+select_pin+'_'+cancel_pin]='boolean _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n'; Blockly.Arduino.definitions_['declare_var_button_acceptUI_'+select_pin+'_'+cancel_pin]='boolean _acceptUI_'+select_pin+'_'+cancel_pin+'=false;\n'; Blockly.Arduino.definitions_['declare_var_button_menu_level_'+select_pin+'_'+cancel_pin]='int _menu_level_'+select_pin+'_'+cancel_pin+'=0;\n'; Blockly.Arduino.definitions_['declare_var_button_menu_'+select_pin+'_'+cancel_pin]='int _menu_'+select_pin+'_'+cancel_pin+'=-1;\n'; Blockly.Arduino.definitions_['declare_var_button_option_'+select_pin+'_'+cancel_pin]='int _option_'+select_pin+'_'+cancel_pin+'=-1;\n'; Blockly.Arduino.definitions_['declare_var_button_max_menus_'+select_pin+'_'+cancel_pin]='int _max_menus_'+select_pin+'_'+cancel_pin+'='+this.menuCount_+';\n'; Blockly.Arduino.definitions_['declare_var_current_time_'+select_pin+'_'+cancel_pin]='long _currentTime_'+select_pin+'_'+cancel_pin+'=0;\n'; Blockly.Arduino.definitions_['declare_var_refresh_time_'+select_pin+'_'+cancel_pin]='int _refreshTime_'+select_pin+'_'+cancel_pin+'='+this.getFieldValue('TIME')+';\n'; //Compute max options array var opt_array=''; var i=0; for (i=0;i<this.menuCount_;i++) { var option=this.getInputTargetBlock('MENU'+i); if (option) opt_array+=option.optionCount_+','; else opt_array+=','; } opt_array=opt_array.substr(0,opt_array.length-1); Blockly.Arduino.definitions_['declare_var_button_max_options_'+select_pin+'_'+cancel_pin]='int _max_options_'+select_pin+'_'+cancel_pin+'['+this.menuCount_+']={'+opt_array+'};\n'; code+='_currentTime_'+select_pin+'_'+cancel_pin+'=millis();\n'; code+='if (digitalRead('+select_pin+')==LOW) {\n if (_buttonActive_'+select_pin+'==false) {\n _buttonActive_'+select_pin+'=true;\n _buttonTimer_'+select_pin+'=_currentTime_'+select_pin+'_'+cancel_pin+';\n }\n if (((_currentTime_'+select_pin+'_'+cancel_pin+'-_buttonTimer_'+select_pin+')>1000)&&(_longPressActive_'+select_pin+'==false)){\n _longPressActive_'+select_pin+'=true;\n if (_menu_level_'+select_pin+'_'+cancel_pin+'==1)\n {\n _menu_level_'+select_pin+'_'+cancel_pin+'=2;\n _option_'+select_pin+'_'+cancel_pin+'=0;\n _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n }\n else if (_menu_level_'+select_pin+'_'+cancel_pin+'==2)\n {\n _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n _acceptUI_'+select_pin+'_'+cancel_pin+'=true;\n }\n }\n }\n else {\n if (_buttonActive_'+select_pin+'== true){\n if (_longPressActive_'+select_pin+'==true){\n _longPressActive_'+select_pin+'=false;\n }\n else if ((_currentTime_'+select_pin+'_'+cancel_pin+'-_buttonTimer_'+select_pin+')>100){\n if (_menu_level_'+select_pin+'_'+cancel_pin+'==0)\n {\n _menu_'+select_pin+'_'+cancel_pin+'=0;\n _option_'+select_pin+'_'+cancel_pin+'=-1;\n _menu_level_'+select_pin+'_'+cancel_pin+'++;\n _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n }\n else if (_menu_level_'+select_pin+'_'+cancel_pin+'==1)\n {\n _menu_'+select_pin+'_'+cancel_pin+'++;\n if (_menu_'+select_pin+'_'+cancel_pin+'==_max_menus_'+select_pin+'_'+cancel_pin+')\n _menu_'+select_pin+'_'+cancel_pin+'=0;\n _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n }\n else if (_menu_level_'+select_pin+'_'+cancel_pin+'==2)\n {\n _option_'+select_pin+'_'+cancel_pin+'++;\n if (_option_'+select_pin+'_'+cancel_pin+'==_max_options_'+select_pin+'_'+cancel_pin+'[_menu_'+select_pin+'_'+cancel_pin+'])\n _option_'+select_pin+'_'+cancel_pin+'=0;\n _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n }\n }\n _buttonActive_'+select_pin+'=false;\n }\n }\n'; code+=' if (digitalRead('+cancel_pin+')==LOW) {\n if (_buttonActive_'+cancel_pin+'==false) {\n _buttonActive_'+cancel_pin+'=true;\n _buttonTimer_'+cancel_pin+'=_currentTime_'+select_pin+'_'+cancel_pin+';\n }\n }\n else {\n \n if ((_menu_level_'+select_pin+'_'+cancel_pin+'==0)&&(_refreshTime_'+select_pin+'_'+cancel_pin+'>0)&&((_currentTime_'+select_pin+'_'+cancel_pin+'-_buttonTimer_'+cancel_pin+')>_refreshTime_'+select_pin+'_'+cancel_pin+'))\n {\n _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n _buttonTimer_'+cancel_pin+'=_currentTime_'+select_pin+'_'+cancel_pin+';\n }\n if (_buttonActive_'+cancel_pin+'== true){\n if ((_currentTime_'+select_pin+'_'+cancel_pin+'-_buttonTimer_'+cancel_pin+')>100){\n if (_menu_level_'+select_pin+'_'+cancel_pin+'==1)\n {\n _menu_level_'+select_pin+'_'+cancel_pin+'=0;\n _menu_'+select_pin+'_'+cancel_pin+'=-1;\n _option_'+select_pin+'_'+cancel_pin+'=-1;\n _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n }\n else if (_menu_level_'+select_pin+'_'+cancel_pin+'==2)\n {\n _menu_level_'+select_pin+'_'+cancel_pin+'=1;\n _option_'+select_pin+'_'+cancel_pin+'=-1;\n _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n }\n else\n {\n _menu_'+select_pin+'_'+cancel_pin+'=-1;\n _option_'+select_pin+'_'+cancel_pin+'=-1;\n _updateUI_'+select_pin+'_'+cancel_pin+'=true;\n }\n }\n _buttonActive_'+cancel_pin+'=false;\n }\n }\n'; code+='if (_updateUI_'+select_pin+'_'+cancel_pin+'==true)\n {\n _updateUI_'+select_pin+'_'+cancel_pin+'=false;\n if ((_menu_'+select_pin+'_'+cancel_pin+'==-1)&&(_option_'+select_pin+'_'+cancel_pin+'==-1))\n {'+Blockly.Arduino.statementToCode(this, 'GENERAL')+'\n }\n'; var i=0; for (i=0;i<this.menuCount_;i++) { code+=' else if ((_menu_'+select_pin+'_'+cancel_pin+'=='+i+')&&(_option_'+select_pin+'_'+cancel_pin+'==-1))\n {\n '+Blockly.Arduino.statementToCode(this,'MENU_HIGHLIGHTED'+i)+'\n }\n'; var optionInput = this.getInputTargetBlock('MENU'+i); if (optionInput) { var j=0; for (j=0;j<optionInput.optionCount_;j++) { code+=' else if ((_menu_'+select_pin+'_'+cancel_pin+'=='+i+')&&(_option_'+select_pin+'_'+cancel_pin+'=='+j+'))\n {\n if (_acceptUI_'+select_pin+'_'+cancel_pin+'==true)\n {\n '+Blockly.Arduino.statementToCode(optionInput,'OPTION_SELECTED'+j)+'\n }\n else\n {\n '+Blockly.Arduino.statementToCode(optionInput,'OPTION_HIGHLIGHTED'+j)+'\n }\n }\n'; } } } code+=' _acceptUI_'+select_pin+'_'+cancel_pin+'=false;\n }\n'; return code; }; Blockly.Blocks.two_buttons_ui = { category: Facilino.locales.getKey('LANG_CATEGORY_ADVANCED'), subcategory: Facilino.locales.getKey('LANG_SUBCATEGORY_BUTTON'), tags: ['input','output','button'], helpUrl: Facilino.getHelpUrl('two_buttons_ui'), examples: ['button_case_example.bly'], category_colour: Facilino.LANG_COLOUR_ADVANCED, colour: Facilino.LANG_COLOUR_ADVANCED_DIGITAL, keys: ['LANG_TWO_BUTTONS_UI','LANG_TWO_BUTTONS_UI_SELECT','LANG_TWO_BUTTONS_UI_CANCEL','LANG_BQ_BUTTON_TIME','LANG_TWO_BUTTONS_UI_TOOLTIP'], name: Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_NAME'), //bq_button initialization init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_DIGITAL); this.appendValueInput('PIN_SELECT').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/list.svg', 24*options.zoom, 24*options.zoom)).setCheck(['DigitalPin',Number]).appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_SELECT')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/digital_signal.svg', 22*options.zoom, 22*options.zoom)).setAlign(Blockly.ALIGN_RIGHT).setCheck('DigitalPin'); this.appendValueInput('PIN_CANCEL').setCheck(['DigitalPin',Number]).appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_CANCEL')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/digital_signal.svg', 22*options.zoom, 22*options.zoom)).setAlign(Blockly.ALIGN_RIGHT).setCheck('DigitalPin'); this.appendDummyInput('').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_TIME')).appendField(new Blockly.FieldNumber('5000','0'),'TIME').setAlign(Blockly.ALIGN_RIGHT); this.appendStatementInput('GENERAL').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_GENERAL')); this.appendStatementInput('MENU_HIGHLIGHTED0').setCheck('code').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_MENU')+'0 '+Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_HIGHLIGHTED')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/list_selected.svg', 24*options.zoom, 24*options.zoom)); this.appendValueInput('MENU0').setCheck('menu_options').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTIONS')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list.svg', 24*options.zoom, 24*options.zoom)).setAlign(Blockly.ALIGN_RIGHT); this.setOutput(false); this.setMutator(new Blockly.Mutator(['two_buttons_ui_item'])); this.setPreviousStatement(true,'code'); this.setInputsInline(false); this.setNextStatement(true,'code'); this.setTooltip(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_TOOLTIP')); this.menuCount_ = 1; }, default_inputs: function() { var xml=''; xml+='<value name="PIN_SELECT"><shadow type="pin_digital"><field name="PIN">'+Facilino.profiles.default.digital[0][1]+'</field></shadow></value>'; if (Facilino.profiles.default.digital.length>1) xml+='<value name="PIN_CANCEL"><shadow type="pin_digital"><field name="PIN">'+Facilino.profiles.default.digital[1][1]+'</field></shadow></value>'; else xml+='<value name="PIN_CANCEL"><shadow type="pin_digital"><field name="PIN">'+Facilino.profiles.default.digital[0][1]+'</field></shadow></value>'; xml+='<value name="MENU0"><shadow type="two_buttons_ui_option"></shadow></value>'; return xml; }, isNotDuplicable: true, mutationToDom: function() { if (!this.menuCount_) { return null; } var container = document.createElement('mutation'); if (this.menuCount_) { container.setAttribute('item', this.menuCount_); } return container; }, domToMutation: function(xmlElement) { this.menuCount_ = window.parseInt(xmlElement.getAttribute('item'), 10); for (var x = 1; x < this.menuCount_; x++) { this.appendStatementInput('MENU_HIGHLIGHTED'+x).setCheck('code').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_MENU')+x+' '+Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_HIGHLIGHTED')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/list_selected.svg', 24*options.zoom, 24*options.zoom)); this.appendValueInput('MENU' + x).setCheck('menu_options').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTIONS')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list.svg', 24*options.zoom, 24*options.zoom)).setAlign(Blockly.ALIGN_RIGHT); //this.appendStatementInput('DO' + x).appendField(Facilino.locales.getKey('LANG_CONTROLS_DO')).setAlign(Blockly.ALIGN_RIGHT).setCheck('code'); } }, decompose: function(workspace) { var containerBlock = workspace.newBlock('two_buttons_ui_stack'); containerBlock.initSvg(); var connection = containerBlock.getInput('STACK').connection; for (var x = 1; x < this.menuCount_; x++) { var taskBlock = workspace.newBlock('two_buttons_ui_item'); taskBlock.initSvg(); connection.connect(taskBlock.previousConnection); connection = taskBlock.nextConnection; } return containerBlock; }, compose: function(containerBlock) { // Disconnect all the task input blocks and remove the inputs. for (var x = this.menuCount_-1; x >= 1; x--) { this.removeInput('MENU_HIGHLIGHTED'+x); this.removeInput('MENU' + x); //this.removeInput('DO' + x); } this.menuCount_ = 1; // Rebuild the block's optional inputs. var clauseBlock = containerBlock.getInputTargetBlock('STACK'); while (clauseBlock) { switch (clauseBlock.type) { case 'two_buttons_ui_item': var menuStack = this.appendStatementInput('MENU_HIGHLIGHTED'+this.menuCount_).setCheck('code').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_MENU')+this.menuCount_+' '+Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_HIGHLIGHTED')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/list_selected.svg', 24*options.zoom, 24*options.zoom)); var menuInput = this.appendValueInput('MENU'+this.menuCount_).setCheck('menu_options').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTIONS')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list.svg', 24*options.zoom, 24*options.zoom)).setAlign(Blockly.ALIGN_RIGHT); this.menuCount_++; // Reconnect any child blocks. if (clauseBlock.valueConnection_) { menuInput.connection.connect(clauseBlock.valueConnection_); } break; default: throw 'Unknown block type.'; } clauseBlock = clauseBlock.nextConnection && clauseBlock.nextConnection.targetBlock(); } }, saveConnections: function(containerBlock) { // Store a pointer to any connected child blocks. var clauseBlock = containerBlock.getInputTargetBlock('STACK'); var x = 1; while (clauseBlock) { switch (clauseBlock.type) { case 'two_buttons_ui_item': var inputMenu = this.getInput('MENU' + x); clauseBlock.valueConnection_ = inputMenu && inputMenu.connection.targetConnection; x++; break; default: throw 'Unknown block type.'; } clauseBlock = clauseBlock.nextConnection && clauseBlock.nextConnection.targetBlock(); } } }; Blockly.Blocks.two_buttons_ui_stack = { colour: Facilino.LANG_COLOUR_ADVANCED_DIGITAL, keys: ['LANG_TWO_BUTTONS_UI','LANG_TWO_BUTTONS_UI_TOOLTIP'], // Task. init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_DIGITAL); this.appendDummyInput() .appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI')) .setAlign(Blockly.ALIGN_RIGHT); this.appendStatementInput('STACK').setCheck('menu'); this.setTooltip(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_TOOLTIP')); this.contextMenu = false; } }; Blockly.Blocks.two_buttons_ui_item = { colour: Facilino.LANG_COLOUR_ADVANCED_DIGITAL, // Task item. keys: ['LANG_TWO_BUTTONS_UI_MENU','LANG_TWO_BUTTONS_UI_MENU_TOOLTIP'], init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_DIGITAL); this.appendDummyInput() .appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_MENU')) .setAlign(Blockly.ALIGN_RIGHT); this.setPreviousStatement(true,'menu'); this.setNextStatement(true,'menu'); this.setTooltip(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_MENU_TOOLTIP')); this.contextMenu = false; } }; Blockly.Arduino.two_buttons_ui_option = function() { var code = ''; return code; }; Blockly.Blocks.two_buttons_ui_option = { category: Facilino.locales.getKey('LANG_CATEGORY_ADVANCED'), subcategory: Facilino.locales.getKey('LANG_SUBCATEGORY_BUTTON'), tags: ['input','output','button'], helpUrl: Facilino.getHelpUrl('two_buttons_ui_option'), examples: ['button_case_example.bly'], category_colour: Facilino.LANG_COLOUR_ADVANCED, colour: Facilino.LANG_COLOUR_ADVANCED_DIGITAL, keys: ['LANG_TWO_BUTTONS_UI_OPTION_NAME','LANG_TWO_BUTTONS_UI_OPTION_TOOLTIP'], name: Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION_NAME'), init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_DIGITAL); this.appendDummyInput('').appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list.svg', 24*options.zoom, 24*options.zoom)).appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTIONS')).setAlign(Blockly.ALIGN_RIGHT); this.setMutator(new Blockly.Mutator(['two_buttons_ui_option_item'])); this.appendStatementInput('OPTION_HIGHLIGHTED0').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION')+'0 '+Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_HIGHLIGHTED')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list_highlighted.svg', 24*options.zoom, 24*options.zoom)).setAlign(Blockly.ALIGN_RIGHT).setCheck('code'); this.appendStatementInput('OPTION_SELECTED0').setCheck('code').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION')+'0 '+Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_SELECTED')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list_selected.svg', 24*options.zoom, 24*options.zoom)).setAlign(Blockly.ALIGN_RIGHT); this.setPreviousStatement(false,null); this.setInputsInline(false); this.setNextStatement(false,null); this.setTooltip(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION_TOOLTIP')); this.setOutput(true,'menu_options'); this.optionCount_ = 1; }, mutationToDom: function() { if (!this.optionCount_) { return null; } var container = document.createElement('mutation'); if (this.optionCount_) { container.setAttribute('item', this.optionCount_); } return container; }, domToMutation: function(xmlElement) { this.optionCount_ = window.parseInt(xmlElement.getAttribute('item'), 10); for (var x = 1; x < this.optionCount_; x++) { this.appendStatementInput('OPTION_HIGHLIGHTED' + x).appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION')+x+' '+Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_HIGHLIGHTED')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list_highlighted.svg', 24*options.zoom, 24*options.zoom)).setAlign(Blockly.ALIGN_RIGHT).setCheck('code'); this.appendStatementInput('OPTION_SELECTED'+x).setCheck('code').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION')+x+' '+Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_SELECTED')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list_selected.svg', 24*options.zoom, 24*options.zoom)).setAlign(Blockly.ALIGN_RIGHT); } }, decompose: function(workspace) { var containerBlock = workspace.newBlock('two_buttons_ui_option_stack'); containerBlock.initSvg(); var connection = containerBlock.getInput('STACK').connection; for (var x = 1; x < this.optionCount_; x++) { var taskBlock = workspace.newBlock('two_buttons_ui_option_item'); taskBlock.initSvg(); connection.connect(taskBlock.previousConnection); connection = taskBlock.nextConnection; } return containerBlock; }, compose: function(containerBlock) { // Disconnect all the task input blocks and remove the inputs. for (var x = this.optionCount_-1; x >= 1; x--) { this.removeInput('OPTION_HIGHLIGHTED' + x); this.removeInput('OPTION_SELECTED'+x); } this.optionCount_ = 1; // Rebuild the block's optional inputs. var clauseBlock = containerBlock.getInputTargetBlock('STACK'); while (clauseBlock) { switch (clauseBlock.type) { case 'two_buttons_ui_option_item': var option = this.appendStatementInput('OPTION_HIGHLIGHTED'+this.optionCount_).setCheck('code').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION')+this.optionCount_+' '+Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_HIGHLIGHTED')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list_highlighted.svg', 24*options.zoom, 24*options.zoom)).setAlign(Blockly.ALIGN_RIGHT); var optionSelected = this.appendStatementInput('OPTION_SELECTED'+this.optionCount_).setCheck('code').appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION')+this.optionCount_+' '+Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_SELECTED')).appendField(new Blockly.FieldImage(Facilino.path+'img/blocks/option_list_selected.svg', 24*options.zoom, 24*options.zoom)).setAlign(Blockly.ALIGN_RIGHT); this.optionCount_++; // Reconnect any child blocks. if (clauseBlock.valueConnection_) { optionSelected.connection.connect(clauseBlock.valueConnection_); option.connection.connect(clauseBlock.valueConnection_); } break; default: throw 'Unknown block type.'; } clauseBlock = clauseBlock.nextConnection && clauseBlock.nextConnection.targetBlock(); } }, saveConnections: function(containerBlock) { // Store a pointer to any connected child blocks. var clauseBlock = containerBlock.getInputTargetBlock('STACK'); var x = 0; while (clauseBlock) { switch (clauseBlock.type) { case 'two_buttons_ui_option_item': var inputOption = this.getInput('OPTION' + x); clauseBlock.valueConnection_ = inputOption && inputOption.connection.targetConnection; x++; break; default: throw 'Unknown block type.'; } clauseBlock = clauseBlock.nextConnection && clauseBlock.nextConnection.targetBlock(); } } }; Blockly.Blocks.two_buttons_ui_option_stack = { colour: Facilino.LANG_COLOUR_ADVANCED_DIGITAL, keys: ['LANG_TWO_BUTTONS_UI_MENU','LANG_TWO_BUTTONS_UI_OPTION_TOOLTIP'], // Task. init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_DIGITAL); this.appendDummyInput() .appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_MENU')) .setAlign(Blockly.ALIGN_RIGHT); this.appendStatementInput('STACK').setCheck('option'); this.setTooltip(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION_TOOLTIP')); this.contextMenu = false; } }; Blockly.Blocks.two_buttons_ui_option_item = { colour: Facilino.LANG_COLOUR_ADVANCED_DIGITAL, // Task item. keys: ['LANG_TWO_BUTTONS_UI_OPTION','LANG_TWO_BUTTONS_UI_OPTION_TOOLTIP'], init: function() { this.setColour(Facilino.LANG_COLOUR_ADVANCED_DIGITAL); this.appendDummyInput() .appendField(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION')) .setAlign(Blockly.ALIGN_RIGHT); this.setPreviousStatement(true,'option'); this.setNextStatement(true,'option'); this.setTooltip(Facilino.locales.getKey('LANG_TWO_BUTTONS_UI_OPTION_TOOLTIP')); this.contextMenu = false; } }; } }; var FacilinoButtons = { load: load }; if (typeof define === 'function' && define.amd) { return FacilinoButtons; } else { window.FacilinoButtons = FacilinoButtons; } }));
import { InputType, Float, Field } from "@nestjs/graphql"; import { IsNotEmpty, IsOptional, IsPositive } from "class-validator"; @InputType() export class CreateCocineroInput { @Field(() => String) @IsNotEmpty() nombre: string; @Field(() => Float) @IsPositive() sueldoBasico: number; @Field(() => Boolean) @IsOptional() estado: boolean; }
# 22 UX Writing The Voice and Tone Part 1 ## _Resume_ Pada materi ini, saya mempelajari : ``` 1. Apa itu Microcopy 2. Voice and Tone Design 3. Conversational Writing ``` # Apa itu Design System Menurut Kinneret Yiffrah, microcopy adalah kata atau frasa di UI yang terkait langsung dengan tindakan yang dilakukan user : ``` 1. Motivasi sebelum tindakan 2. Instruksi yang menyertai tindakan 3. Feedback setelah user mengambil tindakan ``` ### Peran Microcopy di UX : Selama bertahun-tahun, trennya adalah membuat interface itu "clean". Banyak orang mengklaim bahwa kata-kata membebani interface dan dianggap sebagai ancaman oleh user. Di sisi lain, juga meminimalkan pentingnya kata-kata dan menegaskan tidak ada yang membacanya. Dengan kata lain, jika kalian ingin membuat interface yang terdengar “manusia” dan berhubungan dengan orang yang menggunakannya, kalian perlu kata-kata (copies). ### Dampak Microcopy di UI Ada 3 dampak yang sering ditemui : ``` 1. Menciptakan experience yang positif dan melibatkan user 2. Meningkatkan dari sisi usability 3. Meningkatkan branding dan diferensiasi ``` # Voice and Tone Design Voice and Tone Design menentukan bahasa yang akan digunakan pada brand saat berkomunikasi dengan user di UI kalian. # Conversational Writing Dalam praktiknya, sebagian besar UI digital jauh dari kesan manusia. Tulisannya sering kali bersifat robotik, dan tidak menimbulkan rasa perhatian secara personal.
import type { PuppetInstance } from '../index'; export async function setOrgIpPools(options: { puppetInstance: PuppetInstance; orgId: number; orgPublicId: string; poolId: string | string[]; }): Promise<{ orgId: number; pools: string[]; }> { try { const poolIds = Array.isArray(options.poolId) ? options.poolId : [options.poolId]; const enabledPools = []; await options.puppetInstance.page.goto( `${options.puppetInstance.url}/org/${options.orgPublicId}/ip_pools` ); await options.puppetInstance.page.waitForNetworkIdle(); await options.puppetInstance.page.waitForSelector(`input[type='checkbox']`); const poolCheckboxes = await options.puppetInstance.page.$$( `input[type='checkbox']` ); for (const checkBox of poolCheckboxes) { const checkBoxId = await (await checkBox.getProperty('id')).jsonValue(); const status = await (await checkBox.getProperty('checked')).jsonValue(); if (poolIds.includes(checkBoxId) && !status) { await checkBox.click(); // enable the checkbox enabledPools.push(checkBoxId); } if (!poolIds.includes(checkBoxId) && status) { await checkBox.click(); // disable the checkbox } } await options.puppetInstance.page.click('[name="commit"]'); await options.puppetInstance.page.waitForNetworkIdle(); return { orgId: options.orgId, pools: enabledPools }; } catch (error: any) { console.log('Postal: setOrgIpPools Error:', error); throw new Error(error); } }
import mysql.connector import GuiDBConfig as guiConf class MySQL(): # class attribute GUIDB = 'GuiDB' # ------------------------------------------------ def connect(self): # connect by unpacking dictionary credentials conn = mysql.connector.connect(**guiConf.dbConfig) # create cursor cursor = conn.cursor() return conn, cursor # ------------------------------------------------ def close(self, cursor, conn): # close cursor cursor.close() # close connection to MySQL conn.close() # ------------------------------------------------ def showDBs(self): # connect to MySQL conn, cursor = self.connect() # print results cursor.execute("SHOW DATABASES") print(cursor) print(cursor.fetchall()) # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def createGuiDB(self): # connect to MySQL conn, cursor = self.connect() try: cursor.execute( "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'".format(MySQL.GUIDB)) except mysql.connector.Error as err: print("Failed to create DB: {}".format(err)) # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def dropGuiDB(self): # connect to MySQL conn, cursor = self.connect() try: cursor.execute( "DROP DATABASE {}".format(MySQL.GUIDB)) except mysql.connector.Error as err: print("Failed to drop DB: {}".format(err)) # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def useGuiDB(self, cursor): '''Expects open connection.''' # select DB cursor.execute("USE guidb") # ------------------------------------------------ def createTables(self): # connect to MySQL conn, cursor = self.connect() self.useGuiDB(cursor) # create Table inside DB cursor.execute("CREATE TABLE Books ( \ Book_ID INT NOT NULL AUTO_INCREMENT, \ Book_Title VARCHAR(25) NOT NULL, \ Book_Page INT NOT NULL, \ PRIMARY KEY (Book_ID) \ ) ENGINE=InnoDB") # create second Table inside DB cursor.execute("CREATE TABLE Quotations ( \ Quote_ID INT AUTO_INCREMENT, \ Quotation VARCHAR(250), \ PRIMARY KEY (Quote_ID), \ FOREIGN KEY (Books_Book_ID) \ REFERENCES Books(Book_ID) \ ON DELETE CASCADE \ ) ENGINE=InnoDB") # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def dropTables(self): # connect to MySQL conn, cursor = self.connect() self.useGuiDB(cursor) cursor.execute("DROP TABLE quotations") cursor.execute("DROP TABLE books") # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def showTables(self): # connect to MySQL conn, cursor = self.connect() # show Tables from guidb DB cursor.execute("SHOW TABLES FROM guidb") print(cursor.fetchall()) # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def insertBooks(self, title, page, bookQuote): # connect to MySQL conn, cursor = self.connect() self.useGuiDB(cursor) # insert data cursor.execute("INSERT INTO books (Book_Title, Book_Page) VALUES (%s,%s)", (title, page)) # last inserted auto increment value keyID = cursor.lastrowid # print(keyID) cursor.execute("INSERT INTO quotations (Quotation, Books_Book_ID) VALUES (%s, %s)", \ (bookQuote, keyID)) # commit transaction conn.commit() # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def insertBooksExample(self): # connect to MySQL conn, cursor = self.connect() self.useGuiDB(cursor) # insert hard-coded data cursor.execute("INSERT INTO books (Book_Title, Book_Page) VALUES ('Design Patterns', 17)") # last inserted auto increment value keyID = cursor.lastrowid print(keyID) cursor.execute("INSERT INTO quotations (Quotation, Books_Book_ID) VALUES (%s, %s)", \ ('Programming to an Interface, not an Implementation', keyID)) # commit transaction conn.commit() # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def showBooks(self): # connect to MySQL conn, cursor = self.connect() self.useGuiDB(cursor) # print results cursor.execute("SELECT * FROM Books") allBooks = cursor.fetchall() print(allBooks) # close cursor and connection self.close(cursor, conn) return allBooks # ------------------------------------------------ def showColumns(self): # connect to MySQL conn, cursor = self.connect() self.useGuiDB(cursor) # execute command cursor.execute("SHOW COLUMNS FROM quotations") print(cursor.fetchall()) print('\n Pretty Print:\n--------------') from pprint import pprint # execute command cursor.execute("SHOW COLUMNS FROM quotations") pprint(cursor.fetchall()) # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def showData(self): # connect to MySQL conn, cursor = self.connect() self.useGuiDB(cursor) # execute command cursor.execute("SELECT * FROM books") print(cursor.fetchall()) cursor.execute("SELECT * FROM quotations") print(cursor.fetchall()) # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def updateGOF_commit(self, title, quote): # connect to MySQL conn, cursor = self.connect() cursor = conn.cursor(buffered=True) self.useGuiDB(cursor) # execute command cursor.execute("SELECT Book_ID FROM books WHERE Book_Title = 'Design Patterns'") primKey = cursor.fetchall()[0][0] # print(primKey) cursor.execute("SELECT * FROM quotations WHERE Books_Book_ID = (%s)", (primKey,)) # print(cursor.fetchall()) cursor.execute("UPDATE quotations SET Quotation = (%s) WHERE Books_Book_ID = (%s)", \ ("Pythonic Duck Typing: If it walks like a duck and talks like a duck it probably is a duck...", primKey)) # commit transaction conn.commit() cursor.execute("SELECT * FROM quotations WHERE Books_Book_ID = (%s)", (primKey,)) print(cursor.fetchall()) # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def showDataWithReturn(self): # connect to MySQL conn, cursor = self.connect() self.useGuiDB(cursor) # execute command cursor.execute("SELECT * FROM books") booksData = cursor.fetchall() cursor.execute("SELECT * FROM quotations") quoteData = cursor.fetchall() # close cursor and connection self.close(cursor, conn) # print(booksData, quoteData) for record in quoteData: print(record) return booksData, quoteData # ------------------------------------------------ def deleteRecord(self): # connect to MySQL conn, cursor = self.connect() self.useGuiDB(cursor) try: # execute command cursor.execute("SELECT Books_ID FROM books WHERE Book_Title = 'Design Patterns'") primKey = cursor.fetchall()[0][0] # print(primKey) cursor.execute("DELETE FROM books WHERE Book_ID = (%s)", (primKey,)) # commit transaction conn.commit() except: pass # close cursor and connection self.close(cursor, conn) # ------------------------------------------------ def ModyQuote(self): title = self.bookTitle.get() if __name__ == '__main__': mySQL = MySQL() # mySQL.showData() # mySQL.createTablesNoFK() # mySQL.insertnBooksExample() # mySQL.insertnBooksExample() # mySQL.insertnBooksExample() # nbooks에 삽입되도록 코드 수정 mySQL.updateGOF_commit() # nbooks에 삽입되도록 코드 수정, 데이터 업데이트 book, quote = mySQL.showDataWithReturn() print(book, quote) try: mySQL.createTables() mySQL.showTables() # -------------------- mySQL.showBooks() # -------------------- mySQL.showColumns() # -------------------- mySQL.insertBooksExample() # -------------------- mySQL.insertBooks('Design Patterns', 7, 'Programming to an Interface, not an Implementation') mySQL.insertBooks('xUnit Test Patterns', 31, 'Philosophy of Test Automation') mySQL.showData() except Exception as ex: print(ex)
let weather = { "apiKey": "6cf35140277e3103ec57d264df4cddff", fetchWeather: function (city) { fetch( "https://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + this.apiKey ).then((response) => response.json() ).then((data) => this.displayWeather(data)); }, displayWeather: function(data) { const { name } = data; const { icon, description } = data.weather[0]; const { temp, humidity } = data.main; const { speed } = data.wind; console.log(name,icon,description,temp,humidity,speed); document.querySelector(".city").innerText = "Weather in " + name; document.querySelector(".icon").src = "https://openweathermap.org/img/wn/" + icon + ".png"; document.querySelector(".description").innerText = description; document.querySelector(".temp").innerText = temp + "°K"; document.querySelector(".humidity").innerText = "Humidity :" + humidity + "%" document.querySelector(".wind").innerText = "Wind speed :" + speed + "km/h" document.querySelector(".weather").classList.remove("loading"); document.body.style.backgroundImage = "url('https://source.unsplash.com/1600x900/?" + name + "')" }, search: function () { this.fetchWeather(document.querySelector(".search-bar").value) } }; document .querySelector(".search button") .addEventListener("click", function () { weather.search(); }); document .querySelector(".search-bar") .addEventListener("keyup", function (event) { if (event.key == "Enter") { weather.search(); } }); weather.fetchWeather("Tbilisi");
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use App\Providers\RouteServiceProvider; use Illuminate\Foundation\Auth\AuthenticatesUsers; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { /* |-------------------------------------------------------------------------- | Login Controller |-------------------------------------------------------------------------- | | This controller handles authenticating users for the application and | redirecting them to your home screen. The controller uses a trait | to conveniently provide its functionality to your applications. | */ use AuthenticatesUsers; /** * Where to redirect users after login. * * @var string */ // protected $redirectTo = '/product'; protected function redirectTo() { $logging_in_user_id = Auth::id();//Auth::user() to fetch all record of the loggin in user. $admin_panel_allowed = auth()->user()->isAllowed($logging_in_user_id); if ($admin_panel_allowed) { return '/product'; } return '/'; } /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('guest')->except('logout'); } }
require 'rails_helper' feature 'User can delete links added to their question', %q{ In order to delete wrong link As a question's author I'd like to be able to delete links } do given(:user) { create(:user) } given!(:question) { create(:question, :with_link, author: user) } given!(:other_question) { create(:question, :with_link) } describe 'Authenticated user' do background { sign_in(user) } scenario 'tries to delete link on their question', js: true do visit question_path(question) within '.links' do click_on 'Delete' expect(page).to_not have_link 'Google' end end scenario 'tries to delete link on other user question' do visit question_path(other_question) within '.links' do expect(page).to_not have_link 'Delete' end end end scenario 'Unauthenticated user tries to delete link on question' do visit question_path(question) within '.links' do expect(page).to_not have_link 'Delete' end end end
import { Component, OnInit } from '@angular/core'; import {Cliente} from '../../shared/model/cliente'; import {ActivatedRoute} from '@angular/router'; import {ClienteService} from '../../shared/services/cliente.service'; @Component({ selector: 'app-cadastro-cliente', templateUrl: './cadastro-cliente.component.html', styleUrls: ['./cadastro-cliente.component.scss'] }) export class CadastroClienteComponent implements OnInit { clienteAtual: Cliente; inserindo: boolean = true; nomeBotao: string = 'Inserir'; constructor(private rotaAtual: ActivatedRoute, private clienteService: ClienteService) { this.clienteAtual = new Cliente('', 0, '', '', ''); if (rotaAtual.snapshot.paramMap.has('id')) { const idParaEdicao = rotaAtual.snapshot.paramMap.get('id'); if (idParaEdicao) { this.inserindo = false; this.nomeBotao = 'Atualizar'; const clienteEncontrado = this.clienteService.pesquisarPorId(idParaEdicao).subscribe( clienteEncontrado => this.clienteAtual = clienteEncontrado ); } } } ngOnInit() { } inserirOuAtualizarCliente() { if (this.inserindo) { this.clienteService.inserir(this.clienteAtual).subscribe( clienteInserido => console.log(clienteInserido) ); this.clienteAtual = new Cliente('', 0, '', '', ''); } else { this.clienteService.atualizar(this.clienteAtual).subscribe( clienteAtualizado => console.log(clienteAtualizado) ) } } atualizaNome(novoNome: string) { this.clienteAtual.nome = novoNome; } }
/* * Copyright (c) 2021-2023 Huawei Device Co., Ltd. * 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. */ /** * @file * @kit ArkUI */ /** * The information of sheet. * * @interface SheetInfo * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * The information of sheet. * * @interface SheetInfo * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * The information of sheet. * * @interface SheetInfo * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ interface SheetInfo { /** * Title Properties * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Title Properties * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Title Properties * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ title: string | Resource; /** * Icon Properties. * * @type { ?(string | Resource) } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Icon Properties. * * @type { ?(string | Resource) } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Icon Properties. * * @type { ?(string | Resource) } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ icon?: string | Resource; /** * Callback method after the operation. * * @type { function } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Callback method after the operation. * * @type { function } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Callback method after the operation. * * @type { function } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ action: () => void; } /** * Component dialog dismiss action. * * @interface DismissDialogAction * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ declare interface DismissDialogAction { /** * Defines dialog dismiss function. * * @type { Callback<void> } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ dismiss: Callback<void>; /** * Dismiss reason type. * * @type { DismissReason } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ reason: DismissReason; } /** * The options of ActionSheet. * * @interface ActionSheetOptions * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * The options of ActionSheet. * * @interface ActionSheetOptions * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * The options of ActionSheet. * * @interface ActionSheetOptions * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ interface ActionSheetOptions { /** * Title Properties * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Title Properties * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Title Properties * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ title: string | Resource; /** * Subtitle Properties * @type { ?ResourceStr } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Subtitle Properties * @type { ?ResourceStr } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ subtitle?: ResourceStr; /** * message Properties * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * message Properties * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * message Properties * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ message: string | Resource; /** * Invoke the commit function. * * @type { ?object } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Invoke the commit function. * * @type { ?object } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Invoke the commit function. * * @type { ?object } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ confirm?: { /** * Enable switch of confirmation button * @type { ?boolean } * @default true * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Enable switch of confirmation button * @type { ?boolean } * @default true * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ enabled?: boolean; /** * Default focus switch of confirmation button * @type { ?boolean } * @default false * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Default focus switch of confirmation button * @type { ?boolean } * @default false * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ defaultFocus?: boolean; /** * Style of confirmation button. * @type { ?DialogButtonStyle } * @default DialogButtonStyle.DEFAULT * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Style of confirmation button. * @type { ?DialogButtonStyle } * @default DialogButtonStyle.DEFAULT * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ style?: DialogButtonStyle; /** * Text content of the confirmation button. * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Text content of the confirmation button. * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Text content of the confirmation button. * * @type { string | Resource } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ value: string | Resource; /** * Method executed by the callback. * * @type { function } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Method executed by the callback. * * @type { function } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Method executed by the callback. * * @type { function } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ action: () => void; }; /** * Execute Cancel Function. * * @type { ?function } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Execute Cancel Function. * * @type { ?function } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Execute Cancel Function. * * @type { ?function } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ cancel?: () => void; /** * The Array of sheets * * @type { Array<SheetInfo> } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * The Array of sheets * * @type { Array<SheetInfo> } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * The Array of sheets * * @type { Array<SheetInfo> } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ sheets: Array<SheetInfo>; /** * Allows users to click the mask layer to exit. * * @type { ?boolean } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Allows users to click the mask layer to exit. * * @type { ?boolean } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Allows users to click the mask layer to exit. * * @type { ?boolean } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ autoCancel?: boolean; /** * Alignment in the vertical direction. * * @type { ?DialogAlignment } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Alignment in the vertical direction. * * @type { ?DialogAlignment } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Alignment in the vertical direction. * * @type { ?DialogAlignment } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ alignment?: DialogAlignment; /** * Offset of the pop-up window relative to the alignment position. * * @type { ?object } * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Offset of the pop-up window relative to the alignment position. * * @type { ?object } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Offset of the pop-up window relative to the alignment position. * * @type { ?object } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ offset?: { dx: number | string | Resource; dy: number | string | Resource }; /** * Mask Region of dialog. The size cannot exceed the main window. * * @type { ?Rectangle } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Mask Region of dialog. The size cannot exceed the main window. * * @type { ?Rectangle } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ maskRect?: Rectangle; /** * Whether to display in the sub window. * * @type { ?boolean } * @default false * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 11 */ /** * Whether to display in the sub window. * * @type { ?boolean } * @default false * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 12 */ showInSubWindow?: boolean; /** * Whether it is a modal dialog * @type { ?boolean } * @default true * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 11 */ /** * Whether it is a modal dialog * @type { ?boolean } * @default true * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 12 */ isModal?: boolean; /** * Defines the actionSheet's background color * * @type { ?ResourceColor } * @default Color.Transparent * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 11 */ /** * Defines the actionSheet's background color * * @type { ?ResourceColor } * @default Color.Transparent * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 12 */ backgroundColor?: ResourceColor; /** * Defines the actionSheet's background blur Style * * @type { ?BlurStyle } * @default BlurStyle.COMPONENT_ULTRA_THICK * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 11 */ /** * Defines the actionSheet's background blur Style * * @type { ?BlurStyle } * @default BlurStyle.COMPONENT_ULTRA_THICK * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 12 */ backgroundBlurStyle?: BlurStyle; /** * Callback function when the actionSheet interactive dismiss * * @type { ?Callback<DismissDialogAction> } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ onWillDismiss?: Callback<DismissDialogAction>; /** * Transition parameters of opening/closing ActionSheet. * * @type { ?TransitionEffect } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ transition?: TransitionEffect; /** * Defines the actionSheet's corner radius. * * @type { ?(Dimension | BorderRadiuses | LocalizedBorderRadiuses) } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ cornerRadius?: Dimension | BorderRadiuses | LocalizedBorderRadiuses; /** * Defines the actionSheet's width. * * @type { ?Dimension } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ width?: Dimension; /** * Defines the actionSheet's height. * * @type { ?Dimension } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ height?: Dimension; /** * Defines the actionSheet's border width. * * @type { ?(Dimension | EdgeWidths | LocalizedEdgeWidths) } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ borderWidth?: Dimension | EdgeWidths | LocalizedEdgeWidths; /** * Defines the actionSheet's border color. * * @type { ?(ResourceColor | EdgeColors | LocalizedEdgeColors) } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ borderColor?: ResourceColor | EdgeColors | LocalizedEdgeColors; /** * Defines the actionSheet's border style. * * @type { ?(BorderStyle | EdgeStyles) } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ borderStyle?: BorderStyle | EdgeStyles; /** * Defines the actionSheet's shadow. * * @type { ?(ShadowOptions | ShadowStyle) } * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 12 */ shadow?: ShadowOptions | ShadowStyle; } /** * Declare the ActionSheet * * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Declare the ActionSheet * * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Declare the ActionSheet * * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ declare class ActionSheet { /** * Invoking method display. * * @param { ActionSheetOptions } value * @syscap SystemCapability.ArkUI.ArkUI.Full * @since 8 */ /** * Invoking method display. * * @param { ActionSheetOptions } value * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @since 10 */ /** * Invoking method display. * * @param { ActionSheetOptions } value * @syscap SystemCapability.ArkUI.ArkUI.Full * @crossplatform * @atomicservice * @since 11 */ static show(value: ActionSheetOptions); }
import React, { useEffect, useState } from 'react'; import { Layout, Menu } from 'antd'; import { useRouter } from 'next/router'; import HeaderDashboard from './HeaderDashboard'; import { PreImage } from '@/components/common/PreImage'; import { useAppDispatch } from '@/hooks/useRedux'; import { getCookie } from 'cookies-next'; import { APP_SAVE_KEY } from '@/utils/constants'; import { login } from 'src/shared/stores/appSlice'; import jwt_decode from 'jwt-decode'; import { IInforUserStored } from 'src/shared/types/user.type'; import { menuAdmin, menuUser } from '@/mocks/menu/dashboard'; import { useTheme } from 'next-themes'; const { Content, Footer, Sider } = Layout; interface Props { children: React.ReactNode; } const DashboardLayout = ({ children }: Props) => { const { theme } = useTheme() const [isAdmin, setIsAdmin] = useState(false) const router = useRouter(); const currentPath = router.pathname; const dispatch = useAppDispatch(); useEffect(() => { const token = getCookie(APP_SAVE_KEY.TOKEN_KEY); if (!token) { router.push('/login'); } else { const decodeData: IInforUserStored = jwt_decode(token as string); if (decodeData.role === "Admin") { setIsAdmin(true) } else { setIsAdmin(false) } dispatch(login(decodeData)); } }, []); return ( <> <Layout style={{ minHeight: '100vh' }}> <Sider style={{ backgroundColor: theme === 'light' ? "#fff" : "#001629" }}> <div className='flex justify-center items-center'> <PreImage className='cursor-pointer' height={100} width={100} src={'/Logo2.png'} alt={'Logo'} layer={false} onClick={() => router.push("/")} /> </div> <Menu className='items-start justify-start' onClick={item => router.push(item.key)} theme={theme === 'light' ? 'light' : 'dark'} defaultSelectedKeys={[`${currentPath.split('/').splice(0, 3).join('/')}` || `${currentPath}`]} mode='inline' items={isAdmin ? menuAdmin : menuUser} ></Menu> </Sider> <Layout> <HeaderDashboard /> <Content className='m-6 min-h-screen rounded-lg light:bg-white mobile:m-4'> <div className='p-2'>{children}</div> </Content> <Footer style={{ textAlign: 'center' }}>Copyright ©2023 Created by Coffee Information&Service 2023</Footer> </Layout> </Layout> </> ); }; export default DashboardLayout;
/** * TASK 1 * * @param {number} num - number that must be reversed * @returns {number} - reversed number * */ function reverseNum(num){ let digit, reversedNum = 0; while (num) { digit = num % 10; reversedNum = (reversedNum * 10) + digit; num = num/10 | 0; // using bitwise operator to take integer part } return reversedNum; } /** * TASK 2 * * @param {string} text - string that must be checked * @returns {boolean} - returns true if string is palindrome */ function isPalindrome(text){ for (let i=0; i<text.length/2;i++) { if(text.at(i) != text.at(-1)) { console.log("Given string is NOT palindrome!"); return false; } console.log("Given string is palindrome!"); return true; } } /** * TASK 3 * * @param {String} text - String parameter * @returns [] - Array of all combinations */ function stringCombinations(text) { let combinations = []; let i = 0; while(i < text.length) { let char = text.charAt(i); let arrTemp = [char]; for (let x of combinations) { arrTemp.push("" + x + char); } combinations = combinations.concat(arrTemp); i++; } return combinations; } console.log(stringCombinations("dog")); /** * TASK 4 * * @param {String} text - String which will be sorted * @returns {String} - Sorted string */ function sortInAlphabeticalOrder(text) { const sortedArray = Array.from(text).sort(); const sortedString = sortedArray.join(''); return sortedString; } /** * TASK 5 * * @param {String} text - Parameter whose each words' first letters will be converted to upper case * @returns {String} - Already converted string */ function firstLetterUpperCase(text) { let result = text.split(" "); for (let i = 0; i < result.length; i++) { result[i] = result[i].charAt(0).toUpperCase() + result[i].slice(1); } return result.join(" "); } /** * TASK 6 * * @param {String} text - String in which we must find the longest word * @returns {String} - The longest word */ function findLongestWord(text) { let stringArray = text.split(" "); let longest = text[0]; for(let i = 1; i < stringArray.length; i++) { if (stringArray[i].length > longest.length) { longest = stringArray[i]; } } return longest; } /** * TASK 7 * * @param {String} text - Text which function will check for vowels * @returns {Number} - Number of vowel letters */ function countVowels(text) { let vowels = ['a','e','i','o','u']; let vowelCount = 0; for (let i of text.toLowerCase()) { if(vowels.includes(i)) { vowelCount++; } } return vowelCount; } /** * TASK 8 * * @param {Number} num - Number which will be checked if it's prime or not * @returns {Boolean} - Return value after checking */ function isPrime (num) { if (num === 1){ return false; } else if (num === 2) { return true; } else { for(let i = 2; i < num; i++) { if (num % i === 0){ return false; } } return true; } } /** * * @param {*} parameter - Value whose type function detects * @returns {*} - Type name */ function checkType(parameter) { let types = ['object', 'boolean', 'function', 'number', 'string', 'undefined']; for (let i = 0; i < types.length; i++) { if (typeof parameter === types[i]) { return types[i]; } } } /** * TASK 10 * * @param {Number} size - Size of rows and columns * @returns {[]} - 2D array of identity matrix */ function makeIdentityMatrix(size) { let identityMatrix = []; for (let i = 0; i < size; i++) { for(let j = 0; j < size; j++){ identityMatrix.push(i === j ? 1 : 0); } } return identityMatrix; }
import argparse import numpy as np import pandas as pd import sys import random from functools import partial from collections import defaultdict from sklearn import metrics from multiprocessing import Pool import load_data as ld import set_analysis_func as func if __name__=='__main__': parser = argparse.ArgumentParser( description='calculate gene sets similarity in a embedding space') parser.add_argument('--emb', dest='emb_f', type=str, help='input file path and file name for embedding') parser.add_argument('--genelist', dest='genelist_f', type=str, help='input file path and file name for embedding genes') parser.add_argument('--geneset1', dest='geneset1_f', type=str, help='input file path and file name for the first gene set database') parser.add_argument('--geneset2', dest='geneset2_f', type=str, help='input file path and file name for the second gene set database') parser.add_argument('--out', dest='out_f', type=str, help='output file path and name') parser.add_argument('-n', '--n_processor', dest='n_process', type=int, default=10, help='number of processors') parser.add_argument('--min', dest='min_size', type=int, default=10, help='the minimum number of genes in a set') parser.add_argument('--max', dest='max_size', type=int, default=300, help='the maximum number of genes in a set') args = parser.parse_args() # load embedding node_vectors = np.loadtxt(args.emb_f, delimiter=',') node_list = [] with open(args.genelist_f, 'r') as f: for line in f: node_list.append(line.strip()) print('finish load embedding') if len(node_list)!=node_vectors.shape[0]: print('embedding dimension must match the number of gene ids') sys.exit() print(str(len(node_list)), 'genes') S = metrics.pairwise.cosine_similarity(node_vectors, node_vectors) # create gene to embedding id mapping g_node2index = {j:i for i,j in enumerate(node_list)} g_index2node = {i:j for i,j in enumerate(node_list)} g_node2index = defaultdict(lambda:-1, g_node2index) # load gene set data geneset1 = ld.load_gmt(args.geneset1_f) geneset1_indices = ld.term2indexes( geneset1, g_node2index, upper=args.max_size, lower=args.min_size) geneset2 = ld.load_gmt(args.geneset2_f) geneset2_indices = ld.term2indexes( geneset2, g_node2index, upper=args.max_size, lower=args.min_size) # get background genes geneset1_all_genes = set() for x in geneset1: geneset1_all_genes = geneset1_all_genes.union(geneset1[x]) geneset1_all_genes = geneset1_all_genes.intersection(node_list) geneset1_all_indices = [g_node2index[x] for x in geneset1_all_genes] geneset1_terms = list(geneset1_indices) geneset2_all_genes = set() for x in geneset2: geneset2_all_genes = geneset2_all_genes.union(geneset2[x]) geneset2_all_genes = geneset2_all_genes.intersection(node_list) geneset2_all_indices = [g_node2index[x] for x in geneset2_all_genes] geneset2_terms = list(geneset2_indices) print('database 1:', str(len(geneset1_terms)), 'terms,', str(len(geneset1_all_indices)), 'background genes') print('database 2:', str(len(geneset2_terms)), 'terms,', str(len(geneset2_all_indices)), 'background genes') # define andes function f = partial(func.andes, matrix=S, g1_term2index=geneset1_indices, g2_term2index=geneset2_indices, g1_population=geneset1_all_indices, g2_population=geneset2_all_indices) all_terms = [(x,y) for x in geneset1_terms for y in geneset2_terms] shuffled_terms = random.sample(all_terms, len(all_terms)) geneset1_term2index = {j:i for i,j in enumerate(geneset1_terms)} geneset2_term2index = {j:i for i,j in enumerate(geneset2_terms)} with Pool(args.n_process) as p: rets = p.map(f, shuffled_terms) zscores = np.zeros((len(geneset1_terms), len(geneset2_terms))) for i, (x,y) in enumerate(shuffled_terms): idx = geneset1_term2index[x] idy = geneset2_term2index[y] zscores[idx, idy] = rets[i][1] zscores = pd.DataFrame(zscores, index=geneset1_terms, columns=geneset2_terms) zscores.to_csv(args.out_f, sep=',')
# Copyright (c) Microsoft. All rights reserved. import semantic_kernel as sk from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion from semantic_kernel.core_plugins import ( MathPlugin, TextPlugin, TimePlugin, ) from semantic_kernel.planners import ActionPlanner async def main(): kernel = sk.Kernel() api_key, org_id = sk.openai_settings_from_dot_env() service_id = "chat-gpt" kernel.add_service( OpenAIChatCompletion(service_id=service_id, ai_model_id="gpt-3.5-turbo", api_key=api_key, org_id=org_id) ) kernel.import_plugin_from_object(MathPlugin(), "math") kernel.import_plugin_from_object(TimePlugin(), "time") kernel.import_plugin_from_object(TextPlugin(), "text") # create an instance of action planner. planner = ActionPlanner(kernel, service_id) # the ask for which the action planner is going to find a relevant function. ask = "What is the sum of 110 and 990?" # ask the action planner to identify a suitable function from the list of functions available. plan = await planner.create_plan(goal=ask) # ask the action planner to execute the identified function. result = await plan.invoke(kernel) print(result) """ Output: 1100 """ if __name__ == "__main__": import asyncio asyncio.run(main())
// SPDX-License-Identifier: agpl-3.0 pragma solidity ^0.8.0; import {IERC20} from '../interfaces/IERC20.sol'; import {IStakedTokenV2} from '../interfaces/IStakedTokenV2.sol'; import {ERC20} from '../lib/ERC20.sol'; import {DistributionTypes} from '../lib/DistributionTypes.sol'; import {SafeERC20} from '../lib/SafeERC20.sol'; import {VersionedInitializable} from '../utils/VersionedInitializable.sol'; import {AaveDistributionManager} from './AaveDistributionManager.sol'; import {GovernancePowerWithSnapshot} from '../lib/GovernancePowerWithSnapshot.sol'; /** * @title StakedTokenV2 * @notice Contract to stake Aave token, tokenize the position and get rewards, inheriting from a distribution manager contract * @author BGD Labs */ abstract contract StakedTokenV2 is IStakedTokenV2, GovernancePowerWithSnapshot, VersionedInitializable, AaveDistributionManager { using SafeERC20 for IERC20; IERC20 public immutable STAKED_TOKEN; IERC20 public immutable REWARD_TOKEN; /// @notice Seconds available to redeem once the cooldown period is fulfilled uint256 public immutable UNSTAKE_WINDOW; /// @notice Address to pull from the rewards, needs to have approved this contract address public immutable REWARDS_VAULT; mapping(address => uint256) public stakerRewardsToClaim; mapping(address => CooldownSnapshot) public stakersCooldowns; /// @dev End of Storage layout from StakedToken v1 /// @dev To see the voting mappings, go to GovernancePowerWithSnapshot.sol mapping(address => address) internal _votingDelegates; mapping(address => mapping(uint256 => Snapshot)) internal _propositionPowerSnapshots; mapping(address => uint256) internal _propositionPowerSnapshotsCounts; mapping(address => address) internal _propositionPowerDelegates; bytes32 public DOMAIN_SEPARATOR; bytes public constant EIP712_REVISION = bytes('1'); bytes32 internal constant EIP712_DOMAIN = keccak256( 'EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)' ); bytes32 public constant PERMIT_TYPEHASH = keccak256( 'Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)' ); /// @dev owner => next valid nonce to submit with permit() mapping(address => uint256) public _nonces; constructor( IERC20 stakedToken, IERC20 rewardToken, uint256 unstakeWindow, address rewardsVault, address emissionManager, uint128 distributionDuration ) ERC20() AaveDistributionManager(emissionManager, distributionDuration) { STAKED_TOKEN = stakedToken; REWARD_TOKEN = rewardToken; UNSTAKE_WINDOW = unstakeWindow; REWARDS_VAULT = rewardsVault; } /// @inheritdoc IStakedTokenV2 function stake(address onBehalfOf, uint256 amount) external virtual override; /// @inheritdoc IStakedTokenV2 function redeem(address to, uint256 amount) external virtual override; /// @inheritdoc IStakedTokenV2 function cooldown() external virtual override; /// @inheritdoc IStakedTokenV2 function claimRewards(address to, uint256 amount) external virtual override; /// @inheritdoc IStakedTokenV2 function getTotalRewardsBalance(address staker) external view returns (uint256) { DistributionTypes.UserStakeInput[] memory userStakeInputs = new DistributionTypes.UserStakeInput[](1); userStakeInputs[0] = DistributionTypes.UserStakeInput({ underlyingAsset: address(this), stakedByUser: balanceOf(staker), totalStaked: totalSupply() }); return stakerRewardsToClaim[staker] + _getUnclaimedRewards(staker, userStakeInputs); } /// @inheritdoc IStakedTokenV2 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner != address(0), 'INVALID_OWNER'); //solium-disable-next-line require(block.timestamp <= deadline, 'INVALID_EXPIRATION'); uint256 currentValidNonce = _nonces[owner]; bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline ) ) ) ); require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE'); unchecked { _nonces[owner] = currentValidNonce + 1; } _approve(owner, spender, value); } /** * @dev Delegates power from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param delegationType the type of delegation (VOTING_POWER, PROPOSITION_POWER) * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateByTypeBySig( address delegatee, DelegationType delegationType, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256( abi.encode( DELEGATE_BY_TYPE_TYPEHASH, delegatee, uint256(delegationType), nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), 'INVALID_SIGNATURE'); require(nonce == _nonces[signatory]++, 'INVALID_NONCE'); require(block.timestamp <= expiry, 'INVALID_EXPIRATION'); _delegateByType(signatory, delegatee, delegationType); } /** * @dev Delegates power from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public { bytes32 structHash = keccak256( abi.encode(DELEGATE_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, structHash) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), 'INVALID_SIGNATURE'); require(nonce == _nonces[signatory]++, 'INVALID_NONCE'); require(block.timestamp <= expiry, 'INVALID_EXPIRATION'); _delegateByType(signatory, delegatee, DelegationType.VOTING_POWER); _delegateByType(signatory, delegatee, DelegationType.PROPOSITION_POWER); } /** * @dev Updates the user state related with his accrued rewards * @param user Address of the user * @param userBalance The current balance of the user * @param updateStorage Boolean flag used to update or not the stakerRewardsToClaim of the user * @return The unclaimed rewards that were added to the total accrued */ function _updateCurrentUnclaimedRewards( address user, uint256 userBalance, bool updateStorage ) internal returns (uint256) { uint256 accruedRewards = _updateUserAssetInternal( user, address(this), userBalance, totalSupply() ); uint256 unclaimedRewards = stakerRewardsToClaim[user] + accruedRewards; if (accruedRewards != 0) { if (updateStorage) { stakerRewardsToClaim[user] = unclaimedRewards; } emit RewardsAccrued(user, accruedRewards); } return unclaimedRewards; } /** * @dev returns relevant storage slots for a DelegationType * @param delegationType the requested DelegationType * @return the relevant storage */ function _getDelegationDataByType(DelegationType delegationType) internal view override returns ( mapping(address => mapping(uint256 => Snapshot)) storage, //snapshots mapping(address => uint256) storage, //snapshots count mapping(address => address) storage //delegatees list ) { if (delegationType == DelegationType.VOTING_POWER) { return (_votingSnapshots, _votingSnapshotsCounts, _votingDelegates); } else { return ( _propositionPowerSnapshots, _propositionPowerSnapshotsCounts, _propositionPowerDelegates ); } } }
<!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>Set</title> <script> /* Set -Set用来创建一个集合 - 它的功能和数组类似,不同点在于Set中不能存储重复的数据 -使用方式: 创建 - new Set() - new Set([...]) 方法 size 获取数量 add() 添加元素 has() 检查元素 delete() 删除元素 */ //创建一个Set const set = new Set() console.log(set); //向set中添加数据 set.add(10) set.add("孙悟空") set.add(10) //不能存储重复的数据 console.log(set); for(const item of set){ console.log(item); }; const arr = [...set] console.log(arr); const arr2 = [1,2,3,2,1,3,4,5,6,7,7,8,9,10] const set2 = new Set(arr2) console.log(arr2); //存储到数组里 console.log([...set2]); const set3 = new Set([1,2,3,2,1,3,4,5,6,7,7,8,9,10,"hello"]) console.log(set3); </script> </head> <body> </body> </html>
import React from 'react' import { QueryClient } from 'react-query' import { offerResponseSnap } from 'features/offer/api/snaps/offerResponseSnap' import { reactQueryProviderHOC } from 'tests/reactQueryProviderHOC' import { CustomRenderOptions, render } from 'tests/utils/web' import { OfferPartialDescription } from '../OfferPartialDescription' const defaultDescription = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua: https://google.com' const offerId = 123 type Setup = (queryClient: QueryClient) => void const defaultSetup: Setup = (queryClient) => { queryClient.removeQueries() queryClient.setQueryData(['offer', offerId], offerResponseSnap) } type Params = { description?: string setup: Setup options?: CustomRenderOptions } const defaultParams: Params = { description: defaultDescription, setup: defaultSetup, options: undefined, } describe('OfferPartialDescription', () => { it('centers CTA when provided description is empty', () => { const { getByTestId } = renderOfferDescription({ ...defaultParams, description: '', }) const offerSeeMoreContainer = getByTestId('offerSeeMoreContainer') // @ts-expect-error FIXME see how to fix typing const { 'align-self': alignSelf } = offerSeeMoreContainer.style expect(alignSelf).toBe('center') }) it('places CTA on flex-end when provided a description', () => { const { getByTestId } = renderOfferDescription(defaultParams) const offerSeeMoreContainer = getByTestId('offerSeeMoreContainer') // @ts-expect-error FIXME see how to fix typing const { 'align-self': alignSelf } = offerSeeMoreContainer.style expect(alignSelf).toBe('flex-end') }) it('renders externalLinks if http(s) url are present in the description', () => { const { queryByTestId } = renderOfferDescription(defaultParams) expect(queryByTestId('externalSiteIcon')).toBeTruthy() }) it("shouldn't render an empty line and a spacer when description is empty", () => { const { queryByTestId } = renderOfferDescription({ ...defaultParams, description: undefined, }) expect(queryByTestId('offerPartialDescriptionBody')).toBeFalsy() }) describe('SeeMore button', () => { const setupWithNoDataInDescriptionPage: Setup = (queryClient) => { queryClient.setQueryData(['offer', offerId], { ...offerResponseSnap, image: {}, extraData: {}, }) } it('should be rendered when there is some content on the description page', () => { const { queryByTestId } = renderOfferDescription(defaultParams) expect(queryByTestId('offerSeeMoreContainer')).toBeTruthy() }) describe('should be rendered', () => { it('on phone when the description is ellipsed', () => { const { queryByTestId } = renderOfferDescription({ ...defaultParams, setup: (queryClient) => { queryClient.setQueryData(['offer', offerId], { image: {}, extraData: {}, }) }, options: { theme: { isMobileViewport: true, isTabletViewport: false, isDesktopViewport: false, }, }, }) expect(queryByTestId('offerSeeMoreContainer')).toBeTruthy() }) it('when there is image on the description page', () => { const { queryByTestId } = renderOfferDescription({ ...defaultParams, description: undefined, setup: (queryClient) => { queryClient.setQueryData(['offer', offerId], { image: offerResponseSnap.image, extraData: {}, }) }, }) expect(queryByTestId('offerSeeMoreContainer')).toBeTruthy() }) it('when there is extraData on the description page', () => { const { queryByTestId } = renderOfferDescription({ ...defaultParams, description: undefined, setup: (queryClient) => { queryClient.setQueryData(['offer', offerId], { image: {}, extraData: { author: 'John Lang' }, }) }, }) expect(queryByTestId('offerSeeMoreContainer')).toBeTruthy() }) }) describe("shouldn't be rendered", () => { it('when there is no content on the description page', () => { const { queryByTestId } = renderOfferDescription({ description: undefined, setup: setupWithNoDataInDescriptionPage, }) expect(queryByTestId('offerSeeMoreContainer')).toBeFalsy() }) it('on desktop when there is only description on the description page', () => { const { queryByTestId } = renderOfferDescription({ ...defaultParams, setup: setupWithNoDataInDescriptionPage, options: { theme: { isMobileViewport: false, isTabletViewport: false, isDesktopViewport: true, }, }, }) expect(queryByTestId('offerSeeMoreContainer')).toBeFalsy() }) }) }) }) const renderOfferDescription = ({ description, setup, options }: Params) => { const wrapper = render( // eslint-disable-next-line local-rules/no-react-query-provider-hoc reactQueryProviderHOC( <OfferPartialDescription id={offerId} description={description} />, setup ), options ) return wrapper }
# Travailler avec Python Pour pouvoir utiliser un langage de programmation, on a besoin d'un [IDE](https://fr.wikipedia.org/wiki/Environnement_de_d%C3%A9veloppement) (environnement de développement). Il en existe beaucoup... ## En ligne Sur l'ENT, lancer l'application **Capytale**. ![](capytale.png){: .center} Puis créer une activité de type «Script-Console» ![](activite_capytale.png){: .center } ![](basthon.png) <p align="center"> <em>Éditeur à gauche, console à droite</em> </p> ## Au lycée (ou à la maison) On privilégiera l'IDE **Thonny** (installé en E417 et E420), ou à défaut EduPython. ![](thonny.png){align=left} Pour installer Thonny sur son PC personnel (ou familial): 1. Rendez vous sur la page [https://thonny.org/](https://thonny.org/) 2. Téléchargez et installez la version qui correspond à votre système d'exploitation (Windows, Mac, Linux). <br> <br> ![](thonny2.png){: .center .w640} <p align="center"> <em>Éditeur en haut, console en bas</em> </p> ## Ici, sur ce site Dans certaines activités, vous trouverez une console intégrée. Vous pouvez y entrer des instructions simples: {{ terminal() }} Ou bien un mini-IDE intégré: {{ IDEv() }} ## Éditeur ou console? !!! info "Éditeur et console" Un IDE, quel qu'il soit (Basthon en ligne, Thonny, EduPython, etc) comporte deux espaces importants: - l'**éditeur (ou zone de script)** : c'est la partie où l'on tape son programme (les lignes sont généralement numérotées). La zone de script est **asynchrone**. Il ne se passera rien tant que vous n'aurez pas exécuté le script (par F5 avec Thonny par exemple). - la **console**: c'est l'endroit où s'affichent les sorties du programme, et où on peut également entrer des instructions simples. On le repère à l'aide des chevrons `>>>` . La console est **synchrone** : elle répond dès que vous appuyez sur la touche Entrée. Elle sert donc aux petits tests rapides, ou bien tests post-exécution d'un code. Et bien entendu, un bouton "Exécuter" (triangle vert bien souvent) pour... exécuter le code. !!! note "Utilisation classique du couple script / console" 1. On écrit son code dans la zone de script. 2. On l'exécute. 3. On interroge la console pour connaître l'état des variables, pour utiliser les fonctions construites dans le script. Pour les extraits de code présents sur ce site : - tout le code qui est précédé d'une numérotation de ligne est à écrire en zone de script. Exemple : ```python linenums='1' def accueil(n): for k in range(n): print("bonjour") ``` - tout le code qui est précédé ```>>>``` est à taper en console. Exemple : ```python >>> accueil(5) ```
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <!-- cdn fontawesone --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"> <!-- link css --> <link rel="stylesheet" href="css/style.css"> </head> <body> <header class="header"> <a href="" class="logo"><i class="fa-solid fa-fire-burner"></i></a> <nav class="navbar"> <a href="#home">home</a> <a href="#sobre">sobre</a> <a href="#produtos">produtos</a> <a href="#contato">contato</a> </nav> <div class="icons"> <i class="fas fa-user"></i> <i class="fas fa-heart"></i> <i class="fas fa-cart-shopping"></i> </div> </header> <div class="home-bg" > <section class="home" id="home"> <div class="content"> <h3>Forno a lenha</h3> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta repudiandae magni atque?</p> <a href="#produtos" class="btn">nossos produtos</a> </div> </section> </div> <section class="about" id="sobre"> <div class="image"> <img src="images/padeiro.png" alt=""> </div> <div class="content"> <h3>O melhor pão para começa seu dia</h3> <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Eius, itaque. Maxime deserunt repellat mollitia laboriosam perferendis quas recusandae dolore nostrum.</p> <a href="#contato" class="btn">contate-nos</a> </div> </section> <section class="produtos" id="produtos"> <div class="heading"> <img src="images/heading-img.png" alt=""> <h3>produtos</h3> </div> <div class="box-container"> <div class="box"> <a href="" class="fas fa-heart"></a> <a href="" class="fas fa-eye"></a> <img src="images/bolo-de-chocolate.jpg" alt=""> <h3>bolo de chocolate</h3> <div class="stars"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star-half-alt"></i> </div> <span>R$20.99</span> <a href="" class="btn">adicionar carrinho</a> </div> <div class="box"> <a href="" class="fas fa-heart"></a> <a href="" class="fas fa-eye"></a> <img src="images/bolo-de-morango.png" alt=""> <h3>bolo de morango</h3> <div class="stars"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star-half-alt"></i> </div> <span>R$20.99</span> <a href="" class="btn">adicionar carrinho</a> </div> <div class="box"> <a href="" class="fas fa-heart"></a> <a href="" class="fas fa-eye"></a> <img src="images/bolo-de-fuba.png" alt=""> <h3>bolo de fuba</h3> <div class="stars"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star-half-alt"></i> </div> <span>R$20.99</span> <a href="" class="btn">adicionar carrinho</a> </div> <div class="box"> <a href="" class="fas fa-heart"></a> <a href="" class="fas fa-eye"></a> <img src="images/torta_de_limao.jpg" alt=""> <h3>torta de limao</h3> <div class="stars"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star-half-alt"></i> </div> <span>R$20.99</span> <a href="" class="btn">adicionar carrinho</a> </div> <div class="box"> <a href="" class="fas fa-heart"></a> <a href="" class="fas fa-eye"></a> <img src="images/torta_de_amora.png" alt=""> <h3>torta de amora</h3> <div class="stars"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star-half-alt"></i> </div> <span>R$20.99</span> <a href="" class="btn">adicionar carrinho</a> </div> <div class="box"> <a href="" class="fas fa-heart"></a> <a href="" class="fas fa-eye"></a> <img src="images/torta_de_coco.png" alt=""> <h3>torta de coco</h3> <div class="stars"> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star"></i> <i class="fas fa-star-half-alt"></i> </div> <span>R$20.99</span> <a href="" class="btn">adicionar carrinho</a> </div> </div> </section> <section class="contact" id="contato"> <div class="heading"> <img src="images/heading-img.png" alt=""> <h3>contato</h3> </div> <div class="row"> <div class="image"> <img src="images/Call center-bro.png" alt=""> </div> <form action="" method="post"> <h3>fale conosco</h3> <input type="text" required class="box" maxlength="20" placeholder="coloque seu nome"> <input type="email" required class="box" placeholder="coloque seu email"> <input type="number" required class="box" maxlength="20" placeholder="coloque seu número" min="0" max="9999999999" onkeypress="if(this.value.legth ==10) return false"> <textarea cols="50" rows="10"></textarea> <input type="submit" class="btn"> </form> </div> </section> <section class="footer"> <div class="box-container"> <div class="box"> <i class="fas fa-envelope"></i> <h3>nosso email</h3> <p>joseph.robert.carvalho@gmail.com</p> <p>outroemail@gmail.com</p> </div> <div class="box"> <i class="fas fa-clock"></i> <h3>hora de abertura</h3> <p>06:00am até 20:00pm</p> </div> <div class="box"> <i class="fas fa-map-marker-alt"></i> <h3>local</h3> <p>Brasil,rio de janeiro - 25555-800</p> </div> <div class="box"> <i class="fas fa-phone"></i> <h3>nosso número</h3> <p>(21)9 9985-6323</p> </div> </div> <div class="credit"> &copy; copyright @ 2022 by <span>Joseph robert</span> | todos direitos reservados </div> </section> </body> </html>
/* * Copyright (c) Code Developed by Prof. Fabio Ciravegna * All rights Reserved */ package it.torino.tracker.data_upload.data_senders import android.content.Context import android.util.Log import it.torino.tracker.Repository import it.torino.tracker.data_upload.HttpsServer import it.torino.tracker.tracker.sensors.activity_recognition.ActivityData import it.torino.tracker.utils.Globals import org.json.JSONObject import uk.ac.shef.tracker.core.serialization.ActivitiesRequest class ActivityDataSender(val context: Context) { private val TAG: String? = this::class.simpleName private val repositoryInstance: Repository? = Repository.getInstance(context) private var activitiesToSend: List<ActivityData?>? = null /** * it sends the activity data and if successful it marks them as sent * @param context * @param userID */ fun sendActivityData(userID: String) { val dataToSend: JSONObject = prepareActivityData(userID) ?: return val url: String = Globals.SERVER_URI + Globals.SERVER_PORT + Globals.SERVER_INSERT_ACTIVITIES_URL val httpServer = HttpsServer() val returnedJSONObject: JSONObject? = httpServer.sendToServer(url, dataToSend) if (returnedJSONObject != null) { val activitiesIds = activitiesToSend!!.map { it!!.id } repositoryInstance?.dBActivityDao?.updateSentFlag(activitiesIds) } } /** * it prepares the activities to be sent to the server * * @param context * @param userID * @return it returns a json object to send to the server or null */ private fun prepareActivityData(userID: String): JSONObject? { val dataObject = JSONObject() dataObject.put(Globals.USER_ID, userID) activitiesToSend = collectActivitiesFromDatabase() if (activitiesToSend != null && activitiesToSend!!.isNotEmpty()) { Log.i(TAG, "Sending ${activitiesToSend!!.size} activities") val activityDTSList: MutableList<ActivitiesRequest.ActivityRequest> = mutableListOf() for (activity in activitiesToSend!!) if (activity != null) activityDTSList.add(ActivitiesRequest.ActivityRequest(activity)) val dataSenderUtils = DataSenderUtils() dataObject.put(Globals.ACTIVITIES_ON_SERVER, dataSenderUtils.getJSONArrayOfObjects(activityDTSList)) return dataObject } else { Log.i(TAG, "No activities to send") } return null } private fun collectActivitiesFromDatabase(): List<ActivityData?>? { return repositoryInstance?.dBActivityDao?.getUnsentActivities(600)!! } }
package com.example.authentication.controller; import com.example.authentication.dto.PermissionHandler; import com.example.authentication.model.Permission; import com.example.authentication.model.STUser; import com.example.authentication.repository.UserRepo; import com.example.authentication.service.PermissionServiceImpl; import com.example.authentication.service.UserService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Map; @RestController @RequestMapping("/api/permissions") @RequiredArgsConstructor @CrossOrigin("*") public class PermissionController { @Autowired private PermissionServiceImpl permissionService; @Autowired private UserService userService; @Autowired private UserRepo userRepo; @PostMapping("/update") public ResponseEntity<Object> updatePermissions(@RequestParam Integer userId, @RequestParam String label, @RequestBody PermissionHandler permHand) { try{ Permission permission = permissionService.updatePermissions(userId, label, permHand); return new ResponseEntity<>("Permissions updated successfully", HttpStatus.OK); } catch (Exception e){ return new ResponseEntity<>("Error code 4006 : Bad request ", HttpStatus.BAD_REQUEST); } } @GetMapping("/permissionsByUser") public ResponseEntity<Map<String, Object>> getPermissionsByUser(@RequestParam Integer userId) { STUser user = userRepo.findById(userId).get(); if (user == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null); } Map<String, Object> permissions = permissionService.getPermissionsByUser(user); return ResponseEntity.ok(permissions); } }
// ********************************************** // ******************* PART 1 ******************* // ********************************************** // Create a variable called highScore that can be a number OR a boolean let highScore : number | boolean; highScore = 30; highScore = true; // ********************************************** // ******************* PART 2 ******************* // ********************************************** // create an array called stuff // it can be an array of numbers OR an array of strings // it cannot be an array of numbers and strings (mixed together) let stuff : number[] | string[] = [1, 2, 3, 4]; stuff = ["aa", "bb", "cc"]; // ********************************************** // ******************* PART 3 ******************* // ********************************************** // Create a literal type called SkillLevel // There are 4 allowed values: "Beginner", "Intermediate", "Advanced", and "Expert" type SkillLevel = "Beginner" | "Intermediate" | "Advanced" | "Expert" const level : SkillLevel = "Expert"; // ********************************************** // ******************* PART 4 ******************* // ********************************************** // Create a type called SkiSchoolStudent // name must be a string // age must be a number // sport must be "ski" or "snowboard" // level must be a value from the SkillLevel type (from above) type SkiSchoolStudent = { name: string; age: number; sport: "ski" | "snowboard"; level: SkiSchoolStudent; } // ********************************************** // ******************* PART 5 ******************* // ********************************************** // Define a type to represent an RGB color // r should be a number // g should be a number // b should be a number // Define a type to represent an HSL color // h should be a number // s should be a number // l should be a number // Create an array called colors that can hold a mixture of RGB and HSL color types type RGB = { r: number; g: number; b: number; } type HSL = { h: number; s: number; l: number; } let colors : (RGB | HSL)[] = [ { r : 255, g : 0, b : 255 } ]; // ********************************************** // ******************* PART 6 ******************* // ********************************************** // Write a function called greet that accepts a single string OR an array of strings // It should print "Hello, <name>" for that single person OR greet each person in the array with the same format const greet = (input : string | string[]) => { if(typeof input === "string") { console.log("Hello, " + input); return; } input.forEach(name => console.log("Hello, " + name)); } const names = ["bala", "jeeto", "abhi", "prince"]; greet("elton"); greet(names);
package com.example.maternalhealthriskprediction; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; public class Register extends AppCompatActivity { EditText RegisterFullName, RegisterEmail, RegisterPassword, RegisterReEnterPassword; Button registerBtn, gotologin; FirebaseAuth fauth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_register); RegisterFullName = findViewById(R.id.username); RegisterEmail = findViewById(R.id.email); RegisterPassword = findViewById(R.id.password); RegisterReEnterPassword = findViewById(R.id.reenterpassword); registerBtn = findViewById(R.id.signupbutton); gotologin = findViewById(R.id.login); fauth = FirebaseAuth.getInstance(); registerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String fullname = RegisterFullName.getText().toString(); String email = RegisterEmail.getText().toString(); String password = RegisterPassword.getText().toString(); String reenterpassword = RegisterReEnterPassword.getText().toString(); if(fullname.isEmpty()){ RegisterFullName.setError("Full Name is required!"); return; } if(email.isEmpty()){ RegisterEmail.setError("Email is required!"); return; } if(password.isEmpty()){ RegisterPassword.setError("Password is required!"); return; } if(reenterpassword.isEmpty()){ RegisterReEnterPassword.setError("Re-Enter Password is required!"); return; } if(!password.equals(reenterpassword)){ RegisterReEnterPassword.setError("Password do not match!"); return; } Toast.makeText(Register.this, "Data Validated!", Toast.LENGTH_SHORT).show(); fauth.createUserWithEmailAndPassword(email, password).addOnSuccessListener(new OnSuccessListener<AuthResult>() { @Override public void onSuccess(AuthResult authResult) { startActivity(new Intent(getApplicationContext(), Main.class)); finish(); } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast.makeText(Register.this, e.getMessage(), Toast.LENGTH_SHORT).show(); } }); } }); } }
<template lang="pug"> p.text-error(v-if="errors.length" v-for="error in errors") {{ error }} form.form-horizontal(@submit="submitForm") .form-group .col-3 label.form-label Description .col-9 input.form-input(type="text" v-model="description" placeholder="Type picture description...") .form-group .col-3 label.form-label Image File .col-9 input.form-input(type="file" v-on:change="createBase64Image" accept="image/*" ref="fileupload") textarea.form-input(v-model="base64textString" rows=8 style="display:none;") .form-group .col-3 .col-9 button.btn.btn-primary(type="submit") Create </template> <script> export default { name: 'create-picture', data () { return { 'description': '', 'base64textString': '', 'errors': [] } }, methods: { checkForm: function (event) { this.errors = []; if (this.description === '' || this.$refs.fileupload.value === '') { this.errors.push( "All fields are required." ); } else { this.createPicture() } }, createBase64Image: function (event) { const file = event.target.files[0]; const reader = new FileReader(); reader.readAsDataURL(file); reader.onload = () => { this.base64textString = reader.result; }; }, submitForm (event) { this.checkForm(); this.description = ''; this.base64textString = ''; this.$refs.fileupload.value = null; event.preventDefault() }, createPicture () { this.$store.dispatch('createPicture', { description: this.description, image: this.base64textString }) } } } </script>
--- title: Créer des formes et des mises en page de documents visuellement impressionnantes linktitle: Créer des formes et des mises en page de documents visuellement impressionnantes second_title: API de gestion de documents Python Aspose.Words description: Créez des mises en page de documents visuellement époustouflantes à l'aide d'Aspose.Words pour Python. Apprenez à ajouter des formes, à personnaliser des styles, à insérer des images, à gérer le flux de texte et à améliorer l'attrait. type: docs weight: 13 url: /fr/python-net/data-visualization-and-formatting/document-shape-handling-formatting/ --- ## Introduction Les documents modernes ne se limitent pas au contenu qu’ils contiennent ; leur attrait visuel joue un rôle important dans l’engagement des lecteurs. Aspose.Words for Python propose une boîte à outils puissante pour manipuler des documents par programmation, vous permettant de créer des mises en page visuellement frappantes qui trouvent un écho auprès de votre public. ## Configuration de l'environnement Avant de nous lancer dans la création de formes de documents impressionnantes, assurez-vous que Aspose.Words for Python est installé. Vous pouvez le télécharger depuis le[lien de téléchargement](https://releases.aspose.com/words/python/) . De plus, reportez-vous au[Documentation](https://reference.aspose.com/words/python-net/) pour des conseils complets sur l’utilisation de la bibliothèque. ## Création d'un document de base Commençons par créer un document de base à l'aide d'Aspose.Words pour Python. Voici un simple extrait de code pour vous aider à démarrer : ```python import aspose.words as aw # Create a new document doc = aw.Document() # Add a paragraph with some text paragraph = doc.get_first_section().get_body().append_paragraph("Hello, Aspose!") # Save the document doc.save("basic_document.docx") ``` Cet extrait de code initialise un nouveau document, ajoute un paragraphe avec le texte « Bonjour, Aspose ! » et l'enregistre sous "basic_document.docx". ## Ajouter des formes élégantes Les formes sont un moyen fantastique d'ajouter des éléments visuels à votre document. Aspose.Words for Python vous permet d'insérer diverses formes, telles que des rectangles, des cercles et des flèches. Ajoutons un rectangle à notre document : ```python # Add a rectangle shape shape = paragraph.append_shape(aw.drawing.ShapeType.RECTANGLE, aw.drawing.RelativeHorizontalPosition.LEFT_MARGIN, 100, aw.drawing.RelativeVerticalPosition.TOP_MARGIN, 100, 200, 100) ``` ## Personnalisation des formes et des mises en page Pour rendre votre document visuellement impressionnant, vous pouvez personnaliser les formes et les mises en page. Voyons comment changer la couleur et la position de notre rectangle : ```python # Customize shape properties shape.fill.color = aw.drawing.Color.BLUE shape.left = aw.drawing.Length.from_inch(1.5) shape.top = aw.drawing.Length.from_inch(2) ``` ## Améliorer l'attrait visuel avec des images Les images sont des outils puissants pour améliorer l’attrait des documents. Voici comment ajouter une image à votre document à l'aide d'Aspose.Words pour Python : ```python # Add an image image_path = "image.jpg" image = paragraph.append_image(image_path) ``` ## Gestion du flux et du retour à la ligne du texte Le flux et l'habillage du texte jouent un rôle crucial dans la mise en page du document. Aspose.Words for Python fournit des options pour contrôler la façon dont le texte circule autour des formes et des images. Voyons comment : ```python # Set text wrapping style image.text_wrapping.style = aw.drawing.TextWrappingStyle.TIGHT image.text_wrapping.side = aw.drawing.TextWrappingSide.BOTH ``` ## Intégration de fonctionnalités avancées Aspose.Words for Python offre des fonctionnalités avancées pour améliorer davantage la mise en page de vos documents. Il s'agit notamment de l'ajout de tableaux, de graphiques, de liens hypertexte, etc. Explorez la documentation pour une liste complète des possibilités. ## Conclusion Créer des formes et des mises en page de documents visuellement impressionnantes n'est plus une tâche complexe, grâce aux capacités d'Aspose.Words pour Python. Grâce à ses fonctionnalités puissantes, vous pouvez transformer des documents banals en pièces visuellement captivantes qui engagent et trouvent un écho auprès de votre public. ## FAQ ### Comment télécharger Aspose.Words pour Python ? Vous pouvez télécharger Aspose.Words pour Python à partir du[lien de téléchargement](https://releases.aspose.com/words/python/). ### Où puis-je trouver une documentation complète pour Aspose.Words pour Python ? Se référer au[Documentation](https://reference.aspose.com/words/python-net/) pour des conseils détaillés sur l’utilisation d’Aspose.Words pour Python. ### Puis-je personnaliser les couleurs et les styles des formes ? Absolument! Aspose.Words for Python fournit des options pour personnaliser les couleurs, les tailles et les styles des formes en fonction de vos préférences de conception. ### Comment puis-je ajouter des images à mon document ? Vous pouvez ajouter des images à votre document en utilisant le`append_image` méthode, fournissant le chemin d’accès au fichier image. ### Existe-t-il des fonctionnalités plus avancées disponibles dans Aspose.Words pour Python ? Oui, Aspose.Words for Python offre un large éventail de fonctionnalités avancées, notamment des tableaux, des graphiques, des hyperliens, etc., pour créer des documents dynamiques et attrayants.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Sort</title> </head> <body> <script> var arr1 = [43, 54, 4, -4, 84, 100, 58, 27, 140]; var arr2 = ['apple', 'dog', 'cat', 'car', 'zoo', 'orange', 'airplane']; var arr3 = [[10, 14], [16, 60], [7, 44], [26, 35], [22, 63]]; var arr4 = [ { id: 1, name: 'candy', value: 40 }, { id: 2, name: 'Simon', value: 50 }, { id: 3, name: 'Tony', value: 45 }, { id: 4, name: 'Annie', value: 60 } ]; console.log("从大到小排序"); arr1.sort(function (a, b) { return b - a; }); console.log(arr1); console.log('从小到大排序'); arr1.sort(); console.log(arr1); console.log("按字母顺序a-z排序"); arr2.sort(); console.log(arr2); console.log("按照字母顺序z-a排序"); arr2.sort(function (a, b) { return b - a; }); console.log(arr2); console.log("二维数组第二个元素从大到小"); arr3.sort(function (a, b) { return b[1] - a[1]; }); console.log(arr3); console.log("对象的value值从小到大进行排序"); arr4.sort(function (a, b) { return a.value - b.value; }); console.log(arr4); </script> </body> </html>
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import { Parser } from './parser'; import { Channel } from './channel'; import { ChannelService } from './channel.service'; import { StorageService } from './storage.service'; @Injectable() export class ParserService { private parser: Parser = new Parser(); constructor( private http: Http, private channelService: ChannelService, private storageService: StorageService ) { } public init(): void { // this.update(); this.storageService.removeSync('myLastChannel'); } public update(): Promise<void> { var self = this; return new Promise<void>((resolve, reject) => { console.log('updating...'); this.http.get('https://www.youtube.com/').subscribe(response => { var html = response.text(); var domParser = new DOMParser(); var dom = domParser.parseFromString(html, 'text/html'); var channels = this.parser.getChannels(dom) self.saveChannelsToStorage(channels).then(resolve, reject); }, reject); }); } saveChannelsToStorage(channels: Channel[]): Promise<void> { return new Promise<void>((resolve, reject) => { this.channelService.addOrUpdateChannels(channels) .then(resolve, reject); }); } }
<a name="readme-top"></a> <h1 align="center"> JavaScript Basics for Beginners </h1> <img src="https://github.com/ahmedeid6842/cheat-sheet/assets/57197702/bd580e39-bae5-4d17-b9a2-e14a01cd5347" /> - [Basics](#section-1--basics) - [Variable types](#there-are-two-types-of-variables--primitive-and-reference-data-type) - [Dynamic language](#javascript--is-dynamic-programming-language-exg) - [Objects](#object) - [Array](#array) - [Functions](#functions) - [Operators](#section-2--operator) - [Equality operator](#equality-operator) - [Ternary operator](#ternary-operator-truefalse) - [Control flow](#section-3--control-flow) - [if condition](#if-condition) - [switch case](#switch-case) - [for](#for) - [while](#while) - [do-while](#do-while) - [for-in](#for-in) - [for-of](#for-of) - [Exercises](#exercise--landscape-portrait) - [Objects](#section-4--objects) - [defining an object](#defining-an-object) - [factory function](#factory-function) - [constructor function](#constructor-function) - [primitive and reference](#primitive-and-reference) - [Exercises](#exercise--address-object) - [Arrays](#section-5--array) - [adding in array](#adding-in-array) - [removing in array](#removing-in-array) - [find in array](#find-in-array) - [emptying array](#emptying-array) - [combining array](#combining-array) - [spread operator](#spread-operator) - [iteration](#iteration) - [joining array](#joining-array) - [sorting array](#sorting-array) - [testing array](#testing-array) - [Exercises](#exercise--array-range) - [Functions](#section-6--functions) - [arguments & parameters](#arguments--parameters) - [getter & setter](#getter-and-setter) - [errors & exception](#errors-and-exception) - [let vs var](#let-vs-var) - [This keyword](#this-keyword) - [Exercises](#exercise--area-of-circle) --- # section 1 : Basics ## there are two types of variables : primitive and reference Data type **primitive types** String Number Boolean undefined null **reference types object array function** <p align="right">(<a href="#readme-top">back to top</a>)</p> ## javascript : is dynamic programming language (ex) ```jsx let check = "verified"; if(true){ check = true ; // note : check variable above was string but here it's changed into true } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## Object ### defining object ```jsx let obj = { key : "value", key2 : "value2" } ``` ### accessing object dot notation : console. log(objName.key); bracket notation : console.log(objName[’key’]); <p align="right">(<a href="#readme-top">back to top</a>)</p> ## Array - array can store multiple data type let arr = [”ahmed”, “mohamed”,3]; - arrays the original of it, is object console.log(typeof(arr)); <p align="right">(<a href="#readme-top">back to top</a>)</p> ## Functions ### defining function ```jsx function fun_Name(parameters){ code return value ; } fun_Name(argument); //calling function ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> # section 2 : Operator ## equality operator - strict equality “===” : (type + value) the two values must be the same in the type an value - lose equality “==” : the value must be equal in value only doesn’t matter the type ,,,, means “1” equal 1 <p align="right">(<a href="#readme-top">back to top</a>)</p> ## ternary operator ?true:false ```jsx let point = 90 ; let type = point > 100 ? 'gold' : 'sliver' ; console.log(type); ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> <p align="right">(<a href="#readme-top">back to top</a>)</p> # section 3 : Control flow ## if condition ```jsx /* if (condition){ execute this statement }else if (condition){ execute this statement }else{ execute this statement } */ let hour = 24; if (hour >= 6 && hour <= 12) { console.log("good morning"); }else if (hour > 12 && hour < 18) { console.log("good afternoon") } else { console.log("good evening"); } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## switch… case ```jsx /* let varName switch(varName){ case 1 : execute this code break ; case 2 : execute this code break ; default : execute this code break; } */ let hour = 2; switch (hour) { case 1: console.log("good morning"); break; case 2: console.log("good evening"); break; default: console.log("default"); break; } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## for it’s used to repeat block of code number of times ```jsx /* for(intial expression ; condtion ; iteratble ){ code block } */ for(let i =0 ; i<5;i++){ console.log(hello world); } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## while while loop to iterate based on condition ,,, initial expression doesn’t set in it’s body ```jsx /* while(condition){ code } */ let i=0; while(i>5){ console.log(i); i++ } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## do-while it execute your code then check your condition ,,, it’s guarantee execute your code at least once ```jsx /* do{ }while(condition) */ do { console.log("hi") }while(false) ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## for-in it iterate over your object keys ,,, don’t have to use tradition defination of for(intial express; cond; ++) ```jsx for(let key in object){ console.log (key , object[key]) } for(let key in arr){ console.log(key,arr[key]); // in this example the key will be indeces of your array } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## for-of it iterate over your array value , <aside> 👀 note : you can’t use for-of with object because it’s not iteratble data type </aside> ```jsx for(let value of arr){ console.log(value) } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## exercise : Landscape portrait ```jsx function isLandScape(width,height) { return (width>height) } console.log(isLandScape(100, 96)); ``` ## exercise : fizzbuzz ```jsx // divisble by 3 => fizz // divisble by 5 => Buzz // divisble by both 3 and 5 => fizzBuzz // not divisble by both 3 or 5 => input // not a number => "not a number" function fizzBuzz(input) { if (typeof input != "number") { console.log("not a number"); return; } if (input % 3 == 0 && input % 5 == 0) { console.log("fizzBuzz"); } else if (input % 5 == 0) { console.log("Buzz"); } else if (input % 3 == 0) { console.log("fizz"); } else { console.log(input); } } fizzBuzz(3); fizzBuzz(5); fizzBuzz(15); fizzBuzz(7); fizzBuzz("hi"); ``` ## exercise : demerit points ```jsx //speed limit = 70 // 5 => 1 point // Math.floor(1.3) // 12 points -> suspended function checkSpeed(speed) { points = Math.floor((speed - 70) / 5); if (points == 0) { console.log("you are OK"); } else if (points > 12) { console.log("suspended"); } else { console.log(points); } } checkSpeed(180); ``` ## exercise : even or odd ```jsx // number = 10 // 0 -> 10 determine if even or odd function showNumbers(limits) { let type; for (let i = 0; i <= limits; i++) { type = i % 2 == 0 ? "even" : "false"; console.log(i, type) } } showNumbers(10); ``` ## exercise : string properties ```jsx // print string values in an object let person = { name: "ahmed", age: 25, grade: "A" } showProperties(person); function showProperties(obj) { for (let key in obj) { if (typeof obj[key] == "string") { console.log(key, obj[key]); } } } ``` ## exercise : sum of multiple ```jsx // print string values in an object let person = { name: "ahmed", age: 25, grade: "A" } showProperties(person); function showProperties(obj) { for (let key in obj) { if (typeof obj[key] == "string") { console.log(key, obj[key]); } } } ``` ## exercise : Grade ```jsx // average // 1-59 : F // 60-69 : D // 70-79 : C // 80-89 : B // 90-100 : A const marks = [80, 80, 50]; function calculateGrade(marks) { let sumGrade = 0 , average; for (let value of marks) { sumGrade += value; } average = sumGrade / marks.length; if (average > 90 && average <= 100) return "A"; if (average > 80 && average <= 90) return "B" if (average > 70 && average <= 80) return "C" if (average > 60 && average <= 70) return "D" if (average > 1 && average <= 59) return "F" } console.log(calculateGrade(marks)); ``` ## exercise : show stars ```jsx // print stars // showstars(5) //* //** //*** //**** //***** function showStars(number) { for (let i = 0; i <= number; i++) { let output = ""; for (let j = 0; j < i; j++) { output += "*" } console.log(output); } } showStars(5) ``` ## exercise : show primes ```jsx // showPrimes(10) // show prime number between 1 to 10 function showPrimes(limit) { for (let number = 2; number < limit; number++){ let status = true ; for (let factor = 2; factor < number; factor++){ if (number % factor == 0) { status = false; break; } } if (status == true) console.log(number); } } showPrimes(2); ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> # section 4 : Objects > **Object** : it’s used to hold multiple property with different data types related to one big variable like circle “object” with it’s property “radius , color” > ## defining an object ```jsx let circle = { radius : 5, color: "string", draw(){ //method console.log(radius,color) } }; circle.draw(); console.log(circle.radius) ``` <aside> 👀 if function part of object we call it **method** like “draw function above” </aside> <p align="right">(<a href="#readme-top">back to top</a>)</p> ## factory function **factory function :** is used to define multiple object for example if we have multiple circle we don’t have to implement new object for each one **camal notation** ```jsx function factoryFunction(radius, color) { return { radius, color, draw() { console.log(`radius:${radius} color:${color}`); } } } let circle1 = factoryFunction(1, "blue"); let circle1 = factoryFunction(2, "green"); circle1.draw(); circle2.draw(); ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## constructor function **constructor function :** it’s the same as factory function with different implementation **pascal notation** ```jsx function ConstructorFunction(radius, color) { this.radius = radius; this.color = color; this.draw = function (radius, color) { console.log(`radius:${this.radius} color:${this.color}`); } } let circle1 = new ConstructorFunction(2, "green"); circle1.draw(); ``` new key word do three things : 1. create new empty object 2. assign this.property to the new object 3. return the object with it’s property <p align="right">(<a href="#readme-top">back to top</a>)</p> ## Primitive and reference **primitives data types** : are copied by value “string,number,bool,..etc” ```jsx let x=5 ; let y=x; // we copy value of x into y x++; console.log(y); // will print 5 ``` **references data types** : are copied by reference “object , array , function ” ```jsx let x = {value : 20 } let y = x ; x.value++ ; console.log(y.value); // will print 21 because we change the refernce of value object in memory ``` ### cloning object we have three different way to copy values of object into another object : 1. iterate over each value in the object and copy it to another value ```jsx let person= { name:"ahmed", age: 30 } let person2 = {} for(let key in Object.keys(person)){ person2[key] = person[key] } ``` 1. using spread operator … ```jsx let person= { name:"ahmed", age: 30 } let person2= {...person}; ``` 1. using Object.assign() method ```jsx let person= { name:"ahmed", age: 30 } let perons2 = Object.assign({},person); // {} is intial object that added person to it ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## exercise : address object ```jsx function showAdress(adress) { for (let key in adress) console.log(`${key} : ${adress[key]}`); } let adress = { street: "bank street", city: "ismalia", zipcode: 562, } showAdress(adress); ``` ## exercise : constructor & factory address object ```jsx function ConstructorFunction(street, city, zipcode) { this.street = street; this.city = city; this.zipcode = zipcode; } function factoryFunction(street, city, zipcode) { return { street, city, zipcode, } } let address1 = new ConstructorFunction("bank street", "ismalia", 456); let address2 = factoryFunction("bank street", "ismalia", 456); console.log(address1); console.log(address2); ``` ## exercise : Object equality ```jsx // areEqual(obj1, obj2) => check if the two object are equal in values and keys // areSame(obj1,obj2) => check if the two object points to the same adress function ConstructorFunction(street, city, zipcode) { this.street = street; this.city = city; this.zipcode = zipcode; } let address1 = new ConstructorFunction("bank street", "ismalia", 456); let address2 = new ConstructorFunction("bank street", "ismalia", 456); let address3 = address1 function areEqual(address1, address2) { for (let key in address1) { if (address1[key] !== address2[key]) return false; } return true; } function areSame(address1, address2) { return address1 === address2 ? true : false; } console.log(areEqual(address1, address2)); console.log(areSame(address1, address3)); ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> # section 5 : array ## adding in array we have three ways with three different position for add into array : 1. at the end: arr.push(5); 2. at the front : arr.unshift(1); 3. at the middle : arr.splice(1,0,5); ```jsx let arr = [1,2,3]; arr.push(4); //adding at the end arr.unshift(1); //adding at the front arr.splice(1,0,5,6,7); //adding at the middle ,,, splice(index elemetnt to start with , Nof element in you want to delete , elements you want to add) ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## removing in array we have three ways with three different position for deleting from array : 1. at the end: arr.pop(5); 2. at the front : arr.shift(1); 3. at the middle : arr.splice(1,2); ```jsx let arr = [1,2,3]; arr.pop(4); //removing at the end arr.shift(1); //removing at the front arr.splice(1,2); //adding at the middle ,,, splice(index elemetnt to start with , Nof element in you want to delete , elements you want to add) ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## find in array - to find index of element in array we use **arrName.findIndex(element)** - to check if the element exists in array or not we use **arrName.includes(element)** - to find reference datatype element we use arrName.find((element) ⇒ return condition) - to find index of reference datatype element we use arrName.findIndex((element) ⇒ return condition) ```jsx let arr = [3,4,5,6]; console.log(arr.findIndex(3)); // will print 0 console.log(arr.includes(7)); // will return false because "arr" doesn't have "7" let persons = [ { name: "ahmed eid", age: "24" }, { name: "soliman faisel", age : "42"} ] console.log(persons.find((element) => { return element.name == "ahmed eid" })) console.log(persons.findIndex((element) => { return element.name == "soliman faisel" })) ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## emptying array - arr = [] we use this way if your array doesn’t refered by other variables - arr.length=0 - arr.splice(0,arr.length); <p align="right">(<a href="#readme-top">back to top</a>)</p> ## combining array - concat method : used to merge two arrays and return array as result - slice : to cut a slice or part of an array and return it ```jsx let arr1=[1,2,3]; let arr2=[4,5,6]; let result = arr1.concat(arr2); // result = [1,2,3]+[4,5,6] = [1,2,3,4,5,6] let shot = arr.slice(2,4); ``` <aside> 🔥 those two method when we use in array of reference data type like object it’s concat by refernce </aside> <aside> 🔥 we can use slice to take a copy of arrays value into another array ,,, copy by value let arr1=[1,2,3] let arr2= arr1.slice() </aside> <p align="right">(<a href="#readme-top">back to top</a>)</p> ## spread operator - take a copy or merge arrays to new array ```jsx let arr=[1,2,3]; let arr2=[4,5,6]; let result = [...arr1,"a","b","c", ...arr2] ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## iteration ```jsx let arr = ["first","second","third"] ; arr.forEach((element)=>{console.log(`this is ${element}`)}) ; // this iteration don't change the orginal value of array ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## joining array we have two methods : - join() : convert array to string [1,2,3].join(”/”) ⇒ “1/2/3” - split(): convert string to array “hello it’s me”.split(” “) ⇒ [”hello”, ”it’s” , “me” ] <p align="right">(<a href="#readme-top">back to top</a>)</p> ## sorting array we have two methods : - sort() : sort array from assending [1,7,2,5,3].sort() ⇒ [1,2,3,5,7] - reverse() : reverse the array elements [1,2,3,5,7].reverse() ⇒ [7,5,3,2,1] <p align="right">(<a href="#readme-top">back to top</a>)</p> ## testing array we have two methods : - every () : to check that every element in array based in condition - some() : to check if at least one of the element do condition ```jsx let arr1 = [2,4,6,8] ; let arr2 = [-1,4,2,3]; let checkEven = arr1.every(element => element%2==0); let atLeastOneNegative = arr.some(element => element<0) ``` ## filter array return filtered array based on condition ```jsx let arr = [-1,4,2,3]; let onlyPositive = arr.filter(element => element>0) ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## exercise : array range ```jsx function arrRange(start, end) { let arr = []; for (start; start <= end; start++) arr.push(start); return arr; } let result = arrRange(1, 5); console.log(result); ``` ## exercise : includes ```jsx function includes(arr, searchElement) { for (let value of arr) { if (searchElement === value) return true; } return false; } let arr = [1, 2, 3, 4]; console.log(arr.includes(2)); ``` ## exercise : except ```jsx // remove elements from array function except(array, execluded) { return array.filter((elemment) => { return !(execluded.includes(elemment)) }) } let numbers = [1, 2, 3, 4]; const output = except(numbers, [1]); console.log(output); ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> # section 6 : functions ## arguments & parameters > every function have a special object called arguments which return parameters you passed as itertable object object it’s useful if you have undetermined number of arguments > ```jsx function person(){ console.log(arguments); } person("ahmed",24,"egypt"); ``` > if you want to point to group of arguments in one parameter we use spread operator “…” it return parameters as an array > ```jsx function person(name,...parameters){ console.log(name); // this will print "ahmed" console.log(parameters); // this will print [25, "egypt","software"] } person("ahmed",25,"egypt","software"); ``` ### default paramters ```jsx function person(name,age = 22 , address){ console.log(name,age,address); // this will print "ahmed",22,address } person("ahmed",undefined, "egypt"); ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## getter and setter > getter and setter : if we want to create a function that return object data and access it as property with dot notation > ```jsx let person = { firstName: "ahmed", lastName: "eid", get fullName() { return `${this.firstName} ${this.lastName}` }, set fullName(value) { fullNameArray = value.split(" ") this.firstName = fullNameArray[0]; this.lastName = fullNameArray[1]; } } person.fullName = "mohamed hassan" console.log(person.fullName); ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## errors and exception <aside> 🔥 error is defining Error object, exception where we throw the error we define </aside> ```jsx function onlyPositive(number) { if (number < 0) { throw new Error("only positive values"); } else { console.log(`${number} is postive`); } } try { onlyPositive(-5) } catch (error) { // error : is the Error object we throw console.log(error); } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## let vs var <aside> 🔥 let is block scope but var is function scope </aside> ```jsx //let function test(){ if(true){ let number = 5; } console.log(number); // will return error because "number" variable aren't defined in this scope } //var function test2(){ if(true){ var number = 5; } console.log(number); // will return "5" because "number variables" assigned to test2() function scope } ``` <aside> 🔥 var isn’t recommended because if we define it in global scope it’s assigned to window object so if window object use third party that have the same var variable name it will be overwritten </aside> <p align="right">(<a href="#readme-top">back to top</a>)</p> ## This keyword <aside> 🔥 this is the object that executing the current object </aside> ```jsx let obj = { name:"ahmed", tags : ["egypt",25,"bank street"] display(){ console.log(this) } } obj.display(); // it's will print the object that contain this obj = {name: "ahmed , tags : [...]} ``` > in methods this refer to object which it’s belongs to in functions this refer to window or global object > ```jsx let obj = { name:"ahmed", tags : ["egypt",25,"bank street"] display(){ console.log(this) // this refers to obj object } } function test(){ console.log(this); //this refer to window object } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ### changing this ```jsx let obj = { name:"ahmed", tags : ["egypt",25,"bank street"] display(){ this.tags.forEach(function (tag){ console.log(this.name); // it will print undefined because "this" refer to window object // function is part of window scope }) } } //solution1 bind() // bind() it's bind your function to new object and return new function with new object binded let obj = { name:"ahmed", tags : ["egypt",25,"bank street"] display(){ this.tags.forEach(function (tag){ console.log(this.name); }.bind(this)); } } //solution2 arrow function // arrow function ()=>{} : inhernet this from containg function let obj = { name:"ahmed", tags : ["egypt",25,"bank street"] display(){ this.tags.forEach((tag)=>{ console.log(this.name); }); } } ``` <p align="right">(<a href="#readme-top">back to top</a>)</p> ## exercise : sum of arguments ```jsx // return sum of arguments you passed in calling // although accept if the arguments is array function sum(...pars) { let total = 0; for (let value of pars) { if (Array.isArray(value)) { for (let arrValue of value) { total += arrValue; } } else { total += value; } } return total; } console.log(sum([1,2,3,4,5],1, 2, 3, 4, [6],5)); ``` ## exercise : area of circle ```jsx let circle = { radius: 5, get area() { return Math.PI * Math.pow(this.radius, 2); }, set radiusSet(value) { this.radius = value; } } circle.radiusSet = 10; console.log(circle.area); ``` <p align="right">(<a href="#readme-top">back to top</a>)</p>
# ProGen <img align="right" src=".github/assets/PG1-4-3-1.png" alt="drawing" width="60" /> [![test](https://github.com/kozmod/progen/actions/workflows/test.yml/badge.svg)](https://github.com/kozmod/progen/actions/workflows/test.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/kozmod/progen)](https://goreportcard.com/report/github.com/kozmod/progen) ![GitHub go.mod Go version](https://img.shields.io/github/go-mod/go-version/kozmod/progen) ![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/kozmod/progen) ![GitHub release date](https://img.shields.io/github/release-date/kozmod/progen) ![GitHub last commit](https://img.shields.io/github/last-commit/kozmod/progen) [![GitHub MIT license](https://img.shields.io/github/license/kozmod/progen)](https://github.com/kozmod/progen/blob/main/LICENSE) A flexible, language and frameworks agnostic tool that allows you to generate projects structure from templates based on `yaml` configuration (generate directories, files and execute commands). ___ ### Installation ```shell go install github.com/kozmod/progen@latest ``` ### Build from source ```shell make build ``` ___ ### Flags | Name | Type | Default | Description | |:------------------------------------------------|:--------:|:------------:|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `-f`[<sup>**ⓘ**</sup>](#config_file) | string | `progen.yml` | specify configuration file path | | `-v` | bool | `false` | verbose output | | `-dr`[<sup>**ⓘ**</sup>](#dry_run) | bool | `false` | `dry run` mode <br/>(to verbose output should be combine with`-v`) | | `-awd`[<sup>**ⓘ**</sup>](#awd) | string | `.` | application working directory | | `-printconf`[<sup>**ⓘ**</sup>](#print_config) | bool | `false` | output processed config | | `-errtrace`[<sup>**ⓘ**</sup>](#print_err_trace) | bool | `false` | output errors stack trace | | `-pf`[<sup>**ⓘ**</sup>](#files_preprocessing) | bool | `true` | `preprocessing files`: load and process all files <br/>(all files `actions`[<sup>**ⓘ**</sup>](#files_actio_desk)) as [text/template](https://pkg.go.dev/text/template) before creating | | `-tvar`[<sup>**ⓘ**</sup>](#tvar) | []string | `[ ]` | [text/template](https://pkg.go.dev/text/template) variables <br/>(override config variables tree) | | `-missingkey` | []string | `error` | set `missingkey`[text/template.Option](https://pkg.go.dev/text/template#Template.Option) execution option | | `-skip`[<sup>**ⓘ**</sup>](#skip_actions) | []string | `[ ]` | skip any `action` tag <br/>(regular expression) | | `-gp`[<sup>**ⓘ**</sup>](#groups_of_actions) | []string | `[ ]` | set of the action's groups to execution | | `-version` | bool | `false` | print version | | `-help` | bool | `false` | show flags | ___ ### Actions and tags | Key | Type | Optional | Description | |:--------------------------------------------------------------------------------|:-----------------:|:---------|:------------------------------------------------------------------------------------------------------------| | | | | | | settings | | ✅ | `progen` settings section | | | | | | settings.http[<sup>**ⓘ**</sup>](#http_client) | | ✅ | http client configuration | | settings.http.debug | bool | ✅ | http client `DEBUG` mode | | settings.http.base_url | string | ✅ | http client base `URL` | | settings.http.headers | map[string]string | ✅ | http client base request `Headers` | | settings.http.query_params | map[string]string | ✅ | http client base request `Query Parameters` | | | | | | | settings.groups[<sup>**ⓘ**</sup>](#groups_of_actions) | | ✅ | groups of actions | | settings.groups.name | string | ✅ | group's name | | settings.groups.actions | []string | ✅ | actions names | | settings.groups.manual | bool | ✅ | determines that the group starts automatically (default `false`) | | | | | | | dirs`<unique_suffix>`[<sup>**ⓘ**</sup>](#Generate) | []string | ✅ | list of directories to create | | | | | | | rm`<unique_suffix>`[<sup>**ⓘ**</sup>](#rm) | []string | ✅ | list for remove (files, dirs, all file in a dir) | | | | | | | <a name="files_actio_desk"><a/>files`<unique_suffix>`[<sup>**ⓘ**</sup>](#Files) | | ✅ | list file's `path` and `data` | | files.path | string | ❌ | save file `path` | | files.local | string | `❕` | local file path to copy | | files.data | string | `❕` | save file `data` | | | | | | | files.get | | `❕` | struct describe `GET` request for getting file's data | | files.get.url | string | ❌ | request `URL` | | files.get.headers | map[string]string | ✅ | request `Headers` | | files.get.query_params | map[string]string | ✅ | request `Query Parameters` | | | | | | | cmd`<unique_suffix>`[<sup>**ⓘ**</sup>](#Commands) | | ✅ | configuration command list | | cmd.exec | string | ❌ | command to execution | | cmd.args | []slice | ✅ | list of command's arguments | | cmd.dir | string | ✅ | execution commands (`cmd.exec`) directory | | | | | | | fs[<sup>**ⓘ**</sup>](#fs) | []string | ✅ | execute [text/template.Option](https://pkg.go.dev/text/template#Template.Option) on the list of directories | `❕` only one must be specified in parent section ___ ## Usage ### Generate The cli executes commands and generate files and directories based on configuration file ```yaml ## progen.yml # list directories to creation dirs: - x/y # list files to creation files: - path: x/some_file.txt data: | some data # list commands to execution cmd: - touch second_file.txt - tree ``` ```console % progen -v 2023-02-05 14:11:47 INFO application working directory: /Users/user_1/GoProjects/service 2023-02-05 14:11:47 INFO configuration file: progen.yml 2023-02-05 14:11:47 INFO file process: x/some_file.txt 2023-02-05 14:11:47 INFO dir created: x/y 2023-02-05 14:11:47 INFO file saved: x/some_file.txt 2023-02-05 14:11:47 INFO execute [dir: .]: touch second_file.txt 2023-02-05 14:11:47 INFO execute [dir: .]: tree out: . ├── second_file.txt └── x ├── some_file.txt └── y 2 directories, 2 files ``` ### Execution All actions execute in declared order. Base actions (`dir`, `files`,`cmd`) could be configured with `<unique_suffix>` to separate action execution. ```yaml ## progen.yml dirs1: - api/some_project/v1 cmd1: - chmod -R 777 api dirs2: - api/some_project_2/v1 cmd2: - chmod -R 777 api ``` ```console % progen -v 2023-01-22 13:38:52 INFO application working direcotry: /Users/user_1/GoProjects/service 2023-01-22 13:38:52 INFO dir created: api/some_project/v1 2023-01-22 13:38:52 INFO execute [dir: .]: chmod -R 777 api 2023-01-22 13:38:52 INFO dir created: api/some_project_2/v1 2023-01-22 13:38:52 INFO execute [dir: .]: chmod -R 777 api ``` ### Templates Configuration preprocessing uses [text/template](https://pkg.go.dev/text/template) of golang's `stdlib`. Using templates could be useful to avoiding duplication in configuration file. All `text/template` variables must be declared as comments and can be used only to configure data of configuration file (all ones skipping for `file.data` section). Configuration's `yaml` tag tree also use as `text/template` variables dictionary and can be use for avoiding duplication in configuration file and files contents (`files` section). ```yaml ## progen.yml ## `text/template` variables declaration 👇 # {{$project_name := "SOME_PROJECT"}} ## unmapped section (not `dirs`, `files`, `cmd`, `http`) can be use as template variables vars: file_path: some/file/path dirs: - api/{{$project_name}}/v1 # used from `text/template` variables - internal/{{.vars.file_path}} # used from `vars` section - pkg/{{printf `%s-%s` $project_name `data`}} files: - path: internal/{{$project_name}}.txt data: | Project name:{{$project_name}} - path: pkg/{{printf `%s-%s` $project_name `data`}}/some_file.txt data: | {{$project_name}} cmd: - "cat internal/{{$project_name}}.txt" - exec: ls dir: . args: [ -l ] - exec: tree ``` ```console % progen -v 2023-01-22 13:03:58 INFO current working direcotry: /Users/user_1/GoProjects/service 2023-02-05 14:47:25 INFO application working directory: /Users/user_1/GoProjects/service 2023-02-05 14:47:25 INFO configuration file: progen.yaml 2023-02-05 14:47:25 INFO file process: internal/SOME_PROJECT.txt 2023-02-05 14:47:25 INFO file process: pkg/SOME_PROJECT-data/some_file.txt 2023-02-05 14:47:25 INFO dir created: api/SOME_PROJECT/v1 2023-02-05 14:47:25 INFO dir created: internal/some/file/path 2023-02-05 14:47:25 INFO dir created: pkg/SOME_PROJECT-data 2023-02-05 14:47:25 INFO file saved: internal/SOME_PROJECT.txt 2023-02-05 14:47:25 INFO file saved: pkg/SOME_PROJECT-data/some_file.txt 2023-02-05 14:47:25 INFO execute [dir: .]: cat internal/SOME_PROJECT.txt out: Project name:SOME_PROJECT 2023-02-05 14:47:25 INFO execute [dir: .]: ls -l out: total 0 drwxr-xr-x 3 19798572 646495703 96 Feb 5 14:47 api drwxr-xr-x 4 19798572 646495703 128 Feb 5 14:47 internal drwxr-xr-x 3 19798572 646495703 96 Feb 5 14:47 pkg 2023-02-05 14:47:25 INFO execute [dir: .]: tree out: . ├── api │   └── SOME_PROJECT │   └── v1 ├── internal │   ├── SOME_PROJECT.txt │   └── some │   └── file │   └── path ├── pkg │   └── SOME_PROJECT-data │   └── some_file.txt └── progen.yml 9 directories, 2 files ``` #### Custom template functions | Function | args | Description | |:------------------|:----------------------------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | `random` | | `random.Alpha` | length `int` | Generates a random alphabetical `(A-Z, a-z)` string of a desired length. | | `random.Num` | length `int` | Generates a random numeric `(0-9)` string of a desired length. | | `random.AlphaNum` | length `int` | Generates a random alphanumeric `(0-9, A-Z, a-z)` string of a desired length. | | `random.ASCII` | length `int` | Generates a random string of a desired length, containing the set of printable characters from the 7-bit ASCII set. This includes space (’ ‘), but no other whitespace character. | | `slice` | | | | `slice.New` | N `any` elements | Create new slice from any numbers of elements <br/>(`{ $element := slice.New "a" 1 "b" }}`) | | `slice.Append` | slice,<br/> N `any` elements | Add element to exists slice <br/>(`{{ $element := slice.Append $element "b"}}`) | | `strings` | | | | `strings.Replace` | s, old, new string, n int | Replace returns a copy of the string `s` with `old` replaced by `new` (work the same as `strings.Replace` from `stdlib`). | Custom template's functions added as custom arguments to the template [function map](https://pkg.go.dev/text/template#hdr-Functions). --- ## Flags ### <a name="config_file"><a/>Configuration file By default `progen` try to find `progen.yml` file for execution. `-f` flag specify custom configuration file location: ```console progen -f custom_conf.yaml ``` Instead of specifying a config file, you can pass a single configuration file in the pipe the file in via `STDIN`. To pipe a `progen.yml` from `STDIN`: ```console progen - < progen.yml ``` or ```console cat progen.yml | progen - ``` If you use `STDIN` the system ignores any `-f` option. **Example** (get `progen.yml` from gitlab repository with replacing [text/template](https://pkg.go.dev/text/template) variables using `-tvar` flag): ```console curl -H PRIVATE-TOKEN:token https://gitlab.some.com/api/v4/projects/13/repository/files/shared%2Fteplates%2Fsimple%2Fprogen.yml/raw\?ref\=feature/templates | progen -v -dr -tvar=.vars.GOPROXY=some_proxy - ``` ### <a name="print_err_trace"><a/>Print error stack trace To print a stack trace of the error which occurred during execution of the `cli`, use `-errtrace` flag: ```console % progen -f ../not_exists_config.yml 2023-03-04 15:05:54 FATAL read config: config file: github.com/kozmod/progen/internal/config.(*Reader).Read /Users/some_user/projects/progen/internal/config/reader.go:39 - open ../not_exists_config.yml: no such file or directory ``` ### <a name="dry_run"><a/>Dry Run mode The `-dr` flag uses to execute configuration in dry run mod. All `action` will be executed without applying. ```yaml ## progen.yml # {{$project_name := "SOME_PROJECT"}} dirs: - api/{{ $project_name }}/v1 # apply template variables, but not create directories on 'dry run' cmd: - tree # not execute on 'dry run' mode files: - path: api/v1/some_file.txt # apply template variables and only printing the file's data data: | some file data data fot project: {{ $project_name }} ``` ```console % progen -v -dr 2023-03-07 07:57:52 INFO application working directory: /Users/user_1/GoProjects/service 2023-03-07 07:57:52 INFO configuration file: progen.yml 2023-03-07 07:57:52 INFO file process: api/v1/some_file.txt 2023-03-07 07:57:52 INFO dir created: api/SOME_PROJECT/v1 2023-03-07 07:57:52 INFO execute [dir: .]: tree 2023-03-07 07:57:52 INFO save file: create dir [api/v1] to store file [%!s(func() string=0x136ecc0)] 2023-03-07 07:57:52 INFO file saved [path: api/v1/some_file.txt]: some file data data fot project: SOME_PROJECT 2023-03-07 07:57:52 INFO execution time: 3.69506ms ``` ### <a name="awd"><a/>Application working directory The `-awd` flag uses for setting application working directory. All `paths` declared in the config file are calculated considering the root directory. ### <a name="print_config"><a/>Print configuration file To print the configuration file after processing as [text/template](https://pkg.go.dev/text/template), use `-printconf` flag: ```yaml ## progen.yml vars: some_data: VARS_SOME_DATA # {{- $var_1 := random.AlphaNum 15}} # {{- $var_2 := "echo some_%s"}} cmd: - echo {{ $var_1 }} - "{{ printf $var_2 `value` }}" - echo {{ .vars.some_data }} ``` ```console % progen -printconf 2023-03-04 14:57:43 INFO preprocessed config: vars: some_data: VARS_SOME_DATA # # cmd: - echo AHNsgyzVxRqeqLt - "echo some_value" - echo VARS_SOME_DATA ``` ### <a name="files_preprocessing"><a/>Files preprocessing By default, all files loading to the memory and process as [text/template](https://pkg.go.dev/text/template) before saving to a file system. To change this behavior, set `-pf=false`. ```console % progen -v -dr -f progen.yml 2023-02-05 14:15:54 INFO application working directory: /Users/user_1/GoProjects/service 2023-02-05 14:15:54 INFO configuration file: progen.yml 2023-02-05 14:15:54 INFO file process: api/v1/some_file.txt 2023-02-05 14:15:54 INFO dir created: api/SOME_PROJECT/v1 2023-02-05 14:15:54 INFO execute cmd: chmod -R 777 api/v1 2023-02-05 14:15:54 INFO save file: create dir [api/v1] to store file [some_file.txt] 2023-02-05 14:15:54 INFO file saved [path: api/v1/some_file.txt]: some file data data fot project: SOME_PROJECT ``` ### <a name="tvar"><a/>Template variables Any part of template variable tree can be overrides using `-tvar` flag ```yaml ## progen.yml ## `text/template` variables declaration 👇 # {{$project_name := "SOME_PROJECT"}} ## unmapped section (not `dirs`, `files`, `cmd`, `http`) can be use as template variables vars: file_path: some/file/path file_path_2: some/file/path_2 dirs: - api/{{$project_name}}/v1 # used from `text/template` variables - internal/{{.vars.file_path}} # used from `vars` section - internal/{{.vars.file_path_2}} # used overridden `vars` which set through args (-tvar=.vars.file_path 2=override path) ``` ```console % progen -v -dr -tvar=.vars.file_path_2=overrided_path 2023-02-05 14:51:38 INFO application working directory: /Users/user_1/GoProjects/service 2023-02-05 14:51:38 INFO configuration file: progen.yml 2023-02-05 14:51:38 INFO dir created: api/SOME_PROJECT/v1 2023-02-05 14:51:38 INFO dir created: internal/some/file/path 2023-02-05 14:51:38 INFO dir created: internal/overrided_path ``` ### <a name="skip_actions"><a/>Skip `actions` Set `-skip` flag to skip any `action` (only root actions: `cmd`, `files`, `dirs`). Value of the flag is a regular expression. ```yaml ## progen.yml dirs: - api/v1 cmd: - chmod -R 777 api/v1 dirs1: - api/v2 cmd1: - chmod -R 777 api/v2 dirs2: - api/v3 cmd2: - chmod -R 777 api/v3 ``` ```console % progen -v -dr -f progen.yml -skip=^dirs$ -skip=cmd.+ 2023-02-05 14:18:11 INFO application working directory: /Users/user_1/GoProjects/service 2023-02-05 14:18:11 INFO configuration file: progen.yml 2023-02-05 14:18:11 INFO action will be skipped: [cmd1] 2023-02-05 14:18:11 INFO action will be skipped: [cmd2] 2023-02-05 14:18:11 INFO action will be skipped: [dirs] 2023-02-05 14:18:11 INFO execute cmd: chmod -R 777 api/v1 2023-02-05 14:18:11 INFO dir created: api/v2 2023-02-05 14:18:11 INFO dir created: api/v3 ``` --- ## Actions and tags ### <a name="http_client"></a>Http Client HTTP client configuration ```yaml ## progen.yml settings: http: debug: false base_url: https://gitlab.repo_2.com/api/v4/projects/5/repository/files/ headers: PRIVATE-TOKEN: glpat-SOME_TOKEN query_params: PARAM_1: Val_1 ``` ### <a name="groups_of_actions"></a>Groups of actions All actions execute in declaration order in the config file and can be union to groups. All actions in `manual` groups will be skipped during execution process. ```yaml settings: groups: - name: group1 actions: [ cmd, cmd_2 ] manual: true - name: group2 actions: [ cmd_2 ] manual: true cmd: - echo CMD_1 cmd_2: - echo CMD_2 cmd_3: - echo CMD_3 cmd_4: - echo CMD_4 ``` ```console % progen -v 2024-02-05 23:08:21 INFO application working directory: /Users/user_1/GoProjects/service 2024-02-05 23:08:21 INFO configuration file: progen.yml 2024-02-05 23:08:21 INFO manual actions will be skipped: [cmd, cmd_2] 2024-02-05 23:08:21 INFO execute [dir: .]: echo CMD_3 out: CMD_3 2024-02-05 23:08:21 INFO execute [dir: .]: echo CMD_4 out: CMD_4 2024-02-05 23:08:21 INFO execution time: 7.916615ms ``` Actions in `manual` groups execute using `gp` flag (all action execute only once independent on declaration's quantity in different groups). ```console % progen -v -gp=group1 -gp=group2 2024-02-05 23:19:50 INFO application working directory: /Users/user_1/GoProjects/service 2024-02-05 23:19:50 INFO configuration file: progen.yml 2024-02-05 23:19:50 INFO groups will be execute: [group1, group2] 2024-02-05 23:19:50 INFO execute [dir: .]: echo CMD_1 out: CMD_1 2024-02-05 23:19:50 INFO execute [dir: .]: echo CMD_2 out: CMD_2 2024-02-05 23:19:50 INFO execution time: 7.192257ms ``` ### Files File's content can be declared in configuration file (`files.data` tag) or can be received from local (`files.local`) or remote (`files.get`) storage. Any file's content uses as [text/template](https://pkg.go.dev/text/template) and configuration's `yaml` tag tree applies as template variables. ```yaml ## progen.yml # settings of the cli settings: # common http client configuration http: debug: false base_url: https://gitlab.repo_2.com/api/v4/projects/5/repository/files/ headers: PRIVATE-TOKEN: glpat-SOME_TOKEN # {{$project_name := "SOME_PROJECT"}} # {{$gitlab_suffix := "/raw?ref=some_branch"}} files: - path: files/Readme.md data: | Project name: {{$project_name}} - path: files/.gitignore # copy file from location local: some/dir/.gitignore.gotmpl - path: files/.editorconfig get: url: "{{printf `%s%s` `.editorconfig` $gitlab_suffix}}" - path: files/.gitlab-ci.yml # GET file from remote storage get: # reset URL which set in http client configuration (http.base_url) url: "https://some_file_server.com/files/.gitlab-ci.yml" # reset headers of common http client configuration (http.headers) headers: some_header: header query_params: PARAM_1: Val_1 - path: files/Dockerfile # GET file from remote storage (using common http client config) get: # reuse `base` URL of common http client config (http.base_url) url: Dockerfile/raw?ref=feature/project_templates" ``` ```console % progen -v 2023-02-05 14:47:25 INFO current working direcotry: /Users/user_1/GoProjects/service 2023-02-05 14:47:25 INFO configuration file: progen.yaml 2023-02-05 14:47:25 INFO file process: files/Readme.md 2023-02-05 14:47:25 INFO file process: files/.gitignore 2023-02-05 14:47:25 INFO file process: files/.editorconfig 2023-02-05 14:47:25 INFO file process: files/.gitlab-ci.yml 2023-02-05 14:47:25 INFO file process: files/Dockerfile ... 2023-02-05 14:47:25 INFO file saved: files/Readme.md 2023-02-05 14:47:25 INFO file saved: files/.gitignore 2023-02-05 14:47:25 INFO file saved: files/.editorconfig 2023-02-05 14:47:25 INFO file saved: files/.gitlab-ci.yml 2023-02-05 14:47:25 INFO file saved: files/Dockerfile ... ``` ### Commands Execution commands process configured by specifying __commands working directory__ and commands definition. Default value of __commands working directory__ (`dir` tag) is `.`. __Commands working directory__ calculate from the __application working directory__. ```yaml ## progen.yml cmd: - exec: ls -l args: [ - l ] dir: .github/workflows - exec: tree args: [ -L, 1 ] ``` ```console % progen -v 2023-02-02 22:18:20 INFO application working directory: /Users/user_1/GoProjects/progen 2023-02-02 22:18:20 INFO configuration read: progen.yml 2023-02-02 22:18:20 INFO execute [dir: .github/workflows]: ls -l out: total 16 -rw-r--r-- 1 19798572 646495703 762 Feb 1 09:15 release.yml -rw-r--r-- 1 19798572 646495703 377 Jan 24 20:06 test.yml 2023-02-02 22:18:20 INFO execute [dir: .]: tree -L 1 out: . ├── LICENSE ├── Makefile ├── Readme.md ├── go.mod ├── go.sum ├── internal ├── main.go └── tmp 2 directories, 6 files ``` `cmd` action maintains "short" declaration syntax ```yaml ## progen.yml cmd: - pwd - ls -a ``` ```console % progen -v -dr 2023-02-15 17:56:58 INFO application working directory: /Users/user_1/GoProjects/progen 2023-02-15 17:56:58 INFO configuration file: short.yml 2023-02-15 17:56:58 INFO execute [dir: .]: pwd 2023-02-15 17:56:58 INFO execute [dir: .]: ls -a ``` ### <a name="fs"></a>File System `fs` section configure execution [text/template](https://pkg.go.dev/text/template) on a directories tree. All files in the `tree` processed as `template`. Files and directories names also could be configured as templates. ```yaml ## progen.yml var_d: VAR_d var_f: VAR_f cmd: - cp -a ../asserts/. ../out/ - exec: tree dir: . fs: - test_dir - test_dir_2 cmd_finish: - exec: tree dir: . ``` ```console % progen -v -awd=out -f ../progen.yml 2023-02-12 14:01:45 INFO application working directory: /Users/user_1/GoProjects/progen 2023-02-12 14:01:45 INFO configuration file: ../progen.yml 2023-02-12 14:01:45 INFO execute [dir: .]: cp -a ../asserts/. ../out/ 2023-02-12 14:01:45 INFO execute [dir: .]: tree out: . ├── test_dir │   ├── file1 │   └── {{ .var_d }} │   └── {{ .var_f }} └── test_dir_2 ├── file1 └── {{ .var_d }} └── {{ .var_f }} 4 directories, 4 files 2023-02-12 14:01:45 INFO dir created: test_dir/VAR_d 2023-02-12 14:01:45 INFO file saved: test_dir/file1 2023-02-12 14:01:45 INFO file saved: test_dir/VAR_d/VAR_f 2023-02-12 14:01:45 INFO dir created: test_dir_2/VAR_d 2023-02-12 14:01:45 INFO file saved: test_dir_2/file1 2023-02-12 14:01:45 INFO file saved: test_dir_2/VAR_d/VAR_f 2023-02-12 14:01:45 INFO fs: remove: test_dir_2/{{ .var_d }}/{{ .var_f }} 2023-02-12 14:01:45 INFO fs: remove: test_dir_2/{{ .var_d }} 2023-02-12 14:01:45 INFO execute [dir: .]: tree out: . ├── test_dir │   ├── VAR_d │   │   └── VAR_f │   └── file1 └── test_dir_2 ├── VAR_d │   └── VAR_f └── file1 ``` ### <a name="rm"></a>Rm `rm` use to remove files, directories or files inside a directory. ```yaml rm: # remove the dir - some_dir # remove all files in the dir - some_dir_2/* # remove the file - some_dir_3/file.txt ``` ```console % progen -v 2024-02-09 22:50:51 INFO application working directory: /Users/user_1/GoProjects/progen 2023-02-12 14:01:45 INFO configuration file: progen.yml 2024-02-09 22:50:51 INFO rm: some_dir 2024-02-09 22:50:51 INFO rm all: some_dir_2/* 2024-02-09 22:50:51 INFO rm: some_dir_3/file.txt 2024-02-09 22:50:51 INFO execution time: 350.149µs ``` --- ### Examples [progen-example](https://github.com/kozmod/progen-examples) repository contains useful examples of usage cli
/* * Copyright 2024 MusicScience37 (Kenta Kabashima) * * 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. */ /*! * \file * \brief Definition of object class. */ #pragma once #include <cstring> #include "msgpack_light/details/allocator_wrapper.h" // IWYU pragma: export #include "msgpack_light/details/array_iterator.h" // IWYU pragma: export #include "msgpack_light/details/array_iterator_impl.h" // IWYU pragma: export #include "msgpack_light/details/array_ref.h" // IWYU pragma: export #include "msgpack_light/details/array_ref_impl.h" // IWYU pragma: export #include "msgpack_light/details/extension_ref.h" // IWYU pragma: export #include "msgpack_light/details/map_iterator.h" // IWYU pragma: export #include "msgpack_light/details/map_iterator_impl.h" // IWYU pragma: export #include "msgpack_light/details/map_ref.h" // IWYU pragma: export #include "msgpack_light/details/map_ref_impl.h" // IWYU pragma: export #include "msgpack_light/details/object_base.h" // IWYU pragma: export #include "msgpack_light/details/object_data.h" // IWYU pragma: export #include "msgpack_light/details/object_helper.h" // IWYU pragma: export #include "msgpack_light/details/object_ref.h" // IWYU pragma: export #include "msgpack_light/details/object_ref_decl.h" // IWYU pragma: export #include "msgpack_light/standard_allocator.h" namespace msgpack_light { /*! * \brief Class of objects in MessagePack. * * \tparam Allocator Type of the allocator. */ template <typename Allocator = standard_allocator> class object : public details::mutable_object_base<object<Allocator>, Allocator> { public: //! Type of the base class. using base_type = details::mutable_object_base<object<Allocator>, Allocator>; #ifndef MSGPACK_LIGHT_DOCUMENTATION using base_type::clear; using typename base_type::allocator_type; #endif /*! * \name Initialization and finalization */ //!\{ /*! * \brief Constructor. * * \param[in] allocator Allocator. */ explicit object(allocator_type allocator = allocator_type()) : allocator_(std::move(allocator)) {} /*! * \brief Copy constructor. * * \param[in] other Another instance to copy from. */ object(const object& other) : allocator_(other.allocator_) { details::copy_object_data(data_, other.data_, allocator_); } /*! * \brief Move constructor. * * \param[in,out] other Another instance to move from. */ object(object&& other) noexcept : data_(other.data_), allocator_(std::move(other.allocator_)) { std::memset(&other.data_, 0, sizeof(other.data_)); } /*! * \brief Copy assignment operator. * * \param[in] other Another instance to copy from. * \return This instance after copy. */ object& operator=(const object& other) { if (this == &other) { return *this; } clear(); details::copy_object_data(data_, other.data_, allocator_); return *this; } /*! * \brief Move assignment operator. * * \param[in,out] other Another instance to move from. * \return This instance after move. */ object& operator=(object&& other) noexcept { swap(other); return *this; } /*! * \brief Swap this instance with another instance. * * \param[in,out] other Another instance to move with. */ void swap(object& other) noexcept { std::swap(data_, other.data_); std::swap(allocator_, other.allocator_); } /*! * \brief Destructor. */ ~object() { clear(); } //!\} /*! * \name Internal data * * \warning These functions are for internal implementation of this library. */ //!\{ /*! * \brief Get the internal data. * * \return Internal data. */ [[nodiscard]] details::object_data& data() noexcept { return data_; } /*! * \brief Get the internal data. * * \return Internal data. */ [[nodiscard]] const details::object_data& data() const noexcept { return data_; } /*! * \brief Get the allocator. * * \return Allocator. */ [[nodiscard]] details::allocator_wrapper<Allocator>& allocator() noexcept { return allocator_; } //!\} private: //! Data. details::object_data data_{}; //! Allocator. details::allocator_wrapper<Allocator> allocator_; }; } // namespace msgpack_light
import io import os import random import numpy as np import onnxruntime as ort import telebot from dotenv import load_dotenv from PIL import Image from telebot import types from utils import CLASSES, PATH_TO_MODEL, TRANSFORM load_dotenv() tg_token = os.getenv('tg_token') bot = telebot.TeleBot(tg_token) bot.set_my_commands([ types.BotCommand('/help', 'Инструкция'), ]) @bot.message_handler(commands=['start', 'help']) def start(message): bot.send_message( message.chat.id, text=start_text, parse_mode='html' ) @bot.message_handler(content_types=['photo']) def predict_class(message): file_info = bot.get_file(message.photo[-1].file_id) dwn_file = bot.download_file(file_info.file_path) byte_obj = io.BytesIO(dwn_file) img = Image.open(byte_obj) img = np.array(img, dtype=np.float32) img = TRANSFORM(image=img)['image'] img = np.transpose(img, (2, 0, 1)) ort_inputs = {'input': img[None, ...]} ort_outs = ort_session.run(None, ort_inputs) bot.send_message( message.chat.id, text=f'Предсказанный класс: <b>{CLASSES[ort_outs[0].argmax()]}</b>', parse_mode='html' ) @bot.message_handler(content_types=['text']) def get_user_text(message): """ Обработка текстовых сообщений """ if message.text in ['❤️', '❤️❤️', '❤️❤️❤️']: to_send = '❤️' * random.choice([1, 3]) else: to_send = 'К сожалению, я тебя не понимаю ' to_send += random.choice(['😿', '😭', '😤', '😇', '😅']) to_send += '\n\nОзнакомиться с инструкцией можно в меню тг-бота!' bot.send_message( message.chat.id, text=to_send ) if __name__ == '__main__': with open('texts/start.txt', 'r') as f: start_text = f.read() ort_session = ort.InferenceSession( PATH_TO_MODEL, providers=["CPUExecutionProvider"] ) bot.infinity_polling()
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">Manage Questionnaire</div> <div class="card-body"> @if (session('status')) <div class="alert alert-success" role="alert"> {{ session('status') }} </div> @endif <!---You are logged in!---> <div class="panel-body"> <div> <div class="float-md-left"><h1>Questionnaire</h1> </div> <div class="float-md-right"><a href="{{ URL::to('/') }}/questions/create" class="btn btn-primary">Create Question</a> </div> </div> @if(count($questions)>0) <table class="table table-striped"> <tr> <th>Name</th> <th></th> <th></th> </tr> @foreach($questions as $questions) <tr> <td><a href="{{ URL::to('/') }}/questions/{{$questions->id}}">{{$questions->question_en}}</a></td> <td><a href="{{ URL::to('/') }}/questions/{{$questions->id}}/edit" class="btn btn-warning">Edit</a></td> <td> {!!Form::open(['action' => ['QuestionsController@destroy', $questions->id], 'method' => 'POST', 'class' => 'pull-right', 'onsubmit' => "return confirm('Please confirm deletion')" ])!!} {{Form::hidden('_method', 'DELETE')}} {{Form::submit('Delete', ['class' => 'btn btn-danger'] )}} {!!Form::close()!!} </td> </tr> @endforeach </table> @else <br><br><br> <p>There are no registered questions.</p> @endif </div> </div> </div> </div> </div> </div> @endsection
<?php namespace App\Http\Requests\Admin; use Illuminate\Foundation\Http\FormRequest; class StoreLetterRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => 'required', 'nik' => 'integer|required|unique:letters', 'ttl' => 'required', 'negara' => 'required', 'agama' => 'required', 'pekerjaan' => 'required', 'jenis_kelamin' => 'required', 'alamat' => 'required', 'category_id' => 'required' ]; } }
package commands import ( "fmt" "github.com/nknorg/nkn/v2/common" nknwallet "github.com/omani/nkn-wallet" "github.com/spf13/cobra" ) var transferCmd = &cobra.Command{ Use: "transfer", Short: "Transfer funds to another NKN address", PreRun: func(cmd *cobra.Command, args []string) { cmd.MarkFlagRequired("index") }, RunE: func(cmd *cobra.Command, args []string) error { return runTransfer() }, } var ( to string amount string fee string ) func init() { rootCmd.AddCommand(transferCmd) transferCmd.Flags().StringVar(&to, "to", "", "NKN Address of recipient.") transferCmd.Flags().StringVar(&amount, "amount", "", "Amount of funds to transfer.") transferCmd.Flags().StringVar(&fee, "fee", "", "Make miners happy by specifying an optional fee for the transaction.") transferCmd.MarkFlagRequired("amount") transferCmd.MarkFlagRequired("to") } func runTransfer() error { _, err := common.ToScriptHash(to) checkerr(err) store, err := nknwallet.NewStore(path) checkerr(err) wallet, err := getWallet(store, index) checkerr(err) if amount == "all" { a, err := wallet.Balance() checkerr(err) amount = a.String() } a, err := common.StringToFixed64(amount) checkerr(err) if a == 0 || amount == "0" { cobra.CheckErr("Trying to send amount of 0. Aborting!") } txhash, err := wallet.Transfer(to, a.String(), nil) checkerr(err) fmt.Printf("Successfully sent %s NKN from %s to %s. txHash: %s\n", a, wallet.Address(), to, txhash) return nil }
<template> <h1 class="my-4 text-3xl font-bold text-white">忘記密碼</h1> <form> <div v-if="step === 1" class="flex flex-col"> <label class="text-white" for="email">信箱</label> <input v-model="v$.userEmail.$model" type="text" class="rounded border p-1" :class="{ 'mb-4': !v$.userEmail.$errors.length }" name="email" @keypress.enter="nextStep" /> <in-spin v-show="isLoading" :size="40" class="absolute right-3 top-[70%] -translate-y-1/2" /> <div v-for="error of v$.userEmail.$errors" :key="error.$uid" class="mb-4 text-red-500"> {{ error.$message }} </div> <button type="button" :disabled="isLoading" class="mt-2 w-20 rounded border bg-black text-white" @click="nextStep" > 繼續 </button> </div> <div v-if="step === 2" class="flex flex-col"> <p class="text-white">已寄送重設密碼的連結,請至信箱查收</p> </div> </form> </template> <script lang="ts" setup> import { reactive, ref } from 'vue' import { useVuelidate } from '@vuelidate/core' import { required, email, helpers } from '@vuelidate/validators' import useNotification from '~~/stores/useNotification' definePageMeta({ layout: 'login-form' }) const { notification } = useNotification() const formFields = reactive({ userEmail: '', password: '', confirmPassword: '' }) const rules = { userEmail: { required: helpers.withMessage('請輸入信箱', required), email: helpers.withMessage('請填入正確的信箱', email) } } const v$ = useVuelidate(rules, formFields) const step = ref(1) const { $api } = useNuxtApp() const isLoading = ref(false) // 往下一步移動 const nextStep = async () => { try { isLoading.value = true const emailExist: any = await $api.user.isEmailRegister({ email: formFields.userEmail }) if (emailExist.success) { step.value += 1 } else { notification.error(emailExist.message) } } catch (err: any) { notification.error(err.message) } finally { isLoading.value = false } } </script>
@php function rupiah($angka) { $hasil_rupiah = 'Rp' . number_format($angka, 0, ',', '.'); return $hasil_rupiah; } @endphp @extends('base.administrator') @section('css') <link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css"> <link rel="stylesheet" href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.bootstrap5.min.css"> @endsection @section('content') <div class="container-fluid"> @if (session('error')) <div class="alert alert-danger alert-dismissible fade show" role="alert"> {{ session('error') }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> @endif @if (session('success')) <div class="alert alert-success alert-dismissible fade show" role="alert"> {{ session('success') }} <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> @endif </div> <div class="row me-3 ms-3"> <div class="col"> <div class="card w-100"> <div class="card-body p-4"> <div class="row"> <div class="col"> <h5 class="card-title fw-semibold mb-4">Armada</h5> </div> <div class="col"> <button class="btn btn-primary float-end" data-bs-toggle="modal" data-bs-target="#addArmadaModal">Tambah</button> </div> </div> <div class="table-responsive"> <table id="table" class="table text-nowrap mb-0 align-middle"> <thead class="text-dark fs-4"> <tr> <th class="border-bottom-0"> <h6 class="fw-semibold mb-0">Nomor Armada</h6> </th> <th class="border-bottom-0"> <h6 class="fw-semibold mb-0">Nama Driver</h6> </th> <th class="border-bottom-0"> <h6 class="fw-semibold mb-0">Nomor Polisi</h6> </th> <th class="border-bottom-0"> <h6 class="fw-semibold mb-0">ID GPS</h6> </th> <th class="border-bottom-0"> <h6 class="fw-semibold mb-0">Wilayah</h6> </th> <th class="border-bottom-0"> <h6 class="fw-semibold mb-0">Aksi</h6> </th> </tr> </thead> <tbody> @foreach ($armadas as $armada) <tr> <td class="border-bottom-0"> <h6 class="fw-semibold mb-0">{{ $armada->armada_id }}</h6> </td> <td class="border-bottom-0"> <h6 class="fw-semibold mb-0">{{ $armada->armada_driver }}</h6> </td> <td class="border-bottom-0"> <h6 class="fw-semibold mb-0">{{ $armada->armada_plat }}</h6> </td> <td class="border-bottom-0"> <h6 class="fw-semibold mb-0">{{ $armada->armada_id_gps }}</h6> </td> <td class="border-bottom-0"> <h6 class="fw-semibold mb-0">{{ $armada->kecamatan->nama }}</h6> </td> <td class="border-bottom-0"> <button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#detailArmadaModal{{ $armada->armada_id }}">Lihat Driver</button> <button class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#editArmadaModal{{ $armada->armada_id }}">Ubah</button> <button class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteArmadaModal{{ $armada->armada_id }}">Hapus</button> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> <div class="row me-3 ms-3"> <div class="col"> <div class="card w-100"> <div class="card-body p-4"> <div class="row"> <div class="col"> <h5 class="card-title fw-semibold mb-4">Pendapatan Armada</h5> </div> </div> <div class="row mb-4"> <div class="col"> <select name="time" id="time" class="form-control" onchange="refreshTable()"> <option value="harian">Harian</option> <option value="bulanan">Bulanan</option> </select> </div> <div class="col"> <select name="status_job" id="status_job" class="form-control" onchange="refreshTable()"> <option value="all">Semua Status</option> <option value="on_queue">Dalam Antrian</option> <option value="on_the_way">Dalam Perjalanan</option> <option value="on_process">Dalam Pengerjaan</option> <option value="done">Selesai</option> </select> </div> <div class="col"> <select name="driver" id="driver" class="form-control" onchange="refreshTable()"> <option value="all">Semua Driver</option> @foreach ($armadas as $armada) <option value="{{ $armada->armada_id }}">{{ $armada->armada_id }} - {{ $armada->armada_driver }}</option> @endforeach </select> </div> </div> <div class="table-responsive"> <table id="table-revenue" class="table text-nowrap" style="width: 100%;"> <thead> <tr> <th>Armada</th> <th>Invoice</th> <th>Tahap Pengerjaan</th> <th>Pendapatan</th> </tr> </thead> <tbody id="tbody"> @php $sum = 0; @endphp @foreach ($armadaAssigns as $armadaAssign) @php $sum += $armadaAssign->order_price; @endphp <tr> <td>{{ $armadaAssign->armada->armada_id }} - {{ $armadaAssign->armada->armada_driver }}</td> <td>{{ $armadaAssign->order_invoice }}</td> <td> @if ($armadaAssign->order_status_job == 'not_start') <span class="badge bg-dark rounded-3 fw-semibold">Belum Dimulai</span> @elseif($armadaAssign->order_status_job == 'on_queue') <span class="badge bg-info rounded-3 fw-semibold">Dalam Antrian</span> @elseif($armadaAssign->order_status_job == 'on_the_way') <span class="badge bg-info rounded-3 fw-semibold">Sedang Dijalan</span> @elseif($armadaAssign->order_status_job == 'on_process') <span class="badge bg-info rounded-3 fw-semibold">Sedang Dikerjakan</span> @elseif($armadaAssign->order_status_job == 'done') <span class="badge bg-success rounded-3 fw-semibold">Selesai</span> @elseif($armadaAssign->order_status_job == 'rejected') <span class="badge bg-danger rounded-3 fw-semibold">Ditolak</span> @endif </td> <td>{{ rupiah($armadaAssign->order_price) }}</td> </tr> @endforeach </tbody> <tfoot> <tr> <td>Total Pendapatan</td> <td style="display: none;"></td> <td style="display: none;"></td> <td><b id="total-sum">{{ rupiah($sum) }}</b></td> </tr> </tfoot> </table> </div> </div> </div> </div> </div> <div class="modal fade" id="addArmadaModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Tambah Armada</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form action="/administrator/tambah-armada" method="POST" enctype="multipart/form-data"> @csrf <div class="modal-body"> <div class="row mb-3"> <div class="col-12 mb-3"> <label for="" class="form-label">Nomor Armada</label> <input type="text" value="{{ $newIdArmada }}" class="form-control" id="" required readonly name="armada_id"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Username</label> <input type="text" class="form-control" id="" required name="username"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Password</label> <input type="text" class="form-control" id="" required name="password"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Nama Driver</label> <input type="text" class="form-control" id="" required name="armada_driver"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Nomor Polisi</label> <input type="text" class="form-control" id="" required name="armada_plat"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">ID GPS</label> <input type="text" class="form-control" id="" required name="armada_id_gps"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Nomor Telpon</label> <input type="text" class="form-control" id="" required name="armada_phone"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Wilayah</label> <select name="armada_subdistinct" id="" class="form-control"> @foreach ($kecamatans as $kecamatan) <option value="{{ $kecamatan->kecamatan_id }}">{{ $kecamatan->nama }}</option> @endforeach </select> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Foto Driver</label> <input type="file" class="form-control" id="" required name="armada_driver_photo" accept="image/png, image/jpg, image/jpeg"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button> <button type="submit" class="btn btn-primary">Tambah</button> </div> </form> </div> </div> </div> @foreach ($armadas as $armada) <div class="modal fade" id="detailArmadaModal{{ $armada->armada_id }}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Detail Armada</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body text-center"> <img src="{{ $armada->armada_driver_photo }}" width=200> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button> </div> </div> </div> </div> <div class="modal fade" id="deleteArmadaModal{{ $armada->armada_id }}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Hapus Armada</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> anda yakin ingin menghapus armada <b>{{ $armada->armada_id }}</b>? </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button> <a href="/administrator/hapus-armada/{{ $armada->armada_id }}" class="btn btn-danger">Hapus</a> </div>0 </div> </div> </div> <div class="modal fade" id="editArmadaModal{{ $armada->armada_id }}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Ubah Armada</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form action="/administrator/ubah-armada" method="POST" enctype="multipart/form-data"> @csrf <div class="modal-body"> <div class="row mb-3"> <div class="col-12 mb-3"> <label for="" class="form-label">Nomor Armada</label> <input type="text" value="{{ $armada->armada_id }}" class="form-control" id="" required readonly name="armada_id"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Username</label> <input type="text" value="{{ $armada->user->nik }}" class="form-control" id="" required name="username"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Password</label> <input type="text" class="form-control" id="" name="password"> <div class="form-text">Silakan isi jika ingin merubah password.</div> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Nama Driver</label> <input type="text" value="{{ $armada->armada_driver }}" class="form-control" id="" required name="armada_driver"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Nomor Polisi</label> <input type="text" value="{{ $armada->armada_plat }}" class="form-control" id="" required name="armada_plat"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">ID GPS</label> <input type="text" value="{{ $armada->armada_id_gps }}" class="form-control" id="" required name="armada_id_gps"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Nomor Telpon</label> <input type="text" value="{{ $armada->armada_phone }}" class="form-control" id="" required name="armada_phone"> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Wilayah</label> <select name="armada_subdistinct" id="" class="form-control"> @foreach ($kecamatans as $kecamatan) @if ($kecamatan->kecamatan_id == $armada->armada_subdistinct) <option value="{{ $kecamatan->kecamatan_id }}" selected> {{ $kecamatan->nama }}</option> @else <option value="{{ $kecamatan->kecamatan_id }}">{{ $kecamatan->nama }} </option> @endif @endforeach </select> </div> <div class="col-12 mb-3"> <label for="" class="form-label">Foto Driver</label> <input type="file" class="form-control" id="" name="armada_driver_photo" accept="image/png, image/jpg, image/jpeg"> <div class="form-text">Silakan isi jika ingin merubah foto driver.</div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button> <button type="submit" class="btn btn-primary">Ubah</button> </div> </form> </div> </div> </div> @endforeach @endsection @section('js') <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script> <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script> <script src="https://cdn.datatables.net/responsive/2.5.0/js/responsive.bootstrap5.min.js"></script> <script> new DataTable('#table', { responsive: true }); let table = new DataTable('#table-revenue', { responsive: true }); function refreshTable() { let tables = document.getElementById('tbody'); table.destroy(); let time = document.getElementById('time').value; let status = document.getElementById('status_job').value; let driver = document.getElementById('driver').value; var datas = { _token: "{{ csrf_token() }}", time: time, status: status, driver: driver, }; tables.innerHTML = ''; $.ajax({ type: 'POST', url: '/administrator/sum-revenue-driver', data: datas, success: function(response) { document.getElementById('total-sum').innerHTML = "Rp. " + formatRupiah(Math.round(response.sum).toString()) + ",00" for (let i = 0; i < response.datas.length; i++) { let statusJob = ''; if(response.datas[i].order_status_job == 'on_queue') { statusJob = `<span class="badge bg-info rounded-3 fw-semibold">Dalam Antrian</span>`; } else if(response.datas[i].order_status_job == 'on_the_way') { statusJob = `<span class="badge bg-info rounded-3 fw-semibold">Sedang Dijalan</span>`; } else if(response.datas[i].order_status_job == 'on_process') { statusJob = `<span class="badge bg-info rounded-3 fw-semibold">Sedang Dikerjakan</span>`; } else if(response.datas[i].order_status_job == 'done') { statusJob = `<span class="badge bg-success rounded-3 fw-semibold">Selesai</span>`; } tables.innerHTML += ` <tr> <td>${response.datas[i].armada.armada_id} - ${response.datas[i].armada.armada_driver}</td> <td>${response.datas[i].order_invoice}</td> <td>${statusJob}</td> <td>Rp.${formatRupiah(Math.round(response.datas[i].order_price).toString())},00</td> </tr> `; } table = $('#table-revenue').DataTable({ responsive: true }); } }); } function formatRupiah(angka, prefix) { var number_string = angka.replace(/[^,\d]/g, '').toString(), split = number_string.split(','), sisa = split[0].length % 3, rupiah = split[0].substr(0, sisa), ribuan = split[0].substr(sisa).match(/\d{3}/gi); if (ribuan) { separator = sisa ? '.' : ''; rupiah += separator + ribuan.join('.'); } rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah; return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : ''); } </script> @endsection
import { RequestHandler } from 'express'; import { Doctor } from '../models/doctor'; // RequestHandler es responsable de manejar una solicitud HTTP, realizar alguna lógica de servidor (como interactuar con la base de datos), // y finalmente enviar una respuesta al cliente export const getDoctors: RequestHandler = async (req, res, next) => { try { const doctors = await Doctor.findAll(); res.status(200).json({ message: 'Operación exitosa', data: doctors }); } catch (error) { const err = error as Error; res.status(500).json({ message: 'Hubo un error al obtener los doctores', error: err.message }); } }; export const getDoctorById: RequestHandler = async (req, res, next) => { try { const doctor = await Doctor.findByPk(req.params.id); if (doctor) { res.status(200).json({ message: 'Operación exitosa', data: doctor }); } else { res.status(404).json({ message: 'Doctor no encontrado' }); } } catch (error) { const err = error as Error; res.status(500).json({ message: 'Hubo un error al obtener el doctor', error: err.message }); } }; export const createDoctor: RequestHandler = async (req, res, next) => { try { const doctor = await Doctor.create(req.body); res.status(201).json({ message: 'Doctor creado exitosamente', data: doctor }); } catch (error) { const err = error as Error; res.status(500).json({ message: 'Hubo un error al crear el doctor', error: err.message }); } }; export const updateDoctor: RequestHandler = async (req, res, next) => { try { const doctor = await Doctor.findByPk(req.params.id); if (!doctor) { res.status(404).json({ message: 'Doctor no encontrado' }); return; } else { await Doctor.update(req.body, { where: { id_profesional: req.params.id } }); const updatedDoctor = await Doctor.findByPk(req.params.id); res.status(200).json({ message: 'Doctor actualizado exitosamente', data: updatedDoctor }); } } catch (error) { const err = error as Error; res.status(500).json({ message: 'Hubo un error al actualizar el doctor', error: err.message }); } }; export const deleteDoctor: RequestHandler = async (req, res, next) => { try { const doctor = await Doctor.findByPk(req.params.id); if (!doctor) { res.status(404).json({ message: 'Doctor no encontrado' }); return; } else { await Doctor.destroy({ where: { id_profesional: req.params.id } }); res.status(200).json({ message: 'Doctor eliminado exitosamente' }); } } catch (error) { const err = error as Error; res.status(500).json({ message: 'Hubo un error al eliminar el doctor', error: err.message }); } };
<app-page-banner [title]="title" [subTitle]="subTitle"></app-page-banner> <main> <header class="main-header"> <p> Please use the form below to register and apply for the National Identification Card. Fill in all the fields that are marked required. In-case you captured some of your information and you saved a draft. Please enter your draft reference number above to retrieve the information. </p> </header> <mat-horizontal-stepper [linear]="isLinear" labelPosition="bottom" #stepper> <!-- <mat-step [stepControl]="firstFormGroup"> <form [formGroup]="firstFormGroup"> --> <mat-step> <ng-template matStepLabel> <h3>PART A</h3> <p>Personal Information</p> </ng-template> <form [formGroup]="formPartA"> <!-- <mat-form-field> <mat-label>Enrolment Location <span class="optional-field">optional</span></mat-label> <input matInputformControlName="firstCtrl"> </mat-form-field> --> <mat-form-field appearance="outline"> <mat-label>Surname <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantSurname"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Given Name <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantGivenName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Other Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantOtherNames"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Maiden Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantMaidenName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Previous Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantPreviousName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sex <span class="required-field">required</span></mat-label> <mat-select formControlName="SexOfApplicant"> <mat-option value="Male">Male</mat-option> <mat-option value="Female">Female</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Date of Birth <span class="required-field">required</span></mat-label> <input color="accent" matInput [max]="maxDate" placeholder="Enter your date of birth" formControlName="DateOfBirth" [matDatepicker]="dob"> <mat-datepicker-toggle matSuffix [for]="dob"></mat-datepicker-toggle> <mat-datepicker #dob disabled="false"></mat-datepicker> <!-- <mat-error *ngIf="step2FormGroup.get('dateOfBirth').invalid">{{ getDateOfBirthErrorMessage() }}</mat-error> --> <mat-hint align="end">Use the icon above to choose a date</mat-hint> </mat-form-field> <mat-checkbox color="primary" [required]="'false'" [checked]="AgeIsEstimated"> Click the box if the Date of Birth is estimated </mat-checkbox> <mat-form-field appearance="outline" hintLabel="Maximum of 50."> <mat-label>Email Address <span class="optional-field">optional</span></mat-label> <input appLowercase matInput #EmailAddressInput formControlName="EMail" maxlength="50" placeholder=""> <!-- <mat-error *ngIf="form.get('EmailAddress').invalid">{{ getEmailAddressErrorMessage() }}</mat-error> --> <mat-hint align="end">{{ EmailAddressInput.value.length }} / 50</mat-hint> </mat-form-field> <mat-form-field appearance="outline" hintLabel="Maximum of 11."> <mat-label>Home Phone No. <span class="optional-field">optional</span></mat-label> <span matPrefix>+256 &nbsp;</span> <input matInput #TelephoneNumberInput appTelephoneFormaterDirective maxlength="11" formControlName="Phone1" placeholder="Ex. 701 000 000"> <!-- <mat-error *ngIf="form.get('TelephoneNumber').invalid">{{ getTelephoneNumberErrorMessage() }}</mat-error> --> <mat-hint align="end">{{ TelephoneNumberInput.value.length }} / 11</mat-hint> </mat-form-field> <mat-form-field appearance="outline" hintLabel="Maximum of 11."> <mat-label>Mobile No. <span class="required-field">required</span></mat-label> <span matPrefix>+256 &nbsp;</span> <input matInput #TelephoneNumberInput appTelephoneFormaterDirective maxlength="11" formControlName="Phone2" placeholder="Ex. 701 000 000"> <!-- <mat-error *ngIf="form.get('TelephoneNumber').invalid">{{ getTelephoneNumberErrorMessage() }}</mat-error> --> <mat-hint align="end">{{ TelephoneNumberInput.value.length }} / 11</mat-hint> </mat-form-field> <mat-form-field appearance="outline" hintLabel="Choose an option."> <mat-label>Highest Level of Education <span class="required-field">required</span></mat-label> <mat-select formControlName="HighestLevelOfEducation"> <mat-option value="1">primary</mat-option> <mat-option value="2">secondary</mat-option> <mat-option value="3">tertiary</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Profession <span class="optional-field">optional</span></mat-label> <textarea #CaseTitleInput matInput formControlName="Profession" placeholder="For Example: Doctor" maxlength="1000"></textarea> <mat-hint align="end">{{ CaseTitleInput.value.length }} / 1000</mat-hint> <!-- <mat-error *ngIf="form.get('CaseTitle').invalid">{{ getCaseTitleErrorMessage() }}</mat-error> --> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Occupation <span class="optional-field">optional</span></mat-label> <textarea #CaseTitleInput matInput formControlName="Occupation" placeholder="For Example: Surgeon" maxlength="1000"></textarea> <mat-hint align="end">{{ CaseTitleInput.value.length }} / 1000</mat-hint> <!-- <mat-error *ngIf="form.get('CaseTitle').invalid">{{ getCaseTitleErrorMessage() }}</mat-error> --> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Religion <span class="required-field">required</span></mat-label> <mat-select formControlName="Religion"> <mat-option value="Anglican">Christian</mat-option> <mat-option value="Muslim">Muslim</mat-option> <mat-option value="Other">Other</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Disabilities <span class="required-field">required</span></mat-label> <mat-select formControlName="Disabilities"> <mat-option *ngFor="let item of Disabilities" [value]="item.DisabilityID">{{ item.Disability }}</mat-option> </mat-select> </mat-form-field> <header class="no-top-margin" matRipple (click)="showPlaceOfOrigin = !showPlaceOfOrigin" [ngClass]="{'expand-section': showPlaceOfOrigin }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Place of Origin</h3> </header> <section [ngClass]="{'expand-section': showPlaceOfOrigin }"> <mat-form-field appearance="outline"> <mat-label>Country <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="CountryOfOrigin" [matAutocomplete]="autoCountryOfOrigin"> <mat-autocomplete #autoCountryOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredCountryOfOrigin | async" [value]="item.CountryName" (click)="CountryOfOriginCountryID = item.CountryID"> {{ item.CountryName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>District <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="DistrictOfOrigin" [matAutocomplete]="autoDistrictOfOrigin"> <mat-autocomplete #autoDistrictOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredDistrictOfOrigin | async" [value]="item.DistrictName" (click)="DistrictOfOriginDistrictID = item.DistrictID"> {{ item.DistrictName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="CountyOfOrigin" [matAutocomplete]="autoCountyOfOrigin"> <mat-autocomplete #autoCountyOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredCountyOfOrigin | async" [value]="item.CountyName" (click)="onCountyOfOrigin(item.CountyID); CountyOfOriginCountyID = item.CountyID"> {{ item.CountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sub County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="SubCountyOfOrigin" [matAutocomplete]="autoSubCountyOfOrigin"> <mat-autocomplete #autoSubCountyOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredSubCountyOfOrigin | async" [value]="item.SubCountyName" (click)="SubCountyOfOriginSubCountyID = item.SubCountyID"> {{ item.SubCountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Parish / Ward <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ParishOfOrigin"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Village <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="VillageOfOrigin"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Indigenous Community / Tribe <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="IndigenousCommunityOrTribe"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Clan <span class="optional-field">optional</span></mat-label> <input matInput formControlName="Clan"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Citizenship Type<span class="required-field">required</span></mat-label> <mat-select formControlName="CitizenshipType"> <mat-option value="1">By Birth</mat-option> <mat-option value="2">By Registration</mat-option> <mat-option value="3">By Naturalization</mat-option> <mat-option value="4">Dual Citizenship</mat-option> <mat-option value="5">Citizenship acquired before 1995 Constitution other than the above stated</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Citizenship Certificate Number <span class="optional-field">optional</span></mat-label> <input matInput formControlName="CitizenshipCertificateNumber"> </mat-form-field> <!-- Question: When I select Dual Citizenship. Doesn't that impy one of them is for Uganda... which --> <!-- means we only need to ask for the second one. --> <mat-form-field appearance="outline" hintLabel="If Dual, state the other Nationality "> <mat-label>State Other CitizenShip <span class="optional-field">optional</span></mat-label> <input matInput formControlName="StateOtherCitizenShip"> </mat-form-field> </section> <header matRipple (click)="showPlaceOfResidence = !showPlaceOfResidence" [ngClass]="{'expand-section': showPlaceOfResidence }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3 class="section-divider">Place of Residence</h3> </header> <section [ngClass]="{'expand-section': showPlaceOfResidence }"> <!-- We do not need this field... Once you select Uganda, we know it's local. --> <!-- <mat-form-field appearance="outline"> <mat-label>Place of Residence <span class="required-field">required</span></mat-label> <mat-select formControlName="PlaceOfResidence"> <mat-option value="Local">Local</mat-option> <mat-option value="Foreign">Foreign</mat-option> </mat-select> </mat-form-field> --> <mat-form-field appearance="outline"> <mat-label>Country <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="ApplicantPlaceOfResidenceCountry" [matAutocomplete]="autoCountryOfResidence"> <mat-autocomplete #autoCountryOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredCountryOfResidence | async" [value]="item.CountryName" (click)="ApplicantPlaceOfResidenceCountryCountryID = item.CountryID"> {{ item.CountryName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>District <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="ApplicantPlaceOfResidenceDistrict" [matAutocomplete]="autoDistrictOfResidence"> <mat-autocomplete #autoDistrictOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredDistrictOfResidence | async" [value]="item.DistrictName" (click)="ApplicantPlaceOfResidenceDistrictDistrictID = item.DistrictID"> {{ item.DistrictName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="ApplicantPlaceOfResidenceCounty" [matAutocomplete]="autoCountyOfResidence"> <mat-autocomplete #autoCountyOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredCountyOfResidence | async" [value]="item.CountyName" (click)="onApplicantPlaceOfResidenceCounty(item.CountyID); ApplicantPlaceOfResidenceCountyCountyID = item.CountyID"> {{ item.CountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sub County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="ApplicantPlaceOfResidenceSubcounty" [matAutocomplete]="autoSubCountyOfResidence"> <mat-autocomplete #autoSubCountyOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredSubCountyOfResidence | async" [value]="item.SubCountyName" (click)="ApplicantPlaceOfResidenceSubcountySubCountyID = item.SubCountyID"> {{ item.SubCountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Parish / Ward <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ParishOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Village <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="VillageOfResidence"> </mat-form-field> <!-- <mat-form-field appearance="outline"> <mat-label>Street <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="StreetOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Plot / House No. <span class="optional-field">optional</span></mat-label> <input matInput formControlName="PlotOfResidence"> </mat-form-field> --> <mat-form-field appearance="outline"> <mat-label>Number of years at this address. <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="NumberOfYearsAtAddress"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Previous District <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="PreviousDistrictOfResidence" [matAutocomplete]="autoPreviousDistrictOfResidence"> <mat-autocomplete #autoPreviousDistrictOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredPreviousDistrictOfResidence | async" [value]="item.DistrictName"> {{ item.DistrictName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Postal Address <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="PostalAddress"> </mat-form-field> </section> <header matRipple (click)="showPlaceOfBirth = !showPlaceOfBirth" [ngClass]="{'expand-section': showPlaceOfBirth }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Place of Birth (<span>Which place were you born ?</span>)</h3> </header> <section [ngClass]="{'expand-section': showPlaceOfBirth }"> <!-- <mat-form-field appearance="outline"> <mat-label>Country <span class="required-field">required</span></mat-label> <mat-select formControlName="CountryOfBirth"> <mat-option value="1">Uganda</mat-option> <mat-option value="2">Kenya</mat-option> <mat-option value="3">Tanzania</mat-option> <mat-option value="4">England</mat-option> </mat-select> </mat-form-field> --> <mat-form-field appearance="outline"> <mat-label>Country <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="CountryOfBirth" [matAutocomplete]="autoCountryOfBirth"> <mat-autocomplete #autoCountryOfBirth="matAutocomplete"> <mat-option *ngFor="let item of filteredCountryOfBirth | async" [value]="item.CountryName" (click)="CountryOfBirthCountryID = item.CountryID"> {{ item.CountryName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>District <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="DistrictOfBirth" [matAutocomplete]="autoDistrictOfBirth"> <mat-autocomplete #autoDistrictOfBirth="matAutocomplete"> <mat-option *ngFor="let item of filteredDistrictOfBirth | async" [value]="item.DistrictName" (click)="DistrictOfBirthDistrictID = item.DistrictID"> {{ item.DistrictName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="CountyOfBirth" [matAutocomplete]="autoCountyOfBirth"> <mat-autocomplete #autoCountyOfBirth="matAutocomplete"> <mat-option *ngFor="let item of filteredCountyOfBirth | async" [value]="item.CountyName" (click)="onCountyOfBirth(item.CountyID); CountyOfBirthCountyID = item.CountyID"> {{ item.CountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sub County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="SubCountyOfBirth" [matAutocomplete]="autoSubCountyOfBirth"> <mat-autocomplete #autoSubCountyOfBirth="matAutocomplete"> <mat-option *ngFor="let item of filteredSubCountyOfBirth | async" [value]="item.SubCountyName" (click)="SubCountyOfBirthSubCountyID = item.SubCountyID"> {{ item.SubCountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Parish / Ward <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ParishOfBirth"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Village <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="VillageOfBirth"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>City / Town <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="CityOfBirth"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Health Facility <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="HealthFacility"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Weight at Birth <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="WeightAtBirth"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Time of Birth <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="TimeOfBirth"> </mat-form-field> <mat-form-field appearance="outline" hintLabel="In regard to Mother"> <mat-label>Parity of Child<span class="required-field">required</span></mat-label> <mat-select formControlName="ParityOfChild"> <mat-option value="1">1st born</mat-option> <mat-option value="2">2nd born</mat-option> <mat-option value="3">3rd born</mat-option> <mat-option value="4">4th born</mat-option> <mat-option value="5">5th born</mat-option> <mat-option value="6">6th born</mat-option> <mat-option value="7">7th born</mat-option> <mat-option value="8">8th born</mat-option> </mat-select> </mat-form-field> </section> <header matRipple (click)="showPassportInformation = !showPassportInformation" [ngClass]="{'expand-section': showPassportInformation }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Passport Information</h3> </header> <section class="no-bottom-border" [ngClass]="{'expand-section': showPassportInformation }"> <mat-form-field appearance="outline"> <mat-label>Passport Number <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="PassportNumber"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>File Number <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="PassportFileNumber"> </mat-form-field> </section> </form> <div class="button-wrapper"> <button [ngClass]="{'inline-processing-btn': processing}" mat-raised-button color="primary" [disabled]="formPartA.invalid || processing" (click)="onSaveDraft()"> <app-inline-mat-spinner *ngIf="processing"></app-inline-mat-spinner> <span> Save Draft </span> </button> <button mat-button class="next-btn" color="primary" matStepperNext>Next</button> </div> </mat-step> <mat-step optional> <ng-template matStepLabel> <h3>PART B</h3> <p matTooltip="To be filled for Adult registration only">To be filled for Adult registration only</p> </ng-template> <form [formGroup]="formPartB"> <h3 class="margin-bottom-20">Voter's Information</h3> <mat-form-field appearance="outline"> <mat-label>Preferred Polling Station <span class="required-field">required</span></mat-label> <mat-select formControlName="PreferredPollingStation"> <mat-option value="1">Place of Residence</mat-option> <mat-option value="2">Place of Origin</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Polling Station Name <span class="required-field">required</span></mat-label> <input matInput formControlName="PollingStationName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Marital Status <span class="required-field">required</span></mat-label> <mat-select formControlName="MaritalStatus"> <mat-option value="1">Married</mat-option> <mat-option value="2">Single</mat-option> <mat-option value="3">Divorced</mat-option> <mat-option value="4">Widowed</mat-option> <mat-option value="5">Separeted</mat-option> </mat-select> </mat-form-field> <h3 class="margin-bottom-20">Spouse Details</h3> <section class="expand-section reduced-properties table-wrapper"> <button mat-raised-button [disabled]="processing" class="add-item-button" (click)="onAddASpouse()"> <div class="button-label"> <mat-icon>add</mat-icon> <span>Add A Spouse</span> </div> </button> <div class="table-wrapper"> <table mat-table #spousesMatSort="matSort" matSortDisableClear="true" [dataSource]="spouseDataSource" matSort> <ng-container matColumnDef="Count"> <th mat-header-cell *matHeaderCellDef> # </th> <td mat-cell *matCellDef="let index = index"> {{ index + 1 }} </td> </ng-container> <ng-container matColumnDef="Name"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th> <td mat-cell *matCellDef="let row"> <b> {{ row.Surname }} &nbsp; {{ row.GivenName ? ' ' + row.GivenName : '' }} {{ row.OtherName ? ' ' + row.OtherName : '' }} {{ row.MaidenName ? ' ' + row.MaidenName : '' }} </b> </td> </ng-container> <ng-container matColumnDef="PreviousName"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Previous Name </th> <td mat-cell *matCellDef="let row">{{ row.PreviousName }}</td> </ng-container> <ng-container matColumnDef="NIN"> <th mat-header-cell *matHeaderCellDef mat-sort-header> NIN / Applcation ID </th> <td mat-cell *matCellDef="let row"> {{ row.NIN ? row.NIN : row.ApplicationID }} </td> </ng-container> <ng-container matColumnDef="CitizenshipTypeName"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Citizenship </th> <td mat-cell *matCellDef="let row"> {{ row.CitizenshipTypeName }} </td> </ng-container> <ng-container matColumnDef="CitizenshipCertificateNumber"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Citizenship Cert. No. </th> <td mat-cell *matCellDef="let row"> {{ row.CitizenshipCertificateNumber }} </td> </ng-container> <ng-container matColumnDef="OtherCitizenship"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Other Citizenship</th> <td mat-cell *matCellDef="let row"> {{ row.OtherCitizenship }} </td> </ng-container> <ng-container matColumnDef="PlaceOfMarriage"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Place Of Marriage</th> <td mat-cell *matCellDef="let row"> {{ row.PlaceOfMarriage }} </td> </ng-container> <ng-container matColumnDef="DateOfMarriage"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Date Of Marriage</th> <td mat-cell *matCellDef="let row"> {{ row.DateOfMarriage | date : 'EEE, MMM d, y' }} </td> </ng-container> <ng-container matColumnDef="TypeOfMarriageName"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Type Of Marriage</th> <td mat-cell *matCellDef="let row"> {{ row.TypeOfMarriageName }} </td> </ng-container> <!-- Actions Column --> <ng-container matColumnDef="Actions"> <th mat-header-cell *matHeaderCellDef> Actions </th> <td mat-cell *matCellDef="let row; let index = index"> <button mat-button class="action-btn" [matMenuTriggerFor]="menu" (click)="$event.stopPropagation()" matTooltip="See more options"> <mat-icon>more_vert</mat-icon> </button> <mat-menu yPosition="below" #menu="matMenu" class="more-options-mat-menu"> <button mat-menu-item (click)="$event.stopPropagation();onChangeSpouseInformation(row)"> <mat-icon>edit</mat-icon> <span>Make Changes</span> </button> <hr /> <button mat-menu-item (click)="$event.stopPropagation();onRemoveSpouse(row)"> <mat-icon>delete</mat-icon> <span>Remove</span> </button> </mat-menu> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="spouseDisplayedColumns"></tr> <!-- <tr mat-row *matRowDef="let row; columns: spouseDisplayedColumns;" [ngClass]="{'selected-mat-data-row': selectedCaseFile === row}" class="mat-data-row"></tr> --> <tr mat-row *matRowDef="let row; columns: spouseDisplayedColumns;" [ngClass]="{'selected-mat-data-row': selectedSpouse === row}" class="mat-data-row"></tr> </table> <mat-paginator #spousesPaginator [pageSize]="10" [pageSizeOptions]="[5, 10]"> </mat-paginator> </div> </section> </form> <div class="button-wrapper"> <button mat-button class="back-btn" matStepperPrevious>Back</button> <button [ngClass]="{'inline-processing-btn': processing}" mat-raised-button color="primary" [disabled]="formPartA.invalid || processing" (click)="onSaveDraft()"> <app-inline-mat-spinner *ngIf="processing"></app-inline-mat-spinner> <span> Save Draft </span> </button> <button mat-button class="next-btn" color="primary" matStepperNext>Next</button> </div> </mat-step> <mat-step> <ng-template matStepLabel> <h3>PART C</h3> <p>Parents' Information</p> </ng-template> <form [formGroup]="formPartC"> <header class="no-top-margin" matRipple (click)="showFathersDetails = !showFathersDetails" [ngClass]="{'expand-section': showFathersDetails }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Father's Details</h3> </header> <section [ngClass]="{'expand-section': showFathersDetails }"> <mat-form-field appearance="outline"> <mat-label>Surname <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzSurname"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Given Name <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzGivenName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Other Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzOtherName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Maiden Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzMaidenName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Previous Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzPreviousName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>National ID Number (NIN) <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzNIN"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>ID Card Number <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzCardNumber"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Citizenship Type<span class="required-field">required</span></mat-label> <mat-select formControlName="FatherzCitizenshipType"> <mat-option value="1">By Birth</mat-option> <mat-option value="2">By Registration</mat-option> <mat-option value="3">By Naturalization</mat-option> <mat-option value="4">Dual Citizenship</mat-option> <mat-option value="5">Citizenship acquired before 1995 Constitution other than the above stated</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Citizenship Certificate Number <span class="optional-field">optional</span></mat-label> <input matInput formControlName="FatherzCitizenshipCertificateNumber"> </mat-form-field> <mat-form-field appearance="outline" hintLabel="If Dual, state the other Nationality "> <mat-label>State Other CitizenShip <span class="optional-field">optional</span></mat-label> <input matInput formControlName="FatherzStateOtherCitizenShip"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Living Status<span class="required-field">required</span></mat-label> <mat-select formControlName="FatherzLivingStatus"> <mat-option value="1">Alive</mat-option> <mat-option value="2">Deceased</mat-option> <mat-option value="3">Unknown</mat-option> </mat-select> </mat-form-field> <!-- <mat-form-field appearance="outline" class="full-width"> --> <mat-form-field appearance="outline"> <mat-label>Occupation <span class="optional-field">optional</span></mat-label> <textarea #CaseTitleInput matInput formControlName="FatherzOccupation" placeholder="For Example: Surgeon" maxlength="1000"></textarea> <mat-hint align="end">{{ CaseTitleInput.value.length }} / 1000</mat-hint> <!-- <mat-error *ngIf="form.get('CaseTitle').invalid">{{ getCaseTitleErrorMessage() }}</mat-error> --> </mat-form-field> </section> <header matRipple (click)="showFatherzPlaceOfResidence = !showFatherzPlaceOfResidence" [ngClass]="{'expand-section': showFatherzPlaceOfResidence }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Father's Place of Residence</h3> </header> <section [ngClass]="{'expand-section': showFatherzPlaceOfResidence }"> <mat-form-field appearance="outline"> <mat-label>Country <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="FatherzCountryOfResidence" [matAutocomplete]="autoFatherzCountryOfResidence"> <mat-autocomplete #autoFatherzCountryOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredFatherCountryOfResidence | async" [value]="item.CountryName" (click)="FatherzCountryOfResidenceCountryID = item.CountryID"> {{ item.CountryName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>District <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="FatherzDistrictOfResidence" [matAutocomplete]="autoFatherzDistrictOfResidence"> <mat-autocomplete #autoFatherzDistrictOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredFatherDistrictOfResidence | async" [value]="item.DistrictName" (click)="FatherzDistrictOfResidenceDistrictID = item.DistrictID"> {{ item.DistrictName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="FatherzCountyOfResidence" [matAutocomplete]="autoFatherzCountyOfResidence"> <mat-autocomplete #autoFatherzCountyOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredFatherCountyOfResidence | async" [value]="item.CountyName" (click)="onFatherzCountyOfResidence(item.CountyID); FatherzCountyOfResidenceCountyID = item.CountyID"> {{ item.CountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sub County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="FatherzSubCountyOfResidence" [matAutocomplete]="autoFatherzSubCountyOfResidence"> <mat-autocomplete #autoFatherzSubCountyOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredFatherSubCountyOfResidence | async" [value]="item.SubCountyName" (click)="FatherzSubCountyOfResidenceSubCountyID = item.SubCountyID"> {{ item.SubCountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Parish / Ward <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzParishOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Village <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzVillageOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Street <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzStreetOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Plot No. <span class="optional-field">optional</span></mat-label> <input matInput formControlName="FatherzHouseNoOfResidence"> </mat-form-field> </section> <header matRipple (click)="showFatherzPlaceOfOrigin = !showFatherzPlaceOfOrigin" [ngClass]="{'expand-section': showFatherzPlaceOfOrigin }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Father's Place of Origin</h3> </header> <section [ngClass]="{'expand-section': showFatherzPlaceOfOrigin }"> <mat-form-field appearance="outline"> <mat-label>Country <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="FatherzCountryOfOrigin" [matAutocomplete]="autoFatherzCountryOfOrigin"> <mat-autocomplete #autoFatherzCountryOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredFatherCountryOfOrigin | async" [value]="item.CountryName" (click)="FatherzCountryOfOriginCountryID = item.CountryID"> {{ item.CountryName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>District <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="FatherzDistrictOfOrigin" [matAutocomplete]="autoFatherzDistrictOfOrigin"> <mat-autocomplete #autoFatherzDistrictOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredFatherDistrictOfOrigin | async" [value]="item.DistrictName" (click)="FatherzDistrictOfOriginDistrictID = item.DistrictID"> {{ item.DistrictName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="FatherzCountyOfOrigin" [matAutocomplete]="autoFatherzCountyOfOrigin"> <mat-autocomplete #autoFatherzCountyOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredFatherCountyOfOrigin | async" [value]="item.CountyName" (click)="onFatherzCountyOfOrigin(item.CountyID); FatherzCountyOfOriginCountyID = item.CountyID"> {{ item.CountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sub County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="FatherzSubCountyOfOrigin" [matAutocomplete]="autoFatherzSubCountyOfOrigin"> <mat-autocomplete #autoFatherzSubCountyOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredFatherSubCountyOfOrigin | async" [value]="item.SubCountyName" (click)="FatherzSubCountyOfOriginSubCountyID = item.SubCountyID"> {{ item.SubCountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Parish / Ward <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzParishOfOrigin"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Village <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="FatherzVillageOfOrigin"> </mat-form-field> </section> <header matRipple (click)="showMotherzDetails = !showMotherzDetails" [ngClass]="{'expand-section': showMotherzDetails }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Mother's Details</h3> </header> <section [ngClass]="{'expand-section': showMotherzDetails }"> <mat-form-field appearance="outline"> <mat-label>Surname <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzSurname"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Given Name <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzGivenName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Other Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzOtherName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Maiden Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzMaidenName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Previous Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzPreviousName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>National ID Number (NIN) <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzNIN"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>ID Card Number <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzCardNumber"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Citizenship Type<span class="required-field">required</span></mat-label> <mat-select formControlName="MotherzCitizenshipType"> <mat-option value="1">By Birth</mat-option> <mat-option value="2">By Registration</mat-option> <mat-option value="3">By Naturalization</mat-option> <mat-option value="4">Dual Citizenship</mat-option> <mat-option value="5">Citizenship acquired before 1995 Constitution other than the above stated</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Citizenship Certificate Number <span class="optional-field">optional</span></mat-label> <input matInput formControlName="MotherzCitizenshipCertificateNumber"> </mat-form-field> <mat-form-field appearance="outline" hintLabel="If Dual, state the other Nationality "> <mat-label>State Other CitizenShip <span class="optional-field">optional</span></mat-label> <input matInput formControlName="MotherzStateOtherCitizenShip"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Living Status<span class="required-field">required</span></mat-label> <mat-select formControlName="MotherzLivingStatus"> <mat-option value="1">Alive</mat-option> <mat-option value="2">Deceased</mat-option> <mat-option value="3">Unknown</mat-option> </mat-select> </mat-form-field> <!-- <mat-form-field appearance="outline" class="full-width"> --> <mat-form-field appearance="outline"> <mat-label>Occupation <span class="optional-field">optional</span></mat-label> <textarea #CaseTitleInput matInput formControlName="MotherzOccupation" placeholder="For Example: Surgeon" maxlength="1000"></textarea> <mat-hint align="end">{{ CaseTitleInput.value.length }} / 1000</mat-hint> <!-- <mat-error *ngIf="form.get('CaseTitle').invalid">{{ getCaseTitleErrorMessage() }}</mat-error> --> </mat-form-field> </section> <header matRipple (click)="showMotherzPlaceOfResidence = !showMotherzPlaceOfResidence" [ngClass]="{'expand-section': showMotherzPlaceOfResidence }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Mother's Place of Residence</h3> </header> <section [ngClass]="{'expand-section': showMotherzPlaceOfResidence }"> <mat-form-field appearance="outline"> <mat-label>Country <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="MotherzCountryOfResidence" [matAutocomplete]="autoMotherzCountryOfResidence"> <mat-autocomplete #autoMotherzCountryOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredMotherCountryOfResidence | async" [value]="item.CountryName" (click)="MotherzCountryOfResidenceCountryID = item.CountryID"> {{ item.CountryName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>District <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="MotherzDistrictOfResidence" [matAutocomplete]="autoMotherzDistrictOfResidence"> <mat-autocomplete #autoMotherzDistrictOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredMotherDistrictOfResidence | async" [value]="item.DistrictName" (click)="MotherzDistrictOfResidenceDistrictID = item.DistrictID"> {{ item.DistrictName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="MotherzCountyOfResidence" [matAutocomplete]="autoMotherzCountyOfResidence"> <mat-autocomplete #autoMotherzCountyOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredMotherCountyOfResidence | async" [value]="item.CountyName" (click)="onMotherzCountyOfResidence(item.CountyID); MotherzCountyOfResidenceCountyID = item.CountyID"> {{ item.CountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sub County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="MotherzSubCountyOfResidence" [matAutocomplete]="autoMotherzSubCountyOfResidence"> <mat-autocomplete #autoMotherzSubCountyOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredMotherSubCountyOfResidence | async" [value]="item.SubCountyName" (click)="MotherzSubCountyOfResidenceSubCountyID = item.SubCountyID"> {{ item.SubCountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Parish / Ward <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzParishOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Village <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzVillageOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Street <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzStreetOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Plot No. <span class="optional-field">optional</span></mat-label> <input matInput formControlName="MotherzHouseNoOfResidence"> </mat-form-field> </section> <header matRipple (click)="showMotherzPlaceOfOrigin = !showMotherzPlaceOfOrigin" [ngClass]="{'expand-section': showMotherzPlaceOfOrigin }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Mother's Place of Origin</h3> </header> <section [ngClass]="{'expand-section': showMotherzPlaceOfOrigin }"> <mat-form-field appearance="outline"> <mat-label>Country <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="MotherzCountryOfOrigin" [matAutocomplete]="autoMotherzCountryOfOrigin"> <mat-autocomplete #autoMotherzCountryOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredMotherCountryOfOrigin | async" [value]="item.CountryName" (click)="MotherzCountryOfOriginCountryID = item.CountryID"> {{ item.CountryName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>District <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="MotherzDistrictOfOrigin" [matAutocomplete]="autoMotherzDistrictOfOrigin"> <mat-autocomplete #autoMotherzDistrictOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredMotherDistrictOfOrigin | async" [value]="item.DistrictName" (click)="MotherzDistrictOfOriginDistrictID = item.DistrictID"> {{ item.DistrictName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="MotherzCountyOfOrigin" [matAutocomplete]="autoMotherzCountyOfOrigin"> <mat-autocomplete #autoMotherzCountyOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredMotherCountyOfOrigin | async" [value]="item.CountyName" (click)="onMotherzCountyOfOrigin(item.CountyID); MotherzCountyOfOriginCountyID = item.CountyID"> {{ item.CountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sub County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="MotherzSubCountyOfOrigin" [matAutocomplete]="autoMotherzSubCountyOfOrigin"> <mat-autocomplete #autoMotherzSubCountyOfOrigin="matAutocomplete"> <mat-option *ngFor="let item of filteredMotherSubCountyOfOrigin | async" [value]="item.SubCountyName" (click)="MotherzSubCountyOfOriginSubCountyID = item.SubCountyID"> {{ item.SubCountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Parish / Ward <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzParishOfOrigin"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Village <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="MotherzVillageOfOrigin"> </mat-form-field> </section> <header matRipple (click)="showGuardianzDetails = !showGuardianzDetails" [ngClass]="{'expand-section': showGuardianzDetails }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>1st Adoptive / Guardian's Details</h3> </header> <section [ngClass]="{'expand-section': showGuardianzDetails }"> <mat-form-field appearance="outline"> <mat-label>Surname <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzSurname"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Given Name <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzGivenName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Other Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzOtherName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Occupation <span class="optional-field">optional</span></mat-label> <textarea #CaseTitleInput matInput formControlName="GuardianzOccupation" placeholder="For Example: Surgeon" maxlength="1000"></textarea> <mat-hint align="end">{{ CaseTitleInput.value.length }} / 1000</mat-hint> <!-- <mat-error *ngIf="form.get('CaseTitle').invalid">{{ getCaseTitleErrorMessage() }}</mat-error> --> </mat-form-field> <mat-form-field appearance="outline" hintLabel="A must for Foreigners"> <mat-label>Passport Number <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzPassportNumber"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>National ID Number (NIN) <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzNIN"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Alien ID Number (AIN) <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzAIN"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>ID Card Number <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzCardNumber"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Citizenship Type<span class="required-field">required</span></mat-label> <mat-select formControlName="GuardianzCitizenshipType"> <mat-option value="1">By Birth</mat-option> <mat-option value="2">By Registration</mat-option> <mat-option value="3">By Naturalization</mat-option> <mat-option value="4">Dual Citizenship</mat-option> <mat-option value="5">Citizenship acquired before 1995 Constitution other than the above stated</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Citizenship Certificate Number <span class="optional-field">optional</span></mat-label> <input matInput formControlName="GuardianzCitizenshipCertificateNumber"> </mat-form-field> <mat-form-field appearance="outline" hintLabel="If Dual, state the other Nationality "> <mat-label>State Other CitizenShip <span class="optional-field">optional</span></mat-label> <input matInput formControlName="GuardianzStateOtherCitizenShip"> </mat-form-field> </section> <header matRipple (click)="showGuardianzPlaceOfResidence = !showGuardianzPlaceOfResidence" [ngClass]="{'expand-section': showGuardianzPlaceOfResidence }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Guardian's Place of Residence</h3> </header> <section [ngClass]="{'expand-section': showGuardianzPlaceOfResidence }"> <mat-form-field appearance="outline"> <mat-label>Country <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="GuardianzCountryOfResidence" [matAutocomplete]="autoGuardianzCountryOfResidence"> <mat-autocomplete #autoGuardianzCountryOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredGuardianCountryOfResidence | async" [value]="item.CountryName" (click)="GuardianzCountryOfResidenceCountryID = item.CountryID"> {{ item.CountryName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>District <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="GuardianzDistrictOfResidence" [matAutocomplete]="autoGuardianzDistrictOfResidence"> <mat-autocomplete #autoGuardianzDistrictOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredGuardianDistrictOfResidence | async" [value]="item.DistrictName" (click)="GuardianzDistrictOfResidenceDistrictID = item.DistrictID"> {{ item.DistrictName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="GuardianzCountyOfResidence" [matAutocomplete]="autoGuardianzCountyOfResidence"> <mat-autocomplete #autoGuardianzCountyOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredGuardianCountyOfResidence | async" [value]="item.CountyName" (click)="onGuardianzCountyOfResidence(item.CountyID); GuardianzCountyOfResidenceCountyID = item.CountyID"> {{ item.CountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sub County <span class="required-field">required</span></mat-label> <input type="text" placeholder="Pick one" matInput formControlName="GuardianzSubCountyOfResidence" [matAutocomplete]="autoGuardianzSubCountyOfResidence"> <mat-autocomplete #autoGuardianzSubCountyOfResidence="matAutocomplete"> <mat-option *ngFor="let item of filteredGuardianSubCountyOfResidence | async" [value]="item.SubCountyName" (click)="GuardianzSubCountyOfResidenceSubCountyID = item.SubCountyID"> {{ item.SubCountyName }} </mat-option> </mat-autocomplete> <!-- <mat-error *ngIf="form.get('HearingCourtID').invalid">{{ getSelectErrorMessage() }}</mat-error> --> <mat-hint>Choose from the dropdown.</mat-hint> <mat-icon matSuffix>arrow_drop_down</mat-icon> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Parish / Ward <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzParishOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Village <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzVillageOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Street <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="GuardianzStreetOfResidence"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Plot No. <span class="optional-field">optional</span></mat-label> <input matInput formControlName="GuardianzHouseNoOfResidence"> </mat-form-field> </section> </form> <div class="button-wrapper"> <button mat-button class="back-btn" matStepperPrevious>Back</button> <button [ngClass]="{'inline-processing-btn': processing}" mat-raised-button color="primary" [disabled]="formPartA.invalid || processing" (click)="onSaveDraft()"> <app-inline-mat-spinner *ngIf="processing"></app-inline-mat-spinner> <span> Save Draft </span> </button> <button mat-button class="next-btn" color="primary" matStepperNext>Next</button> </div> </mat-step> <mat-step optional> <ng-template matStepLabel> <h3>PART D</h3> <p>Children Registration.</p> </ng-template> <form> <h3 class="margin-bottom-20">Personal Information (Child being registered)</h3> <section class="expand-section reduced-properties table-wrapper"> <button mat-raised-button [disabled]="processing" class="add-item-button" (click)="onAddAChild()"> <div class="button-label"> <mat-icon>add</mat-icon> <span>Add A Child</span> </div> </button> <div class="table-wrapper"> <table mat-table #childrenMatSort="matSort" matSortDisableClear="true" [dataSource]="childrenDataSource" matSort> <ng-container matColumnDef="Count"> <th mat-header-cell *matHeaderCellDef> # </th> <td mat-cell *matCellDef="let index = index"> {{ index + 1 }} </td> </ng-container> <ng-container matColumnDef="Name"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Name </th> <td mat-cell *matCellDef="let row"> <b> {{ row.Surname }} &nbsp; {{ row.GivenName ? ' ' + row.GivenName : '' }} {{ row.OtherName ? ' ' + row.OtherName : '' }} {{ row.MaidenName ? ' ' + row.MaidenName : '' }} </b> </td> </ng-container> <ng-container matColumnDef="PreviousName"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Previous Name </th> <td mat-cell *matCellDef="let row">{{ row.PreviousName }}</td> </ng-container> <ng-container matColumnDef="ApplicationID"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Applcation ID </th> <td mat-cell *matCellDef="let row"> {{ row.ApplicationID }} </td> </ng-container> <ng-container matColumnDef="Sex"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Sex </th> <td mat-cell *matCellDef="let row"> {{ row.Sex }} </td> </ng-container> <ng-container matColumnDef="DateOfBirth"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Date Of Birth</th> <td mat-cell *matCellDef="let row"> {{ row.DateOfBirth | date : 'EEE, MMM d, y' }} </td> </ng-container> <ng-container matColumnDef="PlaceOfBirth"> <th mat-header-cell *matHeaderCellDef mat-sort-header> Place of Birth </th> <td mat-cell *matCellDef="let row"> {{ row.PlaceOfBirth }} </td> </ng-container> <!-- Actions Column --> <ng-container matColumnDef="Actions"> <th mat-header-cell *matHeaderCellDef> Actions </th> <td mat-cell *matCellDef="let row"> <button mat-button class="action-btn" [matMenuTriggerFor]="menu" (click)="$event.stopPropagation()" matTooltip="See more options"> <mat-icon>more_vert</mat-icon> </button> <mat-menu yPosition="below" #menu="matMenu" class="more-options-mat-menu"> <button mat-menu-item (click)="$event.stopPropagation();onChangeChildInformation(row)"> <mat-icon>edit</mat-icon> <span>Make Changes</span> </button> <hr /> <button mat-menu-item (click)="$event.stopPropagation();onRemoveChild(row)"> <mat-icon>delete</mat-icon> <span>Remove</span> </button> </mat-menu> </td> </ng-container> <tr mat-header-row *matHeaderRowDef="childrenDisplayedColumns"></tr> <!-- <tr mat-row *matRowDef="let row; columns: childrenDisplayedColumns;" [ngClass]="{'selected-mat-data-row': selectedCaseFile === row}" class="mat-data-row"></tr> --> <tr mat-row *matRowDef="let row; columns: childrenDisplayedColumns;" [ngClass]="{'selected-mat-data-row': selectedSpouse === row}" class="mat-data-row"></tr> </table> <mat-paginator #childrenPaginator [pageSize]="10" [pageSizeOptions]="[5, 10]"> </mat-paginator> </div> </section> </form> <div class="button-wrapper"> <button mat-button class="back-btn" matStepperPrevious>Back</button> <button [ngClass]="{'inline-processing-btn': processing}" mat-raised-button color="primary" [disabled]="formPartA.invalid || processing" (click)="onSaveDraft()"> <app-inline-mat-spinner *ngIf="processing"></app-inline-mat-spinner> <span> Save Draft </span> </button> <button mat-button class="next-btn" color="primary" matStepperNext>Next</button> </div> </mat-step> <mat-step label="PART E" optional> <ng-template matStepLabel> <h3>PART E</h3> <p>Declaration of Birth & Child Particulars</p> </ng-template> <form [formGroup]="formPartE"> <section [ngStyle]="{'padding': '5px 15px 20px'}" class="no-bottom-border expand-section two-columns"> <mat-checkbox class="full-width" color="primary" [required]="'false'" formControlName="DeclarationCheckbox" [checked]="estimatedDOB"> I declare that the information above to the birth of the child / applicant and particulars above is true and correct and that I know this of my own knowledge. </mat-checkbox> <mat-form-field appearance="outline"> <mat-label>Name of Declarant <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="DeclarationName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Date of Declaration <span class="required-field">required</span></mat-label> <input color="accent" matInput [max]="maxDate" placeholder="Enter the date of declaration" formControlName="DeclarationDate" [matDatepicker]="dobDeclaration"> <mat-datepicker-toggle matSuffix [for]="dobDeclaration"></mat-datepicker-toggle> <mat-datepicker #dobDeclaration disabled="false"></mat-datepicker> <!-- <mat-error *ngIf="step2FormGroup.get('dateOfBirth').invalid">{{ getDateOfBirthErrorMessage() }}</mat-error> --> <mat-hint align="end">Use the icon above to choose a date</mat-hint> </mat-form-field> </section> <header class="no-top-margin" matRipple (click)="showApplicantzPersonalInformation = !showApplicantzPersonalInformation" [ngClass]="{'expand-section': showApplicantzPersonalInformation }"> <div> <mat-icon>arrow_right</mat-icon> </div> <h3>Applicant's Personal Information (<span>If Child, Person registering the Child</span>)</h3> </header> <section class="no-bottom-border" [ngClass]="{'expand-section': showApplicantzPersonalInformation }"> <mat-form-field appearance="outline"> <mat-label>Surname <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantSurname"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Given Name <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantGivenName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Other Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantOtherName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Maiden Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantMaidenName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Previous Name <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantPreviousName"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Nationality <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantNationality"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label> Residence Status <span class="required-field">required</span></mat-label> <mat-select formControlName="ApplicantResidenceStatus"> <mat-option value="1">Citizen</mat-option> <mat-option value="2">Alien Residenct</mat-option> <mat-option value="3">Foreigner</mat-option> </mat-select> </mat-form-field> <!-- Allow multiple selection --> <mat-form-field appearance="outline"> <mat-label> Support Documents <span class="required-field">required</span></mat-label> <mat-select formControlName="ApplicantSupportDocuments" multiple> <mat-option value="1">Passport</mat-option> <mat-option value="2">National ID Card</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>National ID <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantNIN"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Alien ID <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantAIN"> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Sex <span class="required-field">required</span></mat-label> <mat-select formControlName="ApplicantSex"> <mat-option value="1">Male</mat-option> <mat-option value="2">Female</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Date of Birth <span class="required-field">required</span></mat-label> <input color="accent" matInput [max]="maxDate" placeholder="Enter your date of marriage" formControlName="ApplicantDateOfBirth" [matDatepicker]="dobApplicant"> <mat-datepicker-toggle matSuffix [for]="dobApplicant"></mat-datepicker-toggle> <mat-datepicker #dobApplicant disabled="false"></mat-datepicker> <!-- <mat-error *ngIf="step2FormGroup.get('dateOfBirth').invalid">{{ getDateOfBirthErrorMessage() }}</mat-error> --> <mat-hint align="end">Use the icon above to choose a date</mat-hint> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>Applicant's Role/Capacity <span class="required-field">required</span></mat-label> <mat-select formControlName="ApplicantRole"> <mat-option value="1">Mother</mat-option> <mat-option value="2">Father</mat-option> <mat-option value="3">Guardian</mat-option> <mat-option value="3">Others</mat-option> </mat-select> </mat-form-field> <mat-form-field appearance="outline"> <mat-label>If Others, Please specify <span class="required-field">required</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantRoleOtherSpecify"> </mat-form-field> <mat-form-field appearance="outline" hintLabel="Where the child is being registered from."> <mat-label>Name of the School <span class="optional-field">optional</span></mat-label> <input appRemoveSpaces matInput formControlName="ApplicantSchoolName"> </mat-form-field> </section> </form> <div class="button-wrapper"> <button mat-button class="back-btn" matStepperPrevious>Back</button> <button [ngClass]="{'inline-processing-btn': processing}" mat-raised-button color="primary" [disabled]="formPartA.invalid || processing" (click)="onSaveDraft()"> <app-inline-mat-spinner *ngIf="processing"></app-inline-mat-spinner> <span> Save Draft </span> </button> <button mat-raised-button color="primary" (click)="onSubmit()">Submit to NIRA</button> </div> </mat-step> <!-- <mat-step> <ng-template matStepLabel> <h3>Last Step</h3> </ng-template> <p>You are now done.</p> <div class="button-wrapper"> <button mat-button class="back-btn" matStepperPrevious>Back</button> <button mat-button (click)="stepper.reset()">Reset</button> </div> </mat-step> --> </mat-horizontal-stepper> </main>
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> <c:url var="changeAppointment" value="/controller?command=change_appointment"/> <fmt:setLocale value="${locale}" scope="session"/> <fmt:setBundle basename="languages.locale"/> <html> <head> <title><fmt:message key="change"/> <fmt:message key="appointment"/></title> <c:import url="header.jsp"/> <c:if test="${isAppointmentChanged == false}"> <div class="container-fluid alert-indents"> <div class="alert alert-danger alert-dismissible fade show" role="alert"> <strong><fmt:message key="invalid.data"/></strong> <fmt:message key="try.again"/> <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button> </div> </div> <% request.getSession().removeAttribute("isAppointmentChanged"); %> </c:if> <div class="row"> <div class="col-lg-4"></div> <div class="col-lg-4"> <form class="registration-inputs" action="${changeAppointment}" method="post"> <div class="container-fluid"> <div> <h4>Procedure: ${appointment.procedure.name}</h4> <h4>Doctor: ${appointment.doctor.doctorInfo.surname} ${appointment.doctor.doctorInfo.name}</h4> <h4>Client: ${appointment.userClient.surname} ${appointment.userClient.name}</h4> </div> <div> <input id="appointmentId" class="form-control" value="${appointment.id}" type="hidden" name="appointmentId"/> <input id="clientId" class="form-control" value="${appointment.userClient.id}" type="hidden" name="clientId"/> <input id="doctorId" class="form-control" value="${appointment.doctor.id}" type="hidden" name="doctorId"/> <input id="procedureId" class="form-control" value="${appointment.procedure.id}" type="hidden" name="procedureId"/> </div> <br> <div> <label for="date"> <fmt:message key="date"/></label> <input id="date" class="form-control" value="${appointment.date}" type="date" name="date" required> </div> <br> <div> <label for="startTime"> <fmt:message key="start.time"/></label> <input id="startTime" class="form-control" value="${appointment.startTime}" type="time" name="startTime" required> </div> <br> <div> <label for="status"> <fmt:message key="status"/></label> <select id="status" class="form-select" aria-label="Disabled select example" name="status"> <option selected>${appointment.status}</option> <c:forEach items="${statusList}" var="appointmentStatus"> <c:if test="${appointmentStatus != appointment.status}"> <option value="${appointmentStatus}">${appointmentStatus}</option> </c:if> </c:forEach> </select> </div> <br> <div> <button type="submit" class="btn btn-warning btn-block"><fmt:message key="change"/></button> </div> </div> </form> </div> </div> <c:import url="footer.jsp"/>
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "TP_WeaponComponent.generated.h" class AFPSCharacter; UCLASS(Blueprintable, BlueprintType, ClassGroup = (Custom), meta = (BlueprintSpawnableComponent)) class FPS_API UTP_WeaponComponent : public UActorComponent { GENERATED_BODY() public: /** Projectile class to spawn */ UPROPERTY(EditDefaultsOnly, Category = Projectile) TSubclassOf<class AFPSProjectile> ProjectileClass; /** Sound to play each time we fire */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay) USoundBase* FireSound; /** AnimMontage to play each time we fire */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay) UAnimMontage* FireAnimation; /** Gun muzzle's offset from the characters location */ UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Gameplay) FVector MuzzleOffset; /** Sets default values for this component's properties */ UTP_WeaponComponent(); /** Attaches the actor to a FirstPersonCharacter */ UFUNCTION(BlueprintCallable, Category = "Weapon") void AttachWeapon(AFPSCharacter* TargetCharacter); /** Make the weapon Fire a Projectile */ UFUNCTION(BlueprintCallable, Category = "Weapon") void Fire(); protected: /** Ends gameplay for this component. */ UFUNCTION() virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override; private: /** The Character holding this weapon*/ AFPSCharacter* Character; };
const db = require('./db') const express = require('express') const cors = require('cors') const authenticator = require('./authenticator') const app = express() const authenticate = authenticator({ test_payload_email: process.env['TEST_PAYLOAD_EMAIL'], jwks_uri: 'http://127.0.0.1:5556/dex/keys' }) app.use(require('body-parser').json()) app.use(cors()) app.get('/', (req, res) => { res.send([ '<h1>ECE WebTech Chat</h1>' ].join('')) }) // Channels app.get('/channels', authenticate, async (req, res) => { const channels = await db.channels.list() res.json(channels) }) // app.post('/channels', async (req, res) => { // const channel = await db.channels.create(req.body) // res.status(201).json(channel) // }) app.post('/channels', async (req, res) => { const channel = await db.channels.create(req.body) // add the id of this channel to the array ChannelBelong of the user const user = await db.users.updateUserChannels(channel.id, req.body.userId) res.status(201).json(channel) }) app.get('/channels/:id', async (req, res) => { const channel = await db.channels.get(req.params.id) res.json(channel) }) app.delete('/channelDelete/:id', async (req, res) => { const channel = await db.channels.delete(req.params.id) await db.users.deleteUserChannels(channel.id, req.body.userId) res.json(channel) }) app.put('/channels/:id', async (req, res) => { const channel = await db.channels.update(req.body) res.json(channel) }) // Messages app.get('/channels/:id/messages', async (req, res) => { try{ const channel = await db.channels.get(req.params.id) }catch(err){ return res.status(404).send('Channel does not exist.') } const messages = await db.messages.list(req.params.id) res.json(messages) }) app.post('/channels/:id/messages', async (req, res) => { const message = await db.messages.create(req.params.id, req.body) res.status(201).json(message) }) app.put('/channels/:id/messages', async (req, res) => { const message = await db.messages.update(req.params.id, req.body) res.status(201).json(message) }) app.delete('/channels/:id/messages/:creation', async (req, res) => { console.log("la") const message = await db.messages.delete(req.params.id, req.params.creation) res.status(201).json(message) }) // Users app.get('/users', async (req, res) => { const users = await db.users.list() res.json(users) }) app.post('/users', async (req, res) => { const user = await db.users.create(req.body) res.status(201).json(user) }) app.get('/users/:id', async (req, res) => { const user = await db.users.get(req.params.id) res.json(user) }) app.put('/users/:id', async (req, res) => { const user = await db.users.update(req.body) res.json(user) }) //invite app.get('/invite', async (req, res) => { const invites = await db.invite.list() res.json(invites) }) app.post('/invite', async (req, res) => { const invite = await db.invite.create(req.body.userInvited, req.body.adminUser, req.body.channelId, req.body.channelName) res.status(201).json(invite) }) app.delete('/invite/:id', async (req, res) => { const invite = await db.invite.delete(req.params.id) res.json(invite) }) //Others app.post('/updateChannelBelong', async (req, res) => { const user = await db.users.updateUserChannels(req.body.channelId, req.body.userId) res.json(user) }) module.exports = app
package com.gracedian.explorebojonegoro.ui.dashboard.home.fragmentdetail.adapter import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter import com.gracedian.explorebojonegoro.ui.dashboard.home.fragmentdetail.fragmentdetailsrestoran.GalleryRestoranFragment import com.gracedian.explorebojonegoro.ui.dashboard.home.fragmentdetail.fragmentdetailsrestoran.TentangRestoranFragment import com.gracedian.explorebojonegoro.ui.dashboard.home.fragmentdetail.fragmentdetailsrestoran.UlasanRestoranFragment class RestoranDetailsPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { private var data: Bundle? = null private var fragmentList: List<Fragment> = emptyList() fun setFragmentList(list: List<Fragment>) { fragmentList = list } fun setData(data: Bundle) { this.data = data } override fun createFragment(position: Int): Fragment { return when (position) { 0 -> { val tentangFragment = TentangRestoranFragment() tentangFragment.arguments = data tentangFragment } 1 -> { val galeriFragment = GalleryRestoranFragment() galeriFragment.arguments = data galeriFragment } 2 -> { val ulasanFragment = UlasanRestoranFragment() ulasanFragment.arguments = data ulasanFragment } else -> throw IllegalArgumentException("Invalid position: $position") } } override fun getItemCount(): Int { return 3 } }
#' @name authorModalAdd #' @title authorModalAdd #' @description Opens dialogue to add new authors item. #' @param id Namespace identifier. #' @return HTML source code. #' @export authorModalAdd <- function(id = "authors") { cat("authorModalAdd\n") ns <- NS(id) modalDialog(title = "Add author to model", tagList(textInput(inputId = ns("txbName"), label = "Name *", value = "", placeholder = ""), textInput(inputId = ns("txbInstitution"), label = "Institution *", value = "", placeholder = ""), textInput(inputId = ns("txbEmail"), label = "E-Mail", value = "", placeholder = ""), hr(), strong("* required information")), easyClose = FALSE, footer = tagList(modalButton(label = "Cancel", icon = icon("times-circle")), actionButton(inputId = ns("btnAdd"), label = "Save", icon = icon("plus")))) }
// // String+Extensions.swift // DCUProject // // Created by Yuri on 29/04/2022. // import Foundation extension String { var isValidEmail: Bool { NSPredicate(format: "SELF MATCHES %@", "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}").evaluate(with: self) } var isValidPassword: Bool { // least one uppercase, // least one digit // least one lowercase // least one symbol // min 8 characters total let password = self.trimmingCharacters(in: CharacterSet.whitespaces) let passwordRegex = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&<>*~:`-]).{8,}$" let passwordCheck = NSPredicate(format: "SELF MATCHES %@",passwordRegex) return passwordCheck.evaluate(with: password) } }
declare global { interface Window { tb: any; } } window.tb = window.tb || {}; declare let Threebox: any; import { ElementRef, Injectable } from '@angular/core'; import { Map, LngLatBoundsLike, LngLatLike, MapMouseEvent } from 'mapbox-gl'; import { MapState } from './map.state'; import { centroid } from '@turf/turf'; import { debounce } from 'lodash-es'; @Injectable({ providedIn: 'root', }) export class MapService { map!: Map; tb: any; style$ = this.state.style$; bounds$ = this.state.bounds$; bearing$ = this.state.bearing$; pitch$ = this.state.pitch$; zoom$ = this.state.zoom$; skyLayer$ = this.state.skyLayer$; center$ = this.state.center$; dateTime$ = this.state.dateTime$; follow$ = this.state.follow$; terrain$ = this.state.terrain$; shadows$ = this.state.shadows$; followMouse = debounce((e) => this.onMouseMove(e, this.map), 100); newMap(container: ElementRef): { map: Map; tb: any } { console.log('newMap'); this.map = new Map({ style: 'mapbox://styles/mapbox/streets-v12', container: container.nativeElement, antialias: true, // hash: true, attributionControl: false, preserveDrawingBuffer: true, bearingSnap: 0, accessToken: 'pk.eyJ1IjoiY2hyaXN0b2RvdWxvcyIsImEiOiJja3luYTd3eW0ydGFiMm9xcHRmMGJyOHVrIn0.c1mSurunkjU4Wyf2hxcy0g', }); window.tb = this.newThreeBox(this.map); this.tb = window.tb; return { map: this.map, tb: this.tb }; } newThreeBox(map: Map) { console.log('newTreebox'); return new Threebox(map, map.getCanvas().getContext('webgl'), { willReadFrequently: true, realSunlight: true, sky: true, terrain: true, enableSelectingObjects: true, enableSelectingFeatures: true, }); } add3DBuildingsLayer(map: Map) { console.log('add3DBuildingsLayer'); if (map.getLayer('building')) { map.removeLayer('building'); } if (map.getSource('composite')) { map.addLayer( { id: '3d-buildings', source: 'composite', 'source-layer': 'building', type: 'fill-extrusion', minzoom: 9, paint: { 'fill-extrusion-color': '#ddd', 'fill-extrusion-height': ['number', ['get', 'height'], 5], 'fill-extrusion-base': ['number', ['get', 'min_height'], 0], 'fill-extrusion-opacity': 1, }, }, 'waterway-label' ); } } addSkyLayer() { this.map?.setLight({ anchor: 'map' }); this.map?.addLayer({ id: 'sky-layer', type: 'sky', paint: { 'sky-opacity': [ 'interpolate', ['linear'], ['zoom'], 0, 0, 5, 0.3, 8, 1, ], // set up the sky layer for atmospheric scattering 'sky-type': 'atmosphere', // explicitly set the position of the sun rather than allowing the sun to be attached to the main light source // 'sky-atmosphere-sun': this.getSunPosition(), // set the intensity of the sun as a light source (0-100 with higher values corresponding to brighter skies) 'sky-atmosphere-sun-intensity': 5, }, }); } removeSkyLayer() { this.map?.removeLayer('sky-layer'); } //f addGLBLayer() { // console.log('addGLBLayer'); // // 23.781372557061157, 37.988260208268386 // const te = this.map.queryTerrainElevation([23.73664159, 37.87891007], { // exaggerated: false, // }); // console.log('TERRAIN ELEVATION ', te); // this.map.addLayer({ // id: 'custom_layer', // type: 'custom', // renderingMode: '3d', // // onAdd: function (map, mbxContext) { // onAdd: (map, mbxContext) => { // const options = { // obj: '/assets/flood.glb', // type: 'gltf', // scale: 1, // units: 'meters', // rotation: { x: 90.0, y: 180.0, z: 0 }, // anchor: 'center', // }; // this.tb.loadObj(options, (model: any) => { // model.setCoords([23.73664159, 37.87891007]); // model.color = 0x0000ff; // model.addTooltip('Flood example', true); // this.tb.add(model); // // model.castShadow = true; // this.tb.lights.dirLight.target = model; // }); // }, // // render: function (gl, matrix) { // render: (gl, matrix) => { // // window.tb.update(); // this.tb.update(); // }, // }); // addGLBLayer(map: Map, tb: any) { addGLBLayer( where: LngLatLike, elevated: boolean, modelFile: string, modelCastShadow: boolean = true, modelToolTip: string = '' ) { let elevation = 0; if (elevated) elevation = this.map.queryTerrainElevation(where, { exaggerated: true }) ?? 0; console.log('GLB LAYER TERRAIN ELEVATION ', elevation); this.map.addLayer({ id: 'custom_layer', type: 'custom', renderingMode: '3d', onAdd: () => { const options = { obj: modelFile, type: 'gltf', scale: 1, units: 'meters', rotation: { x: 0.0, y: 0.0, z: 180.0 }, anchor: 'top-right', }; this.tb.loadObj(options, (model: any) => { const pos = elevated ? [...(where as number[]), elevation] : where; model.setCoords(pos); model.color = 0x0000ff; if (modelToolTip) model.addTooltip(modelToolTip, true); this.tb.add(model); model.castShadow = modelCastShadow; this.tb.lights.dirLight.target = model; }); }, render: () => { this.tb.update(); }, }); } onLoad(map: Map) { console.log('MAP LOAD'); this.map = map; this.state.setBounds([ [24.116494, 38.340999], [22.890434, 35.823757], ]); this.addGLBLayer([23.74510255, 37.88579824], false, '/assets/test.glb'); this.map.flyTo({ center: [23.73508263685423, 37.87729612062206], zoom: 15.26, bearing: 46.8, pitch: 75.5, }); } onStyleLoad(map: Map) { console.log('MAP STYLE LOAD'); this.add3DBuildingsLayer(map); } getMapBounds(): number[][] { const bounds = this.map.getBounds(); const ne = bounds.getNorthEast(); const sw = bounds.getSouthWest(); return [ [ne.lng, ne.lat], [sw.lng, ne.lat], ]; } getMapCenter(): number[] { const center = this.map.getCenter(); const lng = center.lng; const lat = center.lat; return [lng, lat]; } getMapZoom(): number { const zoom = this.map.getZoom(); return Math.round((zoom + Number.EPSILON) * 100) / 100; } getMapBearing(): number { const bearing = this.map.getBearing(); return Math.round((bearing + Number.EPSILON) * 100) / 100; } getMapPitch(): number { const pitch = this.map.getPitch(); return Math.round((pitch + Number.EPSILON) * 100) / 100; } setMapCursor(cursor: string) { this.map.getCanvas().style.cursor = cursor; } onMouseMove(e: MapMouseEvent, map: Map) { const point = { x: e.point.x, y: e.point.y }; const lngLat = { lng: e.lngLat.lng, lat: e.lngLat.lat }; const features = map.queryRenderedFeatures(e.point); const properties = features.length ? features[0]['properties'] : {}; const where = { point, lngLat, properties: properties as { [key: string]: any }, }; this.state.setWhere(where); } onZoomEnd(map: Map) { let zoom = map.getZoom(); zoom = Math.round((zoom + Number.EPSILON) * 100) / 100; this.state.setZoom(zoom); } onBoxZoomEnd() { console.log('Box Zoom End, waiting 1 sec to update dashboard ...'); setTimeout(() => { const bounds = this.getMapBounds(); const zoom = this.getMapZoom(); const center = this.getMapCenter(); this.state.update({ bounds, zoom, center }); }, 1000); } onWheel() { const bounds = this.getMapBounds(); const center = this.getMapCenter(); const zoom = this.getMapZoom(); this.state.update({ bounds, center, zoom }); } onRotateEnd() { this.state.setBearing(this.getMapBearing()); } onPitchEnd() { this.state.setPitch(this.getMapPitch()); } onDragEnd() { this.state.setCenter(this.getMapCenter()); } // Map constants mapStyles(): string[] { return [ 'mapbox://styles/mapbox/streets-v12', 'mapbox://styles/mapbox/streets-v9', 'mapbox://styles/mapbox/satellite-streets-v9', 'mapbox://styles/christodoulos/ckzichi5q001l15p1wpq6sbvs', ]; } atticaLandmarks(): string[] { return ['Athens Plant Nursery', 'Hellinikon Development']; } atticaLandmarkPosition(landmark: string): number[] { switch (landmark) { case 'Athens Plant Nursery': return [23.781372557061157, 37.988260208268386]; case 'Hellinikon Development': return [23.73664159, 37.87891007]; default: return [0, 0]; } } constructor(private state: MapState) { // subscribe to map selectors and update map this.style$.subscribe((style) => { this.map && style ? this.map.setStyle(style) : {}; }); this.bounds$.subscribe((bounds) => { this.map && bounds ? this.map.fitBounds(bounds as LngLatBoundsLike) : {}; }); this.bearing$.subscribe((bearing) => { this.map && bearing ? this.map.setBearing(bearing) : {}; }); this.pitch$.subscribe((pitch) => { this.map && pitch ? this.map.setPitch(pitch) : {}; }); this.zoom$.subscribe((zoom) => { this.map && zoom ? this.map.setZoom(zoom) : {}; }); this.skyLayer$.subscribe((visible) => { visible ? this.addSkyLayer() : this.removeSkyLayer(); }); this.center$.subscribe((center) => { this.map && center ? this.map.setCenter(center as LngLatLike) : {}; }); this.dateTime$.subscribe((dateTime) => { this.tb ? this.tb.setSunlight(dateTime) : {}; }); this.follow$.subscribe((follow) => { if (follow) { this.map && this.map.on('mousemove', this.followMouse); } else { this.map && this.map.off('mousemove', this.followMouse); } }); this.terrain$.subscribe((visible) => { if (this.map) this.tb.terrain = visible; }); this.shadows$.subscribe((visible) => { if (this.map && visible) { this.tb.setBuildingShadows({ map: this.map, layerId: 'building-shadows', buildingsLayerId: '3d-buildings', minAltitude: 0.1, }); } else if (this.map) this.tb.removeLayer('building-shadows'); }); } }
package service import ( "context" "time" pb "bibirt-api/api/user/v1" "bibirt-api/internal/biz" "bibirt-api/internal/conf" "bibirt-api/pkg/util" "github.com/gofrs/uuid" "github.com/golang-jwt/jwt/v5" ) type AuthService struct { pb.UnimplementedAuthServer uc *biz.UserUseCase tc *biz.TokenUseCase conf *conf.Server } func NewAuthService(uc *biz.UserUseCase, tc *biz.TokenUseCase, conf *conf.Server) *AuthService { return &AuthService{uc: uc, tc: tc, conf: conf} } func (s *AuthService) RegisterAsAnonymous(ctx context.Context, req *pb.RegisterAsAnonymousRequest) (*pb.RegisterAsAnonymousReply, error) { var err error user := newAnonymousUser() err = s.uc.CreateUser(ctx, user) if err != nil { return nil, err } refreshToken := s.tc.NewRefreshToken(user) token := s.tc.NewAuthToken(refreshToken) return &pb.RegisterAsAnonymousReply{ Token: s.tc.SignedString(token), RefreshToken: s.tc.SignedString(refreshToken), }, nil } func (s *AuthService) WSToken(ctx context.Context, req *pb.WSTokenRequest) (*pb.WSTokenReply, error) { token, err := s.parseAndValidateToken(req.Token) if err != nil { return nil, err } if !s.tc.IsAuthToken(token) { return nil, pb.ErrorTokenInvalid("token invalid") } wsToken := s.tc.NewWSToken(token) return &pb.WSTokenReply{ Token: s.tc.SignedString(wsToken), }, nil } func (s *AuthService) RefreshToken(ctx context.Context, req *pb.RefreshTokenRequest) (*pb.RefreshTokenReply, error) { refreshToken, err := s.parseAndValidateToken(req.RefreshToken) if err != nil { return nil, err } if !s.tc.IsRefreshToken(refreshToken) { return nil, pb.ErrorTokenInvalid("token's subject miss match") } token := s.tc.NewAuthToken(refreshToken) return &pb.RefreshTokenReply{ Token: s.tc.SignedString(token), }, nil } func (s AuthService) UserInfo(ctx context.Context, req *pb.UserInfoRequest) (*pb.UserInfoReply, error) { token, err := s.parseAndValidateToken(req.Token) if err != nil { return nil, err } if !s.tc.IsAuthToken(token) { return nil, pb.ErrorTokenInvalid("token's subject miss match") } claims := s.tc.Claims(token) var user biz.User if s.uc.FindUserByUuid(ctx, claims.UUID, &user) { return &pb.UserInfoReply{ Uuid: claims.UUID, Name: user.Name, Score: user.Score, }, nil } return nil, pb.ErrorUserNotFound("user not found") } func (s *AuthService) WSUserInfo(ctx context.Context, req *pb.WSUserInfoRequest) (*pb.WSUserInfoReply, error) { token, err := s.parseAndValidateToken(req.Token) if err != nil { return nil, err } if !s.tc.IsWSToken(token) { return nil, pb.ErrorTokenInvalid("token's subject miss match") } claims := s.tc.Claims(token) var user biz.User if s.uc.FindUserByUuid(ctx, claims.UUID, &user) { return &pb.WSUserInfoReply{ Uuid: user.Uuid, Name: user.Name, Score: user.Score, }, nil } return nil, pb.ErrorUserNotFound("user not found") } func (s *AuthService) parseAndValidateToken(tokenStr string) (*jwt.Token, error) { token, err := s.tc.ParseToken(tokenStr) if err != nil { return nil, pb.ErrorTokenInvalid("parse token error: %s", err) } if !s.tc.IsTokenValid(token) { return nil, pb.ErrorTokenInvalid("token invalid") } return token, nil } func newAnonymousUser() *biz.User { uuid4 := uuid.Must(uuid.NewV4()) return &biz.User{ Uuid: uuid4.String(), Type: biz.USER_TYPE_TEMP, Name: util.GetRandomStr(6), Status: biz.USER_STATUS_PENDING_TMP, CreatedAt: time.Now(), } }
import AudioVideoMedia, { AudioVideoMediaStatus, } from '@core/shared/domain/value-objects/audio-video-media.vo'; import { VideoId } from './video.aggregate'; import MediaFileValidator from '@core/shared/domain/validations/media-file.validator'; import { Either } from '@core/shared/domain/either'; import MediaFileSizeError from '@core/shared/domain/errors/media-file-size.error'; import MediaFileMimeTypeError from '@core/shared/domain/errors/media-file-mime-type.error'; export default class VideoMedia extends AudioVideoMedia { static MAX_SIZE = 1024 * 1024 * 1024 * 50; // 50GB static MIME_TYPES = ['video/mp4']; static create(name: string, rawLocation: string) { return new VideoMedia({ name, rawLocation, status: AudioVideoMediaStatus.PENDING, }); } static createFromFile( rawName: string, mimeType: string, size: number, videoId: VideoId, ) { const mediaFileValidator = new MediaFileValidator( this.MAX_SIZE, this.MIME_TYPES, ); return Either.safe< VideoMedia, MediaFileSizeError | MediaFileMimeTypeError >(() => { const { name } = mediaFileValidator.validate( rawName, mimeType, size, ); return VideoMedia.create(name, `videos/${videoId.value}/videos`); }); } markAsProcessing() { return new VideoMedia({ name: this.name, rawLocation: this.rawLocation, encodedLocation: this.encodedLocation, status: AudioVideoMediaStatus.PROCESSING, }); } markAsCompleted(encodedLocation: string) { return new VideoMedia({ name: this.name, rawLocation: this.rawLocation, encodedLocation, status: AudioVideoMediaStatus.COMPLETED, }); } markAsFailed() { return new VideoMedia({ name: this.name, rawLocation: this.rawLocation, encodedLocation: this.encodedLocation, status: AudioVideoMediaStatus.FAILED, }); } }
package com.miraeldev.account.presentation.screens.editProfileScreen import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.ButtonDefaults import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedButton import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusEvent import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.miraeldev.account.R import com.miraeldev.designsystem.ErrorValidField import com.miraeldev.designsystem.PasswordField import com.miraeldev.extensions.noRippleEffectClick import com.miraeldev.theme.LocalOrientation import com.miraeldev.utils.PasswordValidationState @Composable fun ChangePasswordDialog( onDismiss: () -> Unit, onChangeClick: () -> Unit, refreshPasswordError: () -> Unit, isPasswordError: PasswordValidationState, isPasswordNotEqualsError: Boolean, serverError: Boolean, newPassword: () -> String, currentPassword: () -> String, repeatedPassword: () -> String, onCurrentPasswordChange: (String) -> Unit, onNewPasswordChange: (String) -> Unit, onRepeatedPasswordChange: (String) -> Unit, ) { val focusManager = LocalFocusManager.current val orientationLandscape = LocalOrientation.current == Configuration.ORIENTATION_LANDSCAPE val clearFocus = remember { { focusManager.clearFocus() } } val focusRequester = remember { FocusRequester() } Column( modifier = Modifier .fillMaxSize() .noRippleEffectClick(onClick = clearFocus) .imePadding() .verticalScroll(rememberScrollState()) .background(Color.Black.copy(alpha = 0.5f)), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Card( modifier = Modifier .fillMaxWidth(0.85f) .systemBarsPadding() .padding(vertical = if (orientationLandscape) 0.dp else 32.dp), shape = RoundedCornerShape(16.dp), backgroundColor = MaterialTheme.colors.background ) { Column( modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { Text( text = stringResource(R.string.change_password), modifier = Modifier .padding(top = 8.dp, bottom = 8.dp), fontSize = 24.sp, ) Column( verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.Start ) { PasswordField( text = currentPassword, isPasswordError = !isPasswordError.successful, onChange = onCurrentPasswordChange, imeAction = ImeAction.Next, modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) .onFocusEvent { if (it.isFocused) { refreshPasswordError() } } ) ErrorValidField( modifier = Modifier.padding(start = 16.dp), isError = !isPasswordError.hasMinimum, error = stringResource(R.string.wrong_current_password) ) } Column( verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.Start ) { PasswordField( text = newPassword, isPasswordError = !isPasswordError.successful, onChange = onNewPasswordChange, imeAction = ImeAction.Next, modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) .onFocusEvent { if (it.isFocused) { refreshPasswordError() } } ) ErrorValidField( modifier = Modifier.padding(start = 16.dp), isError = !isPasswordError.hasMinimum, error = stringResource(R.string.password_must_be_more_than_6_characters) ) ErrorValidField( modifier = Modifier.padding(start = 16.dp), isError = !isPasswordError.hasCapitalizedLetter, error = stringResource(R.string.the_password_must_contain_capital_letters) ) } Column( verticalArrangement = Arrangement.spacedBy(8.dp), horizontalAlignment = Alignment.Start ) { PasswordField( text = repeatedPassword, isPasswordError = !isPasswordNotEqualsError || serverError, onChange = onRepeatedPasswordChange, iconRes = R.drawable.ic_lock, iconSize = 20.dp, modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester) .onFocusEvent { if (it.isFocused) { refreshPasswordError() } } ) ErrorValidField( modifier = Modifier.padding(start = 16.dp), isError = !isPasswordNotEqualsError, error = stringResource(R.string.password_mismatch) ) } Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceEvenly ) { OutlinedButton( modifier = Modifier.weight(1f), onClick = onDismiss, shape = RoundedCornerShape(16.dp), colors = ButtonDefaults.buttonColors( backgroundColor = Color.White, contentColor = MaterialTheme.colors.primary ) ) { Text(text = "Cancel", fontSize = 18.sp) } Spacer(modifier = Modifier.width(4.dp)) OutlinedButton( modifier = Modifier.weight(1f), onClick = onChangeClick, shape = RoundedCornerShape(16.dp), colors = ButtonDefaults.buttonColors( backgroundColor = MaterialTheme.colors.primary, contentColor = Color.White ) ) { Text(text = "Change", fontSize = 18.sp) } } } } } }
use clap::{command, Args, ValueEnum, Subcommand}; use serde::{Deserialize, Serialize}; use std::fs; use crate::{ mapper::{find_environment, find_parent_environment}, prelude::*, }; /// Get information about an environment #[derive(Debug, Args, Clone)] #[command(arg_required_else_help = true)] pub struct CommandInfo { /// Subcommand #[command(subcommand)] pub command: InfoSubcommands, /// Environment where the information will be obtained (if this and path are not specified, use the environment close to the root from the current folder) #[arg(short, long, global=true)] pub environment: Option<String>, /// Path to the environment (if `--environment` is specified ignore, this will be ignored) #[arg(short, long, global=true)] pub path: Option<PathBuf>, } #[derive(Subcommand, Debug, Clone)] pub enum InfoSubcommands { /// Check if the path is within an environment IsEnv, /// get a property from the environment Property { /// The property to get of the environment property : MetadataProperty }, } #[derive(ValueEnum, Copy, Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub enum MetadataProperty { EnvironmentType, Languages, Path, Description, ScriptInterpreter, Name, Directory, } impl MetadataProperty { pub fn check_undefined<T, E, F>(&self, value: T) -> Result<E> where T: Context<E, F>, { value.context(format!("{:?} undefined", self)) } pub fn get_data(&self, metadata: &Metadata) -> Result<String> { Ok(match self { Self::EnvironmentType => { self.check_undefined(metadata.environment_type)?.to_string() } Self::Languages => self.check_undefined(metadata.languages.clone())?.into_iter().collect::<Vec<String>>().join(" "), Self::Path => self .check_undefined(metadata.path.clone())? .to_string_lossy() .to_string(), Self::Directory => metadata.source.to_string_lossy().to_string(), Self::Description => self.check_undefined(metadata.description.clone())?, Self::ScriptInterpreter => { self.check_undefined(metadata.script_interpreter.clone())? } Self::Name => self.check_undefined(metadata.name.clone())?, }) } } impl CommandInfo { /// Execute the command pub fn execute(self, root: &Path) -> Result<()> { let env = if let Some(environment) = self.environment { find_environment(root, &environment).context("environment not found") } else if let Some(mut path) = self.path { path = fs::canonicalize(path).context("invalid path")?; find_parent_environment(&path).context("environment not found") } else { let path = std::env::current_dir().context("failed to get current directory")?; find_parent_environment(&path).context("actual directory isn't a environment") }; match self.command { InfoSubcommands::IsEnv => { println!("{}", env.is_ok()); }, InfoSubcommands::Property { property } => { println!("{}", property.get_data(&Metadata::from(env?))?); }, } Ok(()) } }
# Write a function that takes an array of numbers (integers for the tests) and a target number. It should find two different items in the array that, when added together, give the target value. The indices of these items should then be returned in a tuple / list (depending on your language) like so: (index1, index2). # For the purposes of this kata, some tests may have multiple answers; any valid solutions will be accepted. # The input will always be valid (numbers will be an array of length 2 or greater, and all of the items will be numbers; target will always be the sum of two different items from that array). # Based on: http://oj.leetcode.com/problems/two-sum/ # two_sum([1, 2, 3], 4) # returns [0, 2] or [2, 0] def two_sum(numbers, target): seen = {} for i, num in enumerate(numbers): comp = target - num if comp in seen: return [seen[comp], i] seen[num] = i return [] # so for this one we need to create a dict and use that to keep track of our comp. our comp being the current num - target. # what we are keeping track of is another number that matches our comp in seen, becuase if it does, that means the two numbers together will # equal our target. so each time we itterate we put num in seen with its index because we will need the index later. since we are putting # num in seen, we can check the difference of our current num against target. if we find a match, return comp and our current index
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title> Untitled {{#if (eq type 'blog')}} {{#if (eq blogType 'list')}} - Blog ({{totalEntries}} entries) - Page {{math currentPage '+' 1}} (entries {{math firstIndex '+' 1}} to {{math lastIndex '+' 1}}, {{#with (lookup entries firstIndex)}}{{this.subtitle}}{{/with}} to {{#with (lookup entries lastIndex)}}{{this.subtitle}}{{/with}}) {{else}} - {{entry.subtitle}} - {{entry.title}} {{/if}} {{else if (eq type 'hashtag')}} - Hashtag #{{hashtag}} ({{totalEntries}} occurences) - Page {{math currentPage '+' 1}} (occurences {{math firstIndex '+' 1}} to {{math lastIndex '+' 1}}, {{#with (lookup occurences firstIndex)}}{{this.subtitle}}{{/with}} to {{#with (lookup occurences lastIndex)}}{{this.subtitle}}{{/with}}) {{else if (eq type 'search')}} - Search results {{else}} {{#each titles}} - {{this}}{{/each}} {{/if}} </title> <link rel="stylesheet" href="/assets/css/styles.css" /> </head> <body> <aside class="aside"> <form class="search-form" action="/search.html" method="GET"> <input class="search-form__q" type="text" name="q" value="" /> <input class="search-form__submit" type="submit" value="Search" /> </form> <a class="link link--homepage" href="/">Homepage</a> {{#if (and navigation.pages.nested (gt navigation.pages.nested.length 0))}} <nav class="navigation"> {{> navigation pages=navigation.pages.nested level=1}} </nav> {{/if}} {{#if (and navigation.blog (gt navigation.blog.length 0))}} <nav class="latest"> <ul class="latest__list"> {{#each navigation.blog}} {{#if (lt @index 5)}} <li class="latest__list__item"> <a class="latest__list__item__link" href="{{this.url}}"> {{this.subtitle}} - {{this.title}} </a> </li> {{/if}} {{/each}} </ul> </nav> {{/if}} {{#if (and navigation.hashtags (gt navigation.hashtags.length 0))}} <nav class="hashtags"> <ul class="hashtags__list"> {{#each navigation.hashtags}} <li class="hashtags__list__item"> <a class="hashtags__list__item__link" href="{{this.url}}"> #{{this.hashtag}} ({{this.count}}) </a> </li> {{/each}} </ul> </nav> {{/if}} </aside> <main class="main main--{{type}}">
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ 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/>. Class Foam::HGSSolidMixtureThermo Description Foam::HGSSolidMixtureThermo SourceFiles HGSSolidMixtureThermo.C \*---------------------------------------------------------------------------*/ #ifndef HGSSolidMixtureThermo_H #define HGSSolidMixtureThermo_H #include "HGSSolidThermo.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class HGSSolidMixtureThermo Declaration \*---------------------------------------------------------------------------*/ template<class MixtureType> class HGSSolidMixtureThermo : public HGSSolidThermo, public MixtureType { protected: // Protected data //- Thermal conductivity [W/m/K] volScalarField K_; private: // Private Member Functions //- Calculate K void calculate(); public: //- Runtime type information TypeName("HGSSolidMixtureThermo"); // Constructors //- Construct from mesh HGSSolidMixtureThermo(const fvMesh&); //- Construct from mesh and dictionary HGSSolidMixtureThermo(const fvMesh&, const dictionary&); //- Construct from mesh and dictionary HGSSolidMixtureThermo(const fvMesh&, const dictionary&, const PtrList<volScalarField>& gasPhaseGases); //- Destructor virtual ~HGSSolidMixtureThermo(); // Member functions //- Return the compostion of the solid mixture virtual MixtureType& composition() { return *this; } //- Return the compostion of the solid mixture virtual const MixtureType& composition() const { return *this; } //- Update properties virtual void correct(); // Access functions //- Thermal conductivity [W/m/K] virtual const volScalarField& K() const; // Derived properties //- Specific heat capacity [J/(kg.K)] virtual tmp<volScalarField> Cp() const; //- Heat of formation [J/kg] virtual tmp<volScalarField> Hf() const; //- Sensible enthalpy [J/(kg.K)] virtual tmp<volScalarField> hs() const; // Patches variables //- Density [kg/m3] virtual tmp<scalarField> rho(const label patchI) const; //- Specific heat capacity [J/(kg.K)] virtual tmp<scalarField> Cp(const label patchI) const; //- Sensible enthalpy [J/(kg.K)] virtual tmp<scalarField> hs(const label patchI) const; //- Thermal conductivity [W/(m.K)] virtual tmp<scalarField> K(const label patchI) const; //- Heat of formation [J/kg] virtual tmp<scalarField> Hf(const label patchI) const; //- Scatter coefficient [1/m] virtual tmp<scalarField> sigmaS(const label patchI) const; //- Absorptivity [1/m] virtual tmp<scalarField> kappa(const label patchI) const; //- Emissivity [] virtual tmp<scalarField> emissivity(const label patchI) const; //- Read thermophysicalProperties dictionary virtual bool read(); //- Write the HGSSolidThermo properties virtual bool writeData(Ostream& os) const; }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #ifdef NoRepository # include "HGSSolidMixtureThermo.C" #endif // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
--- title: "Unlock Full Potential of Windows Photos App with Sound & Filter Upgrades for 2024" date: 2024-06-04T15:07:26.211Z updated: 2024-06-05T15:07:26.211Z tags: - screen-recording - ai video - ai audio - ai auto categories: - ai - screen description: "This Article Describes Unlock Full Potential of Windows Photos App with Sound & Filter Upgrades for 2024" excerpt: "This Article Describes Unlock Full Potential of Windows Photos App with Sound & Filter Upgrades for 2024" keywords: "Windows Photo Enhance,Photo App Improvements,Filters for Windows Photos,Audio Sync in Photos,Photo Editing Upgrades,Sound Effects for Windows Photos,Filter Techniques Windows Photos" thumbnail: https://thmb.techidaily.com/9ad9147e4fbb8c24ccda197a0486be5c1d9c044a46c11534bd2a1352ab33e591.png --- ## Unlock Full Potential of Windows Photos App with Sound & Filter Upgrades # How to Add Filters and Music on Windows 10 Photos App ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) ##### Shanoon Cox Mar 27, 2024• Proven solutions Having Windows 10 Photos app is an advantage for you. This is not like any other photo viewing app, but a mighty photo editor as well. If you are thinking that can you **add filters using Windows 10 Photos app**, then we are glad to affirm that, the Photos app does it without much complication. There are inbuilt filters that can come in handy, while you try to add them to any photo. So, without any further ado, let’s learn how you can accomplish this. * [**Part1: How to add filters on Windows 10 Photos App**](#part1) * [**Part2: How to add music on Windows 10 Photos App**](#part2) **You may also like:** [How to Trim Video in Windows 10 Photos Easily >>](https://tools.techidaily.com/wondershare/filmora/download/) ## Part 1: How to add filters on Windows 10 Photos App If you have got Windows 10 Photos app and wish to add filters, though, it is by default a photo viewing app, its editing features are worth to mention. This step by step guide is your perfect savior in that case. **Step 1**: From your folder using ‘File Explorer’, open the desired photo to be edited. Double clicking the picture opens it. Otherwise, you can browse ‘Start’ menu > ‘Photos’ > locate the photo. **Note**: Photos doesn’t systematically arrange images, so finding it through the ‘File Explorer’ is convenient. **Step 2**: Choose the video you want to add filters. Click **New video** at top > Custom video with music. ![ add filters on windows 10 photos app](https://images.wondershare.com/filmora/article-images/add-filters.jpg) **Step 3**: Now, you will be in an video editing page. You can name your video at start or later. **Step 4**: Click Filters at tool bar. Microsoft Photos has 14 filters you can use, including classic, adventure, sepia and so on. ![ add filters on windows 10 photos app](https://images.wondershare.com/filmora/article-images/edit-filters-microsoft-photos.jpg) **Step 5**: Just select one you like. Preview it and then click Done. ## Part 2: How to add music on Windows 10 Photos App Now that you have learnt how to **_add filters using Windows 10 Photos app._** Do you think there is any possibility regarding adding music over it? Adding music to your video would make it more enjoyable. The artificial intelligence feature on Windows 10 Photos app helps it add music to videos with a single click. It’s easy to do, but meanwhile there will be some twitches to the way artificial intelligence videos show up as you try to match the volume and tempo of the music. But, you can do it with the help of default Microsoft tools. **Step 1**: Open Photos app and then tap on the blue color ‘New video’ icon showing on the top. A drop down menu will open after that. **Step 2**: Choose ‘Custom video with music’ and then select the checkbox from the top-right corner of the video. **Step 3**: Now, hit the ‘Create’ button from the top-right followed by dragging the video to Photos timeline. Later, hit on ‘Auio’ at top right. ![ add music on windows 10 photos app](https://images.wondershare.com/filmora/article-images/add-music-to-video-photos-app.jpg) **Step 4**: Pick ‘Your music’ so that you can set up a custom track. There are over 20 music you can choose. You can also sync music to video's beat. You can visit ‘Recommended’ section for adding default ones. ![add music on windows 10 photos app](https://images.wondershare.com/filmora/article-images/choose-music-to-video-photos-app.jpg) **Step 5**: Hit the ‘Done’ button. ## Conclusion From the above article, we conclude that Windows 10 Photos app is an amazing app when it comes to photo editing and screen capturing from a video. While there are numerous options out there, you can **_add filters using Windows 10 Photos app_** in the best way possible. Moreover, this application enables you enable to even add music to videos using Windows 10 Photos app. The advantages of Windows 10 are innumerable, and with the right tools, you can get the best out of it. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox ##### Shanoon Cox Mar 27, 2024• Proven solutions Having Windows 10 Photos app is an advantage for you. This is not like any other photo viewing app, but a mighty photo editor as well. If you are thinking that can you **add filters using Windows 10 Photos app**, then we are glad to affirm that, the Photos app does it without much complication. There are inbuilt filters that can come in handy, while you try to add them to any photo. So, without any further ado, let’s learn how you can accomplish this. * [**Part1: How to add filters on Windows 10 Photos App**](#part1) * [**Part2: How to add music on Windows 10 Photos App**](#part2) **You may also like:** [How to Trim Video in Windows 10 Photos Easily >>](https://tools.techidaily.com/wondershare/filmora/download/) ## Part 1: How to add filters on Windows 10 Photos App If you have got Windows 10 Photos app and wish to add filters, though, it is by default a photo viewing app, its editing features are worth to mention. This step by step guide is your perfect savior in that case. **Step 1**: From your folder using ‘File Explorer’, open the desired photo to be edited. Double clicking the picture opens it. Otherwise, you can browse ‘Start’ menu > ‘Photos’ > locate the photo. **Note**: Photos doesn’t systematically arrange images, so finding it through the ‘File Explorer’ is convenient. **Step 2**: Choose the video you want to add filters. Click **New video** at top > Custom video with music. ![ add filters on windows 10 photos app](https://images.wondershare.com/filmora/article-images/add-filters.jpg) **Step 3**: Now, you will be in an video editing page. You can name your video at start or later. **Step 4**: Click Filters at tool bar. Microsoft Photos has 14 filters you can use, including classic, adventure, sepia and so on. ![ add filters on windows 10 photos app](https://images.wondershare.com/filmora/article-images/edit-filters-microsoft-photos.jpg) **Step 5**: Just select one you like. Preview it and then click Done. ## Part 2: How to add music on Windows 10 Photos App Now that you have learnt how to **_add filters using Windows 10 Photos app._** Do you think there is any possibility regarding adding music over it? Adding music to your video would make it more enjoyable. The artificial intelligence feature on Windows 10 Photos app helps it add music to videos with a single click. It’s easy to do, but meanwhile there will be some twitches to the way artificial intelligence videos show up as you try to match the volume and tempo of the music. But, you can do it with the help of default Microsoft tools. **Step 1**: Open Photos app and then tap on the blue color ‘New video’ icon showing on the top. A drop down menu will open after that. **Step 2**: Choose ‘Custom video with music’ and then select the checkbox from the top-right corner of the video. **Step 3**: Now, hit the ‘Create’ button from the top-right followed by dragging the video to Photos timeline. Later, hit on ‘Auio’ at top right. ![ add music on windows 10 photos app](https://images.wondershare.com/filmora/article-images/add-music-to-video-photos-app.jpg) **Step 4**: Pick ‘Your music’ so that you can set up a custom track. There are over 20 music you can choose. You can also sync music to video's beat. You can visit ‘Recommended’ section for adding default ones. ![add music on windows 10 photos app](https://images.wondershare.com/filmora/article-images/choose-music-to-video-photos-app.jpg) **Step 5**: Hit the ‘Done’ button. ## Conclusion From the above article, we conclude that Windows 10 Photos app is an amazing app when it comes to photo editing and screen capturing from a video. While there are numerous options out there, you can **_add filters using Windows 10 Photos app_** in the best way possible. Moreover, this application enables you enable to even add music to videos using Windows 10 Photos app. The advantages of Windows 10 are innumerable, and with the right tools, you can get the best out of it. ![author avatar](https://images.wondershare.com/filmora/article-images/shannon-cox.jpg) Shanoon Cox Shanoon Cox is a writer and a lover of all things video. Follow @Shanoon Cox <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-format="autorelaxed" data-ad-client="ca-pub-7571918770474297" data-ad-slot="1223367746"></ins> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-7571918770474297" data-ad-slot="8358498916" data-ad-format="auto" data-full-width-responsive="true"></ins> <span class="atpl-alsoreadstyle">Also read:</span> <div><ul> <li><a href="https://some-guidance.techidaily.com/2024-approved-the-essence-of-pixiz-crafting-compelling-stills-to-video-transformations/"><u>2024 Approved The Essence of Pixiz Crafting Compelling Stills-to-Video Transformations</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-the-seamless-shift-an-introduction-to-crossfades/"><u>[Updated] The Seamless Shift An Introduction to Crossfades</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-the-art-of-edible-entertainment-7-steps-to-perfect-plating-on-camera/"><u>[Updated] The Art of Edible Entertainment 7 Steps to Perfect Plating on Camera</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-the-ultimate-step-by-step-for-adding-srt-to-mp4/"><u>[Updated] The Ultimate Step-by-Step for Adding SRT to MP4</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-unveil-clarity-the-finest-10-online-editing-utilities-ranked/"><u>2024 Approved Unveil Clarity The Finest 10 Online Editing Utilities Ranked</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-the-perfect-blend-of-creativity-and-data-for-title-genius/"><u>2024 Approved The Perfect Blend of Creativity & Data for Title Genius</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-superior-sound-swap-technology-the-top-free-option-for-valorant-gamers/"><u>[Updated] Superior Sound Swap Technology The Top Free Option for Valorant Gamers</u></a></li> <li><a href="https://some-guidance.techidaily.com/the-mechanics-of-swift-content-on-facebook-for-2024/"><u>The Mechanics of Swift Content on Facebook for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/the-ultimate-blueprint-for-memetic-virality-for-2024/"><u>The Ultimate Blueprint for Memetic Virality for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-the-beginners-blueprint-for-winning-animation-in-windows/"><u>In 2024, The Beginner’s Blueprint for Winning Animation in Windows</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-the-power-of-precision-in-slug-line-writing-techniques/"><u>In 2024, The Power of Precision in Slug Line Writing Techniques</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-time-travel-through-free-visual-storerooms/"><u>[Updated] Time Travel Through Free Visual Storerooms</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-unleash-the-power-of-windows-11-with-auto-hdr-feature-activation/"><u>[Updated] Unleash the Power of Windows 11 with Auto HDR Feature Activation</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-tale-bearers-school-distinguished-dothee/"><u>[Updated] Tale Bearers School - Distinguished Dothee</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-the-ultimate-guide-to-vivacut-a-detailed-2024-review/"><u>[Updated] The Ultimate Guide to VivaCut A Detailed 2024 Review</u></a></li> <li><a href="https://some-guidance.techidaily.com/tune-travelers-guide-transferring-playlists-with-precision-for-2024/"><u>Tune Traveler's Guide Transferring Playlists with Precision for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-synthesize-and-add-videos-to-your-listing/"><u>In 2024, Synthesize and Add Videos to Your Listing</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-streaming-stats-how-much-does-pewdiepie-earn/"><u>2024 Approved Streaming Stats How Much Does PewDiePie Earn?</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-top-choices-animation-friendly-3d-model-tools/"><u>In 2024, Top Choices Animation-Friendly 3D Model Tools</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-the-art-of-nba-streaming-discover-the-best-15-techniques/"><u>[Updated] The Art of NBA Streaming - Discover the Best 15 Techniques</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-the-best-spots-for-free-downloadable-got-ringtones/"><u>2024 Approved The Best Spots for Free Downloadable GoT Ringtones</u></a></li> <li><a href="https://some-guidance.techidaily.com/in-2024-through-eyes-unseen-an-essential-vr-chronology/"><u>In 2024, Through Eyes Unseen An Essential VR Chronology</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-the-ultimate-toolwiz-photo-experience-analyzed-2023/"><u>2024 Approved The Ultimate Toolwiz Photo Experience, Analyzed 2023</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-top-10-open-source-os-friendly-videography-software/"><u>[Updated] Top 10 Open-Source OS-Friendly Videography Software</u></a></li> <li><a href="https://some-guidance.techidaily.com/unleashing-creativity-in-micro-videography-and-photography-for-2024/"><u>Unleashing Creativity in Micro Videography and Photography for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-the-mac-user-writers-guide-to-dynamic-srt-adjustment/"><u>[New] The Mac User’ Writers Guide to Dynamic SRT Adjustment</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-top-tips-for-flawless-green-screen-cinematography/"><u>2024 Approved Top Tips for Flawless Green-Screen Cinematography</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-the-key-to-spreading-online-jokes-fast/"><u>[New] The Key to Spreading Online Jokes Fast</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-ultimate-guide-selecting-top-notch-free-srt-translators-online/"><u>[Updated] Ultimate Guide Selecting Top-Notch Free SRT Translators Online</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-the-compre-written-by-john-doe-phd-in-psychology-specializing-in-human-behavior-and-motivation-motivational-interviewing/"><u>2024 Approved The Compre Written By John Doe, PhD in Psychology, Specializing in Human Behavior and Motivation (Motivational Interviewing)</u></a></li> <li><a href="https://some-guidance.techidaily.com/transform-your-videos-with-magix-video-pro-x-for-2024/"><u>Transform Your Videos with Magix Video Pro X for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/new-transcending-boundaries-the-vr-evolutionary-journey/"><u>[New] Transcending Boundaries The VR Evolutionary Journey</u></a></li> <li><a href="https://some-guidance.techidaily.com/the-editors-arsenal-advanced-techniques-in-chromatic-tuning-for-2024/"><u>The Editor's Arsenal Advanced Techniques in Chromatic Tuning for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-unlocking-the-secrets-to-iphone-stellar-images/"><u>2024 Approved Unlocking the Secrets to iPhone Stellar Images</u></a></li> <li><a href="https://some-guidance.techidaily.com/top-3-premium-phones-excelling-in-quality-video-capture-for-2024/"><u>Top 3 Premium Phones Excelling in Quality Video Capture for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-unveiling-8-premium-mp3-extraction-software-android/"><u>2024 Approved Unveiling 8 Premium MP3 Extraction Software (Android)</u></a></li> <li><a href="https://some-guidance.techidaily.com/2024-approved-top-8-must-play-virtual-reality-titles-for-now/"><u>2024 Approved Top 8 Must-Play Virtual Reality Titles for Now</u></a></li> <li><a href="https://some-guidance.techidaily.com/tweaking-audio-outputs-sony-ps4-and-ps5-tips-for-2024/"><u>Tweaking Audio Outputs Sony PS4 & PS5 Tips for 2024</u></a></li> <li><a href="https://some-guidance.techidaily.com/updated-the-guide-to-procuring-and-utilizing-free-visual-frame-content/"><u>[Updated] The Guide to Procuring and Utilizing Free Visual Frame Content</u></a></li> <li><a href="https://howto.techidaily.com/4-ways-to-fix-android-blue-screen-of-death-on-vivo-v27e-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>4 Ways to Fix Android Blue Screen of Death On Vivo V27e | Dr.fone</u></a></li> <li><a href="https://sim-unlock.techidaily.com/what-does-enter-puk-code-mean-and-why-did-the-sim-get-puk-blocked-on-huawei-nova-y91-device-by-drfone-android/"><u>What Does Enter PUK Code Mean And Why Did The Sim Get PUK Blocked On Huawei Nova Y91 Device</u></a></li> <li><a href="https://twitter-videos.techidaily.com/new-in-2024-the-visual-vault-techniques-for-capturing-tweets-animated-content/"><u>[New] In 2024, The Visual Vault Techniques for Capturing Tweets’ Animated Content</u></a></li> <li><a href="https://ai-editing-video.techidaily.com/updated-in-2024-how-to-use-speed-ramping-to-create-an-intense-action-footage/"><u>Updated In 2024, How To Use Speed Ramping to Create an Intense Action Footage</u></a></li> <li><a href="https://youtube-videos.techidaily.com/2024-approved-charting-the-future-the-next-gen-youtube-festivals/"><u>2024 Approved Charting the Future The Next Gen Youtube Festivals</u></a></li> <li><a href="https://sound-optimizing.techidaily.com/new-in-2024-essential-mp3-recording-apps-a-list-of-the-top-5-best-on-todays-market/"><u>New In 2024, Essential MP3 Recording Apps A List of the Top 5 Best on Todays Market</u></a></li> <li><a href="https://extra-information.techidaily.com/nostalgic-portraits-retold-transforming-old-prints-to-digital/"><u>Nostalgic Portraits Retold Transforming Old Prints to Digital</u></a></li> <li><a href="https://fix-guide.techidaily.com/play-store-stuck-on-downloading-of-realme-gt-neo-5-se-7-ways-to-resolve-drfone-by-drfone-fix-android-problems-fix-android-problems/"><u>Play Store Stuck on Downloading Of Realme GT Neo 5 SE? 7 Ways to Resolve | Dr.fone</u></a></li> <li><a href="https://review-topics.techidaily.com/how-to-transfer-whatsapp-from-iphone-15-plus-to-other-iphone-15-pro-devices-drfone-by-drfone-transfer-whatsapp-from-ios-transfer-whatsapp-from-ios/"><u>How To Transfer WhatsApp From iPhone 15 Plus to other iPhone 15 Pro devices? | Dr.fone</u></a></li> <li><a href="https://youtube-help.techidaily.com/in-2024-tailor-made-youtube-music-mixes-a-stepwise-technique-for-webmobile-users/"><u>In 2024, Tailor-Made YouTube Music Mixes A Stepwise Technique for Web/Mobile Users</u></a></li> <li><a href="https://ai-voice-clone.techidaily.com/updated-best-narrator-voice-generators/"><u>Updated Best Narrator Voice Generators</u></a></li> <li><a href="https://discord-videos.techidaily.com/2024-approved-audiophiles-guide-to-text-to-speech-on-discord/"><u>2024 Approved Audiophile's Guide to Text-to-Speech on Discord</u></a></li> <li><a href="https://facebook-clips.techidaily.com/in-2024-optimize-iphoneandroid-video-quality-in-online-platforms/"><u>In 2024, Optimize iPhone/Android Video Quality in Online Platforms</u></a></li> <li><a href="https://tiktok-clips.techidaily.com/updated-motivation-at-its-peak-todays-top-15-on-tiktok-for-2024/"><u>[Updated] Motivation at Its Peak Today's Top 15 on TikTok for 2024</u></a></li> <li><a href="https://some-knowledge.techidaily.com/new-how-to-get-final-cut-pro-for-free/"><u>[New] How to Get Final Cut Pro for Free</u></a></li> <li><a href="https://youtube-stream.techidaily.com/how-to-download-part-of-youtube-video-for-2024/"><u>How to Download Part of YouTube Video for 2024</u></a></li> <li><a href="https://sound-tweaking.techidaily.com/in-2024-top-ten-applications-that-alter-male-vocalizations-into-a-feminine-hue/"><u>In 2024, Top Ten Applications That Alter Male Vocalizations Into a Feminine Hue</u></a></li> <li><a href="https://digital-screen-recording.techidaily.com/new-best-free-call-apps-on-android-ranks-them-for-2024/"><u>[New] Best Free Call Apps on Android, Ranks Them for 2024</u></a></li> <li><a href="https://extra-approaches.techidaily.com/2024-approved-paper-artistry-building-harmonious-collages/"><u>2024 Approved Paper Artistry Building Harmonious Collages</u></a></li> <li><a href="https://youtube-stream.techidaily.com/2024-approved-how-to-profit-from-your-youtube-channels/"><u>2024 Approved How to Profit From Your YouTube Channels</u></a></li> <li><a href="https://extra-resources.techidaily.com/2024-approved-advanced-psd-text-styling/"><u>2024 Approved Advanced PSD Text Styling</u></a></li> <li><a href="https://video-ai-editor.techidaily.com/updated-create-stunning-videos-on-windows-imovie-inspired-video-editing-tools/"><u>Updated Create Stunning Videos on Windows IMovie-Inspired Video Editing Tools</u></a></li> </ul></div>
import utilStyles from "../styles/theme.util.module.css"; import React, { useEffect, useState } from "react"; import styles from "../styles/Home.module.css"; import { useTheme, ThemeProvider } from "next-themes"; import PixelButton from "./PixelButton"; export default function ResumeJobs(props) { const [mounted, setMounted] = useState(false); const { resolvedTheme, setTheme } = useTheme(); useEffect(() => { setMounted(true); }, []); if (!mounted) { return null; } let src; function background() { if (resolvedTheme === "light") { return `${utilStyles.ResumeBacker} ${utilStyles.imageRendering}`; } else { return `${utilStyles.ResumeBackerDark} ${utilStyles.imageRendering}`; } } return ( <ThemeProvider> <div className={background()}> <section className={utilStyles.boxLg}> <p>{props.jobName}</p> </section> <section className={utilStyles.box2Md}> <p>{props.employer}</p> </section> <div className={styles.containerAbsolute}> <PixelButton name="Email" url={"mailto:" + props.email} /> </div> </div> </ThemeProvider> ); }
import React from "react"; import "./AddressForm.css"; import axios from "axios"; import { useNavigate } from "react-router-dom"; import buyerService from "../../services/buyerService"; import addressService from "../../services/addressService"; const AddressForm = () => { const navigate = useNavigate(); const [address, setAddress] = React.useState({ street: "", city: "", state: "", zip: "" }); const handleChange = (event) => { const { name, value } = event.target; setAddress((prevAddress) => ({ ...prevAddress, [name]: value })); }; const handleProceedToPayment = (event) => { event.preventDefault(); console.log("Submitting address:", address); buyerService.postBuyerShippingAddress(address) .then((res) => { console.log("Address added successfully", res.status); navigate("/paymentform", {state:{role:'buyer'}}); }).catch((err) => { console.log("Error while adding address", err); }) }; return ( <div className="form-wrapper"> <h2>Add Shipping Address</h2> <form onSubmit={handleProceedToPayment}> <div className="form-group"> <label htmlFor="street">Street:</label> <input type="text" id="street" name="street" value={address.street} onChange={handleChange} /> </div> <div className="form-group"> <label htmlFor="city">City:</label> <input type="text" id="city" name="city" value={address.city} onChange={handleChange} /> </div> <div className="form-group"> <label htmlFor="state">State:</label> <select id="state" name="state" value={address.state} onChange={handleChange} > <option value="">Select State</option> <option value="CA">California</option> <option value="NY">New York</option> <option value="TX">Texas</option> </select> </div> <div className="form-group"> <label htmlFor="zipcode">Zipcode:</label> <input type="text" id="zipcode" name="zipcode" value={address.zipcode} onChange={handleChange} /> </div> <button className="btn-proceed-to-payment" type="submit"> Proceed to Payment </button> </form> </div> ); }; export default AddressForm;
-- Find items with the most maintenance records in the last year -- including their category name and location address -- This can help identify items that require frequent maintenance. SELECT i.ItemID, i.Name AS ItemName, c.Name AS CategoryName, l.Address AS LocationAddress, COUNT(m.MaintenanceID) AS MaintenanceCount FROM Item i JOIN Category c ON i.CategoryID = c.CategoryID JOIN Location l ON i.phoneNumber = l.phoneNumber JOIN Maintenance m ON i.ItemID = m.ItemID WHERE m.MaintenanceDate >= ADD_MONTHS(SYSDATE, -12) GROUP BY i.ItemID, i.Name, c.Name, l.Address HAVING COUNT(m.MaintenanceID) > 0 ORDER BY MaintenanceCount DESC;
from marshmallow import ValidationError, validates, fields, post_load from model.product import Product from marshmallow_sqlalchemy import SQLAlchemyAutoSchema class ProductSchema(SQLAlchemyAutoSchema): class Meta: model = Product # load_instance = True include_relationships = True # strict = True # skip_on_field_errors=False # # INCLUDE: pass those keys/values as is, with no validation performed # unknown = INCLUDE # postprocess = True # sqla_session = db.session quantity = fields.Integer(load_default=0, dump_default=0) comments = fields.List(fields.Nested("CommentSchema", only=("id", "comment","date_created"))) @post_load def create_product(self, data,**kwargs)-> Product: return Product(**data) @validates('name') def validate_name(self,value): if not value: raise ValidationError(f"missing value for column name") if len(value) < 10: raise ValidationError(f"name has to be at least 10 symbols long") return value # @validates('name') # def validate_name_length(self,value): # if not value: # raise ValidationError(f"missing value for column name") # return value @validates('price') def validate_less_zero(self, value): if value: if value < 0: raise ValidationError(f"price ({value}) value cannot be less than zero") return value @validates('quantity') def validate_quantity(self, value): print(f" quantity value {value}") if value: if value < 0: raise ValidationError(f"quantity ({value}) value cannot be less than zero") return value else: return 0
--- id: 6633a2a86218659eb77fb9a1 title: Tarefa 43 challengeType: 22 dashedName: task-43 --- <!-- AUDIO REFERENCE: Sophia: Great question, Tom. Variables can change their values, but constants stay the same. --> # --description-- The modal verb `can` is used to indicate possibility or ability. For example, in the sentence `You can see the stars at night`, `can` shows that it is possible to see the stars during nighttime. `Change` means to make or become different. In everyday life, you might `change` your clothes after work, indicating you switch from work clothes to casual ones. `Stay the same` means to remain unchanged or constant. For example, `The rules of the game stay the same every year.` This means the rules do not alter from one year to the next. # --fillInTheBlank-- ## --sentence-- `Great question, Tom. Variables can _ their values, but constants _ _ _.` ## --blanks-- `change` ### --feedback-- It describes how the values of variables can be altered or modified during the execution of a program. --- `stay` ### --feedback-- It is used here as part of the phrase meaning to remain in the same state or condition. --- `the` ### --feedback-- It is used as part of the phrase indicating that the state being referred to is specific and defined. --- `same` ### --feedback-- It completes the phrase emphasizing that something does not vary or alter from its original state.
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_substr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aenglert <aenglert@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/30 15:10:10 by aenglert #+# #+# */ /* Updated: 2021/06/30 15:10:10 by aenglert ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_substr(char const *s, unsigned int start, size_t len) { char *ptr; size_t i; ptr = (char *)malloc((len + 1) * sizeof(char)); if (ptr == NULL || s == NULL) return (NULL); if (start >= ft_strlen(s)) { *ptr = '\0'; return (ptr); } i = 0; while (i < len && s[start + i] != '\0') { ptr[i] = s[start + i]; i++; } ptr[i] = '\0'; return (ptr); }
// // Created by fail on 6/13/22. // #ifndef STARWARS_SERVER_SERVER_H #define STARWARS_SERVER_SERVER_H #include <boost/asio.hpp> #include <memory> #include <thread> #include <atomic> #include <memory> #include <iostream> #include <utility> #include "Requests.h" #include "World.h" std::string makeString(boost::asio::streambuf& streambuf) { return {buffers_begin(streambuf.data()), buffers_end(streambuf.data())}; } //responsible for handling a single client by reading the request message, processing it, and then sending back the response message. //Each instance of the Service class is intended to handle one connected client //by reading the request message, processing it, and then sending the response message back. class Service { public: //The class's constructor accepts a shared pointer to an object representing a socket connected to a particular client as an argument // and caches this pointer. This socket will be used later to communicate with the client application. explicit Service(std::shared_ptr<boost::asio::ip::tcp::socket> sock) : m_sock(std::move(sock)) {} //This method starts handling the client by initiating the asynchronous reading operation //to read the request message from the client specifying the onRequestReceived() method as a callback. void startHandling() { boost::asio::async_read_until(*m_sock, m_request, '\n', [this]( const boost::system::error_code &ec, std::size_t bytes_transferred) { //When the request reading completes, or an error occurs, the callback method onRequestReceived() is called. onRequestReceived(ec, bytes_transferred); }); } private: void onRequestReceived(const boost::system::error_code &ec, std::size_t bytes_transferred) { //This method first checks whether the reading succeeded by testing the ec argument that contains the operation completion status code. if (ec.value() != 0) { std::cout << "Error occured! Error code = " << ec.value() << ". Message: " << ec.message(); //reading finished with an error, the corresponding message is output to the standard output stream //and then the onFinish() method is called. onFinish(); return; } // Process the request. m_response = processTCPRequest(m_request); // When the ProcessRequest() method completes and returns the string containing the response message, // the asynchronous writing operation is initiated to send this response message back to the client. boost::asio::async_write(*m_sock, boost::asio::buffer(m_response), [this]( const boost::system::error_code &ec, std::size_t bytes_transferred) { //The onResponseSent() method is specified as a callback. onResponseSent(ec, bytes_transferred); }); } void onResponseSent(const boost::system::error_code &ec, std::size_t bytes_transferred) { // This method first checks whether the operation succeeded. if (ec.value() != 0) { // If the operation failed, the corresponding message is output to the standard output stream. std::cout << "Error occured! Error code = " << ec.value() << ". Message: " << ec.message(); } //method is called to perform the cleanup. onFinish(); } // Here we perform the cleanup. void onFinish() { //delete this; } //To keep things simple, we implement a dummy service which only emulates the execution of certain operations //The request processing emulation consists of performing many increment operations to emulate operations //that intensively consume CPU and then putting the thread of control to sleep for some time to emulate I/O operations static std::string processTCPRequest(boost::asio::streambuf &request) { // In this method we parse the request, process it // and prepare the request. // Emulate CPU-consuming operations. // Emulate operations that block the thread // (e.g. synch I/O operations). // Prepare and return the response message. //std::string response = "Response from server\n"; std::string response; /*int kbsize=1; int bytesInKB=1024; for(int j=0; j<kbsize; j++){ for(int i=0; i<bytesInKB; i++){ response.push_back('1'); } } response.push_back('\n');*/ response = RequestManager::processRequest(makeString(request) + "\n"); return response; } private: std::shared_ptr<boost::asio::ip::tcp::socket> m_sock; std::string m_response; boost::asio::streambuf m_request; }; //responsible for accepting the connection requests arriving from clients and instantiating the objects of the Service class, // which will provide the service to connected clients. class Acceptor { public: //Its constructor accepts a port number on which it will listen for the incoming connection requests as its input argument. Acceptor(boost::asio::io_service &ios, unsigned short port_num) : m_ios(ios), //The object of this class contains an instance of the asio::ip::tcp::acceptor class as its member named m_acceptor, //which is constructed in the Acceptor class's constructor. m_acceptor(m_ios, boost::asio::ip::tcp::endpoint( boost::asio::ip::address_v4::any(), port_num)), m_isStopped(false) {} //The Start() method is intended to instruct an object of the Acceptor class to start listening and accepting incoming connection requests. void start() { //It puts the m_acceptor acceptor socket into listening mode m_acceptor.listen(); initAccept(); } // Stop accepting incoming connection requests. void stop() { m_isStopped.store(true); } private: void initAccept() { //constructs an active socket object and initiates the asynchronous accept operation std::shared_ptr<boost::asio::ip::tcp::socket> sock(new boost::asio::ip::tcp::socket(m_ios)); //calling the async_accept() method on the acceptor socket object // and passing the object representing an active socket to it as an argument. m_acceptor.async_accept(*sock, [this, sock]( const boost::system::error_code &error) { //When the connection request is accepted or an error occurs, the callback method onAccept() is called. onAccept(error, sock); }); } void onAccept(const boost::system::error_code &ec, std::shared_ptr<boost::asio::ip::tcp::socket> sock) { if (ec.value() == 0) { //an instance of the Service class is created and its StartHandling() method is called (new Service(std::move(sock)))->startHandling(); } else { //the corresponding message is output to the standard output stream. std::cout << "Error occured! Error code = " << ec.value() << ". Message: " << ec.message(); } // Init next async accept operation if // acceptor has not been stopped yet. if (!m_isStopped.load()) { initAccept(); } else { // Stop accepting incoming connections // and free allocated resources. m_acceptor.close(); } } private: boost::asio::io_service &m_ios; //used to asynchronously accept the incoming connection requests. boost::asio::ip::tcp::acceptor m_acceptor; std::atomic<bool> m_isStopped; }; //represents the server itself class Server { public: Server() { m_work = std::make_unique<boost::asio::io_service::work>(m_ios); } // Start the server. // Accepts a protocol port number on which the server should listen for the incoming connection requests // and the number of threads to add to the pool as input arguments and starts the server // Nonblocking Method void start(unsigned short port_num, unsigned int thread_pool_size) { assert(thread_pool_size > 0); // Create and start Acceptor. acc = std::make_unique<Acceptor>(m_ios, port_num); acc->start(); // Create specified number of threads and // add them to the pool. for (unsigned int i = 0; i < thread_pool_size; i++) { std::unique_ptr<std::thread> th( new std::thread([this]() { m_ios.run(); })); m_thread_pool.push_back(std::move(th)); } } // Stop the server. // Blocks the caller thread until the server is stopped and all the threads running the event loop exit. void stop() { acc->stop(); m_ios.stop(); for (auto &th : m_thread_pool) { th->join(); } } private: boost::asio::io_service m_ios; std::unique_ptr<boost::asio::io_service::work> m_work; std::unique_ptr<Acceptor> acc; std::vector<std::unique_ptr<std::thread>> m_thread_pool; }; #endif //STARWARS_SERVER_SERVER_H
<template> <h1>Add Album</h1> <h4>{{ message }}</h4> <v-form encType = "multipart/form-data"> <v-text-field label="Album Title" v-model="album.title" /> <v-text-field label="Album Category" v-model="album.description" /> <button class="btn btn-info" @click="onPickFile">Upload album image</button> <input type="file" ref="fileInput" accept="image/*" @change="onFilePicked"/> <v-row justify="center"> <v-col col="2"> </v-col> <v-col col="2"> <v-btn color="success" @click="AddAlbum($route.params.id)" >Add album</v-btn > </v-col> <v-col col="2"> <v-btn color="info" @click="cancel()">Cancel</v-btn> </v-col> <v-col col="2"> </v-col> </v-row> </v-form> </template> <script> import AlbumDataService from "../services/AlbumDataService"; export default { name: "add-album", data() { return { album: { id: null, title: "", description: "", published: false }, message: "Enter data and click save", selectedFile: "" }; }, methods: { onPickFile () { this.$refs.fileInput.click() }, onFilePicked (event) { const files = event.target.files let filename = files[0].name const fileReader = new FileReader() fileReader.addEventListener('load', () => { this.imageUrl = fileReader.result }) fileReader.readAsDataURL(files[0]) this.selectedFile = files[0] }, AddAlbum(artistid) { let formData = new FormData(); formData.append("image", this.selectedFile); formData.append("title",this.album.title); formData.append("description",this.album.description); AlbumDataService.create(artistid,formData) .then(response => { this.album.id = response.data.id; console.log("add "+response.data); this.$router.push({ name: 'view' , params: { id: artistid }}); }) .catch(e => { this.message = e.response.data.message; }); }, cancel(){ this.$router.push({ name: 'artists' }); } } } </script> <style> </style>
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { ReactiveFormsModule } from '@angular/forms'; import { AppRoutingModule } from './app-routing.module'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { HttpClientModule } from '@angular/common/http'; import { StoreModule } from '@ngrx/store'; import { StoreDevtoolsModule } from '@ngrx/store-devtools'; import { AppComponent } from './app.component'; import { AuthInterceptorProvider } from './core/interceptors/auth.interceptor'; import { formBuilderReducer } from './shared/state/formbuilder/formbuilder.reducer'; import { ModulesModule } from './modules/modules.module'; import { SharedModule } from './shared/shared.module'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, BrowserAnimationsModule, ReactiveFormsModule, HttpClientModule, StoreModule.forRoot({ formBuilder: formBuilderReducer}), StoreDevtoolsModule.instrument({ maxAge: 25, }), SharedModule, ModulesModule, ], providers: [AuthInterceptorProvider], bootstrap: [AppComponent] }) export class AppModule { }
import util from 'util'; import { Client } from 'discord-rpc'; import { APP_ID as clientId, DEBUG, SHOW_ALBUM_DETAILS, DISABLE_COVERS, } from './Environment'; import MPRIS from './MPRIS'; import Assets from './Assets'; import createLogger from './Console'; import { ms2str } from './Utilities'; const { log, warn } = createLogger('[rpc]'); /** * A Discord RPC client used to send Rich Presence info. */ export default class RPC { /** * Discord RPC client. */ client: Client; /** * MPRIS fetcher instance. */ mpris: MPRIS; /** * Discord Assets API instance. */ assets: Assets; constructor() { this.client = new Client({ transport: 'ipc' }); this.mpris = new MPRIS(); this.assets = new Assets(); } /** * Initializes all instances. */ whenReady(): Promise<void | void[]> { const { client, mpris, assets } = this; return Promise.all([ assets.whenReady(), client.login({ clientId }), mpris.whenReady(), ]).then(() => { if (DEBUG) Object.assign(global, { rpc: this }); mpris.on('update', this.update.bind(this)); log('Ready.'); }); } /** * Updates RPC Presence info. */ async update(): Promise<void> { const { client, mpris, assets } = this; const info = await mpris.getPlaying(); const coverId = DISABLE_COVERS ? 'default' : await assets.get(info.art); log( util.format( '%s %s, written by %s, %s/%s, album cover %s', info.state, info.title, info.artist, ms2str(info.current), ms2str(info.duration), coverId, ), ); try { await client.setActivity({ details: info.title, state: info.artist + (info.album && SHOW_ALBUM_DETAILS ? ` • ${info.album}` : ''), largeImageKey: coverId, largeImageText: info.album || 'discord-mpris', smallImageKey: info.state.toLowerCase(), smallImageText: info.state, startTimestamp: info.state === 'Playing' ? new Date().getTime() - info.current : undefined, }); } catch (ex) { warn(`Couldn't update Rich Presence: ${ex}`); } } }
Contributing guidelines We want to make contributing to this project as easy and transparent as possible. Our Development Process ----------------------- Caterva2 development takes place around its Git repository hosted on GitHub: <https://github.com/ironArray/Caterva2>. New versions are being developed in the `main` branch, or in their own feature branch. When they are deemed ready for a release, they are merged back into `main` again. So all contributions must stage first through `main` or their own feature branch. Pull Requests ------------- We actively welcome your pull requests. 1. Fork the repo and create your branch from `main`. 2. If you've added code that should be tested, add tests. 3. If you've changed APIs, update the documentation. 4. Ensure the test suite passes. 5. Make sure your code does not issue new compiler warnings. Issues ------ We use GitHub issues to track public bugs. Please ensure your description is clear and has sufficient instructions to be able to reproduce the issue. License ------- By contributing to Caterva2, you agree that your contributions will be licensed under the [LICENSE](https://github.com/ironArray/Caterva2/blob/main/LICENSE.txt) file of the project.
/* * Copyright 2012-2013 Oscar Westra van Holthe - Kind * * 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 net.sf.opk.beans; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.enterprise.inject.Instance; import javax.enterprise.util.TypeLiteral; import org.junit.Before; import org.junit.Test; import net.sf.opk.beans.converters.ConversionException; import static java.util.Collections.singletonList; import static net.sf.opk.beans.util.GenericsUtil.resolveType; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ConversionServiceTest { private static final String TEXT = "abc"; private static final Long VALUE = 42L; private ConversionService conversionService; @Before public void initialize() { Converter converter = mock(Converter.class); when(converter.canConvertTo(resolveType(Integer.class))).thenReturn(false); when(converter.canConvertTo(resolveType(String.class))).thenReturn(true); when(converter.convertTo(resolveType(String.class), singletonList(TEXT))).thenReturn(TEXT); when(converter.canConvertTo(resolveType(Long.class))).thenReturn(true); when(converter.convertTo(resolveType(Long.class), singletonList(VALUE.toString()))).thenReturn(VALUE); conversionService = new ConversionService(new ConvertersInstance(converter)); } @Test(expected = ConversionException.class) public void testConversionFailure() { conversionService.convert(null, resolveType(Integer.class)); } @Test public void testConversionSuccess() { assertEquals(TEXT, conversionService.convert(singletonList(TEXT), resolveType(String.class))); assertEquals(VALUE, conversionService.convert(singletonList(VALUE.toString()), resolveType(Long.class))); } @Test public void testConverterCache() { long time1 = System.nanoTime(); String result1 = conversionService.convert(singletonList(TEXT), resolveType(String.class)); long time2 = System.nanoTime(); String result2 = conversionService.convert(singletonList(TEXT), resolveType(String.class)); long time3 = System.nanoTime(); assertEquals(TEXT, result1); assertEquals(TEXT, result2); long beforeCache = time2 - time1; long afterCache = time3 - time2; assertTrue(afterCache < beforeCache); } private class ConvertersInstance implements Instance<Converter> { private List<Converter> converters; private ConvertersInstance(Converter converter) { converters = new ArrayList<>(); converters.add(converter); } @Override public Instance<Converter> select(Annotation... annotations) { throw new UnsupportedOperationException(); } @Override public <U extends Converter> Instance<U> select(Class<U> uClass, Annotation... annotations) { throw new UnsupportedOperationException(); } @Override public <U extends Converter> Instance<U> select(TypeLiteral<U> uTypeLiteral, Annotation... annotations) { throw new UnsupportedOperationException(); } @Override public boolean isUnsatisfied() { throw new UnsupportedOperationException(); } @Override public boolean isAmbiguous() { throw new UnsupportedOperationException(); } @Override public Iterator<Converter> iterator() { return converters.iterator(); } @Override public Converter get() { throw new UnsupportedOperationException(); } } }
import { useEffect } from 'react' import NewNote from './components/NewNote' import Notes from './components/Notes' import VisibilityFilter from './components/VisibilityFilter' import noteService from './services/notes' import { initializeNotes } from './reducers/noteReducer' import { useDispatch } from 'react-redux' const App = () => { const dispatch = useDispatch() useEffect(() => { // noteService // .getAll().then(notes => dispatch(setNotes(notes))) dispatch(initializeNotes()) }, [dispatch]) return ( <div> <NewNote /> <VisibilityFilter /> <Notes /> </div> ) } export default App
# AiNext Template README 🚀 ## Technologies Utilisées 💻 Ce template, situé dans le dossier `aiNext`, est idéal pour créer un site web dans l'univers de l'IA, parfait pour un portfolio ou un blog. Il utilise une combinaison de technologies modernes pour le développement d'applications web. - **Next.js/Vite**: Accélère le développement et le bundling avec un support potentiel pour SSR avec Next.js 🏗️. - **ESLint**: Assure une qualité de code élevée avec une analyse statique 🧐. - **Structure de Dossier**: Code source organisé dans le dossier `src` 📂. - **Fichiers de Configuration**: Gestion des dépendances et scripts de déploiement avec `package.json` ⚙️. ## Prise en Main 🛠️ 1. Exécutez `npm install` pour installer les dépendances nécessaires 📦. 2. Utilisez `npm run dev` pour démarrer le serveur de développement local 🌐. 3. Utilisez `npm run build` pour préparer l'application pour la production 🏭. 4. Suivez les règles ESLint pour un code propre et maintenable 📏. 5. Commencez à personnaliser votre application via le dossier `src` 🎨. Consultez la documentation officielle de Next.js, Vite, et ESLint pour des instructions détaillées. ## Charte Graphique 🎨 **Couleurs**: - Dominante Foncée 🖤 avec des accents néons 🌈 pour une immersion totale dans l'univers de l'IA. **Typographie**: - Police sans serif moderne pour une lecture fluide et une hiérarchisation claire du contenu 🔠. **Mise en Page**: - Design épuré et structuré, parfait pour mettre en valeur des projets de portfolio ou des articles de blog 📐. **Éléments Visuels**: - Imagerie et illustrations de haute qualité qui parlent à l'imaginaire technologique de l'IA 🖼️. **Interactivité**: - Boutons et liens mis en évidence pour une expérience utilisateur intuitive 👆. Ce template est conçu pour mettre en avant un style moderne et technologique, parfait pour un univers centré sur l'intelligence artificielle. ___________________________________ # React + Vite This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. Currently, two official plugins are available: - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh # aiNext
var container = document.querySelector('.row') fetch("https://restcountries.com/v3.1/all") .then((res) => res.json()) .then((data) => { console.log(data) data.map((country) => { var cityName = country.name.common var lat = country.latlng[0] var lon = country.latlng[1] const card = document.createElement('div') card.classList.add('card') card.setAttribute("id", `card_${cityName}`) card.innerHTML = `<div class="card-header "> ${cityName} </div> <div class="card-body"> <img src="${country.flags.png}" alt="image" width="200px" height="150px"> <div class="card-text"> <p>Region: ${country.region} </p> <p>Capital: ${country.capital}</p> <p>Country Code: ${country.cioc}</p> <button class="btn btn-primary" id="wthrbtn" onclick=weather_report('${cityName}','${lat}','${lon}')>Click for Weather</button> </div>` container.appendChild(card) }) }).catch((err) => { console.log(err) alert('Weather details nor available.')}) function weather_report(city, lat, lon) { console.log(city, lat, lon) fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=64aa5a1cf85f3e7f1d8dcf47de9790e2`) .then((res) => res.json()) .then((data) => { console.log(`Temperature:${data.main.temp} Humidity:${data.main.humidity} Pressure:${data.main.pressure} waether:${data.weather[0].main}`) var iconUrl="" if(data.weather[0].main=="Clouds"){ iconUrl="images/clouds.png" } else if(data.weather[0].main=="Clear"){ iconUrl="images/clear.png" } else if(data.weather[0].main=="Mist"){ iconUrl="images/mist.png" } else if(data.weather[0].main=="Rain"){ iconUrl="images/rain.png" } else if(data.weather[0].main=="Drizzle"){ iconUrl="images/drizzle.png" } else if(data.weather[0].main=="Snow"){ iconUrl="images/snow.png" } const weather = document.createElement('div') weather.classList.add('details') weather.innerHTML =`<div class="temp"> <img src=${iconUrl}> <div> <p>${(data.main.temp-273).toFixed()}°C Temp</p> </div> <div class="colum"> <img src="images/humidity.png"> <div> <p>${data.main.humidity}% Humidity</p> </div> <div class="colum"> <img src="images/wind.png"> <div> <p> ${data.wind.speed}Kmph Wind Speed</p> </div> </div>` document.getElementById(`card_${city}`).appendChild(weather) }).catch((err) => { console.log(err) alert('Weather details nor available.') }) }
import React, { Dispatch, SetStateAction, createContext, useContext, useState } from 'react' import { Game } from '@types' /** * This state contains the game. The game is set on the fetch and can be accessed from the children. */ interface GameContextType { game: Game | null setGame: Dispatch<SetStateAction<Game | null>> } const initialState: GameContextType = { game: null, setGame: () => {}, } const GameContext = createContext<GameContextType>(initialState) export const GameContextProvider = ({ children }: { children: React.ReactNode }) => { const [game, setGame] = useState<Game | null>(null) return <GameContext.Provider value={{ game, setGame }}>{children}</GameContext.Provider> } export const useGameContext = (): GameContextType => { const context = useContext(GameContext) if (!context) throw new Error('useGameContext hook must be used within a GameContextProvider') return context }
import React from 'react' import { useState,useCallback,useMemo} from 'react' export default function UseCallBackFunc() { const [count,setCount] = useState(0) // const incrementByOne = useCallback(() => { // console.log("one") // setCount((prevCount)=>{ // prevCount = prevCount + 1; // }) // }, []) const incrementByOne = useCallback(() => { setCount((prevCount)=>prevCount + 1) }, []) const incrementByFive = useCallback(() => { setCount((prevCount)=>{ return prevCount + 5; }) }, []) const isEvenOrOdd =() => { return count % 2 === 0; } return ( <div className='flex-1 my-6'> <p className='text-white'> This is useCallBackFunc counter : </p> <p className='text-white'> {isEvenOrOdd() ? 'Even' : 'Odd'} </p> <div> <p className='text-white'>Count : {count} </p> <button type="button" onClick={incrementByOne} className="btn btn-primary p-2 bg-slate-600 mx-2">Increment by 1</button> <button type="button" onClick={incrementByFive} className="btn btn-primary p-2 bg-lime-600">Increment by 5</button> </div> </div> ) }
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Notification; class MailResetPasswordToken extends Notification { use Queueable; public $token; /** * Create a new notification instance. */ public function __construct($token) { $this->token = $token; } /** * Get the notification's delivery channels. * * @return array<int, string> */ public function via(object $notifiable): array { return ['mail']; } /** * Get the mail representation of the notification. */ public function toMail(object $notifiable): MailMessage { return (new MailMessage) ->subject("Reset your password") ->line('Hey, did you forget your password? Click the button to reset it.') ->action('Reset Password', url('password/reset', $this->token)) ->line('Thank you for using our application!'); } /** * Get the array representation of the notification. * * @return array<string, mixed> */ public function toArray(object $notifiable): array { return [ // ]; } }