text
stringlengths
184
4.48M
[[ch05-builder]] == Builder Pattern === GoF Definition Separate the construction of a complex object from its representation so that the same construction processes can create different representations. === UML Interpretation [plantuml, builder, png] ---- class Product interface Builder class ConcreteBuilder class Director Director o-- Builder Builder <|-- ConcreteBuilder ConcreteBuilder --> Product ---- === Resume Builder Example (((Builder, Resume Builder Example))) [plantuml, resume-builder, png] ---- interface IResumeBuilder { Resume build() } class Resume class AbstractResumeBuilder class ResumeMaker class ProfessionalResumeBuilder class SocialResumeBuilder IResumeBuilder <|.. AbstractResumeBuilder AbstractResumeBuilder <|-- ProfessionalResumeBuilder AbstractResumeBuilder <|-- SocialResumeBuilder ResumeMaker --> IResumeBuilder IResumeBuilder --> Resume ---- [source,java] ---- include::../../../ch05-builder/ex01-resume-builder/src/main/java/com/example/IResumeBuilder.java[tags=source] ---- [source,java] ---- include::../../../ch05-builder/ex01-resume-builder/src/main/java/com/example/Resume.java[tags=source] ---- [source,java] ---- include::../../../ch05-builder/ex01-resume-builder/src/main/java/com/example/AbstractResumeBuilder.java[tags=source] ---- [source,java] ---- include::../../../ch05-builder/ex01-resume-builder/src/main/java/com/example/ResumeMaker.java[tags=source] ---- [source,java] ---- include::../../../ch05-builder/ex01-resume-builder/src/main/java/com/example/ProfessionalResumeBuilder.java[tags=source] ---- [source,java] ---- include::../../../ch05-builder/ex01-resume-builder/src/main/java/com/example/SocialResumeBuilder.java[tags=source] ---- [source,java] ---- include::../../../ch05-builder/ex01-resume-builder/src/test/java/com/example/ResumeMakerTest.java[tags=source] ---- === Builder instances in JDK * java.lang.StringBuilder#append() * java.lang.StringBuffer#append() * java.nio.ByteBuffer#put()
import fenics import vedo.dolfin import numpy as np from utils.mesh_generators import create_xml2Dmesh_withGMSH from braingrowth2D_disk.braingrowthFEM.input_mesh import geometry from braingrowth2D_disk.braingrowthFEM.formulate_problem import problem from braingrowth2D_disk.braingrowthFEM.solve_problem import solver # ************ # # # # Input mesh: # # # # ************ # # Create input gemoetry in the .xml format (readable by FEniCS) mesh_folderpath = './braingrowth2D_disk/data/' geometry_type = 'disk' geometry_name = 'disk_1' # name that will be provided to the mesh file mesh_parameters = {'diskcenter': np.array([0., 0., 0.]), 'radius': 1., 'elementsize': 0.03} brain_representation = 'whole' # 'partial' if mesh does not represent the full brain (e.g. rectangle, halfdisk, quarterdisk); 'whole' otherwise (e.g. in 2D: disk; in 3D: ellipsoid, dhcp, tallinen) --> conditionnes the boundaries that will be computed (e.g. if 'whole: bcs=[]) createdmesh = create_xml2Dmesh_withGMSH.DiskMesh(mesh_folderpath, geometry_name, **mesh_parameters) meshpath = createdmesh.meshfilepath_xml_2D # .xml mesh file mesh = fenics.Mesh(meshpath) # FEniCS mesh vedo.dolfin.plot(mesh, wireframe=False, text='mesh', style='paraview', axes=4).close() # *********************** # # # # Simulation parameters: # # # # *********************** # # Boundaries & subdomains # ----------------------- subdomains_definition_parameters = {'cortical_thickness': 0.05} # Define Dirichlet boundary conditions # ------------------------------------ dirichlet_bcs_parameters = {'consider_brainsurface_bc_TrueorFalse': False, 'brainsurface_bc': None} # e.g. 'consider_brainsurface_bc_TrueorFalse': True + 'brainsurface_bc' = fenics.Constant(0., -0.1); fenics.Expression(...) # 'bottom_bc_type': "fixed"; "plan_rolling" # Define growth tensor: binary, tangential and adaptative # ------------------------------------------------------- cortex_growth_parameters = {'gr_cortex_TAN': 1., # 'gr': yes/no growth mask for each Point. --> further developments: gr differential and not binary; gr=gr(t); gr_cortex(X) != gr_core(X) 'gr_cortex_RAD': 1., 'alpha_cortex_TAN': 1., # 1. for rectangle mesh / 1.829 in original BrainGrowth // g_cortex_TAN[Point] = 1 + dg_cortex_TAN[Point] = 1 + gr_cortex_TAN[Point] * alpha_cortex_TAN * dt 'alpha_cortex_RAD': 0.} # g_cortex_RAD = 1 + dg_cortex_RAD[Point] = 1 + gr_cortex_RAD[Point] * alpha_cortex_RAD * dt core_growth_parameters = {'gr_core_TAN': 0., 'gr_core_RAD':0., 'alpha_core_TAN': 0., 'alpha_core_RAD': 0.} # Define brain constitutive model # ------------------------------- brain_material_parameters = {'type':'elastic', 'constitutive_model': 'neo_hookean', 'rho': 20., # 20. for rectangle mesh / 0.01046 in original BrainGrowth 'damping': 10.} # 10. for rectangle mesh / 0.5 in original BrainGrowth cortex_material_parameters = {'mu': 20., # # 20. for rectangle mesh / 1. in original BrainGrowth 'k': 100.} # 100. for rectangle mesh / 5. in original BrainGrowth core_material_parameters = {'mu': 1., # # 1. for rectangle mesh / 1.167 in original BrainGrowth 'k': 100.} # 100. for rectangle mesh / 5. in original BrainGrowth # External forces # --------------- body_forces = fenics.Constant((0., 0.)) # 2D # Simulation time parameters # -------------------------- simulation_time_parameters = {'tmax': 5., 'number_steps': 50} dt = fenics.Constant(simulation_time_parameters['tmax']/simulation_time_parameters['number_steps']) # as ALPHA_M and ALPHA_F parameters for temporal discretization were choosen to provide IMPLICIT NUMERICAL SCHEME, 'dt' value is a priori arbitrary (no CFL condition). print('time step: ~{:5} s.'.format( float(dt) )) # Numerical scheme parameters # --------------------------- # Temporal discretization parameters (alpha-generalized method) temporal_discretization_parameters = {'alphaM': 0.2, 'alphaF': 0.4 } # alphaM = 0.2; alphaF = 0.4 --> Generalized-α method; Unconditional stability (implicit temporal discretization); Energy-dissipative scheme ("numerical damping") # alphaM = 0.; alphaF = 0. --> Newmark method; Energy-conservative scheme # ************* # # # # Main program: # # # # ************* # # FEniCS based-mesh # ----------------- meshObj = geometry.Mesh(meshpath, mesh_parameters, brain_representation, geometry_type) # Get personalized mesh object from 'mesh' FEniCS object """ mesh_characteristics = meshObj.characteristics centerofgravity_coordinates = meshObj.cog min_mesh_spacing = meshObj.min_mesh_spacing # max_mesh_spacing, average_mesh_spacing """ # Define elastodynamics problem # ----------------------------- braingrowth_problem = problem.NonLinearDynamicMechanicsProblem(meshObj, subdomains_definition_parameters, temporal_discretization_parameters, dt, brain_material_parameters, cortex_material_parameters, core_material_parameters, dirichlet_bcs_parameters, body_forces, results_folderpath='./braingrowth2D_disk/results/') # Define elastodynamics solver # ---------------------------- braingrowth_solver = solver.NonLinearDynamicMechanicsSolver(simulation_time_parameters, dt, braingrowth_problem, cortex_growth_parameters, core_growth_parameters, results_folderpath='./braingrowth2D_disk/results/', results_filename='displacements', results_format='.xmdf') braingrowth_solver.set_solver_parameters(nonlinearsolver="newton", linearsolver="mumps", linearsolver_preconditionner=None) # U=A⁻¹B direct solving method O(N³) # Launch simulation (resolution of elastodynamics variational problem by Finite Element Method) # --------------------------------------------------------------------------------------------- braingrowth_solver.launch_simulation()
<template> <div class="content"> <Navbar @selected-game-change="updateGameDataFromNavbar"/> <b-container class="mt-2 mb-5 pt-3"> <!-- Filters + header --> <b-row> <b-col class="text-left ml-3 mt-2"><h1>{{ getAvailabilityHeader() }}</h1></b-col> <b-col class="text-right" cols="2"> <h1 class="clickable" style="width: fit-content; float: right" @click="filter_visible = !filter_visible" v-b-toggle.filter-collapse > <b-icon :icon="getFilterIcon(filter_visible)"/> </h1> </b-col> </b-row> <!-- Filter collapsible --> <b-row> <b-col class="text-left"> <b-collapse id="filter-collapse"> <b-card> <div v-if="loading" class="filter-loading-overlay loading-gif-container"> <img :src="loading_gif" class="loading-gif"/> </div> <MonthFilter @selected-month-change="updateGameDataFromMonthSelection"/> <hr/> <!-- Sort by --> <b-row class="mb-1"> <b-col xl="1" lg="2" sm="3"> <p class="mb-0"><b>Sort:</b></p> </b-col> <b-col lg="10" sm="12"> <b-form-select v-model="filters.sort_selection" @change="sortAndReorderData" class="w-25 pt-0 pb-0" :options="filters.sort_options" > </b-form-select> </b-col> </b-row> <hr/> <!-- Show caught --> <b-row class="mb-1 pl-3"> <p class="mb-0 mr-3"><b>Show caught:</b></p> <b-form-checkbox id="show-caught-filter" v-model="filters.show_caught" size="lg" switch /> </b-row> <!-- Last month available--> <b-row class="mb-1 pl-3"> <p class="mb-0 mr-3"><b>Last month only:</b></p> <b-form-checkbox id="show-last-month-available-filter" v-model="filters.last_month_only" size="lg" switch /> </b-row> </b-card> </b-collapse> </b-col> </b-row> <!-- Critter section selection buttons --> <b-row> <b-col> <b-row class="critter-section-selection"> <div class="critter-button-wrapper"> <div class="critter-button ml-4" id="fish" @click="critterButtonClick"> <CritterSvg critter_type="fish" :active="filters.critter_selection === 'fish'"/> </div> <div class="critter-button" id="bug" @click="critterButtonClick"> <CritterSvg critter_type="bug" :active="filters.critter_selection === 'bug'"/> </div> <div class="critter-button" v-if="sea_creature_games.includes(game_name)" id="sea_creature" @click="critterButtonClick" > <CritterSvg critter_type="sea_creature" :active="filters.critter_selection === 'sea_creature'" /> </div> </div> <div style="display: flex; align-items: center;" class="ml-4"> <h2 class="critter-section-label"> {{ filters.critter_selection_map[filters.critter_selection] }} </h2> <div class="critter-count-container mb-4 ml-1"> <p class="mb-0">{{ filteredArray(critters[filters.critter_selection]).length }}</p> </div> </div> </b-row> <hr class="divider"/> </b-col> </b-row> <!-- Content --> <b-row class="mt-3 mb-3" style="min-height: 50vh"> <b-col> <div class="loading-gif-container" v-if="loading"> <img :src="loading_gif" class="loading-gif"/> </div> <div v-else-if="error !== null"> <div class="error"> <h3 class="mb-0">{{ error }}<img :src="error_icon"/></h3> </div> </div> <div v-else> <FishSection v-if="filters.critter_selection === 'fish'" :fish="filteredArray(critters.fish)" :month_selected="filters.month_selected" /> <BugSection v-if="filters.critter_selection === 'bug'" :bugs="filteredArray(critters.bug)" :month_selected="filters.month_selected" /> <SeaCreatureSection v-if="filters.critter_selection === 'sea_creature'" :seacreatures="filteredArray(critters.sea_creature)" :month_selected="filters.month_selected" /> </div> </b-col> </b-row> </b-container> <Footer/> </div> </template> <script> import { _ } from 'vue-underscore'; import BugSection from '../components/critterSections/BugSection.vue'; import FishSection from '../components/critterSections/FishSection.vue'; import SeaCreatureSection from '../components/critterSections/SeaCreatureSection.vue'; import CritterSvg from '../components/CritterSvg.vue'; import MonthFilter from '../components/filterComponents/MonthFilter.vue'; import Footer from '../components/Footer.vue'; import Navbar from '../components/Navbar.vue'; import CritterJson from '../assets/critters.json'; export default { components: { BugSection, FishSection, SeaCreatureSection, CritterSvg, Navbar, Footer, MonthFilter, }, data() { return { json: CritterJson, critters: { fish: [], bug: [], sea_creature: [], }, error: null, loading: false, loading_gif: require('@/assets/loading.gif'), // eslint-disable-line error_icon: require('@/assets/icons/resetti_error.png'), // eslint-disable-line sea_creature_games: ['newleaf', 'newhorizons'], game_name: 'newhorizons', // default game selected col_count: null, // set in mounted() new_col_count: null, // set in mounted() filter_visible: false, filters: { month_selected: 'now', // default value availability filter, can also be month // time_selected: 'now', sort_options: [ { value: 'num', text: 'In-game order' }, { value: 'name', text: 'Name' }, { value: 'location', text: 'Habitat' }, { value: 'selling_price', text: 'Price' }, ], month_options: [ // Months dropdown { value: 'january', text: 'January', num: 1 }, { value: 'february', text: 'February', num: 2 }, { value: 'march', text: 'March', num: 3 }, { value: 'april', text: 'April', num: 4 }, { value: 'may', text: 'May', num: 5 }, { value: 'june', text: 'June', num: 6 }, { value: 'july', text: 'July', num: 7 }, { value: 'august', text: 'August', num: 8 }, { value: 'september', text: 'September', num: 9 }, { value: 'october', text: 'October', num: 10 }, { value: 'november', text: 'November', num: 11 }, { value: 'december', text: 'December', num: 12 }, ], sort_selection: 'num', // default value sort dropdown show_caught: true, last_month_only: false, critter_selection: 'fish', critter_selection_map: { fish: 'Fish', bug: 'Bugs', sea_creature: 'Sea Creatures', }, }, }; }, methods: { getData() { this.loading = true; const gameJson = this.json[this.game_name]; this.critters.fish = this.getDataFilter(gameJson.fish); this.critters.bug = this.getDataFilter(gameJson.bug); this.critters.sea_creature = this.getDataFilter(gameJson.sea_creature); // Somehow a short timeout makes it so spinner disappears when data is rendered setTimeout(() => { this.loading = false; }, 400); }, getDataFilter(arr) { if (arr === undefined) { return []; } // Deep copy needed to prevent odd behaviour let filtered = structuredClone(arr); // eslint-disable-line // monthNo also includes hemisphere logic const monthNo = this.getMonthNo(); // Transform time_availability object into array containing times for current month for (let i = 0; i < filtered.length; i += 1) { // Because of some caching we sometimes dont get fresh data from json. So // We need to check if the availability is not already an array. If it is // we do nothing, otherwise we want to get the correct time array from // the time_availability object if (!(filtered[i].time_available instanceof Array)) { let indexToGet = null; // Try to use the current/selected month for time availability // This is not always possible when we want all critters, in this // case we simply take the first time availability array if (monthNo in filtered[i].time_available) { indexToGet = monthNo; } else { indexToGet = Object.keys(filtered[i].time_available)[0]; // eslint-disable-line } filtered[i].time_available = filtered[i].time_available[indexToGet]; } } // Selected month filter if (this.filters.month_selected !== 'all') { // TODO hemisphere shift filtered = filtered.filter((entry) => entry.months_available.includes(monthNo)); } // Time filter when selection is 'now' if (this.filters.month_selected === 'now') { const hour = this.getHour(); const nextHour = hour < 23 ? hour + 1 : 0; // eslint-disable-next-line filtered = filtered.filter((entry) => (entry.time_available.includes(hour) && entry.time_available.includes(nextHour))); } // Shift available months by 6 months if user is in southern hemisphere // This is only cosmetic as filtering has alrady been done. if (this.hemisphereString() === 's') { for (let i = 0; i < filtered.length; i += 1) { // eslint-disable-next-line filtered[i].months_available = filtered[i].months_available.map((m) => this.shiftMonth(m)); } } return filtered; }, updateGameDataFromNavbar(game) { // When switching from game containing sea creatures to game that doesn't we // reset the selected critters to fish if the sea creature section // is currently selected if ( this.sea_creature_games.includes(this.game_name) && !this.sea_creature_games.includes(game) && this.filters.critter_selection === 'sea_creature' ) { this.filters.critter_selection = 'fish'; } // Called when user selects game in header dropdown this.game_name = game; this.getData(); }, updateGameDataFromMonthSelection(month) { // Set selected month before retrieving new data this.filters.month_selected = month; this.getData(); }, hemisphereString() { // NOTE duplicate exists in Availability.vue if (this.game_name === 'newhorizons') { if (!localStorage.hemisphere) { // Default value localStorage.hemisphere = 'n'; } return `${localStorage.hemisphere}`; } // Not needed if not New Horizons return ''; }, sortAndReorderData() { // Sorts data based on field selected in filter sort section // Sorting is done ascending (a-z) this.critters.fish = this.sortArray(this.critters.fish); this.critters.bug = this.sortArray(this.critters.bug); this.critters.sea_creature = this.sortArray(this.critters.sea_creature); // Reorders data so columns can be read left to right this.critters.fish = this.reorderArray(this.critters.fish); this.critters.bug = this.reorderArray(this.critters.bug); this.critters.sea_creature = this.reorderArray(this.critters.sea_creature); }, filteredArray(arr) { // Filters data arrays based on filters selected in front-end if (arr === undefined) { return []; } let out = arr; // Filter out caught critters when Show caught filter is false. if (!this.filters.show_caught) { out = out.filter((c) => !localStorage[`${this.game_name}_${c.name.replace(' ', '_').toLowerCase()}`]); } // Filter out critters available next month if last month only filter is true. if (this.filters.last_month_only) { const currMonth = this.getMonthNo(); const nextMonth = this.getNextMonthNo(); // eslint-disable-next-line out = out.filter((c) => !c.months_available.includes(nextMonth) && c.months_available.includes(currMonth)); } // Sort using selected sort filter out = this.sortArray(out); // Reorder so columns can be read left to right out = this.reorderArray(out); return out; }, sortArray(arr) { // Strange behaviour empties array when length is one, handle this here if (arr.length === 1) { return arr; } return _.sortBy(arr, this.filters.sort_selection); }, reorderArray(arr) { // Reorders array based on amount of columns of cards in card group. // By default the order is top to bottom from left to right column but // this is not intuitive. Here we shift the data in such a way the order // if left to right top to bottom // Handle edge case. On length 1 undefined would be added to array. // On col count 1 there is no need to sort if (arr.length === 1 || this.col_count === 1) { return arr; } let out = []; // Amount of cards per column is roughly the total amount of cards // divided by amount of columns rounded up const rows = Math.ceil(arr.length / this.col_count); // Normal method doesnt work when there are 3 columns and the // amount of cards is n * 3 + 1. In this case we want to fill data row // by row instead of per column. The final 2 rows only have 2 items. if (this.col_count === 3 && arr.length % this.col_count === 1) { // We are going to insert values based on index, so we start with // an array with the correct length filled with nulls, we replace // the nulls in the loop below out = arr.map(() => null); for (let r = 0; r < rows; r += 1) { for (let c = 0; c < this.col_count; c += 1) { const idx = r + (rows * c); // Handle column index 2 on final 2 rows (dont append data) if (r >= rows - 2 && c === 2) { // Do nothing } else { // Add the first item in array to the correct index in out array out[idx] = arr.shift(); } } } } else { // Iterate over column indices for (let c = 0; c < this.col_count; c += 1) { // Per column iterate over row indices for (let r = 0; r < rows; r += 1) { // Calculate index in original data and add to output array const idx = r * this.col_count + c; if (arr[idx]) { out.push(arr[idx]); } } } } return out; }, getFilterIcon() { // Change icon of top filter text to downwards caret if filter collapse // is closed, and upwards caret if filters are open if (this.filter_visible) { return 'filter-square-fill'; } return 'filter'; }, getAvailabilityHeader() { if (this.filters.month_selected === 'now') { return 'Available now'; } if (this.filters.month_selected === 'all') { return 'All critters'; } return `Available in ${this.filters.month_selected}`; }, calculateColCount(width) { // Simple logic determining amount of columns in frontend // depending on width of screen if (width <= 990) { if (width < 576) { return 1; } return 2; } return 3; }, getHour() { // Get current hour const d = new Date(); return d.getHours(); }, getMonthNo() { // NOTE duplicate exists in Availability.vue // Get selected month number, taking into account an 'all' or 'now' selection let monthNo = null; // Easy, just get current month if (this.filters.month_selected === 'all' || this.filters.month_selected === 'now') { // Use current month const d = new Date(); monthNo = d.getMonth() + 1; // Transform month name string into month number } else { // eslint-disable-next-line monthNo = this.filters.month_options.filter((d) => d.value === this.filters.month_selected)[0].num; } // If user is in southern hemisphere and New Horizons is selected as game, // shift month by half a year if (this.hemisphereString() === 's') { monthNo = this.shiftMonth(monthNo); } return monthNo; }, getNextMonthNo() { const monthNo = this.getMonthNo(); // End of year, return January if (monthNo === 12) { return 1; } // Otherwise just month + 1 return monthNo + 1; }, shiftMonth(m) { // NOTE duplicate exists in Availability.vue // Shifts month number to southern hemisphere return m === 6 ? 12 : (m + 6) % 12; }, critterButtonClick(event) { // Use same loading spinner trick as in getData() this.loading = true; // Change shown critter section based on button clicked this.filters.critter_selection = event.currentTarget.id; // Short timeout while rendering, then hide spinner setTimeout(() => { this.loading = false; }, 100); }, }, created() { this.getData(); }, mounted() { // Set col_count based on width on startup this.col_count = this.calculateColCount(window.innerWidth); // Front-end switches to two columns when size is <= 990 pixels, // we check the width and check if col_count variable changed, // if this is the case we reorder the data to the new amount of columns window.addEventListener('resize', () => { this.new_col_count = this.calculateColCount(window.innerWidth); if (this.new_col_count !== this.col_count) { this.col_count = this.new_col_count; this.sortAndReorderData(); } }); }, }; </script>
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; use kartik\tabs\TabsX; use kartik\file\FileInput; use mihaildev\elfinder\ElFinder; use mihaildev\ckeditor\CKEditor; use dosamigos\datepicker\DatePicker; use yii\helpers\ArrayHelper; use backend\models\MenuSub; /* @var $this yii\web\View */ /* @var $model backend\models\Pages */ /* @var $form yii\widgets\ActiveForm */ ?> <div style="background-color: white; padding: 20px; border-radius: 10px 10px 0 0; border-top: 5px solid rgb(183 202 205);"> <?php $form = ActiveForm::begin(); ?> <? $content1 = $form->field($model, 'name_uz')->textInput(['maxlength' => true]). $form->field($model, 'content_uz')->widget(CKEditor::className(),[ 'editorOptions' => ElFinder::ckeditorOptions('elfinder', []), ]); ?> <? $content2 = $form->field($model, 'name_ru')->textInput(['maxlength' => true]). $form->field($model, 'content_ru')->widget(CKEditor::className(),[ 'editorOptions' => ElFinder::ckeditorOptions('elfinder', []), ]); ?> <? $content3 = $form->field($model, 'name_en')->textInput(['maxlength' => true]). $form->field($model, 'content_en')->widget(CKEditor::className(),[ 'editorOptions' => ElFinder::ckeditorOptions('elfinder', []), ]); ?> <? $items = [ [ 'label'=>'<i class="fa fa-home"></i> Uzbek', 'content'=>$content1, ], [ 'label'=>'<i class="fa fa-user"></i> Russian', 'content'=>$content2, ], [ 'label'=>'<i class="fa fa-user"></i> English', 'content'=>$content3, ], ]; ?> <? echo TabsX::widget([ 'items'=>$items, 'position'=>TabsX::POS_ABOVE, 'encodeLabels'=>false ]); ?> <value><b>Date</b></value> <?= DatePicker::widget([ 'model' => $model, 'attribute' => 'date', 'template' => '{addon}{input}', 'clientOptions' => [ 'autoclose' => true, 'format' => 'dd-M-yyyy' ] ]);?> <?= $form->field($model, 'views')->textInput() ?> <?= $form->field($model, 'page_menu_sub_id')->dropDownList( ArrayHelper::map(MenuSub::find()->all(), 'id', 'name_uz'), [ 'prompt' => "Menu Subni tanlang", ]); ?> <? if ($model->img == null) { echo $form->field($model, 'img')->widget(FileInput::classname(), [ 'options' => ['accept' => 'image/*'], ]); }else{ ?> <img src="../../frontend/web/arguments/dr_sl_img/<?=$model->img; ?>" width='50%'> <? } ?> <div class="form-group"> <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?> </div> <?php ActiveForm::end(); ?> </div>
using System.Collections; using System.Runtime.InteropServices; using Microsoft.AspNetCore.Mvc; namespace Kinopoisk.Controllers; [ApiController] [Route("moviesInfos")] public class MovieInfoController : ControllerBase { private readonly IMovieInfoService movieInfoService; public MovieInfoController(IMovieInfoService mS) { movieInfoService = mS; } [HttpGet] public async Task<ActionResult<List<GetMovieDTO>>> Index( [FromQuery(Name = "search")] string searchString = "", [FromQuery(Name = "page")] int? page = null) { switch (searchString) { case "": return Ok(await movieInfoService.GetMovieInfos()); default: return Ok(await movieInfoService.Search(searchString, page)); } } [HttpGet("filter")] public async Task<ActionResult<GetMovieDTO>> Filter([FromQuery] FilterParameters filterParameters) => Ok(await movieInfoService.Filter(filterParameters)); [HttpGet("tops")] public async Task<ActionResult<GetMovieDTO>> Filter([FromQuery] TopType type, [FromQuery(Name = "page")] int? page = null) => Ok(await movieInfoService.GetTop(type, page)); [HttpGet("{name}")] public async Task<ActionResult<GetMovieDTO>> Get(string name) => Ok(await movieInfoService.GetMovieInfo(name)); [HttpGet("{name}/staff")] public async Task<ActionResult<List<GetStaffDTO>>> GetStaff([FromRoute] string name) => Ok(await movieInfoService.GetStaff(name)); [HttpGet("{name}/actors")] public async Task<ActionResult<List<GetStaffDTO>>> GetActors([FromRoute] string name) => Ok(await movieInfoService.GetActors(name)); [HttpGet("{name}/directors")] public async Task<ActionResult<List<GetStaffDTO>>> GetDirectors([FromRoute] string name) => Ok(await movieInfoService.GetDirectors(name)); [HttpPost("create")] public async Task<ActionResult<GetMovieDTO>> Create(CreateUpdateMovieInfoDTO createMovieInfoDTO) => Ok(await movieInfoService.CreateMovieInfo(createMovieInfoDTO)); [HttpPost("create-with-id")] public async Task<ActionResult<GetMovieInfoDTO>> CreateWithKinopoiskId([FromBody] int id) => Ok(await movieInfoService.CreateWithKinopoiskID(id)); [HttpPatch("{name}/edit")] public async Task<ActionResult<GetMovieDTO>> Patch(string name, CreateUpdateMovieInfoDTO createUpdateMovieInfoDTO) => Ok(await movieInfoService.UpdateMovieInfo(createUpdateMovieInfoDTO)); }
DROP TRIGGER IF EXISTS trg_check_end_date ON booking; CREATE OR REPLACE FUNCTION check_end_date() RETURNS TRIGGER AS $$ BEGIN IF NEW.end_date <= NEW.start_date THEN RAISE EXCEPTION 'End date must be after start date'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; CREATE TRIGGER trg_check_end_date BEFORE INSERT OR UPDATE ON booking FOR EACH ROW EXECUTE FUNCTION check_end_date(); CREATE OR REPLACE FUNCTION ensure_one_manager_per_hotel() RETURNS TRIGGER AS $$ BEGIN -- Check if the hotel already has a manager IF EXISTS ( SELECT 1 FROM manages WHERE hotel_ID = NEW.hotel_ID ) THEN RAISE EXCEPTION 'This hotel already has a manager.'; END IF; RETURN NEW; END; $$ LANGUAGE plpgsql; DROP TRIGGER IF EXISTS trigger_ensure_one_manager ON manages; CREATE TRIGGER trigger_ensure_one_manager BEFORE INSERT OR UPDATE ON manages FOR EACH ROW EXECUTE FUNCTION ensure_one_manager_per_hotel(); -- Create or replace the trigger DROP TRIGGER IF EXISTS update_num_rooms_trigger ON room; CREATE OR REPLACE FUNCTION update_num_rooms() RETURNS TRIGGER AS $$ BEGIN IF TG_OP = 'INSERT' THEN -- Increment num_rooms when a room is inserted UPDATE hotel SET num_rooms = num_rooms + 1 WHERE hotel_ID = NEW.hotel_ID; ELSIF TG_OP = 'DELETE' THEN -- Decrement num_rooms when a room is deleted UPDATE hotel SET num_rooms = num_rooms - 1 WHERE hotel_ID = OLD.hotel_ID; END IF; RETURN NULL; END; $$ LANGUAGE plpgsql; -- Attach the trigger to the hotel_rooms table CREATE OR REPLACE TRIGGER update_num_rooms_trigger AFTER INSERT OR DELETE ON room FOR EACH ROW EXECUTE FUNCTION update_num_rooms();
import React, { useEffect, useState } from "react"; import api from "../../api/axios"; import useAuthContext from "../../context/AuthContext"; import Slider from "../../components/Slider"; import { Link } from "react-router-dom"; import Loader from "../../components/Loader"; export default function Cart() { const { user } = useAuthContext(); const [loading, setLoading] = useState(false); const [products, setProducts] = useState([]); const [cartItems, setCartItems] = useState([]); const [quantity, setQuantity] = useState(1); const formatPrice = (price) => { if (price == null) return ""; return price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }; useEffect(() => { window.scrollTo(0, 0); setLoading(true); const storedCartItems = localStorage.getItem("cartItems"); const fetchCartItems = async () => { const response = await api.get("/api/products"); const responseData = response.data; setProducts(responseData.data); if (user) { // User is logged in if (storedCartItems) { // There are items in the local storage const cartItems = JSON.parse(storedCartItems); try { // Send API request to add cart items to the database await api.post("/api/cart", cartItems); // Clear the local storage setLoading(false); localStorage.removeItem("cartItems"); } catch (error) { setLoading(false); console.log(error); } } // Fetch the cart items from the database try { const response1 = await api.get("/api/cart"); setCartItems(response1.data.cart); setLoading(false); } catch (error) { setLoading(false); console.log(error); } } else { setLoading(false); // User is not logged in setCartItems(JSON.parse(storedCartItems)); } }; fetchCartItems(); }, [user]); const handleRemoveFromCart = (product_id, cartId) => { if (user) { const token = localStorage.getItem("token"); api .delete(`http://localhost:8000/api/cart/${cartId}`, { headers: { Authorization: `Bearer ${token}` }, }) .then((response) => { // Remove the deleted cart item from your React state or props const updatedCartItems = cartItems.filter( (item) => item.id !== cartId ); setCartItems(updatedCartItems); }) .catch((error) => { console.log(error); }); } else { const updatedCartItems = cartItems.filter( (item) => item.product_id !== product_id ); setCartItems(updatedCartItems); localStorage.setItem("cartItems", JSON.stringify(updatedCartItems)); } }; const getTotalPrice = () => { return cartItems.reduce((total, item) => { const price = item.product?.price ?? item.price; const quantity = item.product?.quantity ?? item.quantity; return total + price * quantity; }, 0); }; const getTotalQuantity = () => { return cartItems.reduce((total, item) => { const quantity = Number(item.quantity); return total + quantity; }, 0); }; if (loading) { return ( <div className=" flex h-screen justify-center items-center z-40"> <Loader /> </div> ); } const handleDecrement = (cardID) => { setCartItems((cart) => cart.map((item) => cardID === item.id ? { ...item, quantity: item.quantity - (item.quantity > 1 ? 1 : 0) } : item ) ); updateQuantity(cardID, "dec"); }; const handleIncrement = (cardID) => { setCartItems((cart) => cart.map((item) => cardID === item.id ? { ...item, quantity: item.quantity + (item.quantity < 10 ? 1 : 0) } : item ) ); updateQuantity(cardID, "inc"); }; function updateQuantity(cardID, scope) { if (user) { const token = localStorage.getItem("token"); api.put(`http://localhost:8000/api/cart/${cardID}/${scope}`, { headers: { Authorization: `Bearer ${token}` }, }); } else { } } return ( <> <div className=" lg:h-24 h-28"></div> <div className=" lg:container container-fluid"> <div> <h1 className=" font-extrabold">YOUR BAG</h1> </div> <div> {!cartItems?.length ? ( <> <div className=" flex flex-col items-center justify-center h-96"> <p className=" font-semibold text-lg"> Oh No! Your Bag is Empty! </p> <div> <Link to={"/"}>Shop Now!</Link> </div> </div> </> ) : ( <> <div className=" flex flex-col lg:flex-row"> <div className="flex-auto"> <p className=" m-0 text-2xl"> Total &#40;{getTotalQuantity()} items&#41; <span className=" font-bold "> ₱{formatPrice(getTotalPrice())} </span> </p> <p className=" italic"> Items in your bag are not reserved — check out now to make them yours. </p> {cartItems.map((cartItem) => ( <div key={cartItem.id} className="border-2 border-solid border-black mb-3" > <div className="flex"> <div className=" h-full w-1/3 "> <img className="w-full" src={`http://localhost:8000${ cartItem.product?.image ?? cartItem.image }`} alt={cartItem.product?.name ?? cartItem.name} /> </div> <div className="w-2/3 py-3 px-2 flex flex-col justify-between"> <div className="flex justify-between"> <div className="w-4/5"> <p className="text-lg font-semibold truncate m-0"> {cartItem.product?.name ?? cartItem.name} </p> <p className=" m-0"> ₱ {formatPrice( (cartItem.product?.price ?? cartItem.price) * (cartItem.product?.quantity ?? cartItem.quantity) )} </p> </div> <div className="1/5 text-right"> <button onClick={() => handleRemoveFromCart( cartItem.product_id, cartItem.id ) } className="lg:py-2 lg:px-4 px-2 py-1 font-semibold border-2 border-solid border-black hover:border-red-500 hover:bg-red-200 hover:text-red-500" > X </button> </div> </div> <div className=" flex items-center"> <p className=" mb-0 mr-2 font-semibold">Quantity</p> <button className="font-bold px-2 border-2 border-black" onClick={() => handleDecrement(cartItem.id)} > - </button> <input className="w-7 border-y-2 text-center border-black" type="number" value={ cartItem.product?.quantity ?? cartItem.quantity } disabled /> <button className="font-bold px-2 border-2 border-black" onClick={() => handleIncrement(cartItem.id)} > + </button> </div> </div> </div> </div> ))} </div> <div className="flex-auto lg:w-8/12 lg:px-3 lg:m-3"> <hr className="lg:hidden" /> <div className="sticky top-0 lg:pt-5"> <div className=" border-2 border-solid p-5 border-black"> <h2 className=" font-black">ORDER SUMMARY</h2> <div className=" flex justify-between"> <p>{getTotalQuantity()} items</p> <p>₱{formatPrice(getTotalPrice())}</p> </div> <div className=" flex justify-between"> <p>Delivery</p> <p>FREE</p> </div> <hr /> <div className=" flex justify-between"> <p className=" font-bold">Total price</p> <p className=" font-bold"> ₱{formatPrice(getTotalPrice())} </p> </div> <Link to={"/checkout"}> <button className="py-2 px-4 font-semibold text-white bg-black w-full"> Checkout → </button> </Link> </div> </div> </div> </div> </> )} <hr /> <div className="container"> <Slider link={"/product"} productData={products} title={"YOU MAY ALSO LIKE"} /> </div> </div> </div> </> ); }
import React, { useEffect, useState } from "react"; import { debounce } from "lodash"; const Debounce = () => { let timerId; const [inputEl, setInput] = useState("radhe"); const [inputEl2, setInput2] = useState("radhe2"); const makeAPICall = async () => { await fetch("https://jsonplaceholder.typicode.com/posts"); }; const onChangeInput = (event) => { clearTimeout(timerId); // We are executing only when there is a delay in event timerId = setTimeout(() => { setInput(event.target.value); makeAPICall(); console.log("State updated with value of", event.target.value); }, 500); }; // Executing the same using debounce function from lodash const onChangeInput2 = (event) => { const setInputDebounce = debounce(() => { setInput2(event.target.value); }, 1000); setInputDebounce(); }; return ( <div> <input type="text" className="form-control" onChange={onChangeInput} placeholder="Verify deBouncing using custom function" /> <h1>{inputEl}</h1> <input type="text" className="form-control" onChange={onChangeInput2} placeholder="Verify deBouncing using lodash function" /> <h1>{inputEl2}</h1> </div> ); }; export default Debounce;
import csv import datetime import logging import time from io import StringIO import numpy as np import pandas as pd from django.db.models import Q from django.utils import timezone from iotile_cloud.utils.gid import IOTileBlockSlug, IOTileDeviceSlug, IOTileStreamSlug, IOTileVariableSlug from apps.physicaldevice.models import Device from apps.property.models import GenericProperty from apps.sqsworker.exceptions import WorkerActionHardError from apps.stream.models import StreamId, StreamVariable from apps.streamdata.utils import get_stream_output_mdo from apps.utils.aws.redshift import get_ts_from_redshift from apps.utils.data_helpers.manager import DataManager from apps.utils.gid.convert import get_device_and_block_by_did, gid2int from apps.utils.iotile.variable import SYSTEM_VID from apps.utils.objects.utils import get_device_or_block from apps.utils.timezone_utils import convert_to_utc, str_to_dt_utc from ..base import ReportGenerator _TRIP_SUMMARY_VID = gid2int(SYSTEM_VID['TRIP_SUMMARY']) logger = logging.getLogger(__name__) def dt_format(dt): return dt.strftime('%Y-%m-%d %H:%M:%S') class TripSummary(object): """ Represents a Trip Summary """ _lid_map = { '5020': 's_events', '5021': 's_pressure', '5022': 's_humidity', '5023': 's_temp', SYSTEM_VID['TRIP_SUMMARY']: 's_summary', # Trip Report Summary } s_temp = None s_humidity = None s_pressure = None s_events = None s_start = None s_summary = None device_or_block_slug = '' # project_slug = '' ts_start = None ts_end = None data = None no_start_trip = False data_was_masked = False device_or_block = None def __init__(self, device_or_block): self.device_or_block = device_or_block try: self.device_or_block_slug = IOTileDeviceSlug(device_or_block.slug) except ValueError: self.device_or_block_slug = IOTileBlockSlug(device_or_block.slug) # self.project_slug = IOTileProjectSlug(p_slug) self.s_temp = None self.s_humidity = None self.s_pressure = None self.s_events = None self.s_start = None self.s_end = None self.s_summary = None self.ts_start = None self.ts_end = None self.data = None self.no_start_trip = False self.data_was_masked = False @classmethod def compute_time_active(cls, df, condition_met_count): """ This hard-to-name function is used to take a dataframe, and a condition_met_count representing the number of rows that meet some condition (e.g. df['value'] < 17).sum()) The function uses the first and last index to determine the time delta between and with it, the average time delta between values. It then computes the amount of time where the given condition was met. This is used to compute, for example, the amount of time that a POD was under 17C or above 30C :param df: DataFrame with a 'value' column and timestamp index :param condition_met_count: Number of rows that meet condition :return: string representation of the datetime.timedelta """ first_value = df.iloc[0].name last_value = df.iloc[-1].name delta = last_value - first_value count = df['value'].count() if int(condition_met_count): time_in_condition = delta / int(count - 1) * int(condition_met_count) result = str(time_in_condition.to_pytimedelta()) else: result = '0:00:00' return result def _get_stream_slug_for(self, variable): stream_slug = self.device_or_block.get_stream_slug_for(variable) return str(stream_slug) def _q_by_stream(self, stream_slug): """Create QuerySet filter with datetime ranges if available""" q = Q(stream_slug=stream_slug) if self.ts_start: q = q & Q(timestamp__gte=get_ts_from_redshift(self.ts_start)) if self.ts_end: q = q & Q(timestamp__lte=get_ts_from_redshift(self.ts_end)) logger.info('--> {}'.format(q)) return q def add_stream(self, lid, stream): if lid in self._lid_map: self.__setattr__(self._lid_map[lid], stream) def _get_time_dataframe(self, stream): qs = DataManager.df_filter_qs_using_q('data', self._q_by_stream(stream.slug)) df = qs.to_dataframe(['value', ], index='timestamp') mdo = get_stream_output_mdo(stream) if mdo: try: df['value'] = df['value'].apply(lambda x: mdo.compute(x)) except Exception as e: raise WorkerActionHardError(e) return df def _compute_basic_env_stats(self, name, df, units): stats = df.agg(['min', 'median', 'max']) if not stats.empty: return { 'Max {} ({})'.format(name, units): stats.loc['max'].values[0], 'Min {} ({})'.format(name, units): stats.loc['min'].values[0], 'Median {} ({})'.format(name, units): stats.loc['median'].values[0], } return {} def _compute_delta_v(self, x): terms = [x[term] for term in self._delta_v_terms] max_dv = max(*terms) min_dv = min(*terms) if max_dv > abs(min_dv): return max_dv return min_dv def _compute_event_data(self, event_qs, sg_config_consts): dt_index = pd.to_datetime([x.timestamp for x in event_qs]) extra_data = [x.extra_data for x in event_qs] assert 'max_g_col' in sg_config_consts assert 'max_dv_col' in sg_config_consts max_g_col = sg_config_consts['max_g_col'] max_dv_col = sg_config_consts['max_dv_col'] df = pd.DataFrame(extra_data, index=dt_index) # For Saver backwards compatibility, look for alternative labels if max_g_col not in list(df): max_g_col = 'max_peak' if 'max_g' not in list(df): data = { 'Max Peak (G)': 'Error: peak or max_g not found' } return data data = { 'First event at (UTC)': dt_format(df.iloc[0].name), 'Last event at (UTC)': dt_format(df.iloc[-1].name), 'Event Count': int(df[max_g_col].count()) } if self.no_start_trip: # For backwards compatibility, if there was no start trip, use first/last event for duration data['Duration (Days)'] = (df.iloc[-1].name - df.iloc[0].name) / datetime.timedelta(days=1) if max_g_col in list(df): max_g_idx = df[max_g_col].idxmax() if 'delta_v_terms' in sg_config_consts: for col in sg_config_consts['delta_v_terms']: if col in list(df): df[col] = df[col].apply(lambda x: x * sg_config_consts['delta_v_multiplier']) if max_dv_col not in list(df): self._delta_v_terms = sg_config_consts['delta_v_terms'] df[max_dv_col] = df.apply(self._compute_delta_v, axis=1) max_dv_idx = df[max_dv_col].idxmax() data.update({ 'TimeStamp(MaxPeak) (UTC)': dt_format(max_g_idx), 'Max Peak (G)': df[max_g_col].loc[max_g_idx].max(), 'DeltaV at Max Peak (in/s)': df[max_dv_col].loc[max_g_idx].max(), 'TimeStamp(MaxDeltaV) (UTC)': dt_format(max_dv_idx), 'MaxDeltaV (in/s)': df[max_dv_col].loc[max_dv_idx].max(), 'Peak at MaxDeltaV (G)': df[max_g_col].loc[max_dv_idx].max(), }) return data def _get_mask_event(self): """ :return: Dict object if a mask has been set: {'start': '<datetime_str>', 'end': '<datetime_str>'}. None if not set """ mask_stream_slug = self._get_stream_slug_for(SYSTEM_VID['DEVICE_DATA_MASK']) if mask_stream_slug: event = DataManager.filter_qs('event', stream_slug=mask_stream_slug).last() if event: assert ('start' in event.extra_data) assert ('end' in event.extra_data) return event.extra_data return None def calculate_trip_date_ranges(self): """ Figure out the trip Start and End times: 1. Check for TripStart and Trip End 2. Check if TripMask is set. If so, use that (if within trip start/end :return: Nothing """ start_trip_stream_slug = self._get_stream_slug_for(SYSTEM_VID['TRIP_START']) end_trip_stream_slug = self._get_stream_slug_for(SYSTEM_VID['TRIP_END']) qs = DataManager.filter_qs( 'data', stream_slug__in=[start_trip_stream_slug, end_trip_stream_slug] ).order_by('streamer_local_id', 'timestamp') self.ts_start = self.ts_end = None for d in qs: if d.stream_slug == start_trip_stream_slug: self.ts_start = convert_to_utc(d.timestamp) if d.stream_slug == end_trip_stream_slug: self.ts_end = convert_to_utc(d.timestamp) # Check if the device has a data mask. If so, use instead mask_data = self._get_mask_event() if mask_data: if mask_data['start']: self.ts_start = str_to_dt_utc(mask_data['start']) self.data_was_masked = True if mask_data['end']: self.ts_end = str_to_dt_utc(mask_data['end']) self.data_was_masked = True if not self.ts_start: logger.info('No TripStart data found. Looking for oldest data') # For backwards compatibility, if no TRIP_START, look for the oldest Event or Data first_event = DataManager.filter_qs_using_q( 'event', self._q_by_stream(self.s_events.slug) ).exclude(extra_data__has_key='error').first() first_temp = DataManager.filter_qs_using_q( 'data', self._q_by_stream(self.s_temp.slug) ).first() if first_event and first_temp: first = first_temp if convert_to_utc(first_temp.timestamp) < convert_to_utc(first_event.timestamp) else first_event else: first = first_temp or first_event if first: self.ts_start = convert_to_utc(first.timestamp) self.no_start_trip = True else: logger.warning('No TRIP_START or events found') return if self.ts_end and self.ts_end < self.ts_start: # This is the end of a previous trip. Ignore self.ts_end = None logger.info('Trip Date Range: {} to {}'.format( self.ts_start, self.ts_end if self.ts_end else 'NOW' )) def _send_debug_info(self): # Print debug information msg = 'No Events Found: {}'.format(self.device_or_block_slug) q = self._q_by_stream(self.s_events.slug) msg += '\n --> q= {}'.format(str(q)) event_qs = DataManager.filter_qs_using_q( 'event', self._q_by_stream(self.s_events.slug) ).exclude(extra_data__has_key='error') msg += '\n--> events.filter(q): {}'.format(event_qs.count()) q = Q(stream_slug=self.s_events.slug) event_qs = DataManager.filter_qs_using_q( 'event', q ) msg += '\n--> events.filter(slug): {}'.format(event_qs.count()) if self.ts_start: msg += '\n--> start (UTC): {}'.format(convert_to_utc(self.ts_start)) else: msg += '\n--> start (UTC): Not Available' if self.ts_end: msg += '\n--> end (UTC): {}'.format(convert_to_utc(self.ts_end)) else: msg += '\n--> end (UTC): Not Available' logger.info(msg) # Let customer know def calculate_trip_summary_data(self, sg_config): data = { 'Device': str(self.device_or_block_slug), } if self.s_events: q = self._q_by_stream(self.s_events.slug) logger.info('_q_by_stream({}) = {}'.format(self.s_events.slug, q)) event_qs = DataManager.filter_qs_using_q( 'event', self._q_by_stream(self.s_events.slug) ).exclude(extra_data__has_key='error') logger.info('--> Trip {} events: {}'.format(self.device_or_block_slug, event_qs.count())) else: event_qs = DataManager.none_qs('event') data['error'] = 'Error: s_events is None' logger.warning(data['error']) if self.ts_start and not self.no_start_trip: data['START (UTC)'] = dt_format(self.ts_start) if self.ts_end: data['END (UTC)'] = dt_format(self.ts_end) data['Duration (Days)'] = (self.ts_end - self.ts_start) / datetime.timedelta(days=1) else: data['START (UTC)'] = 'Not Available' data['END (UTC)'] = 'Not Available' assert 'START (UTC)' in data if self.data_was_masked: data['Notes'] = 'Trip Start and/or End was overwritten by a set device data mask' if event_qs.count(): if 'consts' in sg_config: sg_config_consts = sg_config['consts'] data.update(self._compute_event_data(event_qs, sg_config_consts)) else: logger.warning('No events found') data['Max Peak (G)'] = 'Error: No events found' data['Event Count'] = 0 self._send_debug_info() if self.s_temp: df = self._get_time_dataframe(self.s_temp) if not df.empty: # Compute time delta so we can show how much time the device was # above or below the required range data.update(self._compute_basic_env_stats('Temp', df, 'C')) data['Below 17C'] = TripSummary.compute_time_active(df=df, condition_met_count=(df['value'] < 17).sum()) data['Above 30C'] = TripSummary.compute_time_active(df=df, condition_met_count=(df['value'] > 30).sum()) else: logger.warning('No Temp stream found') if self.s_humidity: df = self._get_time_dataframe(self.s_humidity) if not df.empty: data.update(self._compute_basic_env_stats('Humidity', df, '% RH')) else: logger.warning('No Humidity stream found') if self.s_pressure: df = self._get_time_dataframe(self.s_pressure) if not df.empty: data.update(self._compute_basic_env_stats('Pressure', df, 'Mbar')) else: logger.warning('No Pressure stream found') self.data = data class EndOfTripReportGenerator(ReportGenerator): _trips = {} def __init__(self, msgs, rpt, start, end, sources=None): super(EndOfTripReportGenerator, self).__init__(msgs, rpt, start, end, sources) self._trips = {} if sources: for source in sources: obj = get_device_or_block(source) if not obj: continue logger.info('creating new TripSummary for device {}'.format(obj.slug)) self._trips[obj.slug] = TripSummary(obj) def _email_template(self): return 'report/end_of_trip' def _create_summary_event(self, trip): if not trip.s_summary: # Need to create Summary Stream if isinstance(trip.device_or_block, Device): device = trip.device_or_block project = device.project block = None else: block = trip.device_or_block device = trip.device_or_block.device project=None trip.s_summary = StreamId.objects.create_stream( project=project, device=device, block=block, variable=None, data_type='E0', var_lid=_TRIP_SUMMARY_VID, var_name='Trip Summary', created_by=device.claimed_by, data_label='Trip Summary: {}'.format(trip.device_or_block_slug) ) summary = DataManager.build( 'event', stream_slug=trip.s_summary.slug, timestamp=timezone.now(), device_timestamp=int(time.time()), streamer_local_id=1, extras={ 'extra_data': trip.data, }, ) summary.deduce_slugs_from_stream_id() try: logger.info('Uploading Trip Summary: {}'.format(trip.s_summary.slug)) DataManager.save('event', summary) except Exception as e: WorkerActionHardError(e) def _get_obj_properties(self, device_or_block): if device_or_block: return GenericProperty.objects.object_properties_qs(obj=device_or_block, is_system=False) return None def _send_summary_email(self, trip, device_or_block, sg_config): template = self._email_template() def_properties = [] property_keys = [] data_table = [] attachment = None if 'summary_keys' in sg_config: def_properties = sg_config['summary_keys'] if 'property_keys' in sg_config: property_keys = sg_config['property_keys'] if len(def_properties) == 0: data_table.append({ 'name': 'Error', 'value': 'Bad SG configuration. Missing summary_keys' }) try: device_model = str(device_or_block.template) except Exception: device_model = 'Unk' property_table = [ { 'name': 'Device', 'value': str(trip.device_or_block_slug) }, { 'name': 'Model', 'value': device_model } ] property_map = {} property_qs = self._get_obj_properties(device_or_block) if property_qs: for property in property_qs: property_map[property.name] = property.value for key in property_keys: if key in property_map: row = { 'name': key, 'value': property_map[key] } property_table.append(row) for key in def_properties: if key in trip.data: row = { 'name': key, 'value': trip.data[key] } if isinstance(trip.data[key], np.float64) or isinstance(trip.data[key], float): row['value'] = '{0:.2f}'.format(trip.data[key]) data_table.append(row) if 'Notes' in trip.data: row = { 'name': 'Notes', 'value': trip.data['Notes'] } data_table.append(row) # Create CSV to attach rows = property_table + [{'name': '', 'value': ''}] + data_table if len(rows): csvfile = StringIO() fieldnames = list(rows[0].keys()) writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for row in rows: writer.writerow(row) attachment = { 'filename': '{}.summary.csv'.format(str(trip.device_or_block_slug)), 'content': csvfile.getvalue(), 'mimetype': 'text/csv' } ctx = { 'device_url': device_or_block.get_webapp_url(), 'property_table': property_table, 'data_table': data_table, 'user': str(self._rpt.created_by) if self._rpt else None, 'org': str(self._rpt.org) if self._rpt else None } self._send_email(template, ctx, attachment) def add_streams_for_qs(self, qs): for stream in qs: stream_slug = IOTileStreamSlug(stream.slug) parts = stream_slug.get_parts() assert 'variable' in parts assert 'device' in parts assert 'project' in parts variable = IOTileVariableSlug(parts['variable']) lid = variable.formatted_local_id() device_or_block_slug = parts['device'] # TODO: Fix correctly # HACK: Try to recover data block block_id, device_id = get_device_and_block_by_did(device_or_block_slug) if block_id > 0: # This is a block device_gid = device_or_block_slug.split('--')[1] device_or_block_slug = '--'.join(['b', device_gid]) if device_or_block_slug not in self._trips: logger.info('creating new TripSummary for device {}'.format(device_or_block_slug)) device_or_block = get_device_or_block(device_or_block_slug) if not device_or_block: continue self._trips[device_or_block_slug] = TripSummary(device_or_block) logger.info('Adding stream {} ({}) for trip summary for {}'.format(stream, lid, device_or_block_slug)) self._trips[device_or_block_slug].add_stream(lid, stream) def process_config(self): # No configuration available yet pass def generate_user_report(self): """ Generate an End of Trip Summary Report :return: Nothing """ for slug in self._trips.keys(): trip = self._trips[slug] device_or_block = trip.device_or_block sg = device_or_block.sg if 'analysis' in sg.ui_extra and 'trip_summary' in sg.ui_extra['analysis']: sg_config = sg.ui_extra['analysis']['trip_summary'] else: sg_config = {} if not trip.s_events: # We have no Events. It is possible the database is not up to date # Reschedule to try again later if self.reschedule_callback: logger.warning('No events. Rescheduling') self.reschedule_callback(900) trip.calculate_trip_date_ranges() if trip.ts_start: # If no start date, there is no data to compute trip.calculate_trip_summary_data(sg_config) if trip.data: # Create a TRIP_SUMMARY StreamEventData record self._create_summary_event(trip) # Send email with summary self._send_summary_email(trip, device_or_block, sg_config) else: logger.info('Cannot create Trip Summary Report: No START signal found')
{% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Pinocchio's</title> <!--Bootstrap--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!--Fonts--> <link href="https://fonts.googleapis.com/css?family=Montserrat+Alternates:400,700,900&display=swap" rel="stylesheet"> <!--Icons--> <script src="https://kit.fontawesome.com/d448299394.js"></script> <!--Styles--> <link rel="stylesheet" type="text/css" href="{% static './css/styles.css' %}"> </head> <body> {% block navbar %} <nav class="navbar navbar-expand-lg fixed-top navigation-nav"> <div class="container nav-content"> {% if user.is_authenticated %} <!-- user login --> <a class="navbar-brand" href="#">{{ user.username }} </a> {% else %} <a class="navbar-brand" href="#">Pinocchio's</a> {% endif %} <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"> <i class="fas fa-bars"></i> </span> </button> <div class="collapse navbar-collapse justify-content-end " id="navbarNavDropdown"> <article class="navbar-nav"> <a href="{% url 'homepage' %}" class="nav-item nav-link">Home</a> <a href="{% url 'menu' %}" class="nav-item nav-link">Menu</a> {% if user.is_authenticated %} <a href="{% url 'order_view' %}" class="nav-item nav-link">Orders</a> <a href="{% url 'logout' %}" class="nav-item nav-link">Logout</a> <a href="{% url 'cart_view' %}" class="nav-item nav-link cart-item"><i class="fas fa-shopping-cart"></i></a> {% else %} <a href="{% url 'login' %}" class="nav-item nav-link">Login</a> {% endif %} </article> </div> </div> </nav> {% endblock navbar %} <!--JS for bootstrap--> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> {% block content %} {% endblock content %} {% block js %} {% endblock js %} </body> </html>
import 'package:expense_tracker/utils/style.dart'; import 'package:flutter/material.dart'; import '../componets/heading.dart'; import '../componets/homeProfile.dart'; import '../componets/recent_transaction.dart'; import '../componets/total_card.dart'; import '../controller/db_helper.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { DbHelper dbhelper = DbHelper(); int totalBalance = 0; int totalIncome = 0; int totalExpense = 0; getTotalBalance(List<Map<dynamic, dynamic>> entireData) { totalBalance = 0; totalIncome = 0; totalExpense = 0; for (var value in entireData) { if (value['type'] == 'Income') { totalBalance += (value['amount'] as int); totalIncome += (value['amount'] as int); } else if (value['type'] == 'Expense') { totalBalance -= (value['amount'] as int); totalExpense += (value['amount'] as int); } } } DateTime? currentBackPressTime; @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () async { if (currentBackPressTime == null || DateTime.now().difference(currentBackPressTime!) > const Duration(seconds: 2)) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( padding: EdgeInsets.all(12.0), shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0))), content: Text('Press back again to exit'), ), ); currentBackPressTime = DateTime.now(); return false; // Do not exit the app } else { // Exit the app when back button is pressed twice within 2 seconds return true; } }, child: SafeArea( child: FutureBuilder<List<Map<dynamic, dynamic>>>( future: dbhelper.fetch(), builder: (context, snapshot) { if (snapshot.hasError) { return const Center(child: Text('Unexpected Error!')); } if (snapshot.hasData) { getTotalBalance(snapshot.data!); return ListView( physics: const BouncingScrollPhysics(), children: [ const HomeProfile(), TotalBalance(totalBalance: totalBalance, totalIncome: totalIncome, totalExpense: totalExpense), const Heading(headng: "Recent Transaction"), RecentTransaction(data: snapshot.data!), SizedBox(height: large) ], ); } else { return const Center(child: Text('Unexpected Error!(else)')); } }, ), ), ); } }
import Joi from "joi"; import User from "../models/user"; import CustomErrorHandler from "../services/CustomErrorHandler"; import bcrypt from 'bcrypt'; import JwtService from '../services/JwtService'; import { REFRESH_SECRET } from '../config'; import refreshToken from "../models/refreshToken"; const loginController = { async login(req,res,next){ //validation const loginSchema = Joi.object({ email: Joi.string().email().required(), password: Joi.string().pattern(new RegExp('^[a-zA-Z0-9]{3,30}$')).required(), }) const { error } = loginSchema.validate(req.body); if(error){ return next(error); } try{ const user = await User.findOne({ email: req.body.email }); if(!user){ return next(CustomErrorHandler.wrongCredentials()); } //compare password const match = await bcrypt.compare(req.body.password, user.password); if(!match){ return next(CustomErrorHandler.wrongCredentials()); } // generate token const access_token = JwtService.sign({_id: user._id, role: user.role }); const refresh_token = JwtService.sign({_id: user._id, role: user.role }, '1y', REFRESH_SECRET); await refreshToken.create({token: refresh_token}); res.json({access_token, refresh_token }); } catch(err){ return next(err); } } } export default loginController;
# Sensor Interfacing ## Objectives Upon completion of this laboratory session, the student should be able to: 1. Understand the concept of I2C in STM32 ARM MCU. 2. Design and develop a program to demonstrate the I2C functionality. ## Equipment 1. Personal computer running Microsoft Windows® 10 (and above) with a minimum of 8GB RAM running STM32CubeIDE, Digilent Waveform Generator and Arduino IDE. 2. STM32 Nucleo development board. 3. I2C Accelerometer. ## Safety 1. Ensure hands are dry when using the equipment or touching the switches. 2. Do not use plugs with cracks, signs of overheating (e.g., discoloration, charring, or deformation) or loosen parts. 3. Stop using the equipment if abnormal operating conditions occur, such as being too noisy or having signs of overheating. 4. Keep all equipment organized and easily reachable without bending or stretching. ## Theory Besides the microcontroller, other devices, such as sensors, switches, displays, keypads, and motors, are important components in an Embedded System. The microcontroller is basically used as the brain or intelligent processing unit to interface with those devices to perform some automation task. A sensor is a device that is used to detect and respond to events or changes in its environment and then provide a corresponding output. A sensor is a type of transducer. An electric sensor converts a physical parameter, for example, temperature, pressure, light, humidity, speed, tilt, moisture, sound, seismic, and many more into an electric signal that can be processed by the microcontroller. The output signal can be an analog voltage changing based on the input physical quantity, or the output can be a digital number or provided in serial communication such as I2C or SPI. Therefore, the datasheet of the sensor is the important reference before interfacing the sensor to the microcontroller. ## Procedures 1. Refer to the datasheet of a sensor and connect it to the STM32 development board accordingly. 2. Create a new project in STM32Cube IDE and develop the program to read the sensor value and display it through the serial port. 3. Compile and debug the project to observe the output. --- *This project is part of the course BENR3523 Embedded System Universiti Teknikal Malaysia Melaka.*
--- obsidianUIMode: preview cssclasses: json5e-monster tags: - compendium/src/5e/vgm - monster/cr/2 - monster/environment/mountain - monster/environment/underdark - monster/size/medium - monster/type/humanoid/orc aliases: ["Orc Claw of Luthic"] --- # Orc Claw of Luthic *Source: Volo's Guide to Monsters p. 183* ![](https://raw.githubusercontent.com/5etools-mirror-2/5etools-img/main/bestiary/VGM/Orc%20Claw%20of%20Luthic.webp#right) To the common folk of the world, an orc is an orc. They know that any one of these savages can tear an ordinary person to pieces, so no further distinction is necessary. Orcs know better. Different groups of orcs exist within a tribe, the actions of each dictated by the deity they pay homage to. To complement the various kinds of warriors that spill forth to ravage the countryside, each tribe has members that remain deep inside the lair, seldom if ever seeing what lies outside the darkness of their den. In addition, orcs have special relationships with two creatures that are sometimes found in their company: the aurochs, a great bull that serves as a mount for warriors that revere Bahgtru, and the tanarukk, a demon-orc crossbreed that is so depraved and destructive that even orcs seek to kill it. The aurochs is described in appendix A. The tanarukk is described below. ## Orc Claw of Luthic Luthic is Gruumsh's wife and the paragon of maternity to all orcs. She is the Cave Mother, a fierce dweller in the darkness who raises new broods of orcs to be vicious and strong. Her symbol is the cave bear, and orc females raise such bears alongside orc whelps. Females particularly attracted to Luthic grow long nails and lacquer them, learning to use these claws as weapons much as Luthic uses her own. Orc females devoted to Luthic are in charge of fortifying and maintaining an orc stronghold. They help to guarantee the survival of the tribe, and most are skilled in the healing arts. The most powerful among Luthic's disciples are the claws of Luthic, which can use the Cave Mother's magic to heal, protect, and curse. ## Statblock ```ad-statblock title: Orc Claw of Luthic ![](https://raw.githubusercontent.com/5etools-mirror-2/5etools-img/main/bestiary/tokens/VGM/Orc%20Claw%20of%20Luthic.webp#token) *Medium humanoid (orc), Chaotic Evil* - **Armor Class** 14 ([hide armor](/3-Mechanics/CLI/items/hide-armor.md)) - **Hit Points** 45 (`6d8 + 18`) - **Speed** 30 ft. |STR|DEX|CON|INT|WIS|CHA| |:---:|:---:|:---:|:---:|:---:|:---:| |14 (+2)|15 (+2)|16 (+3)|10 (+0)|15 (+2)|11 (+0)| - **Proficiency Bonus** +2 - **Saving Throws** ⏤ - **Skills** Intimidation +2, Medicine +4, Survival +4 - **Senses** darkvision 60 ft., passive Perception 12 - **Languages** Common, Orc - **Challenge** 2 ## Traits ***Aggressive.*** As a bonus action, the orc can move up to its speed toward a hostile creature that it can see. ***Spellcasting.*** The orc is a 5th-level spellcaster. Its spellcasting ability is Wisdom (spell save DC 12, +4 to hit with spell attacks). The orc has the following cleric spells prepared: **Cantrips (at will)**: [guidance](/3-Mechanics/CLI/spells/guidance.md), [mending](/3-Mechanics/CLI/spells/mending.md), [resistance](/3-Mechanics/CLI/spells/resistance.md), [thaumaturgy](/3-Mechanics/CLI/spells/thaumaturgy.md) **1st level (4 slots)**: [bane](/3-Mechanics/CLI/spells/bane.md), [cure wounds](/3-Mechanics/CLI/spells/cure-wounds.md), [guiding bolt](/3-Mechanics/CLI/spells/guiding-bolt.md) **2nd level (3 slots)**: [augury](/3-Mechanics/CLI/spells/augury.md), [warding bond](/3-Mechanics/CLI/spells/warding-bond.md) **3rd level (2 slots)**: [bestow curse](/3-Mechanics/CLI/spells/bestow-curse.md), [create food and water](/3-Mechanics/CLI/spells/create-food-and-water.md) ## Actions ***Multiattack.*** The orc makes two claw attacks, or four claw attacks if it has fewer than half of its hit points remaining. ***Claw.*** *Melee Weapon Attack:* +4 to hit, reach 5 ft., one target. *Hit:* 6 (`1d8 + 2`) slashing damage. ``` ^statblock ## Environment underdark, mountain
import React, { useState, useEffect } from "react"; import ContactForm from "./ContactForm"; import fireDb from "../fiebase"; const Contacts = () => { const contactsCollation = fireDb.collection("/contacts"); const [contacts, setContacts] = useState(); const [currentId, setCurrentId] = useState(""); useEffect(() => { fireDb.collection("/contacts").onSnapshot((snapshot) => { const data = snapshot.docs.map((doc) => { return { ...doc.data(), id: doc.id }; }); setContacts(data); console.log(data); }); }, []); const addOrEdit = (contact) => { if (!currentId) { contactsCollation.add(contact); setCurrentId(""); } else { contactsCollation.doc(currentId).update(contact); setCurrentId(""); } }; const onDelete = (key) => { contactsCollation.doc(key).delete(); }; return ( <div> <div className="jumbotron jumbotron-fluid"> <div className="container"> <h1 className="display-4 text-center">Contact Register</h1> </div> </div> <div className="row"> <div className="col-md-5"> <ContactForm {...{ currentId, addOrEdit, contacts }} /> </div> <div className="col-md-7"> <table className="table table-borderless table-responsive table-stripped"> <thead className="thead-light"> <tr> <th>Full Name</th> <th>Mobile</th> <th>Email</th> <th>Action</th> </tr> </thead> {contacts && ( <tbody> {contacts.map((contact) => ( <tr key={contact.id}> <td>{contact.fullname}</td> <td>{contact.mobile}</td> <td>{contact.email}</td> <td> <a href="#" className="btn text-primary" onClick={() => setCurrentId(contact.id)} > <i className="fa fa-pencil"></i> </a> <a href="#" className="btn text-danger" onClick={() => onDelete(contact.id)} > <i className="fa fa-trash"></i> </a> </td> </tr> ))} </tbody> )} </table> </div> </div> </div> ); }; export default Contacts;
# PinKey ビルドガイド ## 1. はじめに 本書は自作キーボードであるPinKeyのビルドガイドです。キーボードとして利用可能になるまでの手順を初心者向けに丁寧に記載したつもりですが、不明な個所などある場合は適時検索するなどして補ってください。 申し訳ないのですがPinKey固有でない一般のご質問にはお答えできません。各自お調べください。 ## 2. 準備 ### 2.1 内容物確認 PinKeyは本体となる基板とキースイッチ固定用のトッププレート、底面を支えるボトムプレートのセットです。キーボードとして使用するにはその他必要な部品を別途調達いただく必要があります。 |品目|数量| |---|---| |PinKey 基板|1| |PinKey トッププレート|1| |PinKey ボトムプレート|1| |六角スペーサー|6(予備1)| |M2ネジ|11(予備1)| ![PinKey内容物](../image/PinKey_contents.jpg) ### 2.2 別途用意が必要な部品 下記部品は国内外の自作キーボード専門店や電子部品販売店などから別途調達してください。 |品目|数量|備考| |---|---|---| |Waveshare RP2040-Zero|1|[Waveshare製RP2040-Zero 純正品](https://www.waveshare.com/wiki/RP2040-Zero)をお勧めします。互換品もありますが動作するかはわかりません| |ピンヘッダ(高さ2mm、ピッチ2.54mm)|23ピン分(9x2、5x1)|RP2040-Zeroにピンヘッダが同梱されていない場合は別途用意してください| |1N4148W ダイオード (SOD123)|64|[Diodes Incorporated社製1N4148W](https://www.diodes.com/part/view/1N4148W)もしくはその互換品| |MX互換キースイッチ|64|[Cherry MX](https://www.cherrymx.de/en/dev.html)もしくはその互換品| |MX互換スイッチソケット|64|[Kailh PCB Socket CPG151101S11](https://www.kailhswitch.com/mechanical-keyboard-switches/box-switches/mechanical-keyboard-switches-kailh-pcb-socket.html)もしくはその互換品| |MX互換キーキャップ|-|[Cherry MX](https://www.cherrymx.de/en/dev.html)もしくはその互換品| |2uサイズPCBマウント型スタビライザー|2|幅の広いキーの押し下げを安定させる部品です。左ShiftキーとEnterキーに用います| |2u or 3uサイズPCBマウント型スタビライザー|1|幅の広いキーの押し下げを安定させる部品です。スペースキーに用います。3uスタビライザーと3uスペースキーの組み合わせが推奨です。2uスタビライザーと2.75uスペースキーの組み合わせでも代用可能ですが、隙間が空きます| ### 必要なキーキャップとサイズ 必要なキーキャップとそのサイズは下図の通りです。キーのサイズは正方形のキーの幅を「1u」と呼称します。2uであれば1uの2倍の幅のキーであることを示します。幅は0.25u刻みで様々なサイズがあります。 ![レイアウト](../image/PinKey_layout_size.png) このうち、標準的なANSI/ISOレイアウト向けのキーキャップセットに含まれていないか、オプション扱いであることが多い注意すべきキーは次の通りです。オプションを購入するか、同じサイズの別の印字のキーキャップで代替してください。 |行|サイズ|初期レイアウトの対応キー名| |---|---|---| |R2|1.5u|Backspaceキー| |R4|2u|左Shiftキー| |R4|1u|右Shiftキー| |R5|1.25u|無変換、変換、Fn| |R5|3u|スペースキー| スペースキーは3uが推奨ですが、3uのスペースキーを用意できない場合は2.75uや2.25uでも代用できます(ただし左右に隙間が空きます)。 ### 2.3 道具 |品目|数量|備考| |---|---|---| |はんだごて、はんだ|1|スイッチソケットのはんだ付けに用います。はんだごては調温機能付きのものを、はんだは鉛入りのものを推奨します| |ニッパー|1|ピンヘッダの余り部分を切断するのに使います| |ピンセット|1|スイッチソケットのはんだ付けの際にあると便利です| |拡大鏡|1|ダイオードの向きを確認する際にあると便利です| |テスター|1|ダイオードの導通を確認する際にあると便利です| |ねじ回し(プラス)|1|基板とボトムプレートを固定する際に用います| ## 3. ファームウェアの書き込み まず初めにRP2040-Zeroの動作確認と、ファームウェアの書き込みを行います。 ## 3.1 ファームウェアのダウンロード 下記からファームウェアをダウンロードしてください。 https://github.com/ymkn/PinKey/blob/main/firmware/QMK/ymkn_PinKey_vial.uf2 画面右上の方に下矢印のダウンロードボタンがあるので、そこを押すことでダウンロードできます。 ![PinKeyファームウェアダウンロード](../image/PinKey_firmwaredownload.png) ## 3.2 RP2040-Zeroの動作確認とファームウェアの書き込み お使いのコンピュータのUSB 2.0以上に対応したUSBコネクタと、RP2040-Zeroを接続してください。RP2040-Zeroが正常であれば、`RPI-RP2`というドライブがマウントされると思います。 もしマウントされない場合は、USBケーブルを接続した状態のままRP2040-ZeroのBOOTボタンを押しながらRESETボタンを押してください。これで`RPI-RP2`というドライブがマウントされれば問題ありません。もしこれでも何も起きない場合、RP2040-Zeroが壊れている可能性があります。。。 この`RPI-RP2`というドライブに、先ほどダウンロードしたファームウェアをコピーしてください。しばらくすると`RPI-RP2`ドライブが消えますので、これでファームウェアの書き込みは完了です。USBケーブルを抜いてください。 何らかの理由でやり直したい場合は、RP2040-ZeroのBOOTボタンを押しながらRESETボタンを押すことで、再び`RPI-RP2`というドライブをマウントすることができます。 ## 4. 組み立て ### 4.1 はんだ付け ![PinKey裏面](../image/PinKey_soldering.jpg) #### 4.1.1 ダイオードのはんだ付け ダイオードは基板の裏面(ICチップ等が実装されている面)に取り付けます。コの字状のガイドが白線でキー数分印刷されていますので、そのすべてにダイオードをはんだ付けします。 ダイオードは向きが決まっています。ダイオード上の目印が印刷されている側(カソード側)が向かって右側になるようにしてください。 まず片足だけをはんだ付けした状態でテスターを使い導通確認をすると安心です。 すべてのダイオードが基板に密着しており、両端とも漏れなくはんだ付けされているか確認してください。基板から浮いていたり、はんだ付けができていないとキースイッチの動作不良の原因になります。 #### 4.1.2 スイッチソケットのはんだ付け スイッチソケットもダイオードと同様に基板の裏面に取り付けます。L字状のガイドが白線でキー数分印刷されていますので、そのすべてにスイッチソケットをはんだ付けします。 すべてのスイッチソケットが基板に密着しており、ソケット両端とも漏れなくはんだ付けされているか確認してください。基板から浮いていたり、はんだ付けができていないとキースイッチの動作不良の原因になります。 #### 4.1.3 RP2040-Zeroのはんだ付け RP2040-Zeroも同様に基板の裏面に取り付けます。基板左上のスルーホールにピンヘッダを差し込み、その上にRP2040-Zeroを差し込んだ形になるようにはんだ付けをしてください。ピンヘッダは足の長い方が基板表面側にに出るようにします。 > [!CAUTION] > RP2040-Zeroの向きを間違えないようにしてください。写真の通り、裏面から見た時に、ボタンが見えるような向きである必要があります。表裏を間違えると動作しませんのでご注意ください。 ![PinKey RP2040-Zero](../image/PinKKey_RP2040-Zero.jpg) 基板スルーホールにピンヘッダとRP2040-Zeroを通した状態で、RP2040-Zero側を先にはんだ付けしてから、基板表面側をはんだ付けすると曲がらずにやりやすいかと思います。 最後に、基板表側に飛び出した足はニッパーで短くカットしてください。ピンヘッダの長さによっては、トッププレートと干渉してしまうためです。 ### 4.2 スタビライザーの取り付け スタビライザーは基板の表面(ロゴが印刷されている面)に取り付けます。 左ShiftキーとEnterキーに2uサイズを、スペースキーに3uサイズ(2.75u以下のキーを代用する場合は2uサイズ)のスタビライザーを取り付けます。取り付け方はスタビライザーごとに異なりますが、一般には大きい穴の方にツメを引っかけ、小さい穴の方にプッシュピンを差し込む、もしくはネジ留めを行います。 ![PinKey表面](../image/PinKey_front.jpg) ### 4.3 ボトムプレートの取り付け スイッチとトッププレートを取り付ける前に、基盤にボトムプレートを取り付けます。 M2と書かれたネジ穴が5ヶ所ありますので、基板表面からネジを差し込み、裏側から六角スペーサーを取り付けてください。 ![PinKeyネジ穴](../image/PinKey_back.jpg) 六角スペーサの上にネジ穴が合うようにボトムプレートを乗せ、ボトムプレート側からネジ留めしてください。 ### 4.4 スイッチとトッププレートの取り付け キースイッチはトッププレートを通して基板のソケットに差し込みます。すべてのキースイッチを一度に取り付けてしまうと基板に差し込むのが大変なので、まずトッププレートの四隅にキースイッチを取り付けて基板に差し込み、その後残りのスイッチを取り付けていくのがおすすめです。 ### 4.5 キーキャップの取り付け 全てのスイッチにキーキャップを取り付けたら完成です! ## 5. 使用 ### 5.1 動作確認 コンピュータにPinKeyを接続し、文字が入力できることを確認してください。 ### 5.2 キーマップのカスタマイズ 本キーボードは[Vial](https://get.vial.today/)というキーマップ変更ツールに対応しています。Vialの詳しい使いかたはVialのドキュメントや世間の情報を参考にしてください。 何らかの理由で既定のレイアウトが必要な場合は下記からVial用のレイアウトデータをダウンロードできます。 https://github.com/ymkn/PinKey/blob/main/firmware/QMK/default_layout_jp.vil > [!WARNING] > RP2040-Zeroをリセット(BOOTボタンを押しながらRESETボタンを押す)すると、既定のレイアウトに戻ってしまいます。 ### 5.3 漢字キー(日本語入力On/Off用のキー)について 本キーボードの初期レイアウトに漢字キーの割り当てはありません。その代わり、スペースキーの左側のキーをImeOffキーに、右側のキーをImeOnキーに割り当てています。ImeOnキーとImeOffキーはWindows 10 1903以降でMicrosoft IMEを使用している場合に利用可能です。漢字キーが必要な場合はレイアウトをカスタマイズして任意のキーに割り当ててください。 参考: [キーボード日本 \- ImeOn / ImeOff の実装 \| Microsoft Learn](https://learn.microsoft.com/ja-jp/windows-hardware/design/component-guidelines/keyboard-japan-ime) ## 6. その他 ### 6.1 ブートモードの入り方 RP2040のブートモードに入るには、左上のキー(Escキー)を押しながらUSBケーブルを接続します。 もしくは、RP2040-ZeroのBOOTボタンを押しながらRESETボタンを押します。 ### 6.2 ソースコード/設計データのありか 本リポジトリ内で公開しています。MITライセンスです。 https://github.com/ymkn/PinKey
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require("@angular/core"); var product_service_1 = require("./product.service"); var ProductListComponent = (function () { //create local variable for the constructor for calling => _productService with type: ProductService. //works with public and protected vars as well //usually a constructor is implicitly created. explicit constructors are used when injecting services //used for initialization function ProductListComponent(_productService) { this._productService = _productService; this.pageTitle = 'Product List'; this.imageWidth = 50; this.imageMargin = 2; this.showImage = false; } ProductListComponent.prototype.toggleImage = function () { this.showImage = !this.showImage; }; ProductListComponent.prototype.ngOnInit = function () { var _this = this; //subscribe to observable this._productService.getProducts() .subscribe(function (products) { return _this.products = products; }, function (error) { return _this.errorMessage = error; }); }; ProductListComponent.prototype.onRatingClicked = function (message) { this.pageTitle = 'Product List: ' + message; }; return ProductListComponent; }()); ProductListComponent = __decorate([ core_1.Component({ //use this to allow for component relative file paths moduleId: module.id, //relative to index.html location templateUrl: 'product-list.component.html', styleUrls: ['product-list.component.css'] }), __metadata("design:paramtypes", [product_service_1.ProductService]) ], ProductListComponent); exports.ProductListComponent = ProductListComponent; //# sourceMappingURL=product-list.component.js.map
<script setup> import { mdiBallotOutline, mdiTableBorder } from "@mdi/js"; import SectionMain from "@/components/SectionMain.vue"; import CardBox from "@/components/CardBox.vue"; import FormCheckRadioGroup from "@/components/FormCheckRadioGroup.vue"; import FormField from "@/components/FormField.vue"; import FormControl from "@/components/FormControl.vue"; import BaseButton from "@/components/BaseButton.vue"; import BaseButtons from "@/components/BaseButtons.vue"; import LayoutAuthenticated from "@/layouts/LayoutAuthenticated.vue"; import SectionTitleLineWithButton from "@/components/SectionTitleLineWithButton.vue"; import NotificationBarInCard from "@/components/NotificationBarInCard.vue"; import { useForm, Head, usePage } from '@inertiajs/vue3' import FormValidationErrors from "@/components/FormValidationErrors.vue"; import { computed } from "vue"; const props = defineProps({ proyecto: { type: Object, required: true, }, incidencia: { type: Object, default: { id: null, sprint_id: '', titulo: '', descripcion: '', epica_id: '', puntaje: '', responsable_id: '', }, }, epicas: { type: Array, default: [], }, usuariosInvitados: { type: Array, default: [], }, }); const epicas = [ { value: null, label: 'Sin asignar' }, ].concat( props.epicas.map(epica => ( { value: epica.id, label: epica.nombre } )) ); const usuariosInvitados = [ { value: null, label: 'Sin asignar' }, { value: usePage().props.auth.user.id, label: usePage().props.auth.user.name + ' - TU' } ].concat( props.usuariosInvitados.map(usuario => ( { value: usuario.id, label: usuario.name } )) ); const form = useForm({ id: props.incidencia.id, sprint_id: props.incidencia.sprint_id, titulo: props.incidencia.titulo, descripcion: props.incidencia.descripcion, epica_id: props.incidencia.epica_id, puntaje: props.incidencia.puntaje, responsable_id: props.incidencia.responsable_id, }); let seguir_creando = false; const crearIncidencia = () => { form.post(route('incidencias.store', props.proyecto.id), { onSuccess: () => { usePage().props.succesForm = true; form.reset(); if(! seguir_creando){ location.href = route('incidencias.index', props.proyecto.id); } }, onError: () => { usePage().props.succesForm = false; }, }); } const editarIncidencia = () => { form.put(route('incidencias.update', [props.proyecto.id, props.incidencia?.id ?? '__id']), { onSuccess: () => { usePage().props.succesForm = true; }, onError: () => { usePage().props.succesForm = false; }, }); } const submit = () => { if(! props.incidencia?.id){ crearIncidencia(); }else{ editarIncidencia(); } }; const reset = () => { if(! props.incidencia?.id){ form.reset(); } usePage().props.succesForm = false; }; </script> <template> <LayoutAuthenticated> <Head title="Incidencias" /> <SectionMain> <SectionTitleLineWithButton :icon="mdiBallotOutline" :title="! props.incidencia?.id ? 'Crear incidencia' : 'Actualizar incidencia'" main> <BaseButton :href="route('incidencias.index', props.proyecto.id)" :icon="mdiTableBorder" label="Listado de incidencias" color="contrast" rounded-full small /> </SectionTitleLineWithButton> <CardBox is-form @submit.prevent="submit"> <FormValidationErrors :formulario="form"/> <FormControl v-if="props.incidencia?.id" v-model="props.incidencia.id" type="hidden" /> <NotificationBarInCard v-if="usePage().props.succesForm" color="success"> {{ ! props.incidencia?.id ? 'Incidencia creada correctamente' : 'Incidencia actualizada correctamente' }} </NotificationBarInCard> <FormField label="Titulo de la incidencia"> <FormControl v-model="form.titulo" type="text" placeholder="Ej: Creacion del login" /> </FormField> <FormField label="Epica"> <FormControl v-model="form.epica_id" :options="epicas" /> </FormField> <FormField label="Responsable"> <FormControl v-model="form.responsable_id" :options="usuariosInvitados" /> </FormField> <FormField label="Descripcion del incidencia"> <FormControl v-model="form.descripcion" type="textarea" placeholder="Ej: Se desea que la aplicacion pueda loguearse por correo y contraseña" /> </FormField> <template #footer> <div class="flex gap-4"> <BaseButtons> <BaseButton type="submit" color="info" :label="! props.incidencia?.id ? 'Crear' : 'Actualizar'"/> <BaseButton type="button" color="info" outline label="Limpiar" @click="reset"/> </BaseButtons> <FormCheckRadioGroup v-if="! props.incidencia?.id" v-model="seguir_creando" type="switch" :options="{ true: 'Seguir creando incidencias' }" /> </div> </template> </CardBox> </SectionMain> </LayoutAuthenticated> </template>
import {LightningElement, wire} from 'lwc'; import getFunctions from '@salesforce/apex/PlaygroundController.getCustomFunctions'; import {operators} from './operators'; import {data} from './functions'; export default class FunctionLibrary extends LightningElement { _categories; functionWithOpenDocumentation; isDocumentationPinned = false; @wire(getFunctions) handleGetPricingVariablesWire({data, error}) { if (data && data.length) { this._categories = data .filter((category) => category.functions.length) .map((category) => { return { category: category.name, values: category.functions.map((fn) => { return { name: fn.name, autoCompleteValue: fn.autoCompleteValue, icon: category.icon, description: fn.description, examples: fn.example ? [fn.example] : undefined }; }) }; }); } else if (error) { console.error(error.body.message); this._categories = undefined; } } get availableFormulaFunctionsAndOperators() { let availableFunctionsAndOperators = [...operators, ...data]; if (this._categories?.length) { availableFunctionsAndOperators = [...availableFunctionsAndOperators, ...this._categories]; } return availableFunctionsAndOperators; } handleDisplayFunctionDocumentation(event) { const functionName = event.target.dataset.item; if (!functionName) { return; } this.functionWithOpenDocumentation = this.getFunctionByName(functionName); } handlePinFunctionDocumentation(event) { event.preventDefault(); this.isDocumentationPinned = !this.isDocumentationPinned; } handleCloseDocumentation(event) { event.preventDefault(); this.isDocumentationPinned = false; this.functionWithOpenDocumentation = undefined; } handleHideFunctionDocumentation() { if (this.isDocumentationPinned) { return; } this.functionWithOpenDocumentation = undefined; } handleFunctionClick(event) { event.preventDefault(); const functionName = event.target.dataset.item; if (!functionName) { return; } const functionToAppend = this.getFunctionByName(functionName); const clickEvent = new CustomEvent('selected', { detail: functionToAppend.autoCompleteValue }); this.dispatchEvent(clickEvent); } getFunctionByName(functionName) { const availableFunctions = this.availableFormulaFunctionsAndOperators.map((item) => item.values).flat(); return availableFunctions.find(item => item.name === functionName); } }
import React, { FC } from 'react' import { ControlBarButton, useLocalVideo, useSelectVideoInputDevice, useVideoInputs } from 'amazon-chime-sdk-component-library-react' import { DeviceConfig } from 'amazon-chime-sdk-component-library-react/lib/types' import { PopOverItemProps } from 'amazon-chime-sdk-component-library-react/lib/components/ui/PopOver/PopOverItem' import { CameraOffIcon } from 'assets/CameraOffIcon' import { CameraOnIcon } from 'assets/CameraOnIcon' import { isOptionActive } from './helpers' import { CustomControlBarButton } from './Styled' import { useTheme } from '@material-ui/core' interface CustomVideoInputControlProps { label?: string } const videoInputConfig: DeviceConfig = { additionalDevices: true } export const CustomVideoInputControl: FC<CustomVideoInputControlProps> = ({ label = 'Video' }) => { const { devices, selectedDevice } = useVideoInputs(videoInputConfig) const { isVideoEnabled, toggleVideo } = useLocalVideo() const selectDevice = useSelectVideoInputDevice() const theme = useTheme() const dropdownOptions: PopOverItemProps[] = devices.map((device: any) => ({ children: <span>{device.label}</span>, checked: isOptionActive(selectedDevice, device.deviceId), onClick: () => selectDevice(device.deviceId) })) return ( <CustomControlBarButton icon={ isVideoEnabled ? <CameraOnIcon width={16} height={16} /> : <CameraOffIcon width={16} height={16} fill='white' /> } onClick={toggleVideo} label={label} popOver={dropdownOptions} backgroundColor={isVideoEnabled ? 'white' : theme.palette.error.main} /> ) }
use Test::More; use Types::Standard qw/Str Object/; { package One::Two::Three; use Moo; with 'MooX::VariantAttribute::Role'; } my $obj = One::Two::Three->new(); my $when = { 'one' => { run => sub { return "$_[1] - cold, cold, cold inside" }, }, 'two' => { run => sub { return "$_[1] - don't look at me that way"; }, }, 'three' => { run => sub { return "$_[1] - how hard will i fall if I live a double life"; }, }, }; is $obj->_find_from_given('one', Str, $when, 'test'), 'one', 'okay we have one'; is $obj->_find_from_given('two', Str, $when, 'test'), 'two', 'okay we have two'; is $obj->_find_from_given('three', Str, $when, 'test'), 'three', 'okay we have three'; { package Random::Parser::Two; use Moo; sub parse_string { return 'parse string'; } sub parse_from_file { return 'parse file'; } } my $when2 = { 'Test::Parser::One' => { alias => { parse_string => 'parse', # parse_file exists }, }, 'Random::Parser::Two' => { alias => { # parse_string exists parse_file => 'parse_from_file', }, }, 'Another::Parser::Three' => { alias => { parse_string => 'meth_one', parse_file => 'meth_two', }, }, }; my $parser = Random::Parser::Two->new(); my $parsers = $obj->_find_from_given($parser, Object, $when2); is( $parsers, 'Random::Parser::Two', 'alias' ); my $when3 = { 'SCALAR' => { run => sub { return 'I am a SCALAR' }, }, 'HASH' => { run => sub { return 'I am a HASH' }, }, 'ARRAY' => { run => sub { return 'I am a ARRAY' }, }, }; my $scalar = $obj->_find_from_given('HEY', sub { ref $_[1] or ref \$_[1] }, $when3, 'test'); is( $scalar, 'SCALAR', 'ref SCALAR' ); my $hash = $obj->_find_from_given({ one => 'two' }, sub { ref $_[1] }, $when3, 'test'); is( $hash, 'HASH', 'ref HASH' ); my $array = $obj->_find_from_given([qw/one two/], sub { ref $_[1] }, $when3, 'test'); is( $array, 'ARRAY', 'ref ARRAY' ); done_testing();
import React, { ChangeEvent, useEffect, useRef, useState } from 'react'; import { useDispatch } from 'react-redux'; import { toast } from 'react-toastify'; import 'react-toastify/dist/ReactToastify.css'; import { CountString, TypeGuitar, TypeGuitarTranslation } from '../../const'; import { useAppSelector } from '../../hooks/main'; import { addFilterStringCount, addFilterType, changeFilterPriceEnd, changeFilterPriceStart, deleteFilterStringCount, deleteFilterType, resetFilter } from '../../store/state-filter-and-sort/state-filter-and-sort'; import { getMaxPrice, getMinPrice } from '../../utils'; function CatalogFilter(): JSX.Element { const {catalogFilteredCards} = useAppSelector(({GUITARS}) => GUITARS); const {catalogCards} = useAppSelector(({GUITARS}) => GUITARS); const {filtersState} = useAppSelector(({FILTERS_AND_SORT}) => FILTERS_AND_SORT); const [isDisabled4, setIsDisabled4] = useState(false); const [isDisabled6, setIsDisabled6] = useState(false); const [isDisabled7, setIsDisabled7] = useState(false); const [isDisabled12, setIsDisabled12] = useState(false); const [isDisabledAcoustic, setIsDisabledAcoustic] = useState(false); const [isDisabledElectric, setIsDisabledElectric] = useState(false); const [isDisabledUkulele, setIsDisabledUkulele] = useState(false); const dispatch = useDispatch(); const minPrice = getMinPrice((catalogFilteredCards) ? catalogFilteredCards : catalogCards); const maxPrice = getMaxPrice((catalogFilteredCards) ? catalogFilteredCards : catalogCards); const minPriceRef = useRef<HTMLInputElement | null>(null); const maxPriceRef = useRef<HTMLInputElement | null>(null); const placeholderMinPrice = (filtersState.priceStart !== 0) ? String(filtersState.priceStart) : String(minPrice); const placeholderMaxPrice = (filtersState.priceEnd !== 0) ? String(filtersState.priceEnd) : String(maxPrice); const handleFilterPriceStart = () => { if(minPriceRef.current !== null ) { const isValid = Number(minPriceRef.current.value) > 0; if (isValid) { if (Number(minPriceRef.current.value) <= minPrice) { minPriceRef.current.value = String(minPrice); } dispatch(changeFilterPriceStart(minPriceRef.current.value)); } else { toast('Ввведите положительное число'); minPriceRef.current.value = ''; } } }; const handleFilterPriceEnd = () => { if(maxPriceRef.current !== null) { const isValid = Number(maxPriceRef.current.value) > 0; if (isValid) { if(Number(maxPriceRef.current.value) >= maxPrice || Number(maxPriceRef.current.value) <= Number(minPriceRef.current?.value)) { maxPriceRef.current.value = String(maxPrice); } dispatch(changeFilterPriceEnd(maxPriceRef.current.value)); } else { toast('Ввведите положительное число'); maxPriceRef.current.value = ''; } } }; const resetIsDisabledCountString = () => { setIsDisabled4(false); setIsDisabled6(false); setIsDisabled7(false); setIsDisabled12(false); }; const resetIsDisabledTypeGuitar = () => { setIsDisabledAcoustic(false); setIsDisabledElectric(false); setIsDisabledUkulele(false); }; const handleChangeTypeGuitar = (evt: ChangeEvent<HTMLInputElement>) => { const typesGuitar = filtersState.typeGuitar; const typeParams = typesGuitar.find((item) => item === evt.target.value); if (typeParams) { dispatch(deleteFilterType(evt.target.value)); } else { dispatch(addFilterType(evt.target.value)); } }; useEffect(() => { if (filtersState.typeGuitar.length === 0) { resetIsDisabledCountString(); } else { setIsDisabled4(!filtersState.typeGuitar.find((item) => TypeGuitar.ukulele === item || TypeGuitar.electric === item)); setIsDisabled6(!filtersState.typeGuitar.find((item) => TypeGuitar.acoustic === item || TypeGuitar.electric === item)); setIsDisabled7(!filtersState.typeGuitar.find((item) => TypeGuitar.acoustic === item || TypeGuitar.electric === item)); setIsDisabled12(!filtersState.typeGuitar.find((item) => TypeGuitar.acoustic === item)); } }, [filtersState.typeGuitar]); useEffect(() => { if (filtersState.stringCount.length === 0) { resetIsDisabledTypeGuitar(); } else { setIsDisabledAcoustic(!filtersState.stringCount.find((item) => CountString.count6 === item || CountString.count7 === item || CountString.count12 === item)); setIsDisabledElectric(!filtersState.stringCount.find((item) => CountString.count4 === item || CountString.count6 === item || CountString.count7 === item)); setIsDisabledUkulele(!filtersState.stringCount.find((item) => CountString.count4 === item)); } }, [filtersState.stringCount]); const handleChangeCountString = (evt: ChangeEvent<HTMLInputElement>) => { const listCount = filtersState.stringCount; const countParams = listCount.find((item) => item === evt.target.value); if(countParams) { dispatch(deleteFilterStringCount(evt.target.value)); } else { dispatch(addFilterStringCount(evt.target.value)); } }; const handleReset = () => { resetIsDisabledCountString(); dispatch(resetFilter()); }; return ( <form className="catalog-filter"> <h2 className="title title--bigger catalog-filter__title">Фильтр</h2> <fieldset className="catalog-filter__block"> <legend className="catalog-filter__block-title">Цена, ₽</legend> <div className="catalog-filter__price-range"> <div className="form-input"> <label className="visually-hidden">Минимальная цена</label> <input type="number" placeholder={placeholderMinPrice} id="priceMin" name="от" ref={minPriceRef} onBlur={handleFilterPriceStart}/> </div> <div className="form-input"> <label className="visually-hidden">Максимальная цена</label> <input type="number" placeholder={placeholderMaxPrice} id="priceMax" name="до" ref={maxPriceRef} onBlur={handleFilterPriceEnd}/> </div> </div> </fieldset> <fieldset className="catalog-filter__block"> <legend className="catalog-filter__block-title">Тип гитар</legend> { Object.keys(TypeGuitar).map((item) => ( <div className="form-checkbox catalog-filter__block-item" key={item}> <input className="visually-hidden" type="checkbox" id={item} name={item} value={item} onChange={handleChangeTypeGuitar} checked={filtersState.typeGuitar.includes(item)} disabled={(isDisabledAcoustic&&(item==='acoustic')) || (isDisabledElectric&&(item==='electric')) || (isDisabledUkulele&&(item==='ukulele'))} /> <label htmlFor={item}>{TypeGuitarTranslation.get(item)}</label> </div>)) } </fieldset> <fieldset className="catalog-filter__block"> <legend className="catalog-filter__block-title">Количество струн</legend> <div className="form-checkbox catalog-filter__block-item"> <input className="visually-hidden" type="checkbox" id="4-strings" value={'4'} name="4-strings" disabled={isDisabled4} checked={filtersState.stringCount.includes('4')} onChange={handleChangeCountString} /> <label htmlFor="4-strings">4</label> </div> <div className="form-checkbox catalog-filter__block-item"> <input className="visually-hidden" type="checkbox" id="6-strings" value={'6'} name="6-strings" disabled={isDisabled6} checked={filtersState.stringCount.includes('6')} onChange={handleChangeCountString} /> <label htmlFor="6-strings">6</label> </div> <div className="form-checkbox catalog-filter__block-item"> <input className="visually-hidden" type="checkbox" id="7-strings" value={'7'} name="7-strings" disabled={isDisabled7} checked={filtersState.stringCount.includes('7')} onChange={handleChangeCountString} /> <label htmlFor="7-strings">7</label> </div> <div className="form-checkbox catalog-filter__block-item"> <input className="visually-hidden" type="checkbox" id="12-strings" value={'12'} name="12-strings" disabled={isDisabled12} checked={filtersState.stringCount.includes('12')} onChange={handleChangeCountString} /> <label htmlFor="12-strings">12</label> </div> </fieldset> <button className="catalog-filter__reset-btn button button--black-border button--medium" type="reset" onClick={handleReset} >Очистить</button> </form> ); } export default React.memo(CatalogFilter);
import React from 'react'; import Link from "next/link"; import ContainerAside from './styles'; import { AiOutlineHome } from "react-icons/ai"; import { GiArchiveRegister } from "react-icons/gi"; import { GiExpense } from "react-icons/gi"; import { GrConfigure } from "react-icons/gr"; import { FiLogOut } from "react-icons/fi"; import { useMenu } from "../../providers/MenuProvider"; import { useAuth } from "../../providers/AuthProvider"; const Aside = () => { const handleLink = (link) => navigate(link); const { left, closeMenu } = useMenu(); const { handleLogout } = useAuth(); return ( <> <ContainerAside left={left}> <ul> <li onClick={() => { closeMenu() }}> <AiOutlineHome /> <Link href="/home">Home</Link> </li> <li onClick={() => { closeMenu() }}> <GiArchiveRegister /> <Link href="/register-expenses">Cadastrar Despesas</Link> </li> <li onClick={() => { closeMenu() }}> <GiExpense /> <Link href="/expenses">Consultar Despesas</Link> </li> <li onClick={() => { closeMenu() }}> <GrConfigure /> <Link href="/config-user">Configurações do Usuário</Link> </li> <li onClick={() => handleLogout()}> <FiLogOut /> Logout </li> </ul> </ContainerAside> </> ); } export default Aside;
package ir.co.sadad.cheque.service; import ir.co.sadad.cheque.domain.dto.*; import ir.co.sadad.cheque.domain.entity.*; import ir.co.sadad.cheque.domain.enums.StakeholderRole; import ir.co.sadad.cheque.management.SsoClientTokenManager; import ir.co.sadad.cheque.repository.*; import ir.co.sadad.cheque.service.mapper.DashboardMapper; import ir.co.sadad.cheque.web.rest.errors.ChakadClientException; import ir.co.sadad.cheque.web.rest.errors.GeneralException; import ir.co.sadad.cheque.web.rest.external.ChakadClient; import ir.co.sadad.cheque.web.rest.external.dto.response.chakad.CartableDto; import ir.co.sadad.cheque.web.rest.external.dto.response.chakad.ChakadResponseDto; import ir.co.sadad.cheque.web.rest.external.dto.response.chakad.TransferChequeResponseDto; import lombok.SneakyThrows; import lombok.extern.log4j.Log4j2; import org.apache.commons.lang.ObjectUtils; import org.hibernate.exception.ConstraintViolationException; import org.springframework.dao.DataIntegrityViolationException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.zalando.problem.Status; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * {@inheritDoc} */ @Service @Log4j2 public class DashboardServiceImpl extends DashboardService { private final DashboardMapper mapper; private final ChakadClient chakadClient; private final ChequeReasonsRepository reasonsRepository; private final ChequeIssueRepository chequeIssueRepository; private final ChequeSignerRepository chequeSignerRepository; private final ChequeStakeholderRepository stakeholderRepository; private final ChequeTransferRepository chequeTransferRepository; public DashboardServiceImpl(HttpServletRequest httpServletRequest, SsoClientTokenManager ssoClientTokenManager, DashboardMapper mapper, ChakadClient chakadClient, ChequeReasonsRepository reasonsRepository, ChequeIssueRepository chequeIssueRepository, ChequeSignerRepository chequeSignerRepository, ChequeStakeholderRepository stakeholderRepository, ChequeTransferRepository chequeTransferRepository) { super(httpServletRequest, ssoClientTokenManager); this.mapper = mapper; this.chakadClient = chakadClient; this.reasonsRepository = reasonsRepository; this.chequeIssueRepository = chequeIssueRepository; this.chequeSignerRepository = chequeSignerRepository; this.stakeholderRepository = stakeholderRepository; this.chequeTransferRepository = chequeTransferRepository; } /** * {@inheritDoc} * * @param authToken token of password credential * @param cartableRequest request * @return */ @Override @SneakyThrows public ChakadCartableResponseDto cartable(String authToken, ChakadCartableRequestDto cartableRequest) { ChakadResponseDto<CartableDto> cartable = chakadClient.cartable(getToken(), getUserAgent(), mapper.toCartableReqDto(cartableRequest)); if (SUCCESS_CHAKAD_CODE.equals(cartable.getMassageCode())) return mapper.toCartableResDto(cartable.getData()); else throw new ChakadClientException(cartable.getMessage()); } /** * {@inheritDoc} * * @param reasonType type of reason * @return */ @Override public List<ReasonResponseDto> getReasons(String reasonType) { if (reasonType.isBlank()) { throw new GeneralException(); } return mapper.toReasonResponse(reasonsRepository.findByReasonType(reasonType)); } @Override @Transactional(propagation = Propagation.NESTED) @SneakyThrows public ResponseEntity<HttpStatus> issue(String authToken, ChakadIssueRequestDto issueRequestDto) { if (issueRequestDto.getCheque().getReason() == null && Long.parseLong(issueRequestDto.getCheque().getAmount()) >= AMOUNT_FOR_REASON) throw new ChakadClientException("chakad.error.reason.is.mandatory", Status.BAD_REQUEST); ChequeReason reason = checkReason(issueRequestDto.getCheque().getReason()); ChakadResponseDto<ObjectUtils.Null> issueResponse = chakadClient.issueCheque(getToken(), getUserAgent(), mapper.toIssueCheque(issueRequestDto)); if (!SUCCESS_CHAKAD_CODE.equals(issueResponse.getMassageCode())) throw new ChakadClientException(issueResponse.getMessage()); try { ChequeIssue chequeIssue = mapper.toIssueEntity(issueRequestDto.getCheque()); chequeIssue.setChequeReason(reason); chequeIssueRepository.saveAndFlush(chequeIssue); saveSigners(issueRequestDto.getCheque().getSigners(), chequeIssue, null); saveStakeholders(issueRequestDto.getCheque().getSayadId(), issueRequestDto.getCheque().getReceivers(), issueRequestDto.getCheque().getGuarantors(), chequeIssue); return new ResponseEntity<>(HttpStatus.OK); } catch (DataIntegrityViolationException e) { throw new ChakadClientException("chakad.issue.database.constraint", Status.BAD_REQUEST); } } @Override @SneakyThrows public ResponseEntity<HttpStatus> transfer(String authToken, ChakadTransferRequestDto transferRequestDto) { //for checking amount of issue which related to transfer // if (transferRequestDto.getTransfer().getReason() == null) { // ChequeIssue relatedIssue = chequeIssueRepository. // findTopBySayadId(transferRequestDto.getTransfer().getSayadId()); // if (relatedIssue != null && Long.parseLong(relatedIssue.getAmount()) >= AMOUNT_FOR_REASON) // throw new ChakadClientException("chakad.error.reason.is.mandatory", Status.BAD_REQUEST); // } ChequeReason reason = checkReason(transferRequestDto.getTransfer().getReason()); ChakadResponseDto<TransferChequeResponseDto> transferResponse = chakadClient.transferCheques(getToken(), getUserAgent(), mapper.toTransferCheque(transferRequestDto)); if (!SUCCESS_CHAKAD_CODE.equals(transferResponse.getMassageCode())) throw new ChakadClientException(transferResponse.getMessage()); try { ChequeTransfer chequeTransfer = mapper.toTransferEntity(transferRequestDto.getTransfer()); chequeTransfer.setChequeReason(reason); chequeTransferRepository.saveAndFlush(chequeTransfer); saveSigners(transferRequestDto.getTransfer().getSigners(), null, chequeTransfer); saveStakeholders(transferRequestDto.getTransfer().getSayadId(), transferRequestDto.getTransfer().getReceivers(), null, chequeTransfer); return new ResponseEntity<>(HttpStatus.OK); } catch (ConstraintViolationException e) { throw new ChakadClientException("chakad.issue.database.constraint", Status.BAD_REQUEST); } } private ChequeReason checkReason(String reason) { ChequeReason existedReason = null; if (reason != null) existedReason = reasonsRepository.findByReasonCode(reason) .orElseThrow(() -> new ChakadClientException("reason.not.find", Status.BAD_REQUEST)); return existedReason; } private void saveSigners(List<ChakadSignerDto> signers, ChequeIssue chequeIssue, ChequeTransfer chequeTransfer) { List<ChequeSigner> chequeSigner = mapper.toSignerEntity(signers); chequeSigner.forEach(s -> { if (chequeIssue != null) { s.setChequeIssue(chequeIssue); } else if (chequeTransfer != null) { s.setChequeTransfer(chequeTransfer); } }); chequeSignerRepository.saveAllAndFlush(chequeSigner); } private <T> void saveStakeholders(String sayadId, List<ChakadReceiverDto> receivers, List<ChakadGuarantorDto> guarantors, T obj) { stakeholderRepository.findAllBySayadIdAndIsFinalTrue(sayadId) .forEach(stk -> { stk.setIsFinal(false); stakeholderRepository.saveAndFlush(stk); }); receivers.forEach(rec -> { ChequeStakeholder stakeholder = new ChequeStakeholder(); stakeholder.setName(rec.getName()); stakeholder.setIdentifier(rec.getIdentifier()); stakeholder.setIdentifierType(rec.getIdentifierType().toString()); stakeholder.setSayadId(sayadId); stakeholder.setRole(StakeholderRole.RECIEVER); stakeholder.setIsFinal(true); if (obj instanceof ChequeIssue) stakeholder.setChequeIssue((ChequeIssue) obj); else if (obj instanceof ChequeTransfer) stakeholder.setChequeTransfer((ChequeTransfer) obj); stakeholderRepository.save(stakeholder); }); if (obj instanceof ChequeIssue) if (guarantors != null) guarantors.forEach(rec -> { ChequeStakeholder granter = new ChequeStakeholder(); granter.setName(rec.getName()); granter.setIdentifier(rec.getIdentifier()); granter.setIdentifierType(rec.getIdentifierType().toString()); granter.setSayadId(sayadId); granter.setRole(StakeholderRole.GRANTER); granter.setIsFinal(true); granter.setChequeIssue((ChequeIssue) obj); stakeholderRepository.save(granter); }); } }
#pragma once #include "Book.h" #include "MyVector.hpp" #ifndef _LIBRARY_ #define _LIBRARY_ const int INITIAL_CAPACITY = 10; class Library { private: MyVector<Book> _books; void sortBooksByAuthorHelper(MyVector<Book>& books, Book currentBook, int size, bool acs); void sortBooksByTitleHelper(MyVector<Book>& books, Book currentBook, int size, bool acs); void sortBooksByRatingHelper(MyVector<Book>& books, Book currentBook, int size, bool acs); void sortBooksByYearHelper(MyVector<Book>& books, Book currentBook, int size, bool acs); public: Library() : _books(10) {} const MyVector<Book>& getBooks() const; void printAll();// prints all books: title, author, genre, isbn void bookInfo(int isbn);//prints info about book with given isbn int findBookIndexByAuthor(const MyString& input); int findBookIndexByGenre(const MyString& input); int findBookIndexByTitle(const MyString& input); void sortBooksByAuthor(bool acs = true);//sort by acsending void sortBooksByRating(bool acs = true);//sort by acsending void sortBooksByTitle(bool acs = true);//sort by acsending void sortBooksByYear(bool acs = true);//sort by acsending void addBook(const Book& obj); void removeBook(const Book& obj); }; #endif // !_LIBRARY_
<html> <head> </head> <body> <div id="sameserverlinks"> <a href="http://localhost:2000/testA"></a> <a href="http://localhost:2000/has/qp?a=1&b=2"></a> <a href="http://localhost:2000/has/hash#blah"></a> <a href="http://localhost:2000/has/qp/and/hash?r=34&hello=world#blah"></a> <a href="http://localhost:2000"></a> <a href="http://localhost:2000/"></a> <a href="http://localhost:2000/endswithslash/"></a> <a href="http://localhost:2000/has/extension.html"></a> <a href="http://localhost:2000/has/json/extension.json"></a> <a href="http://localhost:2000/has/css/extension.css"></a> <a href="http://localhost/wrongport"></a> <a href="http://localhost:2000/#hash"></a> <a href="http://localhost:2000/?q=puppies"></a> <a href="http://localhost:2000/?q=puppies#hash"></a> <a href="http://localhost:2000#hash"></a> <a href="http://localhost:2000?q=puppies"></a> <a href="http://localhost:2000?q=puppies#hash"></a> </div> <div id="relativelinks"> <a href="/test/relative/link"></a> <a href="/test/endswith/slash/"></a> <a href="/has/qp?a=1&b=2"></a> <a href="/has/hash#blah"></a> <a href="/has/qp/and/hash?r=34&hello=world#blah"></a> <a href="/test/relative/linkwith.html"></a> <a href="/"></a> <a href=""></a> </div> <div id="externallinks"> <a href="http://adobe.com/test"></a> <a href="http://adobe.com/test/"></a> <a href="http://google.com"></a> </div> <div id="sameserverlinks-exclude"> <a href="http://localhost:2000/exclude/this/link"></a> <a href="http://localhost:2000/jp/exclude/this/link"></a> <a href="http://localhost:2000/ca_fr/exclude/this/link"></a> <a href="http://localhost:2000/deep/path/exclude/this/link"></a> <a href="http://localhost:2000/this/link/not/excluded"></a> </div> </body> <script type="module"> import { runTests } from '@web/test-runner-mocha'; import { expect } from '@esm-bundle/chai'; import { appendHtmlPostfix, setConfig } from './../../libs/utils/utils.js'; setConfig({ htmlExclude: [ /localhost:2000\/exclude\/.*/, /localhost:2000\/(\w\w|(\w\w_\w\w))\/exclude\/.*/, ], }); runTests(() => { describe('htmlpostfix', () => { it('same server links', async () => { const links = document.getElementById('sameserverlinks'); appendHtmlPostfix(links); const hrefs = [...links.querySelectorAll('a')].map(a => a.getAttribute('href')); expect(hrefs).to.eql([ 'http://localhost:2000/testA.html', 'http://localhost:2000/has/qp.html?a=1&b=2', 'http://localhost:2000/has/hash.html#blah', 'http://localhost:2000/has/qp/and/hash.html?r=34&hello=world#blah', 'http://localhost:2000', 'http://localhost:2000/', 'http://localhost:2000/endswithslash/', 'http://localhost:2000/has/extension.html', 'http://localhost:2000/has/json/extension.json', 'http://localhost:2000/has/css/extension.css', 'http://localhost/wrongport', 'http://localhost:2000/#hash', 'http://localhost:2000/?q=puppies', 'http://localhost:2000/?q=puppies#hash', 'http://localhost:2000#hash', 'http://localhost:2000?q=puppies', 'http://localhost:2000?q=puppies#hash', ]); }); it('relative links', async () => { const links = document.getElementById('relativelinks'); appendHtmlPostfix(links); const hrefs = [...links.querySelectorAll('a')].map(a => a.getAttribute('href')); expect(hrefs).to.eql([ '/test/relative/link.html', '/test/endswith/slash/', '/has/qp.html?a=1&b=2', '/has/hash.html#blah', '/has/qp/and/hash.html?r=34&hello=world#blah', '/test/relative/linkwith.html', '/', '', ]) }); it('external links are not modified', async () => { const links = document.getElementById('externallinks'); appendHtmlPostfix(links); const hrefs = [...links.querySelectorAll('a')].map(a => a.getAttribute('href')); expect(hrefs).to.eql([ 'http://adobe.com/test', 'http://adobe.com/test/', 'http://google.com', ]) }); it('same server links in htmlExclude list not modified', async () => { const links = document.getElementById('sameserverlinks-exclude'); appendHtmlPostfix(links); const hrefs = [...links.querySelectorAll('a')].map(a => a.getAttribute('href')); expect(hrefs).to.eql([ 'http://localhost:2000/exclude/this/link', 'http://localhost:2000/jp/exclude/this/link', 'http://localhost:2000/ca_fr/exclude/this/link', 'http://localhost:2000/deep/path/exclude/this/link.html', 'http://localhost:2000/this/link/not/excluded.html', ]) }); }); }); </script> </html>
#ifndef THREEOFAKINDVALIDATOR_H #define THREEOFAKINDVALIDATOR_H #include "validator.h" #include "count_calulator.h" #include "../card.h" #include <vector> #include <string> class ThreeOfAKindValidator : public Validator { public: ThreeOfAKindValidator() = default; ThreeOfAKindValidator(std::vector<Card> cards) { this->cards = cards; } std::string name() override { return "Three of A Kind"; } bool is_valid() override { std::vector<std::string> ranks_with_three_of_a_kind = CountCalculator::ranks_with_target_count(this->cards, 3); return (ranks_with_three_of_a_kind.size() == 1); } std::vector<Card> valid_cards() override { std::vector<std::string> ranks_with_three_of_a_kind = CountCalculator::ranks_with_target_count(this->cards, 3); for (Card &card : this->cards) { for (std::string rank : ranks_with_three_of_a_kind) { if (card.rank == rank) { this->_valid_cards.push_back(card); } } } return this->_valid_cards; } private: std::vector<Card> cards; std::vector<Card> _valid_cards; }; #endif
import React from 'react'; import { Image, Grid } from 'semantic-ui-react'; import Link from 'next/link'; import { map } from 'lodash'; import useWindowSize from '../../Hook/useWindowSize'; import { breakUpSm, breakUpMd, breakUpLg } from '../../Utils/Breakpoints'; export default function ListGames({ games }) { const { width } = useWindowSize(); const getColumnsRender = () => { switch (true) { case width > breakUpLg: return 5; case width > breakUpMd: return 3; case width > breakUpSm: return 2; default: return 1; } }; return ( <div className='list-games'> <Grid> <Grid.Row columns={getColumnsRender()}> {map(games, (game) => ( <Game key={game.url} game={game} /> ))} </Grid.Row> </Grid> </div> ); } function Game({ game }) { return ( <Grid.Column className='list-games__game'> <Link href={`/${game.url}`}> <a> <div className='list-games__game-poster'> <Image src={game.poster.url} alt={game.title} /> <div className='list-games__game-poster-info'> {game.discount ? <span className='discount'>-{game.discount}%</span> : <span />} <span className='price'>${game.price}</span> </div> </div> <h2>{game.title}</h2> </a> </Link> </Grid.Column> ); }
<!DOCTYPE html> <html lang="en"> <head> <title>Dashboard MARCELO MOTORS</title> <link rel="shortcut icon" type="image/x-icon" href="../img/logis.ico"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,600|Open+Sans" rel="stylesheet"> <link rel="stylesheet" href="../css/estiloVenta.css"> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <?php include '../extend/header.php'; //include '../extend/permiso.php'; ?> </head> <style> @media (max-width: 600px) { #chartContainer { flex-direction: column; } } #chartContainer { display: flex; flex-wrap: wrap; margin: 0 auto; /* Agregamos esta propiedad para centrar los elementos */ max-width: 800px; /* Ajustamos el ancho máximo del contenedor */ } .chart-container { width: 100%; /* Cambiamos el ancho al 100% para dispositivos móviles */ padding: 10px; box-sizing: border-box; } .card-title { color: black; /* Cambiamos el color del texto a negro */ } </style> <body> <div id="chartContainer"> <div class="chart-container"> <div class="card"> <div class="card-content"> <span class="card-title">Producto más vendido</span> <div id="piechart" style="width: 100%; height: 400px;"></div> </div> </div> </div> <div class="chart-container"> <div class="card"> <div class="card-content"> <span class="card-title">Ventas y Compras</span> <canvas id="chart"></canvas> </div> </div> </div> </div> <script type="text/javascript"> google.charts.load('current', {'packages':['corechart']}); google.charts.setOnLoadCallback(drawChart); function drawChart() { var data = new google.visualization.DataTable(); data.addColumn('string', 'Producto'); data.addColumn('number', 'Cantidad'); <?php // Ejemplo utilizando mysqli $host = 'localhost'; $dbname = 'almacen'; $username = 'root'; $password = ''; $conexion = mysqli_connect($host, $username, $password, $dbname); // Verificar si la conexión fue exitosa if (!$conexion) { die("Error al conectarse a la base de datos: " . mysqli_connect_error()); } // Obtener el mes actual $mes_actual = date('m'); // Consulta para obtener los productos más vendidos del mes actual $consulta = "SELECT p.nombre AS producto, SUM(v.cantidad_vendida) AS total_vendido FROM ventas v INNER JOIN productos p ON v.producto_id = p.id WHERE MONTH(v.fechahora) = $mes_actual GROUP BY v.producto_id ORDER BY total_vendido DESC LIMIT 20"; $resultado = mysqli_query($conexion, $consulta); // Verificar si la consulta fue exitosa if (!$resultado) { die("Error al ejecutar la consulta: " . mysqli_error($conexion)); } // Agregar los datos al DataTable while ($fila = mysqli_fetch_assoc($resultado)) { $producto = $fila['producto']; $cantidad = $fila['total_vendido']; echo "data.addRow(['$producto', $cantidad]);"; } // Cerrar la conexión mysqli_close($conexion); ?> var options = { title: 'Productos más vendidos por mes', backgroundColor: { fill: 'transparent' }, legendTextStyle: { color: '#000000' }, titleTextStyle: { color: '#000000' } }; var chart = new google.visualization.PieChart(document.getElementById('piechart')); chart.draw(data, options); } </script> <script> <?php // Configuración de la conexión a la base de datos $host = 'localhost'; $dbname = 'almacen'; $username = 'root'; $password = ''; // Establecer la conexión $conexion = mysqli_connect($host, $username, $password, $dbname); // Verificar si la conexión fue exitosa if (!$conexion) { die("Error al conectarse a la base de datos: " . mysqli_connect_error()); } // Generar un conjunto completo de meses (desde enero hasta diciembre) $mesesCompletos = array(); for ($i = 1; $i <= 12; $i++) { $mesesCompletos[$i] = array('ventas' => 0, 'compras' => 0); } // Consulta para obtener la suma total de ventas por mes $consultaVentas = "SELECT MONTH(fechahora) AS mes, SUM(total) AS total_ventas FROM ventas GROUP BY mes"; $resultadoVentas = mysqli_query($conexion, $consultaVentas); // Verificar si la consulta de ventas fue exitosa if (!$resultadoVentas) { die("Error al ejecutar la consulta de ventas: " . mysqli_error($conexion)); } // Agregar los datos de ventas al arreglo $mesesCompletos while ($filaVentas = mysqli_fetch_assoc($resultadoVentas)) { $mes = (int)$filaVentas['mes']; $totalVentas = (int)$filaVentas['total_ventas']; $mesesCompletos[$mes]['ventas'] = $totalVentas; } // Consulta para obtener la suma total de compras por mes $consultaCompras = "SELECT MONTH(fechahora) AS mes, SUM(precio_compra * cantidad_comprada) AS total_compras FROM compras GROUP BY mes"; $resultadoCompras = mysqli_query($conexion, $consultaCompras); // Verificar si la consulta de compras fue exitosa if (!$resultadoCompras) { die("Error al ejecutar la consulta de compras: " . mysqli_error($conexion)); } // Agregar los datos de compras al arreglo $mesesCompletos while ($filaCompras = mysqli_fetch_assoc($resultadoCompras)) { $mes = (int)$filaCompras['mes']; $totalCompras = (int)$filaCompras['total_compras']; $mesesCompletos[$mes]['compras'] = $totalCompras; } // Extraer los datos de ventas y compras para el gráfico $dataVentas = array(); $dataCompras = array(); for ($i = 1; $i <= 12; $i++) { $dataVentas[] = $mesesCompletos[$i]['ventas']; $dataCompras[] = $mesesCompletos[$i]['compras']; } // Convertir los datos en formato JSON $json_dataVentas = json_encode(array_values($dataVentas)); $json_dataCompras = json_encode(array_values($dataCompras)); ?> // Datos obtenidos de las consultas SQL var dataVentas = <?php echo $json_dataVentas; ?>; var dataCompras = <?php echo $json_dataCompras; ?>; // Nombres de los meses var meses = [ 'Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre' ]; // Crear el gráfico var ctx = document.getElementById('chart').getContext('2d'); var chart = new Chart(ctx, { type: 'bar', data: { labels: meses, datasets: [ { label: 'Ventas', data: dataVentas, backgroundColor: 'rgba(54, 162, 235, 0.2)', // Cambiar el color de las barras de ventas (azul) borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 1 }, { label: 'Compras', data: dataCompras, backgroundColor: 'rgba(255, 99, 132, 0.2)', // Cambiar el color de las barras de compras (rojo) borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 1 } ] }, options: { scales: { y: { beginAtZero: true, stepSize: 1 } }, plugins: { annotation: { annotations: [{ type: 'line', mode: 'horizontal', scaleID: 'y', value: dataVentas[0], borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1, label: { enabled: true, content: 'Ventas: ' + dataVentas[0].toString(), position: 'right' } }, { type: 'line', mode: 'horizontal', scaleID: 'y', value: dataCompras[0], borderColor: 'rgba(54, 162, 235, 1)', borderWidth: 1, label: { enabled: true, content: 'Compras: ' + dataCompras[0].toString(), position: 'right' } }], drawTime: 'afterDatasetsDraw' }, datalabels: { anchor: 'end', align: 'end', color: 'black', font: { weight: 'bold' }, formatter: function(value) { return value.toString(); } } }, onAfterDraw: function(chart) { var ctx = chart.ctx; chart.data.datasets.forEach(function(dataset, datasetIndex) { var meta = chart.getDatasetMeta(datasetIndex); meta.data.forEach(function(bar, index) { var data = dataset.data[index]; ctx.fillStyle = 'black'; ctx.font = '12px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'bottom'; ctx.fillText(data, bar.x, bar.y - 5); }); }); } } }); </script> </body> <?php include '../extend/scripts.php'; ?> </html>
<template> <Toast /> <LoaderView msg="Guardando Cliente" :visible="loading_conexion_API" /> <Button label="Nuevo Cliente" icon="pi pi-user-plus" @click="visible = true" /> <Dialog v-model:visible="visible" modal :header="cliente ? 'Modificar Cliente' : 'Registrar Cliente'" :style="{ width: '30vw' }" class="p-fluid"> <div class="field"> <label for="nombre">Nombre y Apellido</label> <InputText id="nombre" required="true" v-model="customer.nombre_completo" /> </div> <div class="field"> <label for="email">Email</label> <InputText id="email" type="email" required="true" v-model="customer.email" /> </div> <div class="flex justify-content-between"> <div class="field"> <label for="telefono">Telefono</label> <InputNumber id="telefono" required="true" v-model="customer.telefono" :min="60000000" :max="79999999" :useGrouping="false" placeholder="00000000" /> </div> <div class="field nit"> <label for="nit">NIT</label> <InputNumber id="nit" required="true" v-model="customer.nit" :min="1000" :max="9999" :useGrouping="false" placeholder="0000" /> </div> </div> <div class="field"> <label for="direccion">Direccion</label> <InputText id="direccion" required="true" v-model="customer.direccion" /> </div> <div class="field"> <Button label="Guardar" @click="(isEditing ? updateCustomer() : registerCustomer())" /> </div> </Dialog> </template> <script setup lang="ts"> import { ref, watch, watchEffect } from 'vue'; import type { Cliente } from '../types'; import * as serviceCliente from '@/services/cliente.service'; import { useToast } from 'primevue/usetoast'; import { usePinia } from '@/stores/store'; import LoaderView from '../LoaderView.vue'; // PROP const props = defineProps({ cliente: { type: Object as () => Cliente, required: false }, }); // VARIABLES REACTIVAS const visible = ref<boolean>(false); const customer = ref<Cliente>({ nombre_completo: '', email: '', telefono: 0, nit: 0, direccion: '' }); const isEditing = ref<boolean>(false); // Esta es la variable que indica si estamos editando o no const loading_conexion_API = ref<boolean>(false) // Toast const toast = useToast(); // WATCHERS // escucha los cambios que hay en el prop cliente, se usa para editar watch(() => props.cliente, (newValue) => { // Si hay un nuevo valor de cliente, lo asignamos a la variable reactiva y ponemos isEditing en true if (newValue) { customer.value = newValue; isEditing.value = true; } }); // watchEffect para poner en vacio los inputs desdepues de cerrar watchEffect(() => { if (!visible.value) { customer.value = { nombre_completo: '', email: '', telefono: 0, nit: 0, direccion: '' } } }); // FUNCIONES async function registerCustomer(): Promise<void> { // validar los campos try { // iniciamos la carga del guardado loading_conexion_API.value = true; // VARIBLE DE PINIA const pinia = usePinia(); validateRequiredFields(); await serviceCliente.postCliente(customer.value); toast.add({ severity: 'success', summary: "Exito", detail: 'Cliente Registrado', life: 3000 }); pinia.changeCustomer(customer.value); } catch (error: unknown) { showError((error as Error).message) } finally { // cerrarmos el guardado cuando termine de guardar loading_conexion_API.value = false; visible.value = false; } } function updateCustomer(): void { alert("Modificar") } const validateRequiredFields = (): void => { // campos requeridos const requiredFields = { nombre_completo: 'Ingrese su nombre completo', email: 'Ingrese su email', telefono: 'Ingrese su telefono', nit: 'Ingrese su nit', direccion: 'Ingrese su direccion' }; for (const field in requiredFields) { // Aquí tipamos field como una de las claves de Cliente const key = field as keyof Cliente; if (!customer.value[key]) throw new Error(requiredFields[key]); } } const showError = (message: string): void => { toast.add({ severity: 'warn', summary: message, detail: 'Obligatorio', life: 3000 }); } </script> <script lang="ts"> export default { name: "RegisterCliente" } </script> <style> .nit { width: 100px; } </style>
import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule class MyspiderSpider(CrawlSpider): name = "myspider" allowed_domains = ["example.com"] start_urls = ["http://example.com"] # Set the download delay to 1 second custom_settings = { 'DOWNLOAD_DELAY': 3 } rules = (Rule(LinkExtractor(allow=r"Items/"), callback="parse_item", follow=True),) def start_requests(self): with open(r'G:\My Drive\Programming\Misc\Typing Practice Code Editor\urls.txt') as f: urls = f.readlines() for url in urls: url = url.strip() yield scrapy.Request(url=url, callback=self.parse) # url = 'https://www.biblegateway.com/passage/?search=John%206&version=NIV' # yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): # XPath to extract the content # xpath = "//div[@class='std-text']//text()[normalize-space()]" # Select all text nodes within the div # xpath = """ # //div[@class='std-text']//text()[normalize-space()] # [not(parent::sup[@class='crossreference'])] # [not(parent::sup[@class='footnote-marker'])] # [not(parent::span[@class='versenum'])] # """ # xpath = "normalize-space(//div[@class='chapter']//div[@class='version-NIV'])" # xpath = "//span[@class='versenum']//text()" # xpath = "//sup[@class='versenum']/text()" xpath = "//span[@class='chapternum']/following-sibling::text()" chapter_text = response.xpath(xpath).getall() xpath = "//sup[@class='versenum']/following-sibling::text()" passage_text = response.xpath(xpath).getall() # Join the list of text with newlines passage_text = '\n'.join(passage_text) # full_text = '\n'.join([chapter_text, passage_text]) full_text = chapter_text[0] + passage_text # XPpath to get title xpath = "string(//div[@class='dropdown-display-text'])" title = response.xpath(xpath).get() filename = f'G:\My Drive\Programming\Misc\Typing Practice Code Editor\Raw2\{title}.txt' # Save the content to a text file with open(filename, 'w', encoding='utf-8') as file: file.write(full_text) self.log(f'Saved content to {filename}') # yield {'text': passage_text}
import "./index.scss"; import * as React from 'react'; import ReactDOM from 'react-dom'; import Image from "./image"; import Google from "./Google"; import Facebook from "./Facebook"; import Logo from "./Logo"; import UserName from "./userNameInput"; import Password from "./passwordInput"; import Remember from "./Remember"; import LoginButton from "./LoginBtn"; import SignUp from "./Signup"; import CopyRight from "./CopyRight"; interface AppProps { } interface AppState { } class App extends React.Component<AppProps, AppState> { constructor(props: AppProps) { super(props); } render() { return ( <div className="container"> <div className="wrapper-left"> <Image></Image> <div className="wrapper-left-circle"> </div> <div className="wrapper-left-content"> <div className="title"> <span></span> <p>or Sign in with:</p> <span></span> </div> <Google content="Sign in with" subContent="Google"></Google> <Facebook content="Sign in with" subContent="Facebook"></Facebook> </div> </div> <div className="wrapper-right"> <div className="d-flex-col"> <div className="logo"> <Logo></Logo> </div> <div className="Login"> <h1>Login</h1> <UserName></UserName> <Password></Password> </div> <div className="remember"> <div className="remember-left"> <Remember></Remember> </div> <a href="#" className="forgot">Forgot Password?</a> </div> <div className="login"> <LoginButton content="LOGIN"></LoginButton> </div> <SignUp content="Don't have an account?" subContent="Sign up?"></SignUp> </div> <CopyRight content="© 2022 ANFLASH TECHNOLOGY. All rights reserved."></CopyRight> </div> </div> ) } } ReactDOM.render( <App/>, document.getElementById("wrapper") )
import AppConfig from "@/config/appCongif"; import { RootState } from "@/state/store"; import { Box, Table, Thead, Tbody, Tr, Th, Td, Button, Flex, Heading } from "@chakra-ui/react"; import axios from "axios"; import Link from "next/link"; import { useEffect, useState } from "react"; import { useSelector } from "react-redux"; interface Exam { id: number; title: string; venue: string; duration: number; } const ExamList: React.FC = () => { const { admin, error, loading, token } = useSelector( (state: RootState) => state.AdminAuth ); const [exams, setExams] = useState<Exam[]>([]); const fetchExams = async () => { try { const response = await axios.post( `${AppConfig.API}/api/admin/exam/get-exams`, {}, { headers: { Authorization: `Bearer ${token}`, }, } ); setExams(response.data?.exams); } catch (error: any) { let message = error?.response?.data?.message || error.message; alert(message); } }; const handleView = (id: number) => { // Logic to handle viewing exam details }; const handleDelete = async(exam: any) => { try { const response = await axios.post( `${AppConfig.API}/api/admin/exam/delete`, {exam}, { headers: { Authorization: `Bearer ${token}`, }, } ); alert(response?.data?.message); fetchExams() } catch (error: any) { let message = error?.response?.data?.message || error.message; alert(message); } }; useEffect(() => { fetchExams(); }, []); return ( <Box> <Box bg="black" p={1}> <Flex justifyContent="space-between" alignItems="center"> <Link href="/admin/dashboard"> <Button colorScheme="cyan" variant="outline"> Back </Button> </Link> <Heading color="white" size="md"> Exam List </Heading> <Link href="/admin/exam/create"> <Button colorScheme="red">+ Add New Exam</Button> </Link> </Flex> </Box> <Table variant="striped" size={"sm"} > <Thead> <Tr> <Th>Sl. No.</Th> <Th minW={"200px"}>Title</Th> <Th>Venue</Th> <Th>Duration (min)</Th> <Th isNumeric>Action</Th> </Tr> </Thead> <Tbody> {exams.reverse().map((exam:any, index) => ( <Tr key={exam.id}> <Td>{index + 1}</Td> <Td>{exam.title}</Td> <Td>{exam.venue}</Td> <Td>{exam.duration}</Td> <Td isNumeric> <Link href={`/admin/exam/${exam?._id}`}> <Button size={"sm"} colorScheme="blue" mr={2} onClick={() => handleView(exam?._id)} > View </Button></Link> <Button size={"sm"} colorScheme="red" onClick={() => handleDelete(exam?._id)} > Delete </Button> </Td> </Tr> ))} </Tbody> </Table> </Box> ); }; export default ExamList;
// // Copyright (c) 2021 Red Hat, Inc. // 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. //go:build !release package integrationtests import ( "context" "errors" "fmt" "k8s.io/apimachinery/pkg/api/meta" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/uuid" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" ) var fakeError error = errors.New("print the callstack of successful invocation") // LoggingKubernetesClient is a wrapper aroung a Kubernetes client that is capable of logging the calls to the // Kubernetes API. It is meant to be used only in tests and integration tests! type LoggingKubernetesClient struct { Client client.Client LogReads bool LogWrites bool IncludeStacktraces bool } type loggingKubernetesSubresourceWriter struct { scheme *runtime.Scheme writer client.SubResourceWriter includeStacktraces bool } // Create implements client.SubResourceWriter func (w *loggingKubernetesSubresourceWriter) Create(ctx context.Context, obj client.Object, subResource client.Object, opts ...client.SubResourceCreateOption) error { return logAround(func() error { return w.writer.Create(ctx, obj, subResource, opts...) //nolint:wrapcheck }, ctx, w.includeStacktraces, "Status.Create", func() []interface{} { return []interface{}{ "key", client.ObjectKeyFromObject(obj), "kind", getKind(w.scheme, obj), "subResource", client.ObjectKeyFromObject(subResource), "subResourceKind", getKind(w.scheme, subResource), } }) } // Patch implements client.SubResourceWriter func (w *loggingKubernetesSubresourceWriter) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.SubResourcePatchOption) error { return logAround(func() error { return w.writer.Patch(ctx, obj, patch, opts...) //nolint:wrapcheck }, ctx, w.includeStacktraces, "Status.Patch", func() []interface{} { return []interface{}{"key", client.ObjectKeyFromObject(obj), "kind", getKind(w.scheme, obj)} }) } // Update implements client.SubResourceWriter func (w *loggingKubernetesSubresourceWriter) Update(ctx context.Context, obj client.Object, opts ...client.SubResourceUpdateOption) error { return logAround(func() error { return w.writer.Update(ctx, obj, opts...) //nolint:wrapcheck }, ctx, w.includeStacktraces, "Status.Update", func() []interface{} { return []interface{}{"key", client.ObjectKeyFromObject(obj), "kind", getKind(w.scheme, obj)} }) } type loggingSubresourceClient struct { scheme *runtime.Scheme client client.SubResourceClient logReads bool logWrites bool includeStacktraces bool subResource string } // Get implements client.SubResourceClient func (c *loggingSubresourceClient) Get(ctx context.Context, obj client.Object, subResource client.Object, opts ...client.SubResourceGetOption) error { if !c.logReads { return c.client.Get(ctx, obj, subResource, opts...) //nolint:wrapcheck } return logAround(func() error { return c.client.Get(ctx, obj, subResource, opts...) //nolint:wrapcheck }, ctx, false, c.methodName("Get"), func() []interface{} { return []interface{}{ "key", client.ObjectKeyFromObject(obj), "kind", getKind(c.scheme, obj), "subResource", client.ObjectKeyFromObject(subResource), "subResourceKind", getKind(c.scheme, subResource), } }) } // Create implements client.SubResourceClient func (c *loggingSubresourceClient) Create(ctx context.Context, obj client.Object, subResource client.Object, opts ...client.SubResourceCreateOption) error { if !c.logWrites { return c.client.Create(ctx, obj, subResource, opts...) //nolint:wrapcheck } return logAround(func() error { return c.client.Create(ctx, obj, subResource, opts...) //nolint:wrapcheck }, ctx, c.includeStacktraces, c.methodName("Create"), func() []interface{} { return []interface{}{ "key", client.ObjectKeyFromObject(obj), "kind", getKind(c.scheme, obj), "subResource", client.ObjectKeyFromObject(subResource), "subResourceKind", getKind(c.scheme, subResource), } }) } // Patch implements client.SubResourceClient func (c *loggingSubresourceClient) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.SubResourcePatchOption) error { if !c.logWrites { return c.client.Patch(ctx, obj, patch, opts...) //nolint:wrapcheck } return logAround(func() error { return c.client.Patch(ctx, obj, patch, opts...) //nolint:wrapcheck }, ctx, c.includeStacktraces, c.methodName("Patch"), func() []interface{} { return []interface{}{"key", client.ObjectKeyFromObject(obj), "kind", getKind(c.scheme, obj)} }) } // Update implements client.SubResourceClient func (c *loggingSubresourceClient) Update(ctx context.Context, obj client.Object, opts ...client.SubResourceUpdateOption) error { if !c.logWrites { return c.client.Update(ctx, obj, opts...) //nolint:wrapcheck } return logAround(func() error { return c.client.Update(ctx, obj, opts...) //nolint:wrapcheck }, ctx, c.includeStacktraces, c.methodName("Update"), func() []interface{} { return []interface{}{"key", client.ObjectKeyFromObject(obj), "kind", getKind(c.scheme, obj)} }) } func (c *loggingSubresourceClient) methodName(methodName string) string { return fmt.Sprintf("SubResource(%s).%s", c.subResource, methodName) } // Get implements client.Client func (c *LoggingKubernetesClient) Get(ctx context.Context, key types.NamespacedName, obj client.Object, opts ...client.GetOption) error { if !c.LogReads { return c.Client.Get(ctx, key, obj, opts...) //nolint:wrapcheck } return logAround(func() error { return c.Client.Get(ctx, key, obj, opts...) //nolint:wrapcheck }, ctx, false, "Get", func() []interface{} { return []interface{}{"key", key, "kind", c.getKind(obj)} }) } // List implements client.Client func (c *LoggingKubernetesClient) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { if !c.LogReads { return c.Client.List(ctx, list, opts...) //nolint:wrapcheck } return logAround(func() error { return c.Client.List(ctx, list, opts...) //nolint:wrapcheck }, ctx, false, "List", func() []interface{} { return []interface{}{"kind", c.getKind(list)} }) } // Create implements client.Client func (c *LoggingKubernetesClient) Create(ctx context.Context, obj client.Object, opts ...client.CreateOption) error { if !c.LogWrites { return c.Client.Create(ctx, obj, opts...) //nolint:wrapcheck } return logAround(func() error { return c.Client.Create(ctx, obj, opts...) //nolint:wrapcheck }, ctx, c.IncludeStacktraces, "Create", func() []interface{} { return []interface{}{"key", client.ObjectKeyFromObject(obj), "kind", c.getKind(obj)} }) } // Delete implements client.Client func (c *LoggingKubernetesClient) Delete(ctx context.Context, obj client.Object, opts ...client.DeleteOption) error { if !c.LogWrites { return c.Client.Delete(ctx, obj, opts...) //nolint:wrapcheck } return logAround(func() error { return c.Client.Delete(ctx, obj, opts...) //nolint:wrapcheck }, ctx, c.IncludeStacktraces, "Delete", func() []interface{} { return []interface{}{"key", client.ObjectKeyFromObject(obj), "kind", c.getKind(obj)} }) } // DeleteAllOf implements client.Client func (c *LoggingKubernetesClient) DeleteAllOf(ctx context.Context, obj client.Object, opts ...client.DeleteAllOfOption) error { if !c.LogWrites { return c.Client.DeleteAllOf(ctx, obj, opts...) //nolint:wrapcheck } return logAround(func() error { return c.Client.DeleteAllOf(ctx, obj, opts...) //nolint:wrapcheck }, ctx, c.IncludeStacktraces, "DeleteAllOf", func() []interface{} { return []interface{}{"kind", c.getKind(obj)} }) } // Patch implements client.Client func (c *LoggingKubernetesClient) Patch(ctx context.Context, obj client.Object, patch client.Patch, opts ...client.PatchOption) error { if !c.LogWrites { return c.Client.Patch(ctx, obj, patch, opts...) //nolint:wrapcheck } return logAround(func() error { return c.Client.Patch(ctx, obj, patch, opts...) //nolint:wrapcheck }, ctx, c.IncludeStacktraces, "Patch", func() []interface{} { return []interface{}{"key", client.ObjectKeyFromObject(obj), "kind", c.getKind(obj)} }) } // Update implements client.Client func (c *LoggingKubernetesClient) Update(ctx context.Context, obj client.Object, opts ...client.UpdateOption) error { if !c.LogWrites { return c.Client.Update(ctx, obj, opts...) //nolint:wrapcheck } return logAround(func() error { return c.Client.Update(ctx, obj, opts...) //nolint:wrapcheck }, ctx, c.IncludeStacktraces, "Update", func() []interface{} { return []interface{}{"key", client.ObjectKeyFromObject(obj), "kind", c.getKind(obj)} }) } // Status implements client.Client func (c *LoggingKubernetesClient) Status() client.SubResourceWriter { if !c.LogWrites { return c.Client.Status() } return &loggingKubernetesSubresourceWriter{ scheme: c.Client.Scheme(), writer: c.Client.Status(), includeStacktraces: c.IncludeStacktraces, } } // SubResource implements client.Client func (c *LoggingKubernetesClient) SubResource(subResource string) client.SubResourceClient { return &loggingSubresourceClient{ scheme: c.Client.Scheme(), client: c.Client.SubResource(subResource), includeStacktraces: c.IncludeStacktraces, subResource: subResource, } } // RESTMapper implements client.Client func (c *LoggingKubernetesClient) RESTMapper() meta.RESTMapper { return c.Client.RESTMapper() } // Scheme implements client.Client func (c *LoggingKubernetesClient) Scheme() *runtime.Scheme { return c.Client.Scheme() } var _ (client.Client) = (*LoggingKubernetesClient)(nil) func (c *LoggingKubernetesClient) getKind(obj runtime.Object) string { return getKind(c.Client.Scheme(), obj) } func getKind(scheme *runtime.Scheme, obj runtime.Object) string { var kind = "<unknown>" kinds, _, err := scheme.ObjectKinds(obj) if len(kinds) > 0 && err == nil { kind = kinds[0].Kind } return kind } func logAround(fn func() error, ctx context.Context, includeStacktraces bool, methodName string, keysVals func() []interface{}) error { id := uuid.NewUUID() args := keysVals() lg := log.FromContext(ctx) lg.WithValues("inv_id", id).WithValues(args...).Info(fmt.Sprintf(">> %s", methodName)) err := fn() // evaluate the arguments again so that we can gather more info in case pointers are involved args = keysVals() lg = lg.WithValues("inv_id", id).WithValues(args...) if err != nil || includeStacktraces { e := err if e == nil { e = fakeError } lg.Error(e, fmt.Sprintf("<< %s", methodName)) } else { lg.Info(fmt.Sprintf("<< %s", methodName)) } return err }
// Redux 的模块拆分 import React, { PureComponent } from 'react' import Home from './pages/Home' import Profile from './pages/Profile' import About from './pages/About' import Category from './pages/Category' import store from './store' export default class App extends PureComponent { constructor() { super() this.state = { /* 页面初始化时展示store里的默认值; 原来是从store中的state里拿counter数据;模块拆分以后是从counter模块中拿counter数据; 拆分前: state={ counter: 100, banners:[], } 拆分后: { counter:{counter: 100,}, home:{banners:[],recommends} } */ counter: store.getState().counter.counter, } } componentDidMount() { // 订阅,store中的数据一更新就获取过来 store.subscribe(() => { const state = store.getState() this.setState({ counter: state.counter.counter }) }) } render() { return ( <div> <h2>App Counter: {this.state.counter}</h2> <Home /> <Profile /> <About /> <Category /> </div> ) } }
from datasets import Dataset import datasets import subprocess import os # internal imports from compiler_fuzzing.utils.logs import record_case from compiler_fuzzing.utils.files import valid_path from compiler_fuzzing.utils import ( display, files, strings ) def get_base_path(args, config): task = args.task if task == 'module': base_dir = config['module_output_dir'] elif task == 'github_issue': base_dir = config['output_dir'] if args.timestamp is not None: base_path = f"{base_dir}/{args.timestamp}" else: file_list = files.list(base_dir) if 'debug' in file_list : file_list.pop(file_list.index('debug')) if len(file_list) == 0: raise FileNotFoundError( 'No directories in target location. Need to generate ansible files first.' ) src_dir = sorted(file_list)[-1] base_path = f'{base_dir}/' + src_dir return base_path def create_docker_environment(docker_path, project_root_path): # Create New Docker Environment os.chdir(docker_path) docker_stop_command = ["docker", "compose", "stop"] docker_stop_log = subprocess.run( docker_stop_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) docker_up_command = ["docker", "compose", "up", "-d", "--force-recreate"] docker_up_log = subprocess.run( docker_up_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) docker_ps = ["docker", "ps"] docker_networks = ["docker", "network", "list"] docker_ps_log = subprocess.run( docker_ps, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) docker_networks_log = subprocess.run( docker_networks, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) record_case( success=True, tag="docker", **{ "stop log": f"std err: {docker_stop_log.stderr}, std out: {docker_stop_log.stdout}", "up log": f"std err: {docker_up_log.stderr}, std out: {docker_up_log.stdout}", "containers created": f"std err: {docker_ps_log.stderr}, std out: {docker_ps_log.stdout}", "network created": f"std err: {docker_networks_log.stderr}, std out: {docker_networks_log.stdout}", "timestamp": strings.now() } ) os.chdir(project_root_path) def run_ansible_playbook(playbook_path, inventory_path, private_key, become_password_file): ansible_command = [ "ansible-playbook", playbook_path, "-i", inventory_path, "--private-key", private_key, "--become-password-file", become_password_file, "-vvv" ] output = subprocess.run( ansible_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=300, text=True ) return output def subprocess_ansible(sample_data, yaml_base_path, inventory_path, docker_path, private_key, become_password_file, num_digits=5): level = sample_data["level"] issue_id = sample_data["id"] playbook_path = f"{yaml_base_path}/lv{level}/{int(issue_id):0{num_digits}}.yaml" project_root_path = os.getcwd() if not valid_path(playbook_path): return 0 output = "" try: create_docker_environment(docker_path, project_root_path) output = run_ansible_playbook(playbook_path, inventory_path, private_key, become_password_file) record_case( success=True, tag="run", **{ "issue id": sample_data["id"], "issue title": sample_data["title"], "issue prompt": sample_data["prompt"], "issue Output": f"std err: {output.stderr}, std out: {output.stdout}", "timestamp": strings.now() } ) return output.stdout except Exception as e: # logger.error(f"issue id: {issue_id}, issue title: {issue_title}, reason: Invalid syntax., issue prompt: {issue_prompt}") record_case( success=False, **{ "issue id": sample_data["id"], "issue title": sample_data["title"], "reason": f"{e}", "issue prompt": sample_data["prompt"], "timestamp": strings.now() } ) return output if output == "" else output.stdout def subprocess_ansible_module(sample_data, yaml_base_path, inventory_path, docker_path, private_key, become_password_file): playbook_path = f"{yaml_base_path}/lv{sample_data['level']}/{sample_data['name']}" if not valid_path(playbook_path): return 0 files_and_dirs = os.listdir(playbook_path) # Filter out directories files = [f for f in files_and_dirs if os.path.isfile(os.path.join(playbook_path, f))] project_root_path = os.getcwd() output = "" for f in files: output += f"\n\n{f}\n\n" try: playbook_path = os.path.join(playbook_path, f) create_docker_environment(docker_path, project_root_path) console_output = "" console_output = run_ansible_playbook(playbook_path, inventory_path, private_key, become_password_file) output += f"{console_output.stdout}" except Exception as e: # logger.error(f"issue id: {issue_id}, issue title: {issue_title}, reason: Invalid syntax., issue prompt: {issue_prompt}") output += f"{console_output}" if console_output == "" else f"{console_output.stdout}" return output def run_ansible(args, config): task = args.task if task == 'module': base_dir = config['module_output_dir'] elif task == 'github_issue': base_dir = config['output_dir'] if args.timestamp is not None: base_path = f"{base_dir}/{args.timestamp}" else: file_list = files.list(base_dir) if 'debug' in file_list : file_list.pop(file_list.index('debug')) if len(file_list) == 0: raise FileNotFoundError( 'No directories in target location. Need to generate ansible files first.' ) src_dir = sorted(file_list)[-1] base_path = f'{base_dir}/' + src_dir file_path = f"{base_path}/manifest_ds.csv" datasets.disable_caching() ds = Dataset.from_csv(file_path) num_digits = 5 if task == 'module' else len(str(max(ds['id']))) inventory = config["inventory_file"] docker_path = config["docker_dir"] private_key = config["private_key"] become_password_file = config["become_password_file"] def mapper_fn(sample): if sample["syntax"] == 0: ansible_output = None else: if task == 'module': ansible_output = subprocess_ansible_module( sample_data= sample, yaml_base_path= base_path, inventory_path= inventory, docker_path= docker_path, private_key= private_key, become_password_file= become_password_file ) elif task == 'github_issue': ansible_output = subprocess_ansible( sample_data= sample, yaml_base_path= base_path, inventory_path= inventory, docker_path= docker_path, private_key= private_key, become_password_file= become_password_file, num_digits=num_digits ) sample.update({ 'output' : ansible_output }) return sample output_ds = ds.map(mapper_fn) trgt_path = file_path display.green(f'\nsaving data to {trgt_path} ...') try: output_ds.to_csv(trgt_path) except: display.error('csv could not be saved. switching to debug mode') breakpoint() def get_module_based_stat(args, ds, heuristic_list): breakpoint() if args.type == "syntax": stats = {} level_list = heuristic_list for i in level_list: level = i correct = len( ds.filter( lambda example: example['level'] == level and example['syntax'] == 1 and example['response'] != "TIMEOUT ERROR" ) ) total = len( ds.filter( lambda example: example['level'] == level and example['response'] != "TIMEOUT ERROR" ) ) stats[i] = {} stats[i]['heuristic'] = level stats[i]['valid'] = correct stats[i]['total'] = total stats[i]['second_request'] = sum( ds.filter( lambda example: example['level'] == level and example['response'] != "TIMEOUT ERROR" )['second_query'] ) stats[i]['valid_syntax_first_try'] = len( ds.filter( lambda example: example['level'] == level and example['syntax'] == 1 and example['second_query'] == 0 and example['response'] != "TIMEOUT ERROR" ) ) stats[i]['percent'] = (correct / total) * 100 correct = len( ds.filter( lambda example: example['syntax'] == 1 and example['response'] != "TIMEOUT ERROR" ) ) total = len( ds.filter( lambda example: example['response'] != "TIMEOUT ERROR" ) ) stats['Full'] = {} stats['Full']['valid'] = correct stats['Full']['total'] = total stats['Full']['second_request'] = sum( ds.filter( lambda example: example['response'] != "TIMEOUT ERROR" )['second_query'] ) stats['Full']['valid_syntax_first_try'] = len( ds.filter( lambda example: example['syntax'] == 1 and example['second_query'] == 0 and example['response'] != "TIMEOUT ERROR" ) ) stats['Full']['percent'] = (correct / total) * 100 display.print_dict(stats) def get_issue_based_stat(args, ds, level_list): if args.type == "syntax": stats = {} for i in level_list: level = i correct = len( ds.filter( lambda example: example['level'] == level and example['syntax'] == 1 and example['response'] != "TIMEOUT ERROR" ) ) total = len( ds.filter( lambda example: example['level'] == level and example['response'] != "TIMEOUT ERROR" ) ) stats[i] = {} stats[i]['level'] = level stats[i]['valid'] = correct stats[i]['total'] = total stats[i]['second_request'] = sum( ds.filter( lambda example: example['level'] == level )['second_query'] ) stats[i]['valid_syntax_first_try'] = len( ds.filter( lambda example: example['level'] == level and example['syntax'] == 1 and example['second_query'] == 0 and example['response'] != "TIMEOUT ERROR" ) ) stats[i]['percent'] = (correct / total) * 100 display.print_dict(stats) def generate_statistics(args, config): base_path = get_base_path(args, config) file_path = f"{base_path}/manifest_ds.csv" datasets.disable_caching() ds = Dataset.from_csv(file_path) level_list = [int(x) for x in config["levels"].split(",")] heuristic_list = [int(x) for x in config["heuristics"].split(",")] if args.task == 'module': display.green(f"\nSyntax Statistics of file: {file_path}\n") get_module_based_stat(args, ds, heuristic_list) elif args.task == 'github_issue': display.green(f"\nSyntax Statistics of file: {file_path}\n") get_issue_based_stat(args, ds, level_list)
import './App.css'; import React, { Component } from 'react' import Navbar from './components/Navbar'; import News from './components/News'; import { BrowserRouter, Routes, Route } from "react-router-dom"; export default class App extends Component { render() { return ( <div> <BrowserRouter> <Navbar/> <Routes> <Route exact path='/' element = {<News key="general" pageSize={6} country='in' category='general'/>}></Route> <Route exact path='/business' element = {<News key="business" pageSize={6} country='in' category='business'/>}></Route> <Route exact path='/entertainment' element = {<News key="entertainment" pageSize={6} country='in' category='entertainment'/>}></Route> <Route exact path='/health' element = {<News key="health" pageSize={6} country='in' category='health'/>}></Route> <Route exact path='/science' element = {<News key="science" pageSize={6} country='in' category='science'/>}></Route> <Route exact path='/sports' element = {<News key="sports" pageSize={6} country='in' category='sports'/>}></Route> <Route exact path='/technology' element = {<News key="technology" pageSize={6} country='in' category='technology'/>}></Route> </Routes> </BrowserRouter> </div> ) } }
using System; namespace CursoCSharp.CursoCSharp.ClassesEMetodos { class Pessoa { public string Nome; // valor padrão é Null public int Idade; // valor padrão é 0 public string Apresentar () { // Como o método apresentar está dentro da classe Pessoa, então não precisamos // colocar nenhum parâmetro dentro dos parênteses, // pois temos acesso as variáveis Nome e Idade. return string.Format($"Olá! Me chamo {Nome} e tenho {Idade} anos."); } public void ApresentarNoConsole() { Console.WriteLine(Apresentar()); // Imprimir no console não faz com que o método retorne algo, por isso é void } public void Zerar() { Nome = ""; Idade = 0; } } }
import React from 'react' import Select from 'react-select'; import { useQueryClient, useQuery } from "@tanstack/react-query"; import { getHashtags } from '../Requests/ArticleRequest'; import makeAnimated from 'react-select/animated'; const animatedComponents = makeAnimated(); const SearchBar = ({searchQuery, setSearchQuery, selectedTags, setSelectedTags}) => { const hashtagsResult = useQuery({ queryKey: ["hashtags"], queryFn: getHashtags, }); if (hashtagsResult.isError) { return <div></div>; } const hashtags = hashtagsResult.data; const hashtagsOptions = [] for (const key in hashtags) { hashtagsOptions.push({ value: key, label: key }) } return ( <div className='px-8'> <div className="flex bg-white bg-opacity-50 rounded-3xl px-8 py-4 m-4 items-center transition-all duration-100"> <i class="fa-solid fa-magnifying-glass mr-4"></i> <input className="hidden lg:inline-block grow mx-4 px-4 py-2 align-baseline bg-transparent outline-none focus:text-3xl transition-all duration-100" placeholder="Title" onChange={(e) => setSearchQuery(e.target.value)} value={searchQuery} > </input> <Select isMulti options={hashtagsOptions} components={animatedComponents} onChange={(change) => { setSelectedTags(change?.map(selected => selected.label)) }} className="w-full lg:w-[25%]"/> </div> </div> ) } export default SearchBar
<!DOCTYPE html> <html> <head> <!-- Character Encoding of default character set for HTML5 --> <meta charset="UTF-8"> <!-- title of the webpage --> <title>Blog</title> <!-- meta tags for the webpage blog --> <meta name="description" content="Blog about technology"> <meta name="keywords" content="HTML, CSS, javascript, blog, FDIUb Tech, technology, advantages and disadvantages of technology"> <meta name="author" content="Prasanna Ratna Kansakar"> <!-- link to external CSS for the webpage --> <link href="../CSS/mystyle.css" rel="stylesheet" type="text/css"> <!-- internal CSS for the webpage --> <style type="text/css"> /*Style for main tag*/ main{ margin: 0 auto; width: 100%; height: 2450px; background-color: #81D8D0; color: white; } /*Style for element with the class container*/ main .container{ width: 80%; height: 100%; margin: 0 auto; background-color: #4682B4; } /*Style for h1 tag inside the element with the class container*/ main .container h1{ margin: 0; font-weight: bold; font-size: 50px; padding: 10px 0 0 40px; } /*Style for span tag inside the element with the class container*/ main .container span{ font-style: italic; padding: 15px 0 0 60px; font-size: 20px; } /*Style for p tag inside the element with the class container*/ main .container p{ text-indent: 50px; text-align: justify; width: 93%; padding: 10px 0 0 40px; margin: 0; font-size: 25px; } /*Style for h2 tag inside the element with the class container*/ main .container h2{ padding: 10px 0 0 40px; margin: 0; font-size: 40px; } /*Style for element with the class A*/ main .A{ display: block; margin-left: auto; margin-right: auto; width: 400px; height: 300px; } </style> </head> <body> <!-- Start of header tag that contains logo, site name, search bar and clock--> <header> <img src="../images/OKYD0B1.png"> <!-- Start of div with class title --> <div class="title"> <h1>FDIUb Tech</h1> <h3>To Achieve Greatness</h3> </div> <!-- End of div with class title --> <!-- Start of div with class Search --> <div class="search"> <span>Search Website</span><br><br> <input type="text" name="search" placeholder=" Search Website"> <button onclick="alert('Work in progress')">Search</button> </div> <!-- End of div with class search --> <!-- Start of div with class clock and onload function clock()--> <div id="MyClockDisplay" class="clock" onload="clock()"> </div> <!-- External link to javascript --> <script type="text/javascript" src="../JS/clock.js"></script> </header> <!-- End of Header tag --> <!-- Start of nav tag that contains internal links to other webpages--> <nav> <!-- Start of unordered listing --> <ul> <li><a href="../index.html">Home</a></li> <li><a href="CV.html">CV</a></li> <li><a href="Blog.html" >Blog</a></li> <li><a href="Research.html">Research</a></li> <li><a href="ContactUs.html">Contact Us</a></li> </ul> <!-- End of unordered listing --> </nav> <!-- End of nav tag --> <!-- Start of main tag with contains multiple div and images --> <main> <!-- Start of div with class container --> <div class="container"> <h1>Technology Both an ability and a disability</h1> <span>-by Prasanna Ratna Kansakar(13<sup>th</sup> January 2020)</span> <p>Technology is being used in almost every aspect in our day to day life to accomplish specific tasks. Technology has changed the way we work. It reduces errors caused by humans which can be caused by too much work or stress. It is used in various fields such as education, transport, economy and many more. But like everything in life it comes with its fair share of advantages and disadvantages.</p><br> <img src="../images/t.png" class="A"><br> <h2> An Ability</h2> <p>Development and improvement of technology has been going on since the dawn of civillization. Whatever technology we have accumulated is the result of millions of years of developmengt of technology. Development of technology contiued on for generation after generation only because it was beneficial to humans. The advancement in technology at the medicial field can help treat more sick people and consequently save many lives. It also helps to combat many harmful viruses and bacteria. Technology has further advanced communication systems as well and with the development of devices such as a computer, process of research has been further simplified. With the rise of internet, there is also rise in online transaction thus sales and purchases can be facilitated and possible worldwide. Exchanges are also fasters. In Similar way technology has also increased the productivity of almost every industry in the world. Things deemed impossible at one stage such as space exploration is now possible through the development of technology. Technology has not only helped the industry it has also massively helped in our daily lives. From the light we turn on in our homes to the computer we use for work all is possible due to the advancement of technology.</p><br> <img src="../images/A.png" class="A"><br> <h2>But Also a Disability</h2> <p>Technology without a doubt has a massive impact in our lives and may even be the most important part in human civilization. The number of advantages may have increased over time but so has the disadvantges. As time continues we humans and became more and more dependent to technology. A calculator may be a revolutionary discovery but current time has reached at a point where a person can't make mental calculation. Logical thinking has slowly started to disapear. Technology has also lead to creation of various weapons of mass destruction such missiles, nukes, etc. Technology has also made humans more and more lazy. People often opt to use vechiles instead of walking even if it is a short distance. Not to mention the massive environmental problems technology has lead us. As most technological discoveries aim to reduce human effort, it would imply that more work is done by machines. This equates to less work for people: the human is becoming ever so obsolete by the day, as processes become automated and jobs are made redundant. There are also problems such as addiction, negative effects to children, negative health effects etc.</p><br> <img src="../images/B.png" class="A"><br> <h2>Verdict</h2> <p>Despite the numerous disadvantages we cannot deny the fact that no matter what development of technology is an absolute necessity. The advantages out weigh the advantages and we have to move further with new technolgy that is going to help us in further developing the civilization. However, we cannot completely ignore the disadvantages.The use of technology certainly needs rule and new laws. We need to make sure technology is used in a safe and sustainable manner. We also need to make sure that freedom of technology be properly implemented for certain technology. Making of technology that is harmful for us such as weapons of mass technology need to be full of restriction. In fact, regulations are difficult to implement but it is better than doing nothing.</p> </div> <!-- End of div with class container --> </main> <!-- End of main tag --> <!-- Start of footer tag that contains links to social media, input field to request VIP access and copyright info--> <footer> <!-- Start of div with class follow --> <div class="follow"> Follow us on Social Media:<br> <!-- Start of unordered listing --> <ul> <li><a href="https://www.facebook.com" target="_blank">Facebook</a></li> <li><a href="https://www.instagram.com/" target="_blank">Instagram</a></li> <li><a href="https://twitter.com/" target="_blank">Twiiter</a></li> </ul> <!-- End of unordered listing --> </div> <!-- End of dive with class follow --> <img src="../images/OKYD0B1.png"> <!-- Start of div with class trade --> <div class="trade"> &copy Copyright 2020 FDIUb Tech<br> All Rights Reserved. </div> <!-- Start of div with class member --> <div class="member"> Request VIP membership<br> <input type="text" name="Request" placeholder="Enter Email"> <button onclick="alert('Work in progress')">Submit</button> </div> <!-- End of div with class member --> </footer> <!-- End of the footer tag --> </body> </html>
#include <stdio.h> #include <stdlib.h> #include "dog.h" /** * print_dog - Prints all the data of a dog * @d: A dog structure * * Return: Nothing */ void print_dog(struct dog *d) { if (d != NULL) { printf("Name: %s\n", (d->name != NULL) ? d->name : "(nil)"); printf("Age: %.6f\n", d->age); printf("Owner: %s\n", (d->owner != NULL) ? d->owner : "(nil)"); } }
package com.project.kupuvalnik.configuration; import com.project.kupuvalnik.models.entity.enums.UserRoleEnum; import org.springframework.boot.autoconfigure.security.servlet.PathRequest; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; @Configuration public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter { private final UserDetailsService userDetailsService; private final PasswordEncoder passwordEncoder; public ApplicationSecurityConfiguration(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) { this.userDetailsService = userDetailsService; this.passwordEncoder = passwordEncoder; } @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() //allow access to static resources .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll() // access to pages for everyone .antMatchers("/", "/users/login", "/users/register").permitAll() .antMatchers("/stats").hasRole(UserRoleEnum.ADMIN.name()) //we forbid all other pages for unauthenticated users .antMatchers("/**").authenticated() .and() //configure login from html form with username and password input field .formLogin() .loginPage("/users/login") //this is the input from username in the login template .usernameParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_USERNAME_KEY) //this is the input from password in the login template .passwordParameter(UsernamePasswordAuthenticationFilter.SPRING_SECURITY_FORM_PASSWORD_KEY) //where to go when the login is succeeded .defaultSuccessUrl("/") //if there is an error in the login .failureForwardUrl("/users/login-error") .and() .logout() //logout url .logoutUrl("/users/logout") //where to go when logged out .logoutSuccessUrl("/") //remove the session from server .invalidateHttpSession(true) //delete the cookie from the session .deleteCookies("JSESSIONID"); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder); } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %> <%@ page import="java.util.List" %> <%@ page import="com.springbook.biz.board.impl.BoardDAO" %> <%@ page import="com.springbook.biz.board.BoardVO" %> <% // 세션에 저장된 글 목록을 꺼낸다. List<BoardVO> boardList = (List) session.getAttribute("boardList"); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"> <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"></script> <title>글 목록</title> <style type="text/css"> .listtable{margin:0 auto; width:1200px; border:1px solid black; border-collapse:collapse;} tr,td,th{border:1px solid black;} /* .container1{color:black;} */ p{text-align:center;} </style> </head> <body> <div class="jumbotron jumbotron-fluid"> <div class="container"> <h1><spring:message code="message.board.list.mainTitle"/></h1><br> <h5>%{userName }<spring:message code="message.board.list.welcomeMsg"/><a href="logout.do">Log-out</a></h5> </div> </div> <div class="container bg-dark"> <form action="getBoardList.do" method="post"> <select name="searchCondition"> <c:forEach items="${conditionMap}" var="option"> <option value="${option.value}">${option.key}</option> </c:forEach> <!-- <option value="TITLE">제목</option> --> <!-- <option value="CONTENT">내용</option> --> </select> <input name="searchKeyword" type="text"> <input type="submit" value="<spring:message code="message.board.list.search.condition.btn"/>"> </form> </div> <br> <!-- 검색 종료 --> <table class="listtable"> <tr> <th><spring:message code="message.board.list.table.head.seq"/></th> <th><spring:message code="message.board.list.table.head.title"/></th> <th><spring:message code="message.board.list.table.head.writer"/></th> <th><spring:message code="message.board.list.table.head.regDate"/></th> <th><spring:message code="message.board.list.table.head.cnt"/></th> </tr> <c:forEach items="${boardList }" var="board"> <tr> <td>${board.seq}</td> <td align="left"><a href="getBoard.do?seq=${board.seq }">${board.title }</a></td> <td>${board.writer }</td> <td>${board.regDate }</td> <td>${board.cnt }</td> </tr> </c:forEach> </table><br> <p><a href="insertBoard.jsp"><spring:message code="message.board.list.link.insertBoard"/></a></p> </body> </html>
package Examples.simpleGame.entities; import Examples.simpleGame.utils.TxtManager; import artemis.Vector2; import artemis.controller.KeyControl; import artemis.game.Body; import artemis.game.CollisionBox; import artemis.game.Game; import artemis.game.Sprite; import artemis.render.Scene; import java.awt.*; import java.io.Serializable; public class SimpleInteractableToilet extends Body implements Serializable { private Sprite skin; private SimplePopup popup; private KeyControl keyboard; private String txt; public SimpleInteractableToilet(Game game, Scene scene, Vector2 position, double[] size, SimplePopup popup) { super(game, scene, position, size); this.skin = new Sprite(game, scene, this.center, size, new String[] { "src/Examples/simpleGame/assets/toilet/toilet.png", "src/Examples/simpleGame/assets/toilet/toilet_2.png" }); this.collisionBox = new CollisionBox(game, scene, this.center, size, this); this.popup = popup; this.keyboard = new KeyControl(game); TxtManager txt = new TxtManager("src/Examples/simpleGame/persistent/poudialog.txt"); txt.read(); this.txt = txt.getContent(); } @Override public void _onReady() { this.skin.getReady(); this.collisionBox.getReady(); this.keyboard.registerKey('e'); } @Override public boolean isOnScreen() { return false; } @Override public void _physicsProcess(double delta) { if(this.collisionBox.isColliding()) { if(this.keyboard.isKeyPressed('e')) { this.skin.currentFrame = 1; this.popup.setVisibility(true); } } } @Override public void _process(double delta) { if(this.popup.button.clicked()) { this.popup.text.getTextArea().setText(txt); } } @Override public void render(Graphics2D ctx) { } }
import React, { useState, useEffect } from 'react'; const CreateProduct = () => { const [categories, setCategories] = useState([]); const [selectedCategory, setSelectedCategory] = useState(''); useEffect(() => { // Fetch the list of categories from the API fetch('/api/categories') .then(res => res.json()) .then(data => setCategories(data.categories)); }, []); const handleSubmit = async (e) => { e.preventDefault(); // Send the POST request to create the product, including the selected category in the request body const res = await fetch('/api/products', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...req.body, category: selectedCategory }) }); const data = await res.json(); // Handle the response from the API }; return ( <form onSubmit={handleSubmit}> {/* ...other form fields for product data... */} <label htmlFor="category">Category:</label> <select id="category" value={selectedCategory} onChange={(e) => setSelectedCategory(e.target.value)}> {categories.map(category => ( <option key={category._id} value={category._id}>{category.name}</option> ))} </select> <button type="submit">Create Product</button> </form> ); }; export default CreateProduct; import React, { useState } from "react"; const CreateProduct = () => { const [formData, setFormData] = useState({ productName: "", productSKU: "", productImage: "", productPrice: "", productStockQuantity: "", productLimitationInStore: "", productPublished: "", category: "", }); const handleChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; const handleSubmit = async (e) => { e.preventDefault(); try { const res = await axios.post("/api/products", formData); console.log(res.data); } catch (err) { console.error(err.response.data); } }; return ( <form onSubmit={handleSubmit}> <div> <label htmlFor="productName">Product Name:</label> <input type="text" name="productName" id="productName" value={formData.productName} onChange={handleChange} /> </div> {/* other input fields for other product details */} <div> <label htmlFor="category">Category:</label> <select name="category" id="category" value={formData.category} onChange={handleChange} > <option value="">Select a category</option> <option value="category1">Category 1</option> <option value="category2">Category 2</option> {/* other category options */} </select> </div> <button type="submit">Create Product</button> </form> ); }; export default CreateProduct; ///fetches the products for a given category: import React, { useState, useEffect } from 'react'; import axios from 'axios'; const CategoryProducts = ({ categoryId }) => { const [products, setProducts] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { const fetchProducts = async () => { try { const response = await axios.get(`/api/categories/${categoryId}/products`); setProducts(response.data.products); } catch (err) { setError(err); } finally { setLoading(false); } }; fetchProducts(); }, [categoryId]); if (loading) { return <div>Loading...</div>; } if (error) { return <div>An error occurred: {error.message}</div>; } return ( <ul> {products.map(product => ( <li key={product._id}>{product.name}</li> ))} </ul> ); }; export default CategoryProducts;
package shaders; import data.Paths; import flixel.FlxCamera; import flixel.system.FlxAssets.FlxShader; import openfl.filters.BitmapFilter; import openfl.filters.ShaderFilter; import shaders.FlxRunTimeShader; import sys.FileSystem; import sys.io.File; class ShaderUtil { public function new() {} public static function getShaderFromFile(name:String):FlxRuntimeShader { return new FlxRuntimeShader(getShaderFrag(name), getShaderVert(name)); } public static function getShaderFrag(name:String):String { var fragPath:Null<String> = Paths.getPreloadPath('shaders/$name.frag'); var frag:Null<String> = null; if (FileSystem.exists(fragPath)) frag = File.getContent(fragPath); return frag; } public static function getShaderVert(name:String):String { var vertPath:Null<String> = Paths.getPreloadPath('shaders/$name.vert'); var vert:Null<String> = null; if (FileSystem.exists(vertPath)) vert = File.getContent(vertPath); return vert; } public static function addShaderToCamera(camera:FlxCamera, shader:FlxShader) { if (camera == null || shader == null) return; @:privateAccess var camShaders:Null<Array<BitmapFilter>> = camera._filters; if (camShaders == null) camShaders = []; camShaders.push(cast new ShaderFilter(shader)); camera.setFilters(camShaders); } }
class Solution { // 二维dp // dp[i][j] represents largest square size when matrix[i][j] as bottom-right point // dp[i][j] = Math.min{ dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1] }; // Time: O(n * m) // Space: O(n * m) public int maximalSquare(char[][] matrix) { // corner case if (matrix == null || matrix.length == 0) { return 0; } int[][] dp = new int[matrix.length][matrix[0].length]; int maxSize = 0; for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[0].length; j++) { // initial values if (i == 0 || j == 0) { dp[i][j] = matrix[i][j] == '1' ? 1 : 0; } else if (matrix[i][j] == '1') { dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])) + 1; } maxSize = Math.max(maxSize, dp[i][j]); } } return maxSize * maxSize; } }
import os import pandas as pd import time import warnings import tqdm import matplotlib.pyplot as plt from selenium import webdriver from selenium.webdriver.chrome.service import Service as ChromeService from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from tqdm import tqdm pd.pandas.set_option('display.max_columns', None) pd.pandas.set_option('display.max_rows', 500) warnings.filterwarnings("ignore") #chromedriverPath = 'ScrapingPart/chromedriver/chromedriver.exe' class newsScraping: start_date = None end_date = None symbol = None driver = None df = None total_news = [] def __init__(self, data, place): pd.set_option('display.max_colwidth', 100) plt.show() pd.options.plotting.backend = "plotly" self.setData(data) self.setDriver() self.pageAnalysis() self.createDataFrame() self.createNewsFile(place) def setData(self, data): self.start_date = data.getStartDate() self.end_date = data.getEndDate() self.symbol = data.getCryptoType() def extract_content(self, driver, count=11): products_content_list_to_return = [] for i in range(1, count): item = {} # DATE EXTRACTION try: date_xpath = "/html/body/div[1]/div[3]/div/div[1]/div[2]/div[" + str(i) + "]/div[2]/div[1]/span/time" date_element = driver.find_elements(By.XPATH, date_xpath)[0].text item['date'] = date_element if (pd.to_datetime(date_element, format='%b %d, %Y') > pd.to_datetime(self.end_date, format='%Y-%m-%d')): continue elif (pd.to_datetime(date_element, format='%b %d, %Y') < pd.to_datetime(self.start_date, format='%Y-%m-%d')): if i == 1: return None break except: item['date'] = "------" # CATEGORY EXTRACTION try: category_xpath = "/html/body/div[1]/div[3]/div/div[1]/div[2]/div[" + str(i) + "]/div[2]/div[1]/a" category_element = driver.find_elements(By.XPATH, category_xpath)[0].text item['category'] = category_element except: item['category'] = "------" # TITLE EXTRACTION try: title_xpath = "/html/body/div[1]/div[3]/div/div[1]/div[2]/div[" + str(i) + "]/div[2]/h3/a" title_element = driver.find_elements(By.XPATH, title_xpath)[0].text item['title'] = title_element except: item['title'] = "------" # DESCRIPTION EXTRACTION try: description_xpath = "/html/body/div[1]/div[3]/div/div[1]/div[2]/div[" + str(i) + "]/div[2]/div[2]" description_element = driver.find_elements(By.XPATH, description_xpath)[0].text item['description'] = description_element except: item['description'] = "------" # URL EXTRACTION try: url_xpath = "/html/body/div[1]/div[3]/div/div[1]/div[2]/div[" + str(i) + "]/div[2]/h3/a" url_element = driver.find_elements(By.XPATH, url_xpath)[0].get_attribute('href') item['url'] = url_element except: item['url'] = "------" print(item) print('\n') print('*****' * 20) print('*****' * 20) print('\n') if item['date'] != "------": products_content_list_to_return.append(item) return products_content_list_to_return def setDriver(self): self.driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) self.driver.get(f'https://news.bitcoin.com/?s={self.symbol}') time.sleep(3) """ service = ChromeService(executable_path=chromedriverPath) self.driver = webdriver.Chrome(service=service) self.driver.get(f'https://news.bitcoin.com/?s={self.symbol}') time.sleep(3) """ def create_url(self, i=2): url = f'https://news.bitcoin.com/page/{str(i)}/?s={self.symbol}' return url def pageAnalysis(self): for i in tqdm(range(1, 2517)): # 2516 try: print(f'PAGE NUMBER: {i}\n') url = self.create_url(i) self.driver.get(url) time.sleep(5) content = self.extract_content(self.driver) if content is None: break self.total_news.append(content) except: print("ERROR") print("ERROR") print("ERROR") print("ERROR") def createDataFrame(self): i = 0 j = 0 k = 0 dictionary_list = [] for i in range(0, len(self.total_news)): for j in range(0, len(self.total_news[i])): dictionary_list.append(self.total_news[i][j]) self.df = pd.DataFrame.from_records(dictionary_list, columns=['date', 'url', 'title', 'description', 'category']) self.df['date'] = pd.to_datetime(self.df['date'], format='%b %d, %Y') def createNewsFile(self, place): pathXlsx = f'Data Files/{self.symbol}/xlsx Files/bitcoin.com_news_url.xlsx' pathCsv = f'Data Files/{self.symbol}/csv Files/bitcoin.com_news_url.csv' if not os.path.exists(pathCsv): self.df.to_csv(pathCsv, index=False, encoding='utf-16') self.df.to_excel(pathXlsx, index=False) return news_df = pd.read_csv(pathCsv, encoding='utf-16') news_df.reset_index(drop=True, inplace=True) self.df['date'] = pd.to_datetime(self.df['date']).dt.date if place == 0: news_df = pd.concat([news_df, self.df], ignore_index=True) else: news_df = pd.concat([self.df, news_df], ignore_index=True) news_df.to_csv(pathCsv, index=False, encoding='utf-16') news_df.to_excel(pathXlsx, index=False)
import 'package:flutter/material.dart'; import '../Includes/widgets/build_screen.dart'; import '../headers.dart'; import '../menu_lateral.dart'; import '../menu_footer.dart'; import '../../../../../Elementos/validaciones_formularios.dart'; //estas dos creo son para las apis que se consumen import 'package:http/http.dart' as http; import 'dart:async'; //Me parece que es para convertir el json import 'dart:convert'; import 'package:json_annotation/json_annotation.dart'; //Paqueteria para sesiones tipo cookies import 'package:shared_preferences/shared_preferences.dart'; import 'package:email_validator/email_validator.dart'; import 'package:mask_text_input_formatter/mask_text_input_formatter.dart'; import 'FinRegMedico30.dart'; import '../PerfilMedico/LoginMed.dart'; import '../RegMedico/RegistroMedOlvidaste.dart'; import '../PerfilMedico/PerfilMedVerificar.dart'; //PAra validar //void main() => runApp(const RegistroMed()); class RegistroMed extends StatefulWidget { const RegistroMed({super.key}); @override State<RegistroMed> createState() => _RegistroMedState(); } class _RegistroMedState extends State<RegistroMed> { @override Widget build(BuildContext context) { return MyCustomFormMedicoRegistro(); // return Scaffold( // appBar: AppBar( // title: const Text('Registro de médico'), // ), // drawer: MenuLateralPage(""), // bottomNavigationBar: MenuFooterPage(), // body: const MyCustomFormMedicoRegistro(), // ); } } // Create a Form widget. class MyCustomFormMedicoRegistro extends StatefulWidget { const MyCustomFormMedicoRegistro({super.key}); @override MyCustomFormMedicoRegistroState createState() { return MyCustomFormMedicoRegistroState(); } } class MyCustomFormMedicoRegistroState extends State<MyCustomFormMedicoRegistro> { var MasccaraCelular = new MaskTextInputFormatter( mask: '## #### ####', filter: {"#": RegExp(r'[0-9]')}); //el fomrKey para formulario final _formKey = GlobalKey<FormState>(); //Los controladores para los input final Correo = TextEditingController(); final Celular = TextEditingController(); final Contrasena = TextEditingController(); final ConfirmarContrasena = TextEditingController(); String CorreoRecibe = ""; String CelularRecibe = ""; String ContrasenaRecibe = ""; String ConfirmarContrasenaRecibe = ""; String email = ""; void Ingresar(Corr, Celu, Cont, ConfCont, AvisoDePrivacidad, TerminosYCondiciones) async { /*print('La información se esta enviando'); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('La información se esta enviando')), );*/ try { /*print('Mandando información'); ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Mandando información')), );*/ var url = Uri.https('fasoluciones.mx', 'api/Medico/Registro'); var response = await http.post(url, body: { 'Correo': Corr, 'Telefono': Celu, 'Contrasena': Cont, 'ConfirmarContrasena': ConfCont, 'AvisoDePrivacidad': "1", 'TerminosYCondiciones': "1", }).timeout(const Duration(seconds: 90)); print(response.body); if (response.body != "0" && response.body != "") { showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text(response.body), ); }); var Respuesta = jsonDecode(response.body); String status = Respuesta['status']; String msg = Respuesta['msg']; if (status == "OK") { int id_medico = Respuesta['id_medico']; /*showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Registrado correctamente'), ); });*/ guardar_datos(id_medico, 'Médico', Corr, Cont, Celu); Navigator.of(context).pushReplacement( MaterialPageRoute(builder: (_) => PerfilMedVerificar())); FocusScope.of(context).unfocus(); } else { //print('Error en el registro'); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text("$msg"), ); }); } } else { //print('Error en el registro'); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text("Error en el registro"), ); }); } } on TimeoutException catch (e) { //print('Tardo muco la conexion'); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('La conexión tardo mucho'), ); }); } on Error catch (e) { //print('http error'); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Error: HTTP://'), ); }); } } //Esto es iun metodo //se usa para guarar dtos es tipo sesiones Future<void> guardar_datos(id_medico, NombreCompletoSession, CorreoSession, ContrasenaSession, CelularSession) async { final prefs = await SharedPreferences.getInstance(); await prefs.setInt('id_medico', id_medico); await prefs.setString('NombreCompletoSession', NombreCompletoSession); await prefs.setString('CorreoSession', CorreoSession); await prefs.setString('ContrasenaSession', ContrasenaSession); await prefs.setString('CelularSession', CelularSession); } bool AvisoDePrivacidad = false; bool TerminosYCondiciones = false; bool passwordObscured = true; bool passwordObscured2 = true; @override Widget build(BuildContext context) { return BuildScreens('Médico', '', '', 'Registro', '', _formulario()); } Widget _formulario() { return Form( key: _formKey, child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ // headerTop('Médico', 'Por favor llena todos los campos'), SubitleCards('Por favor llena todos los campos'), const SizedBox( height: 20, ), _Correo(), _Celular(), _Contrasena(), _ConfirmarContrasena(), CheckboxListTile( controlAffinity: ListTileControlAffinity.leading, title: Text('Aviso de privacidad', style: TextStyle( fontSize: 14, color: const Color.fromARGB(255, 87, 89, 92))), value: AvisoDePrivacidad, onChanged: (value) { //print(value); setState(() { AvisoDePrivacidad = !AvisoDePrivacidad; //print(AvisoDePrivacidad); }); }, ), CheckboxListTile( controlAffinity: ListTileControlAffinity.leading, title: Text('Términos y condiciones', style: TextStyle( fontSize: 14, color: const Color.fromARGB(255, 87, 89, 92))), value: TerminosYCondiciones, onChanged: (value) { setState(() { TerminosYCondiciones = !TerminosYCondiciones; }); }, ), /*SizedBox( height: 20, ),*/ _BotonEnviar(), Container( padding: EdgeInsets.all(15), child: Text( "Al dar clic en crear mi cuenta aceptas los términos y condiciones y el aviso de privacidad de Fasol Soluciones ", textAlign: TextAlign.center, style: TextStyle( fontSize: 12, ), ), ), _BotonIngresar(), //_BotonOlvidaste(), SizedBox( height: 40, ), ]), )); } Widget _Correo() { return Container( padding: EdgeInsets.all(10), child: TextFormField( validator: ObligatorioCorreo, keyboardType: TextInputType.emailAddress, controller: Correo, decoration: InputDecoration( icon: Icon(Icons.email), labelText: 'correo', border: OutlineInputBorder(), isDense: false, contentPadding: EdgeInsets.all(10), hintText: ''), ), ); } Widget _Celular() { return Container( padding: EdgeInsets.all(10), child: TextFormField( inputFormatters: [MasccaraCelular], validator: ObligatorioCelular, keyboardType: TextInputType.phone, controller: Celular, maxLength: 12, decoration: InputDecoration( icon: Icon(Icons.phone), labelText: 'Celular', border: OutlineInputBorder(), isDense: false, contentPadding: EdgeInsets.all(10), hintText: '00 0000 0000', counterText: ''), ), ); } Widget _Contrasena() { return Container( padding: EdgeInsets.all(10), child: TextFormField( validator: ObligatorioContrasena, keyboardType: TextInputType.text, controller: Contrasena, obscureText: passwordObscured, decoration: InputDecoration( icon: Icon(Icons.password), labelText: 'Contraseña', border: OutlineInputBorder(), isDense: false, contentPadding: EdgeInsets.all(10), hintText: '', suffixIcon: IconButton( onPressed: () { setState(() { passwordObscured = !passwordObscured; }); }, icon: Icon( passwordObscured ? Icons.visibility_off : Icons.visibility), ), ), ), ); } Widget _ConfirmarContrasena() { return Container( padding: EdgeInsets.all(10), child: TextFormField( validator: ObligatorioContrasenaConfirmar, keyboardType: TextInputType.text, controller: ConfirmarContrasena, obscureText: passwordObscured2, decoration: InputDecoration( icon: Icon(Icons.password), labelText: 'confirmar contraseña', border: OutlineInputBorder(), isDense: false, contentPadding: EdgeInsets.all(10), hintText: '', suffixIcon: IconButton( onPressed: () { setState(() { passwordObscured2 = !passwordObscured2; }); }, icon: Icon( passwordObscured ? Icons.visibility_off : Icons.visibility), ), ), ), ); } Widget _BotonEnviar() { return Container( width: double.infinity, padding: EdgeInsets.all(10), child: ElevatedButton( onPressed: () { if (_formKey.currentState!.validate()) { CorreoRecibe = Correo.text; CelularRecibe = Celular.text; ContrasenaRecibe = Contrasena.text; ConfirmarContrasenaRecibe = ConfirmarContrasena.text; final bool ValidarCorreo = EmailValidator.validate(CorreoRecibe); var ValidarCorreoFormat = (ValidarCorreo ? 'yes' : 'no'); if (ValidarCorreoFormat == "yes") { if (CorreoRecibe != "" && CelularRecibe != "" && ContrasenaRecibe != "" && ConfirmarContrasenaRecibe != "" && AvisoDePrivacidad == true && TerminosYCondiciones == true) { if (ContrasenaRecibe == ConfirmarContrasenaRecibe) { /*ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Proceando los datos')), );*/ Ingresar( CorreoRecibe, CelularRecibe, ContrasenaRecibe, ConfirmarContrasenaRecibe, AvisoDePrivacidad, TerminosYCondiciones); } else { //print('Error: Las contraseñas no coinciden'); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Error: Las contraseñas no coinciden'), ); }); } } else { //print('Error: Todos los campos son obligatorios'); showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text('Error: Todos los campos son obligatorios'), ); }); } } else { //print('Error: El correo no es valido'); ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Error: El correo no es valido')), ); } } }, child: const Text('Registrarme')), ); } Widget _BotonIngresar() { return Container( width: double.infinity, //padding: EdgeInsets.all(10), child: ListTile( title: new Center( child: new Text( "Ingresar", style: new TextStyle(fontSize: 12.0), )), onTap: () { Navigator.of(context).pop(); Navigator.push( context, MaterialPageRoute(builder: (context) => LoginMed())); }, ), ); } Widget _BotonOlvidaste() { return Container( width: double.infinity, //padding: EdgeInsets.all(10), child: ListTile( title: new Center( child: new Text( "¿Olvidaste tu contraseña?", style: new TextStyle(fontSize: 12.0), )), onTap: () { Navigator.of(context).pop(); Navigator.push(context, MaterialPageRoute(builder: (context) => RegistroMedOlvidaste())); }, ), ); } }
/* ** EPITECH PROJECT, 2024 ** Zappy ** File description: ** Items */ #pragma once #include "irrlicht/irrlicht.h" #include "../interface/AError.hpp" #include <vector> class chessBoard; /** * @brief The Tile class represents a tile in a chessboard. */ class Tile { public: /** * @brief Default constructor for the Tile class. */ Tile(); /** * @brief Constructor for the Tile class. * @param ParentChessBoard A pointer to the chessBoard object that is used as the parent chessboard. * @param tileTexture A pointer to the ITexture object for the tile texture. * @param x The x-coordinate of the tile. * @param y The y-coordinate of the tile. * @param z The z-coordinate of the tile. * @param tileSize The size of the tile. */ Tile(chessBoard *ParentChessBoard, irr::video::ITexture* tileTexture, int x = -1, int y = -1, int z = -1, float tileSize = -1); /** * @brief Destructor for the Tile class. */ ~Tile(); /** * @brief Links the tile to its parent chessboard. * @param ParentChessBoard A pointer to the chessBoard object that is used as the parent chessboard. */ void linkToParent(chessBoard *ParentChessBoard); /** * @brief Initializes the tile. */ void initTile(); /** * @brief Sets the texture of the tile. * @param tileTexture A pointer to the ITexture object for the tile texture. */ void setTexture(irr::video::ITexture* tileTexture); /** * @brief Sets the position of the tile. * @param x The x-coordinate of the tile. * @param y The y-coordinate of the tile. * @param z The z-coordinate of the tile. */ void setPos(int x = -1, int y = -1, int z = -1); /** * @brief Sets the size of the tile. * @param tileSize The size of the tile. */ void setTileSize(float tileSize = -1); /** * @brief Creates the tile. */ void createTile(); /** * @brief Sets the inventory of the tile. * @param food The amount of food in the inventory. * @param linemate The amount of linemate in the inventory. * @param deraumere The amount of deraumere in the inventory. * @param sibur The amount of sibur in the inventory. * @param mendiane The amount of mendiane in the inventory. * @param phiras The amount of phiras in the inventory. * @param thystame The amount of thystame in the inventory. */ void setInventory(int food, int linemate, int deraumere, int sibur, int mendiane, int phiras, int thystame); /** * @brief Prints the inventory of the tile. */ void printInventory(); /** * @brief Sets the player on the tile. * @param player The player on the tile. */ void setPlayer(int player); /** * @brief Sets the egg on the tile. * @param egg The egg on the tile. */ void setEgg(int egg); /** * @brief Gets the node of the tile. * @return The node of the tile. */ irr::scene::ISceneNode *getNode(); /** * @brief Gets the player on the tile. * @return The player on the tile. */ int getPlayer(); /** * @brief Gets the egg on the tile. * @return The egg on the tile. */ int getEgg(); int getPositionX(); int getPositionY(); int getPositionZ(); std::vector<int> getInventory(); /** * @brief Gets the parent chessboard of the tile. * @return The parent chessboard of the tile. */ chessBoard *getParentChessBoard(); class UnsetParentChessboard : public AError { public: /** * @brief Display an error message. * @param message The error message to display. Defaults to "given parent chessboard is null". * * occured when the parent chessboard is null and you try to initialise the tile by calling initTile() or setting the parent chessboard . */ UnsetParentChessboard() : AError("given parent chessboard is null") {} }; class UnsetTileTexture : public AError { public: /** * @brief Display an error message. * @param message The error message to display. Defaults to "given tile texture is null". * * occured when the tile texture is null and you try to set the texture by calling setTexture(). */ UnsetTileTexture() : AError("given tile texture is null") {} }; class UnsetIrrlichVar : public AError { public: /** * @brief Display an error message. * @param message The error message to display. Defaults to "One of the Value that link tiles to irrlich isn't correctly setted". * * occured when the irrlicht device, driver or scene manager is null and you try to create the tile. */ UnsetIrrlichVar() : AError("One of the Value that link tiles to irrlich isn't correctly setted") {} }; class UnsetPos : public AError { public: /** * @brief Display an error message. * @param message The error message to display. Defaults to "One coordinate of the tile isn't correctly setted". * * occured when the x, y or z coordinate is not setted and you try to create the tile. */ UnsetPos() : AError("One coordinate of the tile isn't correctly setted") {} }; class UnsetTileSize : public AError { public: /** * @brief Display an error message. * @param message The error message to display. Defaults to "Tile size isn't correctly setted". * * occured when the tile size is not setted and you try to create the tile. */ UnsetTileSize() : AError("Tile size isn't correctly setted") {} }; class UnsetNode : public AError { public: /** * @brief Display an error message. * @param message The error message to display. Defaults to "Node isn't correctly setted". * * occured when the node is null and you try to create the tile. */ UnsetNode() : AError("Node isn't correctly setted") {} }; private: int _food; ///< The amount of food in the tile's inventory. int _linemate; ///< The amount of linemate in the tile's inventory. int _deraumere; ///< The amount of deraumere in the tile's inventory. int _sibur; ///< The amount of sibur in the tile's inventory. int _mendiane; ///< The amount of mendiane in the tile's inventory. int _phiras; ///< The amount of phiras in the tile's inventory. int _thystame; ///< The amount of thystame in the tile's inventory. int _player; ///< The player on the tile. int _egg; ///< The egg on the tile. int _X; ///< The x-coordinate of the tile. int _Y; ///< The y-coordinate of the tile. int _Z; ///< The z-coordinate of the tile. float _TileSize; ///< The size of the tile. chessBoard *_ParentChessBoard; ///< A pointer to the chessBoard object that is used as the parent chessboard. irr::video::ITexture *_TileTexture; ///< A pointer to the ITexture object for the tile texture. irr::scene::ISceneNode *_Node; ///< A pointer to the ISceneNode object for scene management. irr::scene::ISceneManager *_SceneManager; ///< A pointer to the ISceneManager object for scene management. irr::video::IVideoDriver *_Driver; ///< A pointer to the IVideoDriver object for video rendering. irr::IrrlichtDevice *_Device; ///< A pointer to the IrrlichtDevice object for device management. };
from decimal import Decimal, getcontext import time import pathlib class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKCYAN = '\033[96m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' print( f'''{bcolors.HEADER}Operation modes: {bcolors.OKBLUE} (1 -> Calculation Time) (2 -> Console) (3 -> Write To File){bcolors.ENDC}''' ) mode = input(f'{bcolors.HEADER}Selected mode: {bcolors.OKBLUE} ') if mode not in ['1', '2', '3']: print(f'{bcolors.FAIL}Incorrect Operating Mode!{bcolors.ENDC}') else: if mode == '3': file_name = input(f'{bcolors.HEADER}File Name (pi.txt): {bcolors.ENDC}') file_name = file_name.strip('.txt') number = input( f'{bcolors.HEADER}Number of numbers after the comma: {bcolors.ENDC}') precision = input(f'{bcolors.HEADER}Precision (500): {bcolors.ENDC}') if number != '': if precision == '' or int(precision) > 500: precision = 500 getcontext().prec = int(number) init_time = int(round(time.time())) pi = sum(1/Decimal(16)**k * (Decimal(4)/(8*k+1) - Decimal(2)/(8*k+4) - Decimal(1)/(8*k+5) - Decimal(1)/(8*k+6)) for k in range(int(precision))) if mode == '1': print( f'{bcolors.OKGREEN}Calculation Time: {int(round(time.time())) - init_time} Segundos!{bcolors.ENDC}') elif mode == '2': print(f'{bcolors.OKCYAN}{pi}{bcolors.ENDC}') elif mode == '3': if file_name != '': open(file_name + '.txt', 'w').write(str(pi)) print( f'{bcolors.WARNING}Created file path: {pathlib.Path(__file__).parent.absolute()}\{file_name}.txt {bcolors.ENDC}') else: open('pi.txt', 'w').write(str(pi)) print( f'{bcolors.WARNING}Created file path: {pathlib.Path(__file__).parent.absolute()}\pi.txt {bcolors.ENDC}') print(f'{bcolors.OKGREEN}Success! Saved to File.{bcolors.ENDC}') else: print( f'{bcolors.FAIL}Number of numbers after the comma undefined!{bcolors.ENDC}')
package tech.dut.fasto.web.rest.admin.image.service; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import tech.dut.fasto.common.domain.Voucher; import tech.dut.fasto.common.domain.VoucherImage; import tech.dut.fasto.common.domain.enumeration.VoucherProvider; import tech.dut.fasto.common.repository.VoucherImageRepository; import tech.dut.fasto.common.repository.VoucherRepository; import tech.dut.fasto.common.service.impl.MessageService; import tech.dut.fasto.errors.FastoAlertException; import tech.dut.fasto.web.rest.admin.image.dto.request.AdminImageVoucherRequestDto; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Service @RequiredArgsConstructor public class AdminImageServiceImpl implements AdminImageService { private final VoucherRepository voucherRepository; private final VoucherImageRepository voucherImageRepository; private final MessageService messageService; @Override @Transactional(rollbackFor = FastoAlertException.class) public void createImageForVoucher(AdminImageVoucherRequestDto adminImageVoucherRequestDto) { Optional<Voucher> voucherOptional = voucherRepository.findByIdAndUserType(adminImageVoucherRequestDto.getId(), VoucherProvider.ADMIN); if (voucherOptional.isPresent() && !adminImageVoucherRequestDto.getImages().isEmpty()) { Voucher voucher = voucherOptional.get(); List<VoucherImage> voucherImageList = new ArrayList<>(); for(String item : adminImageVoucherRequestDto.getImages()){ VoucherImage voucherImage = new VoucherImage(); voucherImage.setImage(item); voucherImage.setVoucher(voucher); voucherImageList.add(voucherImage); } voucherImageRepository.saveAll(voucherImageList); } else{ throw new FastoAlertException(this.messageService.getMessage("error.code.voucher.create.image.failed"), this.messageService.getMessage("error.voucher.not.found")); } } @Override @Transactional(readOnly = true) public List<String> getImageForVoucher(Long id) { return voucherImageRepository.findAllByVoucherId(id).stream().map(VoucherImage::getImage).toList(); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <title>Web App</title> <link rel="icon" type="image/x-icon" href="static/assets/favicon.ico" /> <!-- Font Awesome icons (free version)--> <script src="https://use.fontawesome.com/releases/v5.15.3/js/all.js" crossorigin="anonymous"></script> <!-- Google fonts--> <link href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css" /> <!-- Core theme CSS (includes Bootstrap)--> <link href="static/css/styles.css" rel="stylesheet" /> <!-- Main Style Css --> <link rel="stylesheet" href="static/css2/style.css"/> <style> /* Add custom styles for sliders and alignment */ .input-slider-container { width: 80%; /* Adjust the width as needed */ margin: 0 auto; /* Center the sliders */ } .input-slider-label { display: flex; justify-content: space-between; margin-bottom: 10px; } .input-slider { width: 100%; } .slider-value { font-weight: bold; } </style> </head> <body> <!-- Navigation--> <nav class="navbar navbar-expand-lg navbar-light" id="mainNav"> <!-- Replace with your actual navigation content --> <div class="container"> <a class="navbar-brand" href="#">Muru T.</a> <!-- ... (other navigation elements) ... --> </div> </nav> <!-- Page Header--> <header class="masthead" style="background-image: url('static/assets/img/wine.jpg')"> <!-- Replace with your actual header content --> <div class="container"> <div class="row"> <div class="col-lg-8 col-md-10 mx-auto"> <div class="site-heading"> <h1>Engine Quality</h1> <span class="subheading">Sample Engine Logistics</span> </div> </div> </div> </div> </header> <!-- Main Content--> <div class="container px-4 px-lg-5"> <div class="page-content"> <div class="form-v9-content" style="background-image: url('static/assets/img/form-v9.jpg')"> <form class="form-detail" action="/predict" method="post"> <h2>Please Fill The Information</h2> <div class="input-slider-container"> <div class="input-slider-label"> <label for="engine_rpm">Engine RPM: <span class="slider-value" id="engine_rpm_value">50</span></label> </div> <input type="range" name="engine_rpm" id="engine_rpm" min="50" max="2500" step="1" class="input-slider" required> </div> <div class="input-slider-container"> <div class="input-slider-label"> <label for="lub_oil_pressure">Lub oil pressure: <span class="slider-value" id="lub_oil_pressure_value">0</span></label> </div> <input type="range" name="lub_oil_pressure" id="lub_oil_pressure" min="0" max="10" step="0.1" class="input-slider" required> </div> <div class="input-slider-container"> <div class="input-slider-label"> <label for="fuel_pressure">Fuel pressure: <span class="slider-value" id="fuel_pressure_value">0</span></label> </div> <input type="range" name="fuel_pressure" id="fuel_pressure" min="0" max="30" step="0.1" class="input-slider" required> </div> <div class="input-slider-container"> <div class="input-slider-label"> <label for="coolant_pressure">Coolant pressure: <span class="slider-value" id="coolant_pressure_value">0</span></label> </div> <input type="range" name="coolant_pressure" id="coolant_pressure" min="0" max="10" step="0.1" class="input-slider" required> </div> <div class="input-slider-container"> <div class="input-slider-label"> <label for="lub_oil_temp">lub oil temp: <span class="slider-value" id="lub_oil_temp_value">60</span></label> </div> <input type="range" name="lub_oil_temp" id="lub_oil_temp" min="60" max="100" step="0.2" class="input-slider" required> </div> <div class="input-slider-container"> <div class="input-slider-label"> <label for="coolant_temp">Coolant temp: <span class="slider-value" id="coolant_temp_value">60</span></label> </div> <input type="range" name="coolant_temp" id="coolant_temp" min="60" max="150" step="0.2" class="input-slider" required> </div> <!-- Repeat the similar structure for other sliders --> <div class="form-row-last"> <input type="submit" name="register" class="register" value="Predict"> </div> </form> </div> </div> </div> <!-- Footer--> <footer class="border-top"> <!-- Replace with your actual footer content --> <div class="container"> <div class="row"> <div class="col-lg-8 col-md-10 mx-auto"> <ul class="list-inline text-center"> <li class="list-inline-item"> <a href="#"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x"></i> <i class="fab fa-linkedin fa-stack-1x fa-inverse"></i> </span> </a> </li> <li class="list-inline-item"> <a href="#"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x"></i> <i class="fab fa-youtube fa-stack-1x fa-inverse"></i> </span> </a> </li> <li class="list-inline-item"> <a href="#"> <span class="fa-stack fa-lg"> <i class="fas fa-circle fa-stack-2x"></i> <i class="fab fa-github fa-stack-1x fa-inverse"></i> </span> </a> </li> </ul> </div> </div> </div> </footer> <!-- Bootstrap core JS--> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/js/bootstrap.bundle.min.js"></script> <!-- Core theme JS--> <script src="static/js/scripts.js"></script> <script> // Display range slider values const sliders = document.querySelectorAll(".input-slider"); sliders.forEach(slider => { const valueSpan = slider.previousElementSibling.querySelector(".slider-value"); slider.addEventListener("input", () => { valueSpan.textContent = slider.value; }); }); </script> </body> </html>
<?php /** * This is the model class for table "carta_nacional". * * The followings are the available columns in table 'carta_nacional': * @property integer $id * @property string $Nombre * @property integer $Nivel1 * @property integer $Nivel2 * @property string $fecha_creacion * * The followings are the available model relations: * @property Peces[] $peces */ class CartaNacional extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return CartaNacional the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'carta_nacional'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('Nombre, Nivel1, Nivel2, fecha_creacion', 'required'), array('Nivel1, Nivel2', 'numerical', 'integerOnly'=>true), array('Nombre', 'length', 'max'=>45), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('id, Nombre, Nivel1, Nivel2, fecha_creacion', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'peces' => array(self::MANY_MANY, 'Peces', 'pez_carta_nacional(carta_nacional_id, peces_especie_id)'), 'carta' => array(self::MANY_MANY, 'PezCartaNacional', 'pez_carta_nacional(carta_nacional_id, peces_especie_id)'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'Nombre' => 'Nombre', 'Nivel1' => 'Nivel1', 'Nivel2' => 'Nivel2', 'fecha_creacion' => 'Fecha Creacion', ); } public static function join() { return ' LEFT JOIN pez_carta_nacional pcn ON pcn.peces_especie_id=p.especie_id LEFT JOIN carta_nacional cn ON cn.id=pcn.carta_nacional_id '; } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('Nombre',$this->Nombre,true); $criteria->compare('Nivel1',$this->Nivel1); $criteria->compare('Nivel2',$this->Nivel2); $criteria->compare('fecha_creacion',$this->fecha_creacion,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } }
{ stdlib }: let inherit (stdlib.lists) length replicate; inherit (stdlib.strings) concatStringsSep replaceStrings splitString; in rec { # String -> [String] lines = splitString "\n"; # String -> (String -> String) -> String -> String splitMap = splitter: f: string: concatStringsSep splitter (map f (splitString splitter string)); # (String -> String) -> String -> String mapLines = splitMap "\n"; # String -> Int -> String repeatString = string: times: concatStringsSep "" (replicate times string); # Replaces any occurences in a list of strings with a single replacement. # NOTE: This function does not support regex patterns. # # [String] -> String -> String -> String replaceStrings' = from: to: replaceStrings from (replicate (length from) to); # [String] -> String unlines = concatStringsSep "\n"; # [String] -> String unwords = concatStringsSep " "; # String -> [String] words = builtins.split "\\s+"; # String -> String -> String -> String wrap = start: end: string: start + string + end; # String -> String -> String wrap' = wrapper: wrap wrapper wrapper; }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateGrupoDivulgacaoDocumentoTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('grupo_divulgacao_documento', function (Blueprint $table) { $table->increments('id'); $table->integer('documento_id')->unsigned(); $table->foreign('documento_id')->references('id')->on('documento'); $table->integer('usuario_id')->unsigned(); $table->foreign('usuario_id')->references('id')->on('users'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('grupo_divulgacao_documento'); } }
Assignment 2(C)Angular 1.Commands in Terminal npm --version npm install -g @angular/cli@latest ng new part c y css partc/src = >app.component.css >app.component.html >app.component.ts cd part c ng serve y 2.app.component.css input{ width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; box-sizing: border-box; } button{ background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; } 3.app.component.html <h1>{{title}}</h1> <input type="text" #name placeholder="Enter Your Name" name="name"> <br> <input type="text" #address placeholder="Enter Your Address" name="address"> <br> <input type="text" #contact placeholder="Enter Your Contact" name="contact"> <br> <input type="email" #email placeholder="Enter Your email" name="email"> <br> <input type="password" #password placeholder="Enter Your Password" name="password"> <br> <button (click)="getValue(name.value, address.value, contact.value, email.value)">Register</button> <h1>Your Registered Data</h1> <br> <p>Name:{{displayname}}</p> <p>Address:{{displayaddress}}</p> <p>Contact:{{displaycontact}}</p> <p>Email:{{displayemail}}</p> 4.app.component.ts import { Component } from '@angular/core'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], templateUrl: './app.component.html', styleUrl: './app.component.css' }) export class AppComponent { title = 'Registration Form'; displayname = ''; displayaddress = ''; displayemail = ''; displaycontact = ''; getValue(name:string, address:string, email:string, contact:string){ this.displayname = name; this.displayaddress = address; this.displayemail = email; this.displaycontact = contact; } }
<!-- FILEPATH: /c:/Users/drvel/Documents/Key/Study Material/Semester 9/Cloud/WebDevFinalExam-master/WebDevFinalExam-master/views/dashboard.ejs --> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dashboard</title> <!-- Bootstrap CSS --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link rel="stylesheet" href="/styles/dashboard.css"> </head> <body> <!-- Navigation bar --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="navbar-nav"> <a class="nav-item nav-link" href="/dashboard">Dashboard</a> <a class="nav-item nav-link" href="/login-history">Login History</a> <button id="Log-out" class="btn btn-danger ml-auto">Log Out</button> </div> </nav> <div class="container"> <h1 class="text-center text-orange">Dashboard</h1> <!-- Dashboard image --> <div class="image-container text-center"> <img src="/images/exam.png" alt="Dashboard Image" style="width: 300px;"> </div> <div class="row"> <div class="col-md-6"> <h3 class="text-left text-blue">Add Department</h3> <!-- Form for adding a department --> <form id="add-department-form" class="mb-4"> <input type="text" id="department-name" class="form-control mb-2" placeholder="Department Name" required> <button type="submit" class="btn btn-primary">Add Department</button> </form> <!-- Table for displaying departments --> <table id="departments-table" class="table"> <thead> <tr> <th>Department ID</th> <th>Department Name</th> </tr> </thead> <tbody> </tbody> </table> </div> <div class="col-md-6"> <h3 class="text-left text-blue">Add User</h3> <!-- Form for adding a user --> <form id="add-user-form" class="mb-4"> <input type="text" id="username" class="form-control mb-2" placeholder="Username" required> <input type="password" id="password" class="form-control mb-2" placeholder="Password" required> <input type="text" id="department-id" class="form-control mb-2" placeholder="Department ID" required> <button type="submit" class="btn btn-primary">Add User</button> </form> <!-- Table for displaying users --> <table id="users-table" class="table"> <thead> <tr> <th>Username</th> <th>Password</th> <th>Department</th> <th>Action</th> </tr> </thead> <tbody> <!-- User rows with delete button will be added here --> </tbody> </table> </div> </div> </div> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script> // jQuery document ready function $(document).ready(function() { // AJAX for adding a department $('#add-department-form').on('submit', function(e) { e.preventDefault(); var departmentName = $('#department-name').val(); $.ajax({ url: '/api/add_department', type: 'POST', contentType: 'application/json', data: JSON.stringify({ name: departmentName }), success: function(response) { if (response) { // Update the departments table $('#departments-table').append('<tr><td>' + departmentName + '</td></tr>'); $('#department-name').val(''); // Clear the input field } else { alert('Error happened. Please try again later'); } }, error: function() { alert('Error happened. Please try again later'); } }); }); // AJAX for adding a user $('#add-user-form').on('submit', function(e) { e.preventDefault(); var username = $('#username').val(); var password = $('#password').val(); var departmentId = $('#department-id').val(); $.ajax({ url: '/api/adduser', type: 'POST', contentType: 'application/json', data: JSON.stringify({ username: username, password: password, departmentId: departmentId }), success: function(response) { if (response) { // Update the users table $('#users-table').append('<tr><td>' + username + '</td><td>' + departmentId + '</td><td><button class="btn btn-danger delete-user-btn" data-username="' + username + '">Delete</button></td></tr>'); $('#username, #password, #department-id').val(''); // Clear input fields } else { alert('Error happened. Please try again later'); } }, error: function() { alert('Error happened. Please try again later'); } }); }); // AJAX for deleting a user $('#users-table').on('click', '.delete-user-btn', function() { var username = $(this).data('username'); $.ajax({ url: '/api/deleteuser', type: 'POST', contentType: 'application/json', data: JSON.stringify({ username: username }), success: function(response) { if (response) { $('button[data-username="' + username + '"]').closest('tr').remove(); } else { alert('Error happened. Please try again later'); } }, error: function() { alert('Error happened. Please try again later'); } }); }); // AJAX for signing out $('#sign-out').on('click', function() { $.ajax({ url: '/api/logout', type: 'POST', success: function(response) { if (response) { window.location.href = '/'; } else { alert('Logout error'); } }, error: function() { alert('Logout error'); } }); }); }); </script> </body> </html>
import { createSlice, EntityState, PayloadAction } from "@reduxjs/toolkit"; import { fetchCases } from "./caseThunks"; import { caseAdapter, sliceName } from "./caseConstants"; import { fetchState } from "../types"; import { CaseBase, CaseSummary } from "./types"; import { ConsumePartResponse } from "../parts/types"; import { resetAuthentication } from "../auth/authSlice"; interface CurrentCaseSummaries { caseSummaries: EntityState<CaseSummary>; } interface CaseFilters { showAssigned: boolean; showCommitted: boolean; showEnroute: boolean; showArrived: boolean; showComplete: boolean; showHold: boolean; showCity: string; search: string; } type StateShape = CurrentCaseSummaries & { caseFilters: CaseFilters } & { fetchCaseState: fetchState; }; export const initialFilterState: CaseFilters = { showAssigned: true, showCommitted: true, showEnroute: true, showArrived: true, showComplete: false, showHold: true, showCity: "", search: "", }; let initialState: StateShape = { caseSummaries: caseAdapter.getInitialState(), caseFilters: initialFilterState, fetchCaseState: { loading: false, error: "", }, }; export const caseSlice = createSlice({ name: sliceName, initialState, reducers: { upsertCaseSummary(state, action: PayloadAction<CaseBase>) { caseAdapter.upsertOne(state.caseSummaries, action.payload); }, replaceCaseSummaries(state, action: PayloadAction<CaseBase[]>) { caseAdapter.setAll(state.caseSummaries, action.payload); }, deleteCaseSummary(state, action: PayloadAction<string>) { caseAdapter.removeOne(state.caseSummaries, action.payload); }, updateFilters(state, action: PayloadAction<CaseFilters>) { state.caseFilters = action.payload; }, updateCaseActivities(state, action: PayloadAction<ConsumePartResponse>) { state.caseSummaries.entities[action.payload.Id].Activities = action.payload.Activities; }, }, extraReducers: (builder) => { builder .addCase(fetchCases.pending, (state, action) => { state.fetchCaseState.loading = true; state.fetchCaseState.error = ""; }) .addCase(fetchCases.fulfilled, (state, action) => { state.fetchCaseState.loading = false; }) .addCase(fetchCases.rejected, (state, action) => { state.fetchCaseState.loading = false; state.fetchCaseState.error = action.error.message; }) .addCase(resetAuthentication, (state, action) => { state.caseFilters = initialFilterState; caseAdapter.removeAll(state.caseSummaries); }); }, }); export const { replaceCaseSummaries, updateFilters, upsertCaseSummary, deleteCaseSummary, updateCaseActivities, } = caseSlice.actions; export default caseSlice.reducer;
// US_13 import React, { useContext, useEffect } from "react"; import { useLocation, useNavigate } from "react-router-dom"; import headerContext from "../../contexts/headerContext"; import userContext from "../../contexts/userContext"; import Design from "../../Design"; import VenueService from "../../Services/VenueService"; function ConfirmPaymentComponent() { const navigate = useNavigate(); const headerC = useContext(headerContext) const userC = useContext(userContext) const location = useLocation() useEffect(()=>{ if (headerC.state.userType !== "customer") navigate("/customerLogin") },[]) async function confirmPayment(event) { event.preventDefault() // alert("Accept Booking") var newPaymentResponse = { "requestId": location.state.requestId, "requestedAmount": location.state.requestedAmount, "bookingId": location.state.bookingId, "bookedFrom": location.state.bookedFrom, "bookedTo": location.state.bookedTo, "bookingStatus": "accepted", "customerId": location.state.customerId, "venueId": location.state.venueId, "venueName": location.state.venueName, "venueLocation": location.state.venueLocation, "capacity": location.state.capacity, "banquet": location.state.banquet, "dining": location.state.dining, "parking": location.state.parking, "dealerId": location.state.dealerId, "customerFirstName": userC.state.firstName, "customerLastName": userC.state.lastName } // console.log("new request payment in req pay ",newPaymentResponse); var response = await VenueService.savePaymentResponse(headerC.state.jwtToken, userC.state.userId, newPaymentResponse) // console.log("Response in req pay ",response); if (response != "") { alert("Venue booked Successfully!") navigate("/searchVenue") } else { alert("Payment Failed") } } async function declinePaymentRequest(){ var response = VenueService.deletePaymentRequest(headerC.state.jwtToken, userC.state.userId, location.state.requestId) if (response != "") { alert("Payment Request Declined") navigate("/searchVenue") } else { alert("Decline Failed") } } return ( <> <div className="app-background"> <form onSubmit={confirmPayment}> <div className="inner-box"> <span className="dealer-login-span-header">Confirm Payment</span> <div className='dealer-registration-input-row'> <div> <span className="dealer-login-span-input">Venue Name</span> <input type="text" id="dealer-registration-firstname" className="dealer-login-input-field" value={location && location.state && location.state.venueName} readOnly></input> </div> <div> <span className="dealer-login-span-input">Requested from</span> <input type="date" id="dealer-registration-dob" className="dealer-login-input-field" style={{ paddingRight: "1vw" }} value={location && location.state && location.state.bookedFrom} readOnly></input> </div> <div> <span className="dealer-login-span-input">Requested to</span> <input type="date" id="dealer-registration-dob" className="dealer-login-input-field" style={{ paddingRight: "1vw" }} value={location && location.state && location.state.bookedTo} readOnly></input> </div> </div> <div className='dealer-registration-input-row'> <div> <span className="dealer-login-span-input">Amount</span> <input type="number" id="dealer-registration-lastname" className="dealer-login-input-field" placeholder='Enter last name' value={location && location.state && location.state.requestedAmount} readOnly></input> </div> <div> <span className="dealer-login-span-input"> Requested amenities </span> <div> <span className="venue-registration-input-checkbox-label" style={{ display: location && location.state && location.state.banquet == true? "inline-block" : "None"}}>Banquet</span> <span className="venue-registration-input-checkbox-label" style={{ display: location && location.state && location.state.dining == true? "inline-block" : "None"}}>Dining</span> <span className="venue-registration-input-checkbox-label" style={{ display: location && location.state && location.state.parking == true? "inline-block" : "None"}}>Parking</span> </div> </div> </div> <div className="dealer-registration-input-row"> <button className='btn btn-outline-light btn-lg dealer-login-button'>Confirm &amp; Pay</button> <button type="button" className='btn btn-outline-light btn-lg dealer-login-button' onClick={declinePaymentRequest}>Decline</button> </div> </div> </form> </div> </> ); } export default ConfirmPaymentComponent;
import { Box, Heading, Flex, Code, UnorderedList, ListItem, Link, Text, Image, } from '@chakra-ui/react'; import { FC, useMemo } from 'react'; import { EffectCards } from 'swiper'; import { Swiper, SwiperSlide } from 'swiper/react'; import { Project } from '@typings/project'; // eslint-disable-next-line import/no-unresolved import 'swiper/css'; // eslint-disable-next-line import/no-unresolved import 'swiper/css/effect-cards'; interface ProjectRenderProps { data: Project; } const ProjectRender: FC<ProjectRenderProps> = ({ data, }: ProjectRenderProps) => { const { isTeam, summary, title, whatILean, deploy, description, gitLink, images, myRole, useSkills, isCompanyProject, }: Project = useMemo(() => data, [data]); return ( <Box> <Heading>{title}</Heading> {!isCompanyProject && ( <Heading mt="2" fontSize="xl" as="p">{`${ isTeam ? '팀' : '개인' }프로젝트`}</Heading> )} {useSkills && ( <Box> <Box alignItems="center" my={4}> <Text>사용 언어 및 라이브러리</Text> </Box> <Box> <Flex flexWrap="wrap" rowGap="2"> <Text mr="2">Front: </Text> {useSkills.front.map((frontSkill) => ( <Code key={frontSkill} mr="2"> {frontSkill} </Code> ))} </Flex> </Box> {useSkills.back && ( <Box mt="2"> <Flex flexWrap="wrap" rowGap="2"> <Text mr="2">Back: </Text> {useSkills.back.map((backSkill) => ( <Code key={backSkill} mr="2"> {backSkill} </Code> ))} </Flex> </Box> )} </Box> )} <Flex mt="2" flexDirection="column"> <Flex> <Text mr="2">배포여부: </Text> <Text>{deploy ? 'O' : 'X'}</Text> </Flex> {deploy && ( <Flex mt="2"> <Text mr="2">배포링크:</Text> <Link as="a" target="_blank" rel="noreferrer" href={deploy.link}> {deploy.link} </Link> </Flex> )} </Flex> {!isCompanyProject && ( <Flex mt="2"> <Text mr="2">Git: </Text> <Link as="a" target="_blank" rel="noreferrer" href={gitLink}> {gitLink} </Link> </Flex> )} <Flex mt="4" flexDirection="column"> <Heading fontSize="xl">summary</Heading> <Text mt="2">{summary}</Text> </Flex> {description && ( <Flex mt="4" flexDirection="column"> <Heading fontSize="lg">description</Heading> <Text mt="2">{description}</Text> </Flex> )} {myRole && myRole.length > 0 && ( <Box mt="4"> <Heading fontSize="xl">My Role</Heading> <UnorderedList> {myRole.map((role, index) => ( <ListItem mt="2" key={index}> {role} </ListItem> ))} </UnorderedList> </Box> )} <Heading mt="4" fontSize="xl"> Learned </Heading> <UnorderedList mt="2"> {whatILean.map((learn, index) => ( <ListItem mt="2" key={index}> <Text>{learn}</Text> </ListItem> ))} </UnorderedList> {images && images.length > 0 && ( <Box> <Heading mt="4" mb="4" fontSize="xl"> Images </Heading> <Swiper modules={[EffectCards]} grabCursor effect="cards" cardsEffect={{ slideShadows: true }} > {images.map((src, index) => ( <SwiperSlide key={index}> <Box w="100%" borderRadius="24px" textAlign="center" border="2px" pb="100%" position="relative" overflow="hidden" bg="#000" > <Image position="absolute" src={src} alt={src} w="100%" h="100%" objectFit="contain" /> </Box> </SwiperSlide> ))} </Swiper> </Box> )} </Box> ); }; export default ProjectRender;
<?php /** * Sie5Sdk PHP SDK for Sie5 export/import format * based on the Sie5 (http://www.sie.se/sie5.xsd) schema * * This file is a part of Sie5Sdk. * * @author Kjell-Inge Gustafsson, kigkonsult <ical@kigkonsult.se> * @copyright 2019-2021 Kjell-Inge Gustafsson, kigkonsult, All rights reserved * @link https://kigkonsult.se * @license Subject matter of licence is the software Sie5Sdk. * The above copyright, link and package notices, this licence * notice shall be included in all copies or substantial portions * of the Sie5Sdk. * * Sie5Sdk is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * Sie5Sdk is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Sie5Sdk. If not, see <https://www.gnu.org/licenses/>. */ declare( strict_types = 1 ); namespace Kigkonsult\Sie5Sdk\XMLParse; use Exception; use Kigkonsult\DsigSdk\XMLParse\SignatureTypeParser; use Kigkonsult\Sie5Sdk\Dto\Sie; use XMLReader; use function sprintf; class RootSieParser extends Sie5ParserBase { /** * Parse * * @return Sie * @throws Exception * */ public function parse() : Sie { $sie = Sie::factory()->setXMLattributes( $this->reader ); $this->logger->debug( sprintf( self::$FMTstartNode, __METHOD__, self::$nodeTypes[$this->reader->nodeType], $this->reader->localName ) ); if( $this->reader->hasAttributes ) { while( $this->reader->moveToNextAttribute()) { $this->logger->debug( sprintf( self::$FMTattrFound, __METHOD__, $this->reader->name, $this->reader->value ) ); $sie->setXMLattribute( $this->reader->name, $this->reader->value ); } $this->reader->moveToElement(); } // end if if( $this->reader->isEmptyElement ) { return $sie; } $headElement = $this->reader->localName; $customerInvoicesTypeParser = new CustomerInvoicesTypeParser( $this->reader ); $supplierInvoicesTypeParser = new SupplierInvoicesTypeParser( $this->reader ); $fixedAssetsTypeParser = new FixedAssetsTypeParser( $this->reader ); $generalSubdividedAccountTypeParser = new GeneralSubdividedAccountTypeParser( $this->reader ); $journalTypeParser = new JournalTypeParser( $this->reader ); while( @$this->reader->read()) { if( XMLReader::SIGNIFICANT_WHITESPACE !== $this->reader->nodeType ) { $this->logger->debug( sprintf( self::$FMTreadNode, __METHOD__, self::$nodeTypes[$this->reader->nodeType], $this->reader->localName ) ); } switch( true ) { case ( XMLReader::END_ELEMENT === $this->reader->nodeType ) : if( $headElement === $this->reader->localName ) { break 2; } break; case ( XMLReader::ELEMENT !== $this->reader->nodeType ) : break; case ( self::FILEINFO === $this->reader->localName ) : // occurs 1 $sie->setFileInfo( FileInfoTypeParser::factory( $this->reader )->parse()); break; case ( self::ACCOUNTS === $this->reader->localName ) : // occurs 1 $sie->setAccounts( AccountsTypeParser::factory( $this->reader )->parse()); break; case ( self::DIMENSIONS === $this->reader->localName ) : // occurs 0-1 $sie->setDimensions( DimensionsTypeParser::factory( $this->reader )->parse()); break; case ( self::CUSTOMERINVOICES === $this->reader->localName ) : // occurs 0-unbounded $sie->addCustomerInvoices( $customerInvoicesTypeParser->parse()); break; case ( self::SUPPLIERINVOICES === $this->reader->localName ) : // occurs 0-unbounded $sie->addSupplierInvoices( $supplierInvoicesTypeParser->parse()); break; case ( self::FIXEDASSETS === $this->reader->localName ) : // occurs 0-unbounded $sie->addFixedAsset( $fixedAssetsTypeParser->parse()); break; case ( self::GENERALSUBDIVIDEDACCOUNT === $this->reader->localName ) : // occurs 0-unbounded $sie->addGeneralSubdividedAccount( $generalSubdividedAccountTypeParser->parse()); break; case ( self::CUSTOMERS === $this->reader->localName ) : // occurs 0-1 $sie->setCustomers( CustomersTypeParser::factory( $this->reader )->parse()); break; case ( self::SUPPLIERS === $this->reader->localName ) : // occurs 0-1 $sie->setSuppliers( SuppliersTypeParser::factory( $this->reader )->parse()); break; case ( self::ACCOUNTAGGREGATIONS === $this->reader->localName ) : // occurs 0-1 $sie->setAccountAggregations( AccountAggregationsTypeParser::factory( $this->reader )->parse()); break; case ( self::JOURNAL === $this->reader->localName ) : // occurs 0-unbounded $sie->addJournal( $journalTypeParser->parse()); break; case ( self::DOCUMENTS === $this->reader->localName ) : // occurs 0-1 $sie->setDocuments( DocumentsTypeParser::factory( $this->reader )->parse()); break; case ( self::SIGNATURE === $this->reader->localName ) : // occurs 1 $sie->setSignature( SignatureTypeParser::factory( $this->reader )->parse()); break; } // end switch } // end while return $sie; } }
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AboutComponent } from './about/about.component'; import { ManifestSingleComponent } from './manifestations/manifest/manifest-single.component'; import { ManifestationsSearchComponent } from './manifestations/search/manifestations-search.component'; import { ManifestationsListComponent } from './manifestations/list/manifestations-list.component'; import { ManifestationDetailsComponent } from './manifestations/details/manifestation-details.component'; import { ManifestationsListAllComponent } from './manifestations/list/manifestations-list-all.component'; const routes: Routes = [ { path: '', redirectTo: '/about', pathMatch: 'full' }, { path: 'about', component: AboutComponent }, { path: 'register', component: ManifestSingleComponent }, { path: 'search', component: ManifestationsSearchComponent }, { path: 'list', component: ManifestationsListComponent }, { path: 'list-all', component: ManifestationsListAllComponent }, { path: 'manifestations/:id', component: ManifestationDetailsComponent, runGuardsAndResolvers: 'always' }, ]; @NgModule({ imports: [ RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'}) ], exports: [ RouterModule ] }) export class AppRoutingModule {}
import React, { useState, useEffect } from "react"; import styled from "styled-components"; const Div = styled.div` `; const Table = styled.table` width: 1200px; background-color: #fff; padding: 20px; box-shadow: 0px 0px 5px #ccc; border-radius: 1px; margin: 20px auto; word-break: break-all; @media (max-width: 1024px) { width: 965px; padding: 15px; margin: 10px 20px; } @media (max-width: 820px) { width: 780px; padding: 5px; margin: 10px 20px; } @media (max-width: 640px) { width: 580px; padding: 5px; margin: 10px 20px; } @media (max-width: 500px) { width: 480px; padding: 5px; margin: 10px 20px; } @media (max-width: 420px) { width: 370px; padding: 5px; margin: 5px 20px 10px; } `; export const Thead = styled.thead``; export const Tbody = styled.tbody` padding-bottom: 25px; `; export const Tr = styled.tr` text-align: center; padding-bottom: 25px; `; export const Th = styled.th` text-align: start; border-bottom: inset; padding-bottom: 5px; @media (max-width: 640px) { ${(props) => props.onlyWeb && "display: none;"} } @media (max-width: 500px) { ${(props) => props.onlyWeb && "display: none;"} } @media (max-width: 420px) { ${(props) => props.onlyWeb && "display: none;"} } `; export const Td = styled.td` word-break: break-word; padding-top: 15px; padding-bottom: 5px; text-align: ${(props) => (props.alignCenter ? "center" : "start")}; width: ${(props) => (props.width ? props.width : "auto")}; @media (max-width: 640px) { padding-left: 10px; ${(props) => props.onlyWeb && "display: none"} } @media (max-width: 500px) { padding-left: 10px; ${(props) => props.onlyWeb && "display: none"} } @media (max-width: 420px) { padding-left: 10px; ${(props) => props.onlyWeb && "display: none"} } `; export const Th3 = styled.th` @media (max-width: 2640px) { ${(props) => props.onlyWeb2 && "display: none;"} } `; export const Td3 = styled.td` @media (max-width: 2640px) { ${(props) => props.onlyWeb2 && "display: none;"} } `; export const Td1 = styled.td` padding-top: 15px; text-align: start; text-overflow: ellipsis; `; export const Td2 = styled.td` padding-top: 15px; text-align: center; `; const Input = styled.input` width: 345px; padding: 0 10px; border: 1px solid #bbb; border-radius: 1px; height: 37px; @media (max-width: 1024px) { width: 300px; height: 30px; } @media (max-width: 820px) { width: 300px; height: 35px; display: flex; justify-content: flex-start; } @media (max-width: 640px) { width: 300px; height: 35px; } @media (max-width: 420px) { width: 300px; height: 35px; } `; const ButtonContainer = styled.div` display: flex; flex-direction: row; justify-content: center; align-items: center; margin-top: 10px; /* Ajuste conforme necessário para o espaçamento desejado */ `; const Button = styled.button` padding: 10px; cursor: pointer; border-radius: 3px; border: none; background-color: #808080 ; color: white; width: 90px; height: 37px; font-weight: bold; margin: 8px; transition: transform 0.3s; &:hover { transform: scale(1.1); background-color: #0D7E48; } `; const Grid = ({ users }) => { //const [searchTerm, setSearchTerm] = useState(''); const [filteredUsers, setFilteredUsers] = useState(users); const [isLoading, setIsLoading] = useState(true); const [insertedId, setInsertedId] = useState(null); const [searchTerm, setSearchTerm] = useState(''); const urlParams = new URLSearchParams(window.location.search); const queryString = urlParams.get('login'); let logon = null; let insertedId2 = null; console.log("insertedId:", insertedId); if (queryString) { const loginValue = queryString.split('&')[0]; const loginDecoded = decodeURIComponent(loginValue); logon = atob(loginDecoded); // Agora, vamos verificar se existe o parâmetro "insertedId" na URL if (window.location.search.includes('insertedId')) { const insertedIdValue = window.location.search.split('insertedId:')[1]; insertedId = parseInt(insertedIdValue, 10); } console.log("Login:", logon); console.log("insertedId2:", insertedId2); } else { console.log("Login não encontrado na URL."); window.location.href = 'http://avaliacao.cooperval.coop.br/login'; } const loginEncoded = encodeURIComponent(btoa(logon)); //console.log(loginEncoded); const handleDashboard = () => { const url = `http://avaliacao.cooperval.coop.br/?login=${loginEncoded}`; window.location.href = url; }; useEffect(() => { if (insertedId !== null) { setSearchTerm(insertedId); handleSearchButtonClick(); } }, [insertedId]); const handleSearchInputChange = (event) => { const searchTerm = event.target.value; setSearchTerm(searchTerm); }; const handleSearchButtonClick = () => { console.log('Filtrando pelo valor:', searchTerm); const filteredUsers = users.filter((item) => Object.values(item).some((value) => { if (typeof value === 'string' || typeof value === 'number') { if (typeof value === 'string') { return value.toLowerCase().includes(searchTerm.toLowerCase()); } else { return String(value).toLowerCase().includes(searchTerm.toLowerCase()); } } return false; }) ); setFilteredUsers(filteredUsers); setIsLoading(false); }; return ( <div> <Div> <Input type="text" placeholder="Pesquisar..." value={searchTerm} onChange={handleSearchInputChange} /> <ButtonContainer> <Button onClick={() => setInsertedId(searchTerm)}>Pesquisar</Button> <Button onClick={handleDashboard}>Dashboard</Button> </ButtonContainer> </Div> {isLoading ? ( <p></p> ) : ( <Table> <Thead> <Tr> <Th onlyWeb2>ID:</Th> <Th onlyWeb>Avaliador:</Th> <Th onlyWeb>Avaliado:</Th> <Th onlyWeb>Avaliação:</Th> <Th onlyWeb>Pergunta:</Th> <Th onlyWeb>Resposta:</Th> </Tr> </Thead> <Tbody> {filteredUsers.map((item, i) => ( <React.Fragment key={i}> <Tr> <Td1 width="3%" onlyWeb>{item.id_aplicacaoavaliacao}</Td1> <Td1 width="15%" onlyWeb>{item.nome_avaliador}</Td1> <Td1 width="15%" onlyWeb>{item.nome_avaliado}</Td1> <Td1 width="20%" onlyWeb>{item.descricao_sistema_avaliacao}</Td1> <Td1 width="34%" onlyWeb>{item.id_item_avaliacao} - {item.descricao_item_avaliacao}</Td1> <Td2 width="auto" onlyWeb>{item.descricao_faixa_avaliacao}</Td2> </Tr> </React.Fragment> ))} </Tbody> </Table> )} </div> ); }; export default Grid;
import React, { useContext } from "react"; import { observable } from "mobx"; export type Color = { color: string; baseHeight: number; baseBlend: number; noiseFactor: number; noiseFrequency: number; noiseOffset: number; }; const defaults = { minValue: 0.4, strength: 30, roughness: 4, baseRoughness: 0.5, persistance: 0.5, resolution: 255, numberOfLayers: 6, layers: [ { color: "#0062c4", baseHeight: 0, baseBlend: 0, noiseFactor: 0, noiseFrequency: 1, noiseOffset: 0, // texture: waterTexture, }, { color: "#0972d4", baseHeight: 0.1, baseBlend: 0.15, noiseFactor: 0, noiseFrequency: 1, noiseOffset: 0, // texture: waterTexture, }, { color: "#1982e4", baseHeight: 0.2, baseBlend: 0.15, noiseFactor: 0, noiseFrequency: 1, noiseOffset: 0, // texture: waterTexture, }, { color: "#c2b280", baseHeight: 0.28, baseBlend: 0.01, noiseFactor: 0, noiseFrequency: 1, noiseOffset: 0, // texture: new THREE.TextureLoader().load(sandyGrass), }, { color: "#63a375", baseHeight: 0.43, baseBlend: 0.05, noiseFactor: 0.1, noiseFrequency: 0.02, noiseOffset: 0, // texture: new THREE.TextureLoader().load(grass), }, { color: "#197278", baseHeight: 0.55, baseBlend: 0.08, noiseFactor: 0.3, noiseFrequency: 0.02, noiseOffset: 0, // texture: new THREE.TextureLoader().load(stonyGround), }, { color: "#a2abab", baseHeight: 0.7, baseBlend: 0.1, noiseFactor: 0.1, noiseFrequency: 0.02, noiseOffset: 0, // texture: new THREE.TextureLoader().load(rocks1), }, { color: "#ffffff", baseHeight: 0.75, baseBlend: 0.02, noiseFactor: 0.1, noiseFrequency: 0.02, noiseOffset: 0, // texture: new THREE.TextureLoader().load(snow), }, ], setLayer: (index: number) => (newValues: Partial<Color>) => { Object.assign(store.layers[index], newValues); }, }; const store = observable(defaults); export type TerrainFeaturesStore = typeof defaults; export const TerrainFeaturesContext = React.createContext<TerrainFeaturesStore>( store ); export const useTerrainFeaturesContext = () => useContext(TerrainFeaturesContext); export const TerrainFeaturesStoreProvider = ({ children, }: React.PropsWithChildren<{}>) => { return ( <TerrainFeaturesContext.Provider value={store}> {children} </TerrainFeaturesContext.Provider> ); };
# 🗂 Wallet & Custodia ### Cos’è un wallet? <a href="#cose-un-wallet" id="cose-un-wallet"></a> Un **Wallet** (“Portafoglio”) di criptovalute è un dispositivo **hardware** o un programma **software** che **memorizza** le **chiavi private** del tuo portafoglio e consente di **accedere** facilmente alle tue **criptovalute**. Utilizza una connessione a Internet per accedere alla rete blockchain. I wallet contengono una **chiave** **pubblica** (l'indirizzo del wallet) e le **chiavi** **private** necessarie per firmare le transazioni. _Chiunque conosca la chiave privata può controllare le monete associate a quell'indirizzo pubblico_. {% hint style="info" %} Quando si possiedono criptovalute in un **wallet** (non-custodial, ovvero non gestito da terze parti), ciò che si possiede realmente è una **chiave privata**. Le vostre monete sono **associate** a un insieme di "chiavi pubbliche/private". La chiave privata rappresenta **il diritto** di poter spendere le monete che sono associate all’**indirizzo pubblico** del wallet. {% endhint %} {% hint style="danger" %} MAI DIRE A NESSUNO LA TUA CHIAVE PRIVATA, PER NESSUN MOTIVO! {% endhint %} ### A cosa servono? <a href="#a-cosa-servono" id="a-cosa-servono"></a> I Wallet hanno 3 scopi principiali: * **Mantenere** al **sicuro** la propria **chiave** **privata** con la quale abbiamo accesso ai nostri fondi * **Trasferire** i propri **fondi** oppure **comprare** e **vendere** criptovalute * **Interagire** con le applicazioni decentralizzate (“**dApps**”) ### Tipi di Wallet <a href="#tipi-di-wallet" id="tipi-di-wallet"></a> Ci sono essenzialmente due tipologie di Wallet. 1. Gli **Hot Wallet** (programmi software) sono quelli più comunemente utilizzanti in quanto molto **pratici** e **facili** da usare e offrono grande **flessibilità**. Essendo però costantemente collegati ad internet possono essere **vulnerabili** ad attacchi hacker. Esempi di hot wallet: * **“Web-Extension” Wallet**: occorre installare l’estensione del wallet sul proprio browser. Il più utilizzato e sicuro è [Metamask](https://metamask.io/) * **“Desktop”** **Wallet**: occorre installare la applicazione del wallet sul proprio pc. Un esempio è [Exodus Wallet](https://www.exodus.com/download/) * **“Mobile” Wallet**: occorre installare la applicazione del wallet sul proprio smartphone. Anche in questo caso il più utilizzato è [Metamask](https://metamask.io/) 2\. I **Cold Wallet** (dispositivi hardware) sono meno utilizzati in quanto possono risultare meno pratici e un pò più difficili da utilizzare. La loro **sicurezza** risiede nel fatto che sono **completamente offline** e quindi non vulnerabili ad attacchi hacker. Sono dei dispostivi (molto simili a delle penne USB) nei quali vengono salvate offline le proprie chiavi private e pubbliche. Il più utilizzato è il [Ledger](https://www.ledger.com/). ### Consigli pratici per gestire il proprio wallet in sicurezza <a href="#consigli-pratici-per-gestire-il-proprio-wallet-in-sicurezza" id="consigli-pratici-per-gestire-il-proprio-wallet-in-sicurezza"></a> Possiamo individuare **due semplici pratiche** per assicurarci un livello di sicurezza adeguatamente alto senza compromettere la propria flessibilità di utilizzo. 1. **Utilizzare un computer “vergine”** sul quale installare un “Web-Extension” Wallet e utilizzare questo PC solo per l’operatività su Blockchain. In questo modo **evitiamo di usare il proprio PC personale** che potrebbe essere infetto da virus. 2. **Utilizzare un “Hardware” Wallet** per generare la propria chiave privata e importarla su un “Web-Extension” Wallet. In questo modo **otteniamo flessibilità e sicurezza** poiché la chiave privata rimane archiviata offline ma utilizziamo il “Web-Extension” Wallet per l’operatività. Volendo possiamo unire la pratica 1 e 2 per ottenere un grado di sicurezza ancora maggiore. &#x20;
<!--- Christian Kuster, CH-8342 Wernetshausen, christian@kusti.ch Created: 08.01.22 --> <template lang="pug"> div b-form-group.mb-0 b-input-group(size='sm') b-form-input#filter-input( v-model='filter' type='search' placeholder='Zürich Paradeplatz' :disabled="disabled") b-input-group-append b-button(:disabled='!filter' @click="filter = ''") Löschen #property-list b-table( :items="propertyList" :filter-function="filterNames" :filter="filter" :fields="fields" small :per-page="perPage" sort-by="location.name" ) template(#cell(uuid)="row") b-button(size="sm" @click="buyProperty(row.value)" :disabled="disabled") kaufen </template> <script> import $ from 'jquery'; import {GameProperties} from '../../../../lib/gameProperties'; export default { name : 'PropertySelector', components: {}, filters : {}, mixins : [], model : {}, props : { propertyRegister: { type : Object, // a GameProperties Object default: () => { return new GameProperties(); } }, perPage : { type : String, default: () => { return '10' } }, disabled : { type : Boolean, default: () => { return false; } } }, data : function () { return { filter: null, fields: [ {key: 'location.name', label: 'Ort'}, {key: 'pricelist.price', label: 'Preis'}, {key: 'uuid', label: '', thStyle: {width: '10% !important'}} ] }; }, computed : { propertyList() { if (this.filter) { return this.propertyRegister.properties; } return []; } }, mounted : function () { this.resizeHandler(); }, created : function () { this.resizeHandler(); }, methods : { filterNames(row, filter) { return row.location.name.toLowerCase().includes(filter.toLowerCase()); }, buyProperty(p) { console.log('buy', p); this.$emit('buy-property', {uuid: p}); }, /** * Creates the maximum Size of the list */ resizeHandler() { let element = $('#property-list'); let parent = $('#prop-selector'); let parentHeight = parent.height(); let parentOffset = parent.offset(); let offsetElement = element.offset(); if (offsetElement && parentOffset) { element.height(parentHeight - (offsetElement.top - parentOffset.top)); } }, } } </script> <style lang="scss" scoped> #property-list { overflow: auto; height: 200px; } </style>
import 'package:flutter/material.dart'; import 'rental_car.dart'; class HalamanDetail extends StatefulWidget { final RentalCar mobil; const HalamanDetail({Key? key, required this.mobil}) : super(key: key); @override State<HalamanDetail> createState() => _HalamanDetailState(); } class _HalamanDetailState extends State<HalamanDetail> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(widget.mobil.brand), Text(' '), Text(widget.mobil.model) ], ), ), body: SingleChildScrollView( child: Container( child: Column( children: [ Container( padding: EdgeInsets.all(5), width: MediaQuery.of(context).size.width, height: 400, child: ListView.builder( scrollDirection: Axis.horizontal, itemBuilder: (context, index) => Image.network(widget.mobil.images[index]), itemCount: 3, ), ), Padding(padding: EdgeInsets.all(20)), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text(widget.mobil.brand, style: TextStyle(fontSize: 20)), Text(widget.mobil.model, style: TextStyle(fontSize: 20)) ], ), Row( children: [ Column( children: [ Text('Brand : '), Text('Model : '), Text('Tahun : '), Text('Biaya Sewa : '), Text('Status : '), ], ), Column( children: [ Text(widget.mobil.brand), Text(widget.mobil.model), Text(widget.mobil.year.toString()), Text(widget.mobil.rentalPricePerDay), Text(widget.mobil.model), //if(widget.mobil.available = true){} ], ) ], ), Container( padding: EdgeInsets.only(top: 20), width: double.infinity, child: ElevatedButton( style: ElevatedButton.styleFrom(backgroundColor: Colors.green), onPressed: (){}, child: Text('Pesan'), ), ), Container( padding: EdgeInsets.all(10), child: Text(widget.mobil.description), ) ], ), ), ), ); } }
package Sah::Schema::array_from_json; use strict; use warnings; # AUTHORITY # DATE # DIST # VERSION our $schema = [array => { summary => 'Array, coercible from JSON string', 'prefilters' => ['JSON::decode_str'], description => <<'_', You can use this schema if you want to accept an array, but if user supplies a string e.g. in a command-line script as command-line argument or option, the string will be coerced into array if the string contains a JSON-encoded array. Data will not be valid if the string does not contain valid JSON. Note that array data is accepted, unlike the `json_str::array` schema which only accepts JSON-encoded array in string form. _ examples => [ {value=>'', valid=>0, summary=>'Empty string is not a valid JSON'}, {value=>'1', valid=>0, summary=>'Valid JSON but not an array'}, {value=>'{}', valid=>0, summary=>'Valid JSON but not an array'}, {value=>[], valid=>1, summary=>'Already an array'}, {value=>{}, valid=>0, summary=>'Not an array'}, {value=>'foo', valid=>0, summary=>'Not a valid JSON literal'}, {value=>'[1,2,3,{}]', valid=>1, validated_value=>[1,2,3,{}]}, {value=>'[1,2', valid=>0, summary=>'Missing closing square bracket'}, {value=>'[1,2,]', valid=>0, summary=>'Dangling comma'}, ], }]; 1; # ABSTRACT:
import * as React from "react"; import { useState, useEffect } from "react"; import { useParams, useHistory } from "react-router-dom"; import { useDispatch } from "react-redux"; import { checkAccessTags } from "../../util/uam"; import { AlertBox } from "../../components/AlertBox"; import { storedList } from "../../util/localstorage"; import { getWaiverRequestDetailsWatcher, createWaiverRequestWatcher } from "../../actions/waiverRequest.js"; import { getBorrowerDetailsByIdWatcher } from "../../actions/borrowerInfo"; import Table from "react-sdk/dist/components/Table/Table"; import InputBox from "react-sdk/dist/components/InputBox/InputBox"; import Button from "react-sdk/dist/components/Button/Button"; import "react-sdk/dist/styles/_fonts.scss"; export default function WaiverRequest(props) { const user = storedList("user"); const { company_id, product_id, loan_id } = useParams(); const { isPropBased } = props; const cid = isPropBased ? props.company_id : company_id; const pid = isPropBased ? props.product_id : product_id; const lid = isPropBased ? props.loan_id : loan_id; const dispatch = useDispatch(); const history = useHistory(); //alert const [alert, setAlert] = useState(false); const [alertMessage, setAlertMessage] = useState(""); const [severity, setSeverity] = useState(""); const [loanData, setLoanData] = useState(""); const [waiverDetails, setWaiverDetails] = useState(""); //Post waiver fields const [interestWaiver, setInterestWaiver] = useState(0); const [lpiWaiver, setLPIWaiver] = useState(0); const [bounceChargesWaiver, setBounceChargesWaiver] = useState(0); const [gstReversalBC, setGSTReversalBC] = useState(0); const [remarks, setRemarks] = useState(""); //submit button state const [isDisableSubmit, setIsDisableSubmit] = useState(true); const isTagged = process.env.REACT_APP_BUILD_VERSION > 1 ? user?.access_metrix_tags?.length : false; useEffect(() => { if ( (interestWaiver * 1 == 0 && lpiWaiver * 1 == 0 && bounceChargesWaiver * 1 == 0) || remarks.length < 1 ) { setIsDisableSubmit(true); } else { setIsDisableSubmit(false); } }, [interestWaiver, lpiWaiver, bounceChargesWaiver, remarks]); //Show alert const showAlert = (msg, type) => { setAlert(true); setSeverity(type); setAlertMessage(msg); setTimeout(() => { handleAlertClose(); }, 3000); }; //close alert const handleAlertClose = () => { setAlert(false); setSeverity(""); setAlertMessage(""); }; //Fetch waiver details const getWaiverDetails = () => { const payload = { loan_id: lid, company_id: cid, product_id: pid, user_id: user._id }; dispatch( getWaiverRequestDetailsWatcher( payload, (response) => { setWaiverDetails(response); }, (error) => { return showAlert(error.response.data.message, "error"); } ) ); }; //Fetch loan details const fetchLoandetails = () => { const params = { company_id: cid, product_id: pid, loan_id: lid }; dispatch( getBorrowerDetailsByIdWatcher( params, (result) => { setLoanData(result.data); }, (error) => { return showAlert(error?.response?.data?.message, "error"); } ) ); }; //Fetch waiver details and loan details initially useEffect(() => { if ( isTagged && checkAccessTags([ "tag_loan_queue_read_write", "tag_loan_queue_request_waiver" ]) ) { getWaiverDetails(); fetchLoandetails(); } if (!isTagged) { getWaiverDetails(); fetchLoandetails(); } }, []); const handleInputChange = (name, setValue) => (event) => { let { value } = event.target; value = value.replace(/[,₹A-Za-z]/g, ""); if (name === "bounceChargesWaiver") { setGSTReversalBC(Math.round((value * 0.18 + Number.EPSILON) * 100) / 100); } setValue(value); }; const rows = [ { id: 1, title: "Interest", current_value: waiverDetails?.interest, name: "interestWaiver", value: interestWaiver, setValue: setInterestWaiver, remaining: 0 }, { id: 2, title: "LPI Due", current_value: waiverDetails?.lpi, name: "lpiWaiver", value: lpiWaiver, setValue: setLPIWaiver, remaining: 0 }, { id: 3, title: "Bounce Charges", current_value: waiverDetails?.bounce_charges, name: "bounceChargesWaiver", value: bounceChargesWaiver, setValue: setBounceChargesWaiver, remaining: 0 }, { id: 4, title: "GST on Bounce Charges", current_value: waiverDetails?.gst_on_bounce_charges, value: gstReversalBC, name: "gstReversalBC", setValue: setGSTReversalBC, remaining: 0 } ]; const validatePayload = () => { if (interestWaiver * 1 < 0) return showAlert("Waiver input cannot be negative.", "error"); if (lpiWaiver * 1 < 0) return showAlert("Waiver input cannot be negative.", "error"); if (bounceChargesWaiver * 1 < 0) return showAlert("Waiver input cannot be negative.", "error"); if (!remarks) return showAlert("request_remark is required", "error"); return true; }; const handleSubmitWaiverDetails = () => { const validateData = validatePayload(); if (validateData) { const payload = { tokenData: { company_id: cid, product_id: pid, user_id: user._id }, postData: { loan_id: lid, interest_waiver: interestWaiver * 1, bc_waiver: bounceChargesWaiver * 1, gst_reversal_bc: gstReversalBC, lpi_waiver: lpiWaiver * 1, request_remark: remarks } }; setIsDisableSubmit(true); dispatch( createWaiverRequestWatcher( payload, (response) => { setIsDisableSubmit(false); showAlert(response.message, "success"); setTimeout(() => { history.push("/admin/lending/loan_queue"); }, 4000); handleCancel(); }, (error) => { setIsDisableSubmit(false); return showAlert(error.response.data.message, "error"); } ) ); } }; const handleCancel = () => { setInterestWaiver(0); setLPIWaiver(0); setBounceChargesWaiver(0); setGSTReversalBC(0); setRemarks(""); getWaiverDetails(); }; const columns = [ {id: "title", label: "NAME"}, {id: "current_value", label: "CURRENT VALUE"}, {id: "waiver", label: "WAIVER"}, {id: "remaining", label: "REMAINING"} ]; const data = rows && rows.map((item) => { return { title: item.title, current_value: new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(item.current_value), waiver: <input id={`waiver-req-input-${item.title}`} key={`waiver-req-input-${item.title}`} type="text" value={ "\u20B9" + (Number(item.name === "gstReversalBC" ? bounceChargesWaiver ? Math.round( (bounceChargesWaiver * 0.18 + Number.EPSILON) * 100 ) / 100 : 0 : item.value)).toLocaleString('en-IN') } onChange={handleInputChange(item.name, item.setValue)} disabled={item.name === "gstReversalBC"} style={{ width: "217px", height: "44px", padding: "0 16px", borderRadius: "8px", border: "1px solid #BBBFCC", color: "#141519", fontFamily: "Montserrat-Regular", fontSize: "14px", fontWeight: "400", lineHeight: "150%" }} />, remaining: new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format( item?.current_value && item?.value ? Math.round( (item.current_value * 1 - item.value * 1 + Number.EPSILON) * 100 ) / 100 : 0) }; }); return ( <div style={{ display: "flex", width: "100%", flexDirection: "column", alignItems: "flex-start", padding: "16px", paddingTop: "24px", gap: "24px", alignSelf: "stretch" }} > {alert ? ( <AlertBox severity={severity} msg={alertMessage} onClose={handleAlertClose} /> ) : null} <div id="waiver-request-loan-details" style={{ display: "flex", alignItems: "flex-start", gap: "40px", alignSelf: "stretch" }} > <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", flex: "1 0 0", alignSelf: "stretch" }} > <div id="loan_id_title" style={{ fontFamily: "Montserrat-Regular", fontSize: "12px", fontStyle: "normal", fontWeight: "400", lineHeight: "150%", textTransform: "uppercase", color: "#6B6F80" }} > Loan ID </div> <div id="loan_id_title_value" style={{ fontFamily: "Montserrat-Medium", fontSize: "16px", fontStyle: "normal", fontWeight: "500", lineHeight: "150%", alignSelf: "stretch", color: "#141519" }} > {loan_id} </div> </div> <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", flex: "1 0 0", alignSelf: "stretch" }} > <div id="customer_name" style={{ fontFamily: "Montserrat-Regular", fontSize: "12px", fontStyle: "normal", fontWeight: "400", lineHeight: "150%", textTransform: "uppercase", color: "#6B6F80" }} > Customer Name </div> <div id="customer_name_value" style={{ fontFamily: "Montserrat-Medium", fontSize: "16px", fontStyle: "normal", fontWeight: "500", lineHeight: "150%", alignSelf: "stretch", color: "#141519" }} > {`${loanData?.first_name ?? ""} ${loanData?.last_name ?? ""}`} </div> </div> <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", flex: "1 0 0", alignSelf: "stretch" }} > </div> <div style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", flex: "1 0 0", alignSelf: "stretch" }} > </div> </div> {waiverDetails.loan_id ? ( <div id="waiver-request-form" style={{ width: "100%", marginTop: "-20px" }} > <Table columns={columns} data={data} customStyle={{ width: "100%", fontFamily: "Montserrat-Medium", }} /> </div> ) : null} {waiverDetails.loan_id ? ( <div id="waiver-request-form-comment" style={{ display: "flex", flexDirection: "column", alignItems: "flex-start", alignSelf: "stretch", width: "100%" }} > <InputBox label="Add Comment" onClick={(event) => { setRemarks(event.value) }} initialValue={remarks} customClass={{ minWidth: "100%", height: "100px", fontFamily: "Montserrat-Regular" }} customInputClass={{ fontFamily: "Montserrat-Regular", padding: "0px 16px", fontSize: "16px", fontWeight: "400", lineHeight: "150%", color: "#141519", minWidth: "100%", height: "100px" }} /> </div> ) : null} {waiverDetails.loan_id ? ( <div id="waiver-request-form-btns" style={{ display: "flex", justifyContent: "flex-end", alignItems: "flex-start", gap: "16px", alignSelf: "stretch" }} > <Button label="Cancel" onClick={() => handleCancel()} buttonType="secondary" customStyle={{ fontSize: "16px", fontWeight: "600", lineHeight: "150%", borderRadius: "8px", width: "240px", height: "48px", padding: "13px 44px", color: "#475BD8", border: "1px solid #475BD8", boxShadow: "none" }} /> <Button label="Submit" onClick={() => handleSubmitWaiverDetails()} buttonType="primary" isDisabled={isDisableSubmit} customStyle={{ fontSize: "16px", fontWeight: "600", lineHeight: "150%", borderRadius: "8px", width: "240px", height: "48px", padding: "13px 44px" }} /> </div> ) : null} </div> ); }
const getParkingOptions = async () => { try { const res = await fetch('/api/parking/get'); const data = await res.json(); if (data.error) { throw new Error(data.error); } const parkingSelect = document.getElementById('parkingId'); parkingSelect.innerHTML = '<option value="">Выберите стоянку</option>'; data.forEach(parking => { const option = document.createElement('option'); option.value = parking.address; option.textContent = parking.address; parkingSelect.appendChild(option); }); } catch (error) { console.log(error); } }; const getCarNumbers = async () => { try { const res = await fetch("/api/car/getUnparked", { method: "GET", headers: { "Content-Type": "application/json" }, }); const data = await res.json(); if (data.error) { throw new Error(data.error); } const carSelect = document.getElementById('carId'); carSelect.innerHTML = '<option value="">Выберите машину</option>'; data.forEach(car => { const option = document.createElement('option'); option.value = car.number; option.textContent = car.number; carSelect.appendChild(option); }); } catch (error) { console.log(error); } } const placeCar = async (parkingAddress, carNumber) => { try { const res = await fetch("/api/parking/parkCar", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ carNumber, parkingAddress }), }); const data = await res.json(); if (data.error) { throw new Error(data.error); } await getCarNumbers(); const event = new Event('updateMap'); window.dispatchEvent(event); } catch (error) { console.log(error); } } $(document).ready(async function() { await getParkingOptions(); await getCarNumbers(); $('#formPlaceCar').on('submit', async function(e) { e.preventDefault(); const parkingAddress = $('#parkingId').val(); const carNumber = $('#carId').val(); if (parkingAddress && carNumber) { await placeCar(parkingAddress, carNumber); } else { alert("Выберите парковку и машину."); } }); });
package de.cwerl.complexityzoo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import de.cwerl.complexityzoo.model.data.AbstractProblem; import de.cwerl.complexityzoo.model.data.ComplexityClass; import de.cwerl.complexityzoo.model.data.ComplexityDataType; import de.cwerl.complexityzoo.model.data.normal.NormalComplexityClass; import de.cwerl.complexityzoo.model.data.normal.Problem; import de.cwerl.complexityzoo.model.data.para.ParaComplexityClass; import de.cwerl.complexityzoo.model.data.para.Parameterization; import de.cwerl.complexityzoo.model.relations.CTCRelation.CTCRelation; import de.cwerl.complexityzoo.model.relations.CTCRelation.CTCRelationType; import de.cwerl.complexityzoo.model.relations.CTPRelation.CTPRelation; import de.cwerl.complexityzoo.model.relations.CTPRelation.CTPRelationType; import de.cwerl.complexityzoo.model.relations.PTPRelation.PTPRelation; import de.cwerl.complexityzoo.repository.data.ComplexityClassRepository; import de.cwerl.complexityzoo.repository.data.ParameterizationRepository; import de.cwerl.complexityzoo.repository.data.ProblemRepository; import de.cwerl.complexityzoo.repository.relations.CTCRelationRepository; import de.cwerl.complexityzoo.repository.relations.CTPRelationRepository; import de.cwerl.complexityzoo.repository.relations.PTPRelationRepository; import de.cwerl.complexityzoo.security.UserRepository; @Service public class InitDatabaseService { @Autowired UserRepository userRepository; @Autowired ComplexityClassRepository classRepository; @Autowired ProblemRepository problemRepository; @Autowired ParameterizationRepository parameterizationRepository; @Autowired CTCRelationRepository ctcRelationRepository; @Autowired CTPRelationRepository ctpRelationRepository; @Autowired PTPRelationRepository ptpRelationRepository; @Autowired PasswordEncoder encoder; public void init() { if(classRepository.count() == 0 && problemRepository.count() == 0 && parameterizationRepository.count() == 0) { ComplexityClass np = initComplexityClass("NP", ComplexityDataType.NORMAL); ComplexityClass ac = initComplexityClass("AC", ComplexityDataType.NORMAL); ComplexityClass acZero = initComplexityClass("AC$^0$", ComplexityDataType.NORMAL); ComplexityClass acOne = initComplexityClass("AC$^1$", ComplexityDataType.NORMAL); ComplexityClass cfl = initComplexityClass("CFL", ComplexityDataType.NORMAL); ComplexityClass coNL = initComplexityClass("coNL", ComplexityDataType.NORMAL); ComplexityClass coNP = initComplexityClass("coNP", ComplexityDataType.NORMAL); ComplexityClass coRE = initComplexityClass("coRE", ComplexityDataType.NORMAL); ComplexityClass dcfl = initComplexityClass("DCFL", ComplexityDataType.NORMAL); ComplexityClass l = initComplexityClass("L", ComplexityDataType.NORMAL); ComplexityClass linspace = initComplexityClass("LINSPACE", ComplexityDataType.NORMAL); ComplexityClass nc = initComplexityClass("NC", ComplexityDataType.NORMAL); ComplexityClass ncOne = initComplexityClass("NC$^1$", ComplexityDataType.NORMAL); ComplexityClass nl = initComplexityClass("NL", ComplexityDataType.NORMAL); ComplexityClass p = initComplexityClass("P", ComplexityDataType.NORMAL); ComplexityClass pspace = initComplexityClass("PSPACE", ComplexityDataType.NORMAL); ComplexityClass r = initComplexityClass("R", ComplexityDataType.NORMAL); ComplexityClass re = initComplexityClass("RE", ComplexityDataType.NORMAL); ComplexityClass reg = initComplexityClass("REG", ComplexityDataType.NORMAL); ComplexityClass wOne = initComplexityClass("W[1]", ComplexityDataType.PARAMETERIZED); ComplexityClass fpt = initComplexityClass("FPT", ComplexityDataType.PARAMETERIZED); ComplexityClass paraACZero = initComplexityClass("para-AC$^0$", ComplexityDataType.PARAMETERIZED); ComplexityClass paraNP = initComplexityClass("para-NP", ComplexityDataType.PARAMETERIZED); ComplexityClass wP = initComplexityClass("W[P]", ComplexityDataType.PARAMETERIZED); ComplexityClass xacZero = initComplexityClass("XAC$^0$", ComplexityDataType.PARAMETERIZED); ComplexityClass wTwo = initComplexityClass("W[2]", ComplexityDataType.PARAMETERIZED); ComplexityClass xp = initComplexityClass("XP", ComplexityDataType.PARAMETERIZED); initCTCRelation(ac, nc, CTCRelationType.EQUAL_TO); initCTCRelation(ac, acZero, CTCRelationType.SUPERSET_OF); initCTCRelation(ac, acOne, CTCRelationType.SUPERSET_OF); initCTCRelation(ac, p, CTCRelationType.SUBSET_OF); initCTCRelation(acZero, acOne, CTCRelationType.SUBSET_OF); initCTCRelation(acZero, l, CTCRelationType.SUBSET_OF); initCTCRelation(acZero, nl, CTCRelationType.SUBSET_OF); initCTCRelation(acOne, ncOne, CTCRelationType.SUPERSET_OF); initCTCRelation(acOne, nl, CTCRelationType.SUPERSET_OF); initCTCRelation(cfl, dcfl, CTCRelationType.SUPERSET_OF); initCTCRelation(cfl, reg, CTCRelationType.PROPER_SUPERSET_OF); initCTCRelation(cfl, p, CTCRelationType.SUBSET_OF); initCTCRelation(coNL, nl, CTCRelationType.EQUAL_TO); initCTCRelation(coNL, l, CTCRelationType.SUPERSET_OF); initCTCRelation(coNP, p, CTCRelationType.SUPERSET_OF); initCTCRelation(coRE, re, CTCRelationType.NOT_EQUAL_TO); initCTCRelation(coRE, r, CTCRelationType.SUPERSET_OF); initCTCRelation(dcfl, reg, CTCRelationType.PROPER_SUPERSET_OF); initCTCRelation(fpt, wOne, CTCRelationType.SUBSET_OF); initCTCRelation(fpt, wP, CTCRelationType.SUBSET_OF); initCTCRelation(fpt, paraACZero, CTCRelationType.SUPERSET_OF); initCTCRelation(l, nl, CTCRelationType.SUBSET_OF); initCTCRelation(nc, ncOne, CTCRelationType.SUPERSET_OF); initCTCRelation(ncOne, reg, CTCRelationType.SUPERSET_OF); initCTCRelation(nl, p, CTCRelationType.SUBSET_OF); initCTCRelation(np, p, CTCRelationType.SUPERSET_OF); initCTCRelation(p, pspace, CTCRelationType.SUBSET_OF); initCTCRelation(paraACZero, xacZero, CTCRelationType.SUBSET_OF); initCTCRelation(paraACZero, paraNP, CTCRelationType.SUBSET_OF); initCTCRelation(paraNP, wP, CTCRelationType.SUPERSET_OF); initCTCRelation(r, re, CTCRelationType.SUBSET_OF); initCTCRelation(wOne, wTwo, CTCRelationType.SUBSET_OF); initCTCRelation(wOne, wP, CTCRelationType.SUBSET_OF); initCTCRelation(wTwo, wP, CTCRelationType.SUBSET_OF); initCTCRelation(wP, xp, CTCRelationType.SUBSET_OF); initCTCRelation(xacZero, xp, CTCRelationType.SUBSET_OF); Problem twoSat = initProblem("2-SAT"); Problem clique = initProblem("clique"); Problem cnfSat = initProblem("CNF-SAT"); Problem cvp = initProblem("CVP"); Problem halt = initProblem("HALT"); Problem independentSet = initProblem("Independent Set"); Problem parity = initProblem("Parity"); Problem sat = initProblem("SAT"); Problem taut = initProblem("TAUT"); Problem vertexCover = initProblem("Vertex Cover"); Parameterization cliqueK = initParameterization("$k$", "The size of the soughted clique", clique); Parameterization independentSetK = initParameterization("$k$", "Size of the soughted independent set", independentSet); Parameterization independentSetTwG = initParameterization("$tw(G)$", "The tree width of the given graph", independentSet); Parameterization vertexCoverK = initParameterization("$k$","The size of the soughted vertex cover", vertexCover); initPTPRelation(clique, vertexCover, "$\\leq_P$"); initPTPRelation(cliqueK, independentSetK, "$\\leq_{fpt}$"); initPTPRelation(cnfSat, sat, "$\\leq_P$"); initPTPRelation(independentSetK, cliqueK, "$\\leq_{fpt}$"); initPTPRelation(sat, cnfSat, "$\\leq_P$"); initCTPRelation(np, clique, CTPRelationType.IN); initCTPRelation(xacZero, cliqueK, CTPRelationType.IN); initCTPRelation(wTwo, cliqueK, CTPRelationType.IN); initCTPRelation(xp, cliqueK, CTPRelationType.IN); initCTPRelation(np, cnfSat, CTPRelationType.IN); initCTPRelation(p, cvp, CTPRelationType.IN); initCTPRelation(re, halt, CTPRelationType.IN); initCTPRelation(r, halt, CTPRelationType.NOT_IN); initCTPRelation(coRE, halt, CTPRelationType.NOT_IN); initCTPRelation(np, independentSet, CTPRelationType.IN); initCTPRelation(xacZero, independentSetK, CTPRelationType.IN); initCTPRelation(xp, independentSetK, CTPRelationType.IN); initCTPRelation(fpt, independentSetTwG, CTPRelationType.IN); initCTPRelation(acZero, parity, CTPRelationType.NOT_IN); initCTPRelation(ncOne, parity, CTPRelationType.IN); initCTPRelation(np, sat, CTPRelationType.IN); initCTPRelation(coNP, taut, CTPRelationType.IN); initCTPRelation(np, vertexCover, CTPRelationType.IN); initCTPRelation(paraACZero, vertexCoverK, CTPRelationType.IN); initCTPRelation(xp, vertexCoverK, CTPRelationType.IN); } } private ComplexityClass initComplexityClass(String name, ComplexityDataType type) { ComplexityClass c; if(type == ComplexityDataType.NORMAL) { c = new NormalComplexityClass(name); } else { c = new ParaComplexityClass(name); } classRepository.save(c); return c; } private Problem initProblem(String name) { Problem p = new Problem(); p.setName(name); problemRepository.save(p); return p; } private Parameterization initParameterization(String name, String description, Problem parent) { Parameterization p = new Parameterization(); p.setName(name); p.setParent(parent); parameterizationRepository.save(p); return p; } private CTCRelation initCTCRelation(ComplexityClass c1, ComplexityClass c2, CTCRelationType type) { CTCRelation ctc = new CTCRelation(); ctc.setFirstClass(c1); ctc.setSecondClass(c2); ctc.setRelationType(type); ctcRelationRepository.save(ctc); return ctc; } private PTPRelation initPTPRelation(AbstractProblem p1, AbstractProblem p2, String type) { PTPRelation ptp = new PTPRelation(); ptp.setFirstProblem(p1); ptp.setSecondProblem(p2); ptp.setRelationType(type); ptpRelationRepository.save(ptp); return ptp; } private CTPRelation initCTPRelation(ComplexityClass c, AbstractProblem p, CTPRelationType type) { CTPRelation ctp = new CTPRelation(); ctp.setComplexityClass(c); ctp.setProblem(p); ctp.setRelationType(type); ctpRelationRepository.save(ctp); return ctp; } }
import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { LogLoginI, UserI } from './interfaces/user.interface'; import { ApiResponseI } from './interfaces/shared.interface'; @Injectable({ providedIn: 'root' }) export class UserService { constructor(private httpClient: HttpClient) { } public login(user: UserRequest): Observable<any> { return this.httpClient.post<any>(`${environment.urlLocalApi}/auth/login`, user); } public getUserByEmail(userEmail: string): Observable<ApiResponseI<any>> { //const token = localStorage.getItem('token'); //const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`); const params = { email: userEmail }; return this.httpClient.get<ApiResponseI<any>>(`${environment.urlLocalApi}/user/userByEmail`, { params: params },); } public getUserByUsername(userName: string): Observable<ApiResponseI<UserI>> { const token = localStorage.getItem('token'); const headers = new HttpHeaders().set('Authorization', `Bearer ${token}`); const params = { username: userName }; return this.httpClient.get<ApiResponseI<UserI>>(`${environment.urlLocalApi}/user/userByUserName`, { params: params, headers:headers },); } public getLogsByUserId(user_id: number): Observable<ApiResponseI<LogLoginI>> { const params = { user_id: user_id }; return this.httpClient.get<ApiResponseI<LogLoginI>>(`${environment.urlLocalApi}/user/logsByUserId`, { params: params,},); } } export interface UserRequest { userName: string, userPassword: string }
#' A function to turn non-corrected into corrected labelled peptide/protein fractions (Corr LPFs) #' #' This function allows users to input their non-corrected LPF matrix from "AnnotateProteins.R" and correct the fractional enrichment in individual peptides using the enrichment percentages in amino acid soluble pools from paired treatments. The function returns the corrected matrix, which can be directly used to calculate fractional synthesis rates. #' @param InputNonCorrMat #' @param files2correct Defaults to NULL. List of file directories, where each file contains the enrichments in soluble amino acids per treatment evaluated. #' @param AA4correction Defaults to NULL. Character vector with the names of the amino acids to be used for the calculations. The amino acids must be present in the files from the previous parameter. #' @param AAinterprtFileDir File directory to the interpretation file that contains in one column amino acid names and in the second colum the single letter code for those amino acids. #' @param ProtPTMs Character vector with the PTM codes that are part of peptides in the provided dataset. #' @param CorrectMeans Defaults to FALSE. Allows users to return corrected treatment means instead of individual replicates. #' @param EnrBoundary Defaults to one. Allows to define the boundarie of fractional enrichment accepted to be returned. 1 equals to 100%. #' @param GroupPeptides Defaults to FALSE. Allows to group all peptides from a single protein into mean protein enrichment. #' @keywords LCMS kProteomics Tracer Dynamics #' @export #' @examples #' #' ... LPFcorrection <- function(InputNonCorrMat, files2correct = list.files(path = system.file("extdata", package = "ProtSynthesis"), pattern = "Mean_Norm_Factor"), AA4correction = c("Serine", "Glycine"), AAinterprtFileDir = paste0(system.file("extdata", package = "ProtSynthesis"), "/", "AminoAcidNames2SingleLetters.csv"), ProtPTMs = c("OX", "AC"), CorrectMeans = FALSE, EnrBoundary = 1, GroupPeptides = T) { ### needed functions LPFcorr <- function(Col2correct, CorrectionMat, PTMs, CorrectMeans = CorrectMeans){ ##### write a small function to remove PTMs from peptide sequences before counting AAs (use what was already written in one of the other functions) if(CorrectMeans == T) { corrected_LPF <- c() } else { corrected_LPF <- matrix(NA, nrow = nrow(Col2correct), ncol = ncol(Col2correct)) } #count = 0 for (j in 1:length(rownames(Col2correct))) { #count = count +1 #cat(count, " ") peptide2color <- rownames(Col2correct)[j] if (length(strsplit(peptide2color, "-")[[1]]) > 1){ PTMs <- PTMs split_PTM_peptide <- strsplit(peptide2color, "-")[[1]] out_vec <- c() for (i in 1:length(split_PTM_peptide)) { test <- split_PTM_peptide[i] test1 <- strsplit(split_PTM_peptide[i], "")[[1]] if(length(test1) > 0 & length(unique(test != PTMs)) == 1) { out_vec <- c(out_vec, split_PTM_peptide[i]) } } peptide2color <- paste0(out_vec, collapse = "") pep_sequence <- strsplit(strsplit(peptide2color, "_")[[1]][2], "")[[1]] } else { pep_sequence <- strsplit(strsplit(peptide2color, "_")[[1]][2], "")[[1]] } ##### pep_sequence is already stripped off PTMs - ready to match enriched AAs AAs_MeanEnrichment <- c() for (i in 1:nrow(file_runner_corr_adjusted)) { AA_i <- rownames(file_runner_corr_adjusted)[i] test_AA_in_sequence <- grep(pattern = AA_i, x = pep_sequence) if(length(test_AA_in_sequence) > 0){ AA_i_number <- length(grep(pattern = AA_i, x = pep_sequence)) AA_i_MeanEnr <- mean(apply(file_runner_corr_adjusted[AA_i,], 2, as.numeric)) AAs_MeanEnrichment <- c(AAs_MeanEnrichment, AA_i_MeanEnr) } } ##### correct means with means and not rep with reps if(CorrectMeans == T) { ColMeans2correct <- rowMeans(apply(Col2correct, MARGIN = 2, FUN = as.numeric)) corrected_LPF[j] <- ColMeans2correct[j]/mean(AAs_MeanEnrichment) } else { corrected_LPF[j,] <- apply(Col2correct, MARGIN = 2, FUN = as.numeric)[j,]/mean(AAs_MeanEnrichment) } } if(CorrectMeans == T) { names(corrected_LPF) <- rownames(Col2correct) } else { colnames(corrected_LPF) <- colnames(Col2correct) rownames(corrected_LPF) <- rownames(Col2correct) } return(corrected_LPF) } ### main #### Import files if(!is.null(files2correct)) { test_annotateProt_NL <- InputNonCorrMat out_LPF_corrected_list <- list() out_LPF_corrected_names_list <- list() for (i in 1:length(files2correct)) { file_runner_corr <- read.csv(files2correct[i]) if(!is.null(AA4correction)) { test_names_AA_peaks <- grep(pattern = paste0(AA4correction, collapse = "|"), file_runner_corr$X) if(length(test_names_AA_peaks)>0) { file_runner_corr <- file_runner_corr[test_names_AA_peaks,] } else { stop("ERROR: Amino acid peak names in the correction files do not match the names in AA4correction param") } } cat(paste0(paste(colnames(test_annotateProt_NL), 1:length(colnames(test_annotateProt_NL)), sep = " "), collapse = "\n")) columns2correct <- readline(paste0("which columns equal to these three samples (x): ", paste0(colnames(file_runner_corr), collapse = ",") , " ? (e.g.: 1,2,3)")) colIndexes2correct <- as.numeric(strsplit(columns2correct, ",")[[1]]) subset_mat2correct <- test_annotateProt_NL[,colIndexes2correct] rownames(subset_mat2correct) <- test_annotateProt_NL[,"PeptideID"] #### Correct individual replicates from k-LC/MS with individual paired replicates from k-GC/MS #### When impossible dispose peptides as low quality data AAinterprtFile <- read.csv(AAinterprtFileDir) test_exist_AA <- grep(pattern = paste0(AA4correction, collapse = "|"), AAinterprtFile$Amino.acid) if (length(test_exist_AA) > 0) { ##### loop necessary to have the AA in the right order runner_name_single_letter <- c() for (j in 1:length(AA4correction)) { runner_name_single_letter[j] <- AAinterprtFile$Single.letter.abbreviation[grep(pattern = AA4correction[j], AAinterprtFile$Amino.acid)] } } else { stop("ERROR: given amino acid names in AA4correction param do not coincide with any amino acid in AAinterprtFileDir") } file_runner_corr_adjusted <- file_runner_corr[,2:ncol(file_runner_corr)] rownames(file_runner_corr_adjusted) <- runner_name_single_letter out_LPF_corrected_mat <- LPFcorr(Col2correct = subset_mat2correct, CorrectionMat = file_runner_corr_adjusted, PTMs = ProtPTMs, CorrectMeans = CorrectMeans) #### deleting peptides with impossible enrichment percentages that are product of low quality data if(CorrectMeans == T) { test_zero_peps <- which(out_LPF_corrected_mat > EnrBoundary) if(length(test_zero_peps) == 0) { out_LPF_corrected_list[[i]] <- out_LPF_corrected_mat out_LPF_corrected_names_list[[i]] <- names(out_LPF_corrected_mat) } else { out_LPF_corrected_list[[i]] <- out_LPF_corrected_mat[-c(which(out_LPF_corrected_mat > EnrBoundary))] out_LPF_corrected_names_list[[i]] <- names(out_LPF_corrected_mat[-c(which(out_LPF_corrected_mat > EnrBoundary))]) } } else { out_LPF_corrected_mat <- out_LPF_corrected_mat[which(rowMeans(out_LPF_corrected_mat) < EnrBoundary),] out_LPF_corrected_list[[i]] <- out_LPF_corrected_mat out_LPF_corrected_names_list[[i]] <- rownames(out_LPF_corrected_mat) } } good_quality_peptides <- Reduce(f = intersect, out_LPF_corrected_names_list) if(CorrectMeans == T) { out_mat <- matrix(NA, nrow = length(good_quality_peptides), ncol = length(files2correct)) for (i in 1:length(out_LPF_corrected_list)) { out_mat[,i] <- out_LPF_corrected_list[[i]][good_quality_peptides] } colnames(out_mat) <- paste0("Corr_LPF", list2DF(strsplit(files2correct, "\\.csv"))) rownames(out_mat) <- good_quality_peptides } else { count_ncol <- 0 for (i in 1:length(out_LPF_corrected_list)) { count_ncol <- count_ncol + dim(out_LPF_corrected_list[[i]])[2] } out_mat <- suppressWarnings(matrix(NA, nrow = length(good_quality_peptides), ncol = 0)) colnames_bound <- c() for (i in 1:length(out_LPF_corrected_list)) { out_mat <- cbind(out_mat, out_LPF_corrected_list[[i]][good_quality_peptides,]) colnames_bound <- c(colnames_bound, rep(paste0("Corr_LPF", list2DF(strsplit(files2correct[i], "\\.csv"))), dim(out_LPF_corrected_list[[i]])[2])) } colnames(out_mat) <- colnames_bound rownames(out_mat) <- good_quality_peptides } } #### calling the fully annotated matrix to supplement it with the new data rownames(test_annotateProt_NL) <- test_annotateProt_NL[,"PeptideID"] LPF_plus_mat <- cbind(out_mat, test_annotateProt_NL[good_quality_peptides,]) #### group proteins into a single entry to unify information, conserve multiple peptides in the appropriate slots if(GroupPeptides == T) { ProteinID_vector <- unique(LPF_plus_mat[,"HORVU"]) } else { ProteinID_vector <- unique(LPF_plus_mat[,"PeptideID"]) } consolidated_mat <- matrix(NA, nrow = length(ProteinID_vector), ncol = ncol(LPF_plus_mat)) for (i in 1:length(ProteinID_vector)) { if(GroupPeptides == T) { runner_consolid_mat <- as.matrix(LPF_plus_mat[grep(pattern = ProteinID_vector[i], x = LPF_plus_mat[,"HORVU"]),]) } else { runner_consolid_mat <- as.matrix(LPF_plus_mat[grep(pattern = ProteinID_vector[i], x = LPF_plus_mat[,"PeptideID"]),]) } if(ncol(runner_consolid_mat) == 1){ vector_consolid <- as.character(runner_consolid_mat) names(vector_consolid) <- colnames(LPF_plus_mat) } else { if(CorrectMeans == T) { vector_consolid <- c(colMeans(apply(runner_consolid_mat[,1:2], 2, as.numeric)), unique(runner_consolid_mat[,3:4]), paste0(runner_consolid_mat[,5], collapse = ";"), unique(runner_consolid_mat[,6]), paste0(runner_consolid_mat[,7], collapse = ";"), colMeans(apply(runner_consolid_mat[,8:ncol(runner_consolid_mat)], 2, as.numeric))) names(vector_consolid) <- colnames(LPF_plus_mat) } else { vector_consolid <- c(colMeans(apply(runner_consolid_mat[,1:6], 2, as.numeric)), unique(runner_consolid_mat[,7:8]), paste0(runner_consolid_mat[,9], collapse = ";"), unique(runner_consolid_mat[,10]), paste0(runner_consolid_mat[,11], collapse = ";"), colMeans(apply(runner_consolid_mat[,12:ncol(runner_consolid_mat)], 2, as.numeric))) names(vector_consolid) <- colnames(LPF_plus_mat) } } consolidated_mat[i,] <- vector_consolid } colnames(consolidated_mat) <- colnames(LPF_plus_mat) return(consolidated_mat) }
--- title: Amazon FireOS Native Client API参考 description: Amazon FireOS Native Client API参考 exl-id: 8ac9f976-fd6b-4b19-a80d-49bfe57134b5 source-git-commit: 2ccfa8e018b854a359881eab193c1414103eb903 workflow-type: tm+mt source-wordcount: '3416' ht-degree: 0% --- # Amazon FireOS Native Client API参考 {#amazon-fireos-native-client-api-reference} >[!NOTE] > >此页面上的内容仅供参考。 使用此API需要来自Adobe的当前许可证。 不允许未经授权使用。 </br> ## 介绍 {#intro} 本文档详细介绍Amazon FireOS SDK为Adobe Pass身份验证公开的方法和回调,Adobe Pass身份验证支持这些方法和回调。 此处介绍的方法和回调函数在AccessEnabler.h和EntitlementDelegate.h头文件中定义。 请参阅 <https://tve.zendesk.com/hc/en-us/articles/115005561623-fire-TV-Native-AccessEnabler-Library> 获取最新的Amazon FireOS AccessEnabler SDK。 >[!NOTE] > >Adobe Pass身份验证团队建议您仅使用Adobe Pass身份验证 *公共* API: - 公共API可用 *经过全面测试* 所有受支持的客户端类型。 对于任何公共功能,我们确保每种客户端类型都有相关方法的相应版本。 - 公共API需要尽可能保持稳定,以支持向后兼容性并确保合作伙伴集成不会中断。 但是,对于 *非*-public API,我们保留在以后任何时候更改其签名的权利。 如果您遇到无法通过当前公共Adobe Pass身份验证API调用组合支持的特定流程,最好的方法是告知我们。 根据您的需求,我们可以修改公共API,并在以后提供稳定的解决方案。 ## Amazon FireOS SDK API {#api} - [getInstance](#getInstance) - [setOptions](#fire_setOption) - [setRequestor](#setRequestor) - [setRequestorComplete](#setRequestorComplete) - [checkAuthentication](#checkAuthN) - [getAuthentication](#getAuthN) - [displayProviderDialog](#displayProviderDialog) - [setSelectedProvider](#setSelectedProvider) - [navigateToUrl](#navigagteToUrl) - [getAuthenticationToken](#getAuthNToken) - [setAuthenticationStatus](#setAuthNStatus) - [checkPreauthorizedResources](#checkPreauth) - [preauthorizedResources](#preauthResources) - [checkAuthorization](#checkAuthZ) - [getAuthorization](#getAuthZ) - [setToken](#setToken) - [tokenRequestFailed](#tokenRequestFailed) - [注销](#logout) - [getselectedprovider](#getSelectedProvider) - [selectedprovider](#selectedProvider) - [getMetadata](#getMetadata) - [setmetadatastatus](#setMetadaStatus) - [getVersion](#getVersion) </br> ### Factory.getInstance {#getInstance} **描述:** 实例化访问启用程序对象。 每个应用程序实例应有一个访问启用程序实例。 | API调用:构造函数 | | --- | | ```public static AccessEnabler getInstance(Context appContext, String softwareStatement, String redirectUrl)<br> throws AccessEnablerException```<br><br> | | ```public static AccessEnabler getInstance(Context appContext, String env_url, String softwareStatement, String redirectUrl) throws AccessEnablerException``` | **可用性:** v3.0+ **参数:** - *appContext*:Amazon Fire OS应用程序上下文。 - softwarestatement - redirectUrl :如果是FireOS,则会忽略参数值并将其设置为默认值: adobepass://android.app - env_url:对于使用Adobe暂存环境进行测试,可以将env\_url设置为“sp.auth-staging.adobe.com” **已弃用:** ```java public static AccessEnabler getInstance(Context appContext) throws AccessEnablerException ``` ### setRequestor {#setRequestor} **描述:** 确定程序员的身份。 在为Adobe Pass身份验证系统注册Adobe时,每个程序员都会分配一个唯一的ID。 在应用程序的生命周期中,只应执行一次此设置。 服务器响应包含MVPD列表以及附加到程序员标识的一些配置信息。 服务器响应由访问启用码在内部使用。 通过setRequestorComplete()回调只向应用程序显示操作的状态(即SUCCESS/FAIL)。 如果 *url* 未使用参数,生成的网络调用将定向默认服务提供商URL:Adobe版本/生产环境。 如果为提供了值, *url* 参数,则生成的网络调用将定向于 *url* 参数。 所有配置请求都在单独的线程中同时触发。 在编译MVPD列表时,优先使用第一个响应程序。 对于列表中的每个MVPD, Access Enabler记住关联服务提供商的URL。 所有后续权利请求都定向到与服务提供程序相关联的URL,该URL在配置阶段与目标MVPD配对。 | API调用:请求者配置 | | --- | | ```public void setRequestor(String requestorId)``` | **可用性:** v3.0+ | API调用:请求者配置 | | --- | | ```public void setRequestor(String requestorId, ArrayList<String> urls)``` | **可用性:** v3.0+ **参数:** - *请求者ID*:与程序员关联的唯一ID。 首次向Adobe Pass身份验证服务注册时,将Adobe分配的唯一ID传递到您的网站。 - *url*:可选参数;默认情况下,使用Adobe服务提供程序(http://sp.auth.adobe.com/)。 此阵列允许您为Adobe提供的身份验证和授权服务指定端点(其他实例可能用于调试目的)。 您可以使用此选项指定多个Adobe Pass身份验证服务提供程序实例。 这样做时,MVPD列表由来自所有服务提供商的端点组成。 每个MVPD都与最快的服务提供程序相关联;即首先响应并支持该MVPD的服务提供程序。 **触发的回调:** `setRequestorComplete()` **已弃用:** ``` public void setRequestor(String requestorId, String signedRequestorId) public void setRequestor(String requestorId, String signedRequestorId, ArrayList<String> urls) ``` </br> ### setRequestorComplete {#setRequestorComplete} **描述:** 由Access Enabler触发的回调,通知应用程序配置阶段已完成。 这是一个信号,表明应用程序可以开始发出授权请求。 在配置阶段完成之前,应用程序无法发出任何授权请求。 | 回调:请求者配置完成 | | --- | | ```public void setRequestorComplete(int status)``` | **可用性:** v1.0+ **参数:** - *状态*:可以采用以下值之一: - `AccessEnabler.ACCESS_ENABLER_STATUS_SUCCESS` — 配置阶段已成功完成 - `AccessEnabler.ACCESS_ENABLER_STATUS_ERROR` — 配置阶段失败 **触发者:** `setRequestor()` </br> ### setOptions {#fire_setOption} **描述:** 配置全局SDK选项。 它接受 **映射\&lt;string string=&quot;&quot;>** 作为论据。 映射中的值将与SDK发出的每个网络调用一起传递到服务器。 这些值将传递到服务器,与当前流(身份验证/授权)无关。 如果要更改值,可以随时调用此方法。 | API调用: setOptions | | --- | | ```public void setOptions(HashMap<String,String> options)``` | **可用性:** v3.0+ **参数:** - *options*:地图\&lt;string string=&quot;&quot;> 包含全局SDK选项。 当前提供以下选项: - **applicationprofile** — 可用于根据此值进行服务器配置。 - **ap\_vi** - Experience CloudID服务。 此值以后可用于高级分析报表。 - **device\_info** — 设备信息,如中所述 **传递设备信息指南** </br> ### checkAuthentication {#checkAuthN} **描述:** 检查身份验证状态。 它通过在本地令牌存储空间中搜索有效的身份验证令牌来完成此操作。 调用此方法不会执行任何网络调用。 应用程序使用它来查询用户的身份验证状态并相应地更新UI(即更新登录/注销UI)。 身份验证状态通过 [*setAuthenticationStatus()*](#setAuthNStatus) 回调。 如果MVPD支持“每个请求者的身份验证”功能,则可以在设备上存储多个身份验证令牌。 | API调用:检查身份验证状态 | | --- | | ```public void checkAuthentication()``` | **可用性:** v1.0+ **参数:** 无 **触发的回调:** `setAuthenticationStatus()` </br> ### getAuthentication {#getAuthN} **描述:** 启动完整的身份验证工作流。 首先检查身份验证状态。 如果尚未经过身份验证,则身份验证流状态 — 计算机将启动: - 如果上次验证尝试成功,则会跳过MVPD选择阶段,并且WebView控件将为用户显示MVPD的登录页。 - 如果上次验证尝试不成功,或者用户明确注销,则 [*displayProviderDialog()*](#displayProviderDialog) 会触发回调。 您的应用程序使用此回调来显示MVPD选择UI。 此外,您的应用程序需要通过通知Access Enabler库有关用户的MVPD选择,来恢复身份验证流程。 [setSelectedProvider()](#setSelectedProvider) 方法。 如果MVPD支持“每个请求者的身份验证”功能,则可以在设备上存储多个身份验证令牌(每个程序员一个)。 最后,验证状态通过 *setAuthenticationStatus()* 回调。 | API调用:启动身份验证流程 | | --- | | ```public void getAuthentication()``` | **可用性:** v1.0+ | API调用:启动身份验证流程 | | --- | | ```public void getAuthentication(boolean forceAuthN, Map<String, Object> genericData)``` | **可用性:** v1.0+ **参数:** - *forceAuthn*:指定是否应启动身份验证流程的标记,无论用户是否已进行身份验证。 - *数据*:包含要发送到Pay-TV pass服务的键值对的映射。 Adobe可以使用此数据启用未来的功能,而无需更改SDK。 **触发的回调:** `setAuthenticationStatus(), displayProviderDialog(), sendTrackingData()` </br> ### displayProviderDialog {#displayProviderDialog} **描述** 由Access Enabler触发的回调,用于通知应用程序需要实例化适当的UI元素以允许用户选择所需的MVPD。 回调会提供MVPD对象的列表以及其他有助于正确构建选择UI面板的信息(例如指向MVPD徽标的URL、友好显示名称等) 一旦用户选择了所需的MVPD,则上层应用程序需要通过调用来恢复验证流 *setSelectedProvider()* 并向其传递与用户选择相对应的MVPD的ID。 | **回调:显示MVPD选择UI** | | --- | | ```public void displayProviderDialog(ArrayList<Mvpd> mvpds)``` | **可用性:** v1.0+ **参数**: - *mvpds*:MVPD对象列表,其中包含应用程序可用于构建MVPD选择UI元素的MVPD相关信息。 **触发者:** `getAuthentication(), getAuthorization()` </br> ### setSelectedProvider {#setSelectedProvider} **描述:** 您的应用程序调用此方法以告知访问启用程序用户的MVPD选择。 传递时 *null* 作为参数,Access Enabler将当前MVPD重置为空值。 | **API调用:设置当前选定的提供程序** | | --- | | ```public void setSelectedProvider(String mvpdId)``` | **可用性:**v 1.0+ **参数:** 无 **触发的回调:** `setAuthenticationStatus(), sendTrackingData()` </br> ### navigateToUrl {#navigagteToUrl} **描述:** Android SDK上的Access Enabler触发的回调。 在Amazon FireOS SDK中应忽略该错误。 | **“回调:显示MVPD登录”页** | | --- | | ```public void navigateToUrl(String url)``` | **可用性:** v1.0+ **参数:** - *url*:指向MVPD登录页面的URL **触发者:** `getAuthentication(), setSelectedProvider()` </br> ### getAuthenticationToken {#getAuthNToken} **描述:** 通过从后端服务器请求身份验证令牌来完成身份验证流程。 | **API调用:检索身份验证令牌** | | --- | | ```public void getAuthenticationToken(String cookies)``` | **可用性:** v1.0+ **参数:** - *Cookie*:在Target域中设置的Cookie(请参阅SDK中的演示应用程序以了解参考实施)。 **触发的回调:** `setAuthenticationStatus(), sendTrackingData()` </br> ### setAuthenticationStatus {#setAuthNStatus} **描述:** 由Access Enabler触发的回调,通知应用程序身份验证的状态。 在许多地方,身份验证流程可能会由于用户交互或其他不可预见的情况(如网络连接问题等)而失败。 此回调会通知应用程序身份验证的成功/失败状态,同时还会在需要时提供有关失败原因的其他信息。 此回调也会在注销流完成时发出信号。 | **回调:报告身份验证流的状态** | | --- | | ```public void setAuthenticationStatus(int status, String errorCode)``` | **可用性:** v1.0+ **参数:** - *状态*:可以采用以下值之一: - `AccessEnabler.ACCESS_ENABLER_STATUS_SUCCESS` — 身份验证流程已成功完成 - `AccessEnabler.ACCESS_ENABLER_STATUS_ERROR` — 身份验证流失败 - `AccessEnabler.ACCESS_ENABLER_STATUS_LOGOUT` — 注销 - *代码*:呈现状态的原因。 如果 *状态* 是 `AccessEnabler.ACCESS_ENABLER_STATUS_SUCCESS`,则 *代码* 是一个空字符串(即,由 `AccessEnabler.USER_AUTHENTICATED` 常量)。 如果未经过身份验证,此参数可以采用以下值之一: - `AccessEnabler.USER_NOT_AUTHENTICATED_ERROR` — 用户未经过身份验证。 回应 *checkAuthentication()* 当本地令牌缓存中没有有效的身份验证令牌时,方法调用。 - `AccessEnabler.PROVIDER_NOT_SELECTED_ERROR` - AccessEnabler在上层应用程序通过后重置了身份验证状态计算机 *null* 到 `setSelectedProvider()` 中止身份验证流程。 用户可能已取消身份验证流程(例如,已按下“后退”按钮)。 - `AccessEnabler.GENERIC_AUTHENTICATION_ERROR` — 由于网络不可用或用户明确取消身份验证流等原因,身份验证流失败。 - `AccessEnabler.LOGOUT` — 由于注销操作,用户未被身份验证。 **触发者:** `checkAuthentication(), getAuthentication(), checkAuthorization()` </br> ### checkPreauthorizedResources {#checkPreauth} **描述:** 应用程序使用此方法来确定用户是否已获得查看特定受保护资源的授权。 此方法的主要目的是检索用于装饰UI的信息(例如,使用锁定和解锁图标指示访问状态)。 | **API调用:设置当前选定的提供程序** | | --- | | ```public void checkPreauthorizedResources(ArrayList<String> resources)``` | **可用性:** v1.0+ **&lt;parameters: span=&quot;&quot; id=&quot;1&quot; translate=&quot;no&quot; /> 此 `resources` parameter是应检查其授权的资源数组。**&#x200B;列表中的每个元素都应该是一个表示资源ID的字符串。 资源ID与中的资源ID须遵守相同的限制 `getAuthorization()` 调用,即它应为程序员与MVPD或媒体RSS片段之间建立的商定值。 **已触发回调:** `preauthorizedResources()` </br> ### preauthorizedResources {#preauthResources} **描述:** checkPreauthorizedResources()触发的回调。 提供用户已被授权查看的资源列表。 | **API调用:设置当前选定的提供程序** | | --- | | ```public void checkPreauthorizedResources(ArrayList<String> resources)``` | **可用性:**v 1.0+ **参数:** 此 `resources` parameter是用户已被授权查看的资源数组。 **触发者:** `checkPreauthorizedResources()` <br> ### checkAuthorization {#checkAuthZ} **描述:** 应用程序使用此方法来检查授权状态。 首先检查身份验证状态。 如果未经过身份验证, *setTokenRequestFailed()* 会触发回调,并且方法退出。 如果用户通过了身份验证,它还会触发授权流。 欲知详情,请参阅 *getAuthorization()* 方法。 | **API调用:检查授权状态** | | --- | | ```public void checkAuthorization(String resourceId)``` | **可用性:** v1.0+ | **API调用:检查授权状态** | | --- | | ```public void checkAuthorization(String resourceId, Map<String, Object> genericData)``` | **可用性:** v1.0+ **参数:** - *resourceId*:用户请求授权的资源的ID。 - *数据*:包含要发送到Pay-TV pass服务的键值对的映射。 Adobe可以使用此数据启用未来的功能,而无需更改SDK。 **触发的回调:** `tokenRequestFailed(), setToken(), sendTrackingData(), setAuthenticationStatus()` </br> ### getAuthorization {#getAuthZ} **描述:** 应用程序使用此方法来启动授权流。 如果用户尚未经过身份验证,它还会启动身份验证流程。 如果用户通过了身份验证,Access Enabler将继续发出对授权令牌(如果本地令牌缓存中不存在有效的授权令牌)和短期媒体令牌的请求。 获得短媒体令牌后,授权流程即被视为完成。 此 *setToken()* 会触发回调,并将短媒体令牌作为参数提供给应用程序。 如果由于任何原因,授权失败, *tokenRequestFailed()* 会触发回调,并提供错误代码和详细信息。 | **API调用:启动授权流** | | --- | | ```public void getAuthorization(String resourceId)``` | **可用性:** v1.0+ | **API调用:启动授权流** | | --- | | ```public void getAuthorization(String resourceId, Map<String, Object> genericData)``` | **可用性:** v1.0+ **参数:** - *resourceId*:用户请求授权的资源的ID。 - *数据*:包含要发送到Pay-TV pass服务的键值对的映射。 Adobe可以使用此数据启用未来的功能,而无需更改SDK。 **触发的回调:** `tokenRequestFailed(), setToken(), sendTrackingData()` | | | | --- | --- | | ![](http://learn.adobe.com/wiki/images/icons/emoticons/warning.gif) | **触发了其他回调** <br>此方法还可以触发以下回调(如果还启动了身份验证流程): _setAuthenticationStatus()_, _displayProviderDialog()_ | **注意:请尽量使用checkAuthorization()而不是getAuthorization()。 getAuthorization()方法将启动一个完整的身份验证流程(如果用户未经过身份验证),这可能会导致程序员端的复杂实施。** </br> ### setToken {#setToken} **描述:** 由Access Enabler触发的回调,通知应用程序授权流已成功完成。 短期媒体令牌还会作为参数提供。 | **回调:授权流已成功完成** | | --- | | ```public void setToken(String token, String resourceId)``` | **可用性:**v 1.0+ **参数:** - *令牌*:短期媒体令牌 - *resourceId*:获得授权的资源 **触发者:** `checkAuthorization(), getAuthorization()` <br> ### tokenRequestFailed {#tokenRequestFailed} **描述:** 由Access Enabler触发的回调,通知上层应用程序授权流失败。 | **回调:授权流失败** | | --- | | ```public void tokenRequestFailed(String resourceId, <br> String errorCode, String errorDescription)``` | **可用性:** v1.0+ **参数:** - *resourceId*:获得授权的资源 - *错误代码*:与失败方案关联的错误代码。 可能的值: - `AccessEnabler.USER_NOT_AUTHORIZED_ERROR` — 用户无法授权给定资源 - *errorDescription*:有关失败场景的其他详细信息。 如果此描述性字符串由于任何原因不可用,Adobe Pass身份验证将发送空字符串>**(“”)**. MVPD可使用此字符串传递自定义错误消息或与销售相关的消息。 例如,如果订阅者被拒绝对资源的授权,则MVPD会发送消息,例如:“您当前在包中无法访问此渠道。 如果要升级包,请单击此处。” 消息由Adobe Pass身份验证通过此回调传递给程序员,程序员可以选择显示或忽略该消息。 Adobe Pass身份验证还可以使用此参数来提供可能导致错误的状况通知。 例如,“与提供商的授权服务通信时出现网络错误。” **触发者:** `checkAuthorization(), getAuthorization()` </br> ### 注销 {#logout} **描述:** 使用此方法可启动注销流程。 注销是一系列HTTP重定向操作的结果,这是因为用户既需要从Adobe Pass身份验证服务器注销,也需要从MVPD服务器注销。 | **API调用:启动注销流程** | | --- | | ```public void logout()``` | **可用性:** v1.0+ **参数:** 无 **触发的回调:** 无 </br> ### getselectedprovider {#getSelectedProvider} **描述:** 使用此方法可确定当前选择的提供程序。 | **API调用:确定当前选定的MVPD** | | --- | | ```public void getSelectedProvider()``` | **可用性:** v1.0+ **参数:** 无 **触发的回调:** `selectedProvider()` </br> ### selectedprovider {#selectedProvider} **描述:** 由Access Enabler触发的回调,它将有关当前所选MVPD的信息提供给应用程序。 | **回调:有关当前所选MVPD的信息** | | --- | | ```public void selectedProvider(Mvpd mvpd)``` | **可用性:** v1.0+ **参数:** - *mvpd*:包含有关当前所选MVPD信息的对象 **触发者:** `getSelectedProvider()` </br> ### getMetadata {#getMetadata} **描述:** 使用此方法可检索Access Enabler库公开为元数据的信息。 应用程序可以通过提供复合MetadataKey对象来访问此信息。 | **API调用:查询AccessEnabler以获取元数据** | | --- | | ```public void getMetadata(MetadataKey metadataKey)``` | **可用性:** v1.0+ 有两种类型的元数据可供程序员使用: - 静态元数据(身份验证令牌TTL、授权令牌TTL和设备ID) - 用户元数据(用户特定的信息,例如用户ID和邮政编码;在身份验证和/或授权流期间,从MVPD传递到用户设备) **参数:** - *metadatakey*:封装键和args变量的数据结构,其含义如下: - 如果键为 `METADATA_KEY_TTL_AUTHN` 然后进行查询以获取身份验证令牌过期时间。 - 如果键为 `METADATA_KEY_TTL_AUTHZ` 和参数包含名为=的SerializableNameValuePair对象 `METADATA_ARG_RESOURCE_ID` 和值= `[resource_id]`,然后进行查询以获取与指定资源关联的授权令牌的过期时间。 - 如果键为 `METADATA_KEY_DEVICE_ID` 然后进行查询以获取当前设备id。 请注意,此功能默认处于禁用状态,程序员应联系Adobe以获取有关启用和费用的信息。 - 如果键为 `METADATA_KEY_USER_META` 和参数包含名为=的SerializableNameValuePair对象 `METADATA_KEY_USER_META` 和值= `[metadata_name]`,则查询用户元数据。 可用用户元数据类型的当前列表: - `zip` — 邮政编码 - `householdID` — 家庭标识符。 如果MVPD不支持子帐户,则它与 `userID`. - `maxRating` — 用户的最大家长评级 - `userID` — 用户标识符。 如果MVPD支持子帐户,并且用户不是主帐户, - `channelID` — 用户有权查看的渠道列表 程序员可用的实际用户元数据取决于MVPD提供的内容。 此列表将随着新元数据的推出和添加到Adobe Pass身份验证系统中而进一步扩展。 **触发的回调:** [`setMetadataStatus()`](#setMetadaStatus) **更多信息:** [用户元数据](#setmetadatastatus) </br> ### setmetadatastatus {#setMetadaStatus} **描述:** 由Access Enabler触发的回调,用于提供通过 *getMetadata()* 呼叫。 | **回调:元数据检索请求的结果** | | --- | | ```public void setMetadataStatus(MetadataKey key, MetadataStatus result)``` | **可用性:** v1.0+ **参数:** - *键*:MetadataKey对象,其中包含为其请求元数据值的键和相关参数(请参阅演示应用程序以了解参考实施)。 - *结果*:包含所请求元数据的复合对象。 该对象具有以下字段: - *simpleResult*:一个字符串,表示在请求身份验证TTL、授权TTL或设备ID时的元数据值。 如果为用户元数据发出请求,则此值为null。 - *userMetadataResult*:包含JSON用户元数据有效负载的Java表示法的对象。 例如: ```json { "street": "Main Avenue", "buildings": ["150", "320"] } ``` 翻译为Java的形式: ```java Map("street" -> "Main Avenue", "buildings" -> List("150", "320"))) ``` **用户元数据对象的实际结构类似于以下内容:** ```json { updated: 1334243471, encrypted: ["encryptedProp"], data: { zip: ["12345", "34567"], maxRating: { "MPAA": "PG-13", "VCHIP": "TV-Y", "URL": "http://exam.pl/e/manage/ratings" }, householdID: "3456", userID: "BgSdasfsdk23/dsaf3+saASesadgfsShggssd=", channelID: ["channel-1", "channel-2"] } } ``` 请求简单元数据(身份验证TTL、授权TTL或设备ID)时,该值为空。 - *已加密*:指定是否对检索到的元数据进行加密的布尔值。 此参数仅对用户元数据请求有意义,对于始终未加密接收的静态元数据(例如,身份验证TTL)没有意义。 如果此参数设置为True,则程序员需要通过使用白名单私钥(与在中签名请求者ID时使用的私钥)执行RSA解密来获取未加密的用户元数据值。 [`setRequestor`](#setRequestor) 调用)。 **触发者:** [`getMetadata()`](#getMetadata) **更多信息:** [用户元数据](/help/authentication/user-metadata.md) </br> ## getVersion {#getVersion} **描述:** 使用此方法检索AccessEnabler当前版本 | **API调用:获取AccessEnabler版本** | | --- | | ```public static String getVersion()``` | ## 跟踪事件 {#tracking} Access Enabler会触发一个附加回调,该回调不一定与权利文件流相关。 实现名为的事件跟踪回调函数 *sendTrackingData()* 是可选的,但它使应用程序能够跟踪特定事件并编译统计信息,如成功/失败的身份验证/授权尝试次数。 以下是 *sendTrackingData()* 回调: ### sendTrackingData {#sendTrackingData} **描述:** Access Enabler向应用程序发出各种事件(如身份验证/授权流的完成/失败)的信号时触发的回调。 sendTrackingData()还会报告设备类型、Access Enabler客户端类型和操作系统。 >[!WARNING] > > 设备类型和操作系统通过使用公共Java库(http://java.net/projects/user-agent-utils)和用户代理字符串派生。 请注意,此信息仅以粗略的方式提供,用于按设备类别细分操作量度,但该Adobe对错误结果不承担任何责任。 请相应地使用新功能。 - 设备类型的可能值: - `computer` - `tablet` - `mobile` - `gameconsole` - `unknown` - Access Enabler客户端类型的可能值: - `flash` - `html5` - `ios` - `tvos` - `android` - `firetv` | 回调:跟踪事件 | | --- | | ```public void sendTrackingData(Event event, ArrayList<String> data)``` | **可用性:** v1.0+ **参数:** - *事件*:正在跟踪的事件。 有三种可能的跟踪事件类型: - **授权检测:** 每当授权令牌请求返回时(事件类型为 `EVENT_AUTHZ_DETECTION`) - **authenticationDetection:** 每当进行身份验证检查时(事件类型为 `EVENT_AUTHN_DETECTION`) - **mvpdSelection:** 当用户在MVPD选择表单中选择MVPD时(事件类型为 `EVENT_MVPD_SELECTION`) - *数据*:与所报告事件关联的其他数据。 此数据以值列表的形式提供。 以下说明用于解释 *数据* 数组: - 对于事件类型 *`EVENT_AUTHN_DETECTION`:* - **0** — 令牌请求是否成功(true/false),如果以上为true: - **1** - MVPD ID字符串 - **2** - GUID(md5散列) - **3** — 令牌已在缓存中(true/false) - **4** — 设备类型 - **5** - Access Enabler客户端类型 - **6** — 操作系统类型 - 对于事件类型 `EVENT_AUTHZ_DETECTION` - **0** — 令牌请求是否成功(true/false),如果成功: - **1** - MVPD ID - **2** - GUID(md5散列) - **3** — 令牌已在缓存中(true/false) - **4** — 错误 - **5** — 详细信息 - **6** — 设备类型 - **7** - Access Enabler客户端类型 - **8** — 操作系统类型 - 对于事件类型 `EVENT_MVPD_SELECTION` - **0** — 当前所选MVPD的ID - **1** — 设备类型 - **2** - Access Enabler客户端类型 - **3** — 操作系统类型 **触发者:** `checkAuthentication(), getAuthentication(), checkAuthorization(), getAuthorization(), setSelectedProvider()`
import React from 'react' import Box from '@mui/material/Box'; import Modal from '@mui/material/Modal'; import CardContent from '@mui/material/CardContent'; import Card from '@mui/material/Card'; import Typography from '@mui/material/Typography'; import { useSelector, useDispatch } from 'react-redux'; import { closeModal } from '../../store/modal'; const style = { position: 'absolute', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: 500, bgcolor: 'background.paper', border: '2px solid #000', boxShadow: 24, p: 4, }; export const ModalComponent = ({ children }) => { const { open, title } = useSelector(state => state.modal); const dispatch = useDispatch(); const handleClose = () => dispatch(closeModal()); return ( <Modal open={open} onClose={handleClose} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" > <Box sx={style}> <Card variant='outline'> <CardContent> <Typography sx={{ fontSize: 14 }} color="text.primary" gutterBottom> {title} </Typography> {children} </CardContent> </Card> </Box> </Modal> ) }
// import { useContext } from "react"; // import { // BarChart, // Bar, // XAxis, // YAxis, // Tooltip, // Legend, // ResponsiveContainer, // } from "recharts"; // import { ThemeContext } from "../../../context/ThemeContext"; // import { FaArrowUpLong } from "react-icons/fa6"; // import { LIGHT_THEME } from "../../../constants/themeConstants"; // import "./AreaCharts.scss"; // const data = [ // { // month: "Jan", // loss: 70, // profit: 100, // }, // { // month: "Feb", // loss: 55, // profit: 85, // }, // { // month: "Mar", // loss: 35, // profit: 90, // }, // { // month: "April", // loss: 90, // profit: 70, // }, // { // month: "May", // loss: 55, // profit: 80, // }, // { // month: "Jun", // loss: 30, // profit: 50, // }, // { // month: "Jul", // loss: 32, // profit: 75, // }, // { // month: "Aug", // loss: 62, // profit: 86, // }, // { // month: "Sep", // loss: 55, // profit: 78, // }, // ]; // const AreaBarChart = () => { // const { theme } = useContext(ThemeContext); // const formatTooltipValue = (value) => { // return `${value}k`; // }; // const formatYAxisLabel = (value) => { // return `${value}k`; // }; // const formatLegendValue = (value) => { // return value.charAt(0).toUpperCase() + value.slice(1); // }; // return ( // <div className="bar-chart"> // <div className="bar-chart-info"> // <h5 className="bar-chart-title">Monthly Readings</h5> // <div className="chart-info-data"> // <div className="info-data-value">$50.4K</div> // <div className="info-data-text"> // <FaArrowUpLong /> // <p>5% than last month.</p> // </div> // </div> // </div> // <div className="bar-chart-wrapper"> // <ResponsiveContainer width="100%" height="100%"> // <BarChart // width={500} // height={200} // data={data} // margin={{ // top: 5, // right: 5, // left: 0, // bottom: 5, // }} // > // <XAxis // padding={{ left: 10 }} // dataKey="month" // tickSize={0} // axisLine={false} // tick={{ // fill: `${theme === LIGHT_THEME ? "#676767" : "#f3f3f3"}`, // fontSize: 14, // }} // /> // <YAxis // padding={{ bottom: 10, top: 10 }} // tickFormatter={formatYAxisLabel} // tickCount={6} // axisLine={false} // tickSize={0} // tick={{ // fill: `${theme === LIGHT_THEME ? "#676767" : "#f3f3f3"}`, // }} // /> // <Tooltip // formatter={formatTooltipValue} // cursor={{ fill: "transparent" }} // /> // <Legend // iconType="circle" // iconSize={10} // verticalAlign="top" // align="right" // formatter={formatLegendValue} // /> // <Bar // dataKey="profit" // fill="#475be8" // activeBar={false} // isAnimationActive={false} // barSize={24} // radius={[4, 4, 4, 4]} // /> // <Bar // dataKey="loss" // fill="#e3e7fc" // activeBar={false} // isAnimationActive={false} // barSize={24} // radius={[4, 4, 4, 4]} // /> // </BarChart> // </ResponsiveContainer> // </div> // </div> // ); // }; // export default AreaBarChart; import { useContext } from "react"; import { BarChart, Bar, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer, } from "recharts"; import { ThemeContext } from "../../../context/ThemeContext"; import { FaArrowUpLong } from "react-icons/fa6"; import { LIGHT_THEME } from "../../../constants/themeConstants"; import "./AreaCharts.scss"; const data = [ { day: "Mon", Co2_level: 1000 }, { day: "Tue", Co2_level: 500 }, { day: "Wed", Co2_level: 800 }, { day: "Thur", Co2_level: 1200 }, { day: "Fri", Co2_level: 1400 }, { day: "Sat", Co2_level: 500 }, { day: "Sun", Co2_level: 300 }, ]; const AreaBarChart = () => { const { theme } = useContext(ThemeContext); const formatTooltipValue = (value) => { return `${value}ppm`; }; const formatYAxisLabel = (value) => { return `${value}`; }; const formatLegendValue = (value) => { return value.charAt(0).toUpperCase() + value.slice(1); }; return ( <div className="bar-chart"> <div className="bar-chart-info"> <h2 className="bar-chart-title">Weekly Readings(ppm)</h2> <div className="chart-info-data"> <div className="info-data-value">800ppm</div> <div className="info-data-text"> <FaArrowUpLong /> <p>5% than last week.</p> </div> </div> </div> <div className="bar-chart-wrapper"> <ResponsiveContainer width="100%" height="100%"> <BarChart width={500} height={200} data={data} margin={{ top: 5, right: 5, left: 0, bottom: 5, }} > <XAxis padding={{ left: 10 }} dataKey="day" tickSize={0} axisLine={false} tick={{ fill: `${theme === LIGHT_THEME ? "#676767" : "#f3f3f3"}`, fontSize: 14, }} /> <YAxis padding={{ bottom: 10, top: 10 }} tickFormatter={formatYAxisLabel} tickCount={6} axisLine={false} tickSize={0} tick={{ fill: `${theme === LIGHT_THEME ? "#676767" : "#f3f3f3"}`, }} /> <Tooltip formatter={formatTooltipValue} cursor={{ fill: "transparent" }} /> <Legend iconType="circle" iconSize={10} verticalAlign="top" align="right" formatter={formatLegendValue} /> <Bar dataKey="Co2_level" fill="#475be8" activeBar={false} isAnimationActive={false} barSize={44} radius={[4, 4, 4, 4]} /> {/* <Bar dataKey="loss" fill="#e3e7fc" activeBar={false} isAnimationActive={false} barSize={24} radius={[4, 4, 4, 4]} /> */} </BarChart> </ResponsiveContainer> </div> </div> ); }; export default AreaBarChart;
import classes from './styles.module.scss' import reactPng from './assets/React-icon.png' import { useCallback, useState } from 'react' import { randomInteger } from '../utils/helpers' const App = () => { const [appBackground, setAppBackground] = useState('rgb(255,255,255)') const generateColor = () => { const r = randomInteger(0, 255) const g = randomInteger(0, 255) const b = randomInteger(0, 255) const newColor = `rgb(${r},${g},${b})` setAppBackground(newColor) } const handleButtonClick = useCallback(() => { generateColor() }, []) return ( <div className={classes.app} style={{ background: appBackground }}> <h1>React Boilerplate</h1> <img className={classes.reactIcon} src={reactPng} alt="React icon" /> <button className={classes.changeButton} onClick={handleButtonClick}> Change </button> </div> ) } export default App
import React, {useEffect, useState} from 'react'; import { View, ScrollView, Text, Image, StyleSheet, SafeAreaView, TouchableOpacity, FlatList, Alert, ActivityIndicator, } from 'react-native'; import {useRoute} from '@react-navigation/native'; import {useNavigation} from '@react-navigation/native'; import styles from './styles'; import CustomHeader from '../../components/customHeader/CustomHeader'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import colors from '../../themes/colors'; import MainButton from '../../components/mainButton/MainButton'; import EventLabel from '../../components/enventLabel/EventLabel'; import {calcHeight} from '../../helpers/styles/responsive-helper.service'; import {useSelector} from 'react-redux'; const EventDetails = () => { const route = useRoute(); const {eventId} = route.params; const navigation = useNavigation(); const [events, setEvents] = useState([]); const [isLoading, setIsLoading] = useState(true); const {auth} = useSelector(state => state); const token = auth?.user?.jwt; const getEvents = async () => { try { const response = await fetch( `https://useful-sharing-fa87aa449a.strapiapp.com/api/event-details/${eventId}`, { method: 'GET', headers: { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, }, ); if (!response.ok) { throw new Error('Network response was not ok'); } const json = await response.json(); return json; } catch (error) { throw error; } }; const handleJoinEvent = async () => { fetch('https://useful-sharing-fa87aa449a.strapiapp.com/api/user-bookings', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', Authorization: `Bearer ${token}`, }, body: JSON.stringify({ data: { users_permissions_user: '1', event_details: [events?.data?.id], }, }), }) .then(response => response.json()) .then(json => { if (json?.data) { Alert.alert('Success', 'Event joined successfully'); navigation.navigate('Dashboard'); } else { Alert.alert('Error', 'Error joining event'); } }) .catch(error => { console.error(error); }); }; React.useLayoutEffect(() => { navigation.setOptions({ headerLeft: () => <CustomHeader arrowColor="white" />, }); }, [navigation]); const renderItem = ({item}) => { return ( <EventLabel iconName={item.iconName} title={item[0]} value={item[1]} /> ); }; const fetchData = async () => { try { const eventsData = await getEvents(); setEvents(eventsData); } catch (error) { console.error(error); } finally { setIsLoading(false); } }; const joinEvent = async () => { try { handleJoinEvent(); } catch (error) { console.error(error); } finally { setIsLoading(false); } }; useEffect(() => { fetchData(); }, []); return ( <SafeAreaView style={styles.wrapper}> {isLoading ? ( <View style={styles.indicatorContainer}> <ActivityIndicator size="large" color={colors.primary} /> </View> ) : ( <ScrollView contentContainerStyle={styles.container}> <Image source={{uri: events?.data?.attributes?.imageUrl}} style={styles.eventImage} /> <Text style={styles.eventTitle}> {events?.data?.attributes?.name} </Text> <FlatList scrollEnabled={false} data={ events?.data?.attributes && Object.entries(events?.data?.attributes) } renderItem={renderItem} keyExtractor={item => item} /> <MainButton onPress={joinEvent} style={styles.button} title="Join Event" /> </ScrollView> )} </SafeAreaView> ); }; export default EventDetails;
@extends('layouts.admin') @section('content') <div class="card bg-sucess"> <div class="card-header"> <h4>Add Product</h4> </div> <form action="{{ route('products.store') }}" method="POST" class="border border-primary" enctype="multipart/form-data"> @csrf <div class="row"> <div class="col md-6 mb-3"> <select name="cate_id" value='' class="form-select"> <option selected> Select a Category</option> @foreach ($category as $item) <option value="{{ $item->id }}">{{ $item->name}}</option> @endforeach </select> </div> </div> <div class="row"> <div class="col-md-6"> <label for="">Name</label> <input type="text" class="form-control" name="name"> </div> <div class="col-md-6"> <label for="">Slug</label> <input type="text" class="form-control" name="slug"> </div> </div> <div class="col-md-12"> <label for="">Small Description</label> <textarea name="description" rows="3" class="form-control"></textarea> </div> <div class="row"> <div class="col md-6 mb-3"> <label for="">Original Price</label> <input type="number" class="form-control" name="original_price"> </div> <div class="col md-6 mb-3"> <label for="">Selling Price</label> <input type="number" class="form-control" name="selling_price"> </div> </div> <div class="row"> <div class="col md-6 mb-3"> <label for="">Tax</label> <input type="number" class="form-control" name="tax"> </div> <div class="col md-6 mb-3"> <label for="">Quantity</label> <input type="number" class="form-control" name="quantity"> </div> </div> <div class="row"> <div class="col-md-6 mb-3"> <label for="" class="">Status</label> <input type="checkbox" name="status"> </div> <div class="col-md-6 mb-3"> <label for="">Trending</label> <input type="checkbox" name="trending"> </div> </div> <div class="col-md-6 mb-3"> <label for="">Meta_Title</label> <input type="text" class="form-control" name="meta_title"> </div> <div class="col-md-6 mb-3"> <label for="">Meta_Keywords</label> <textarea name="meta_keywords" class="form-control" rows="3"></textarea> </div> <div class="col-md-6 mb-3"> <label for="">Meta_Description</label> <textarea name="meta_description" class="form-control" rows="3"></textarea> </div> <div class="col-md-6 mb-3"> <input type="file" name="image" class="form-control"> </div> <div class="col-md-6"> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> </div> @endsection
package com.example.studybuddy.Activity import CourseAdapter import SemesterCourse import UserAddSemesterCourseDialogFragment import android.annotation.SuppressLint import android.os.Bundle import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.studybuddy.R import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class UserSemesterCoursesActivity : AppCompatActivity(), CourseAdapter.OnDeleteLongClickListener { private lateinit var recyclerView: RecyclerView private lateinit var adapter: CourseAdapter private var courseList = mutableListOf<SemesterCourse>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.fragment_semester_courses) val customToolbar = findViewById<TextView>(R.id.action_bar_title) customToolbar.text = getString(R.string.courses) recyclerView = findViewById(R.id.semesterRecyclerView) val backButton = findViewById<ImageView>(R.id.backButton) backButton.setOnClickListener { finish() } val addSemesterCourseButton = findViewById<FloatingActionButton>(R.id.addSemesterCourse) addSemesterCourseButton.setOnClickListener { // Open the dialog here val dialog = UserAddSemesterCourseDialogFragment() dialog.setAdapter(adapter, this) // Pass adapter and fragment reference dialog.show(supportFragmentManager, "AddCourseDialogFragment") } val email = GlobalData.userEmail val usersRef = FirebaseDatabase.getInstance().getReference("users") val userQuery = usersRef.orderByChild("email").equalTo(email) println(email) userQuery.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { for (userSnapshot in dataSnapshot.children) { val semesterDataSnapshot = userSnapshot.child("semester") for (semesterSnapshot in semesterDataSnapshot.children) { val semesterName = semesterSnapshot.child("name").getValue(String::class.java) println(semesterName) if (semesterName == intent.getStringExtra("semesterName")) { val coursesSnapshot = semesterSnapshot.child("Courses") for (courseSnapshot in coursesSnapshot.children) { val courseName = courseSnapshot.child("name").getValue(String::class.java) val courseLocation = courseSnapshot.child("location").getValue(String::class.java) val courseTime = courseSnapshot.child("time").getValue(String::class.java) val courseDate = courseSnapshot.child("date").getValue(String::class.java) val semesterCourse = SemesterCourse(courseName ?: "", courseLocation ?: "", courseTime ?: "", courseDate ?: "") println(semesterCourse) semesterCourse.let { courseList.add(semesterCourse) } } } } } println(courseList) adapter = CourseAdapter(courseList, this@UserSemesterCoursesActivity) recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(this@UserSemesterCoursesActivity) } override fun onCancelled(databaseError: DatabaseError) { // Handle any errors that occur } }) } override fun onDeleteLongClick(course: SemesterCourse) { val builder = AlertDialog.Builder(this) builder.setTitle("Delete Course") builder.setMessage("Are you sure you want to delete ${course.name}?") builder.setPositiveButton("Yes") { _, _ -> // Remove the course from the list and update the adapter courseList.remove(course) adapter.notifyDataSetChanged() // Perform deletion from the database deleteCourseFromDatabase(course) } builder.setNegativeButton("No", null) val dialog = builder.create() dialog.show() } private fun deleteCourseFromDatabase(course: SemesterCourse) { val userEmail = GlobalData.userEmail val database = FirebaseDatabase.getInstance().reference val usersRef = database.child("users") val userQuery = usersRef.orderByChild("email").equalTo(userEmail) userQuery.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { dataSnapshot.children.forEach { userSnapshot -> val semesterSnapshot = userSnapshot.child("semester").children.find { it.child("name").getValue(String::class.java) == intent.getStringExtra("semesterName") } semesterSnapshot?.let { semester -> val coursesSnapshot = semester.child("Courses") coursesSnapshot.children.forEach { courseSnapshot -> if (courseSnapshot.child("name").getValue(String::class.java) == course.name) { courseSnapshot.ref.removeValue().addOnCompleteListener { task -> if (task.isSuccessful) { // Deletion successful Toast.makeText(applicationContext, "Course deleted successfully", Toast.LENGTH_SHORT).show() } else { // Handle deletion failure Toast.makeText(applicationContext, "Failed to delete course", Toast.LENGTH_SHORT).show() } } return@forEach } } } } } override fun onCancelled(databaseError: DatabaseError) { // Handle cancellation Toast.makeText(applicationContext, "Database operation cancelled", Toast.LENGTH_SHORT).show() } }) } fun updateAdapterData(newData: List<SemesterCourse>) { courseList.clear() courseList.addAll(newData) adapter.notifyDataSetChanged() } }
/* ----------------------------------------------------------------------------- This source file is part of FRAPPER research.animationsinstitut.de sourceforge.net/projects/frapper Copyright (c) 2008-2016 Filmakademie Baden-Wuerttemberg, Institute of Animation This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; version 2.1 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html ----------------------------------------------------------------------------- */ //! //! \file "PoemReaderNode.h" //! \brief Header file for PoemReaderNode class. //! //! \author Nils Zweiling <nils.zweiling@filmakademie.de> //! \author Stefan Habel <stefan.habel@filmakademie.de> //! \version 1.0 //! \date 29.04.2009 (last updated) //! #ifndef POEMREADERNODE_H #define POEMREADERNODE_H #include "Node.h" #include "ImageNode.h" #include "FrapperPrerequisites.h" #include "BaseGraphicsView.h" #include <qpropertyanimation.h> #include <QPointF> #include <QtCore/QTimer> #include <QtCore/QTime> #include <QtGui> #include <Ogre.h> #if (OGRE_PLATFORM == OGRE_PLATFORM_WIN32) #include <windows.h> #endif namespace PoemReaderNode { using namespace Frapper; //! //! Class representing nodes for head animation logic in a 3D scene. //! class PoemReaderNode : public Node { Q_OBJECT public: // constructors and destructors //! //! Constructor of the PoemReaderNode class. //! //! \param name The name for the new node. //! \param parameterRoot A copy of the parameter tree specific for the type of the node. //! PoemReaderNode ( QString name, ParameterGroup *parameterRoot ); //! //! Destructor of the BorAnimationNode class. //! //! Defined virtual to guarantee that the destructor of a derived class //! will be called if the instance of the derived class is saved in a //! variable of its parent class type. //! virtual ~PoemReaderNode (); public: // functions void createPoemsData(); //! //! Render the words in the scene view. //! //! \param scene The scene where to render //! \param word The string to render. //! \param size Is the point size of the word according to its frequency of appearance //! \param posx Is the position in X that the word will occupy //! \param posy Is the position in Y that the word will occupy //! \param gWordHeight Contains the height of the word with the greates height in one line //! void renderWords(QGraphicsScene *scene, QString word, qreal size, int &posx, int &posy, int &gWordHeight); //! //! Checks if the word is suitable to be in the cloud. For instance, it is not a connector (and, but, with...) or indicates location (this, there, that) ... and so on //! bool wordAccepted(QString word); //! //! Removes the wild cards provided to Kinect to understand better the words: "I choose" and "use ... please" //! QString removeWildCards(QString word); //! //! This function allows to elicit an empathic response from the character //! QString replyFromCharacter(QString word, bool finalWord); public slots: //! //! Loads the XML file. //! void loadXmlFile(); //! //! Reloads the XML file. //! void reloadXmlFile(); private: //methods bool findWord(QString str); bool hasBeenSelected(QString word); void setPoemSelected(QString name, QString replyCharacter); void createPoemParameterGroup(QString poem, int poemId); void createGrammar(QString wordselected); private slots: void reduceWordsCloud(); void updatePoemSelected(); void triggerPoemLines(); void updateFadingOutTimer(); void updateFadingInTimer(); void stopReciting(); signals: void emitGrammar(QString grammar); private: // data QString m_poemsIndexStr; QStringList poems; QStringList selectedWords; QTimer *m_foutTimer; QTimer *m_finTimer; QWidget *parent; int m_numberWords; int poemLine; bool m_recitingPoem; ParameterGroup *parameterRoot; // pointer to this Parameter Root protected: // data ParameterGroup *m_wordsGroup; ParameterGroup *m_poemsGroup; ParameterGroup *m_poemLinesGroup; Parameter *groupParameter; Parameter *inputStringParameter; Parameter *inputTagParameter; Parameter *animStateParameter; Parameter *m_poemSelected; Parameter *m_alphaParameter; Parameter *m_activationParameter; int m_numberWordsSelected; bool m_stopPoem; int m_minFrequency; }; } // namespace PoemReaderNode #endif
// // ViewController.swift // pokedex // // Created by Sai on 07/10/17. // Copyright © 2017 Sai. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate { @IBOutlet weak var collection: UICollectionView! @IBOutlet weak var searchBar: UISearchBar! var pokemons = [Pokemon]() var filteredPokemons = [Pokemon]() var musicPlayer:AVAudioPlayer! var inSearchMode = false override func viewDidLoad() { super.viewDidLoad() collection.dataSource=self collection.delegate=self searchBar.delegate=self searchBar.returnKeyType=UIReturnKeyType.done parsePokemonCsv() initAudio() } func initAudio(){ let path = Bundle.main.path(forResource: "music", ofType: "mp3")! do{ musicPlayer = try AVAudioPlayer(contentsOf: URL(string: path)! ) musicPlayer.prepareToPlay() musicPlayer.numberOfLoops = -1 musicPlayer.play() } catch let err as NSError{ print(err.debugDescription) } } func parsePokemonCsv(){ let path = Bundle.main.path(forResource: "pokemon", ofType: "csv")! do{ let csv = try CSV(contentsOfURL: path) let rows = csv.rows print(rows) for row in rows{ let pokeId = Int(row["id"]!)! let name = row["identifier"]! let newPoke = Pokemon(name: name, pokedexId: pokeId) pokemons.append(newPoke) } } catch let err as NSError { print(err.debugDescription) } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PokeCell", for: indexPath) as? PokeCell { let pokemon:Pokemon if inSearchMode { pokemon = filteredPokemons[indexPath.row] } else{ pokemon = pokemons[indexPath.row] } cell.configureCell(pokemon) return cell }else{ return UICollectionViewCell() } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { var pokemon:Pokemon if inSearchMode { pokemon = filteredPokemons[indexPath.row] }else{ pokemon = pokemons[indexPath.row] } performSegue(withIdentifier: "PokemonDetailVC", sender: pokemon) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if inSearchMode{ return filteredPokemons.count } else{ return pokemons.count } } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: 105, height: 105) } @IBAction func musicBtnPressed(_ sender: UIButton) { if musicPlayer.isPlaying { musicPlayer.pause() sender.alpha=0.2 } else{ musicPlayer.play() sender.alpha=1.0 } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { view.endEditing(true) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text == nil || searchBar.text == "" { inSearchMode=false collection.reloadData() view.endEditing(true) }else{ inSearchMode=true let lower = searchBar.text!.lowercased() filteredPokemons = pokemons.filter({$0.name.range(of: lower) != nil}) collection.reloadData() } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "PokemonDetailVC"{ if let detailsVC = segue.destination as? PokemonDetailVC{ if let poke = sender as? Pokemon{ detailsVC.pokemon = poke } } } } }
// SPDX-FileCopyrightText: 2024 Contributors to the Eclipse Foundation // // See the NOTICE file(s) distributed with this work for additional // information regarding copyright ownership. // // This program and the accompanying materials are made available under the // terms of the Apache License Version 2.0 which is available at // https://www.apache.org/licenses/LICENSE-2.0 // // SPDX-License-Identifier: Apache-2.0 #ifndef UP_CPP_DATAMODEL_VALIDATOR_UMESSAGE_H #define UP_CPP_DATAMODEL_VALIDATOR_UMESSAGE_H #include <uprotocol/v1/umessage.pb.h> #include <optional> #include <string_view> #include <tuple> /// @brief Validators for UMessage objects. /// /// See /// https://github.com/eclipse-uprotocol/up-spec/blob/main/basics/uattributes.adoc namespace uprotocol::datamodel::validator::message { enum class Reason { /// @brief The ID does not pass UUID validity checks BAD_ID, /// @brief The TTL, if present, indicates the ID has expired ID_EXPIRED, /// @brief The Priority, if set, is not within the allowable range PRIORITY_OUT_OF_RANGE, /// @brief The Payload Format is not within the allowable range PAYLOAD_FORMAT_OUT_OF_RANGE, /// @brief The type set in the message is incorrect for the validated mode WRONG_MESSAGE_TYPE, /// @brief Source URI did not pass validity checks BAD_SOURCE_URI, /// @brief Sink URI did not pass validity checks BAD_SINK_URI, /// @brief TTL is set to an invalid value (e.g. 0) INVALID_TTL, /// @brief A field was set that is not allowed for the validated mode DISALLOWED_FIELD_SET, /// @brief The Request ID did not match the ID of the request message REQID_MISMATCH, /// @brief The Priority did not match the Priority of the request message PRIORITY_MISMATCH }; /// @brief Get a descriptive message for a reason code. std::string_view message(Reason); /// @brief Return type for validity checks. /// /// The recommended usage of these checks and return types looks something /// like this: /// /// auto [valid, maybe_reason] = isValidRpcRequest(request); /// if (valid) { /// // Do something with the message /// } else if (maybe_reason) { /// log(message(*maybe_reason); /// } using ValidationResult = std::tuple<bool, std::optional<Reason>>; /// @brief Checks if UMessage is a valid UMessage of any format. /// /// A UMessage is valid if any of these are true: /// /// * isValidRpcRequest() /// * isValidRpcResponse() /// * isValidPublish() /// * isValidNotification() [[nodiscard]] ValidationResult isValid(const v1::UMessage&); /// @brief Checks if common attributes for all UMessage types are valid /// /// These checks must pass: /// * The message ID must be a valid UUID /// * If TTL is specified, the ID must not be expired /// * If Priority is specified, it is within the range of UPriority /// * Payload Format must be within the range of UPayloadFormat [[nodiscard]] ValidationResult areCommonAttributesValid(const v1::UMessage&); /// @brief Checks if UMessage is valid for invoking an RPC method /// /// In addition to all common attributes being valid, these checks must pass: /// * Message type must be UMESSAGE_TYPE_REQUEST /// * Message source must pass uri::isValidRpcResponse() /// * Message sink must pass uri::isValidRpcMethod() /// * Message priority must be UPRIORITY_CS4 or higher /// * Message ttl must be set and greater than zero /// * Message must not set commstatus /// * Message must not set reqid [[nodiscard]] ValidationResult isValidRpcRequest(const v1::UMessage&); /// @brief Checks if UMessage is a valid response /// /// In addition to all common attributes being valid, these checks must pass: /// * Message type must be UMESSAGE_TYPE_RESPONSE /// * Message source must pass uri::isValidRpcMethod() /// * Message sink must pass uri::isValidRpcResponse() /// * Message reqid must be set to a valid, unexpired UUID /// * Message priority must be UPRIORITY_CS4 or higher /// * Message must not set permission_level /// * Message must not set token [[nodiscard]] ValidationResult isValidRpcResponse(const v1::UMessage&); /// @brief Checks if UMessage is a valid response to specific RPC request /// /// In addition to all checks in isValidRpcResponse() passing: /// * Message reqid must be the ID from the request message /// * Message priority must be the priority from the request message [[nodiscard]] ValidationResult isValidRpcResponseFor( const v1::UMessage& request, const v1::UMessage& response); /// @brief Checks if UMessage is valid for publishing to a topic /// /// In addition to all common attributes being valid, these checks must pass: /// * Message type must be UMESSAGE_TYPE_PUBLISH /// * Message source must pass uri::isValidTopic() /// * Message must not set sink /// * Message must not set commstatus /// * Message must not set reqid /// * Message must not set permission_level /// * Message must not set token [[nodiscard]] ValidationResult isValidPublish(const v1::UMessage&); /// @brief Checks if UMessage is valid for sending a notification /// /// In addition to all common attributes being valid, these checks must pass: /// * Message type must be UMESSAGE_TYPE_PUBLISH /// * Message source must pass uri::isValidTopic() /// * Message sink must pass uri::isValidTopic() /// * Message must not set commstatus /// * Message must not set reqid /// * Message must not set permission_level /// * Message must not set token [[nodiscard]] ValidationResult isValidNotification(const v1::UMessage&); /// @brief This exception indicates that a UMessage object was provided that /// did not contain valid UMessage data or was the wrong type. /// /// @remarks Generally used by L2 client interfaces. Not used by checks in this /// file that return ValidationResult. struct InvalidUMessage : public std::invalid_argument { // Inherit constructors using std::invalid_argument::invalid_argument; InvalidUMessage(InvalidUMessage&&) noexcept; InvalidUMessage& operator=(InvalidUMessage&&) noexcept; InvalidUMessage(const InvalidUMessage&); InvalidUMessage& operator=(const InvalidUMessage&); }; } // namespace uprotocol::datamodel::validator::message #endif // UP_CPP_DATAMODEL_VALIDATOR_UMESSAGE_H
// @ts-nocheck import { ActionType, ModalForm, ProColumns, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from '@ant-design/pro-components'; import { Button, Form, Modal, Tag } from 'antd'; import { Fragment, useRef, useState } from 'react'; import { request } from 'umi'; import dayjs from 'dayjs'; export interface IRbacBaseProp { updateAt: string; remark?: string; } interface ISysUserItemProp extends IRbacBaseProp { id: number; username: string; status: number; role?: { id: number; name: string; }; } export default () => { const actionRef = useRef<ActionType>(); const [form] = Form.useForm(); const [modalOption, setModalOption] = useState<{ visible: boolean; title: string; isEdit?: boolean }>(); const columns: ProColumns<ISysUserItemProp>[] = [ { dataIndex: 'id', title: 'ID', width: 60, }, { dataIndex: 'username', title: '用户名', width: 120, }, { dataIndex: 'status', title: '状态', width: 120, valueEnum: { 0: { text: '正常' }, 1: { text: '禁用' }, }, render: (dom, entity) => { return <Tag color={entity.status === 0 ? 'blue' : 'magenta'}>{dom}</Tag>; }, }, { dataIndex: 'role', title: '角色', width: 120, render: (dom, entity) => { return entity.role?.name && <Tag color="green">{entity.role?.name}</Tag>; }, }, { dataIndex: 'remark', title: '备注', width: 120, }, { dataIndex: 'updateAt', title: '更新时间', width: 180, render: (text, record) => { return dayjs(record.updateAt).format('YYYY-MM-DD HH:mm:ss'); }, }, { dataIndex: 'action', title: '操作', valueType: 'option', fixed: 'right', width: 80, render: (text, record, _, action) => [ <a key="edit" onClick={async () => { setModalOption({ visible: true, title: '编辑用户', isEdit: true, }); await Promise.resolve(); form.setFieldsValue(record); }} > 编辑 </a>, <a key="del" onClick={() => { Modal.confirm({ title: '删除', content: '确定删除吗?', onOk: async () => { await request.post('/api/system/user/delete', { method: 'POST', data: { id: +record.id, }, }); action?.reload(); }, }); }} > 删除 </a>, ], }, ]; return ( <Fragment> <ProTable<ISysUserItemProp> search={false} columns={columns} rowKey="id" bordered actionRef={actionRef} scroll={{ x: 1200 }} toolBarRender={() => [ <Button key="add" type="primary" onClick={() => { setModalOption({ visible: true, title: '新增用户', }); }} > 新增 </Button>, ]} request={async (params) => { const result = await request.post('/api/system/user/list', { method: 'POST', data: params, }); return { data: result.data?.list || [], total: result.data?.total || 0, }; }} /> <ModalForm<ISysUserItemProp> title={modalOption?.title} form={form} visible={modalOption?.visible} modalProps={{ destroyOnClose: true, onCancel: () => { setModalOption({ visible: false, isEdit: false, title: modalOption?.title || '', }); }, }} grid rowProps={{ gutter: 32, }} onFinish={async (values) => { await form.validateFields(); if (values.id) { values.id = parseInt(values.id.toString(), 10); } await request.post(`/api/system/user/${values.id ? 'update' : 'add'}`, { method: 'POST', data: values, }); actionRef.current?.reload(); setModalOption({ visible: false, title: modalOption?.title || '', }); }} > <ProFormText name="username" label="用户名" colProps={{ span: 12 }} rules={[ { required: true, message: '请输入用户名', }, ]} /> <ProFormText.Password name="password" hidden={modalOption?.isEdit} label="密码" colProps={{ span: 12 }} rules={[ { required: !modalOption?.isEdit, message: '请输入密码', }, ]} /> <ProFormSelect name={['role', 'id']} label="角色" colProps={{ span: 12 }} fieldProps={{ fieldNames: { label: 'name', value: 'id' }, }} request={async () => { const result = await request.post('/api/system/role/list', { method: 'POST', data: { page: 1, pageSize: 100, }, }); return result.data?.list; }} /> <ProFormRadio.Group label="状态" name="status" initialValue={0} colProps={{ span: 12, }} options={[ { label: '正常', value: 0, }, { label: '禁用', value: 1, }, ]} /> <ProFormTextArea name="remark" label="备注" fieldProps={{ style: { height: 100, }, }} /> <ProFormText name="id" hidden /> </ModalForm> </Fragment> ); };
import { ProjectStatus, TimePreference } from '@prisma/client'; import { IsBoolean, IsDateString, IsEnum, IsOptional, IsString, } from 'class-validator'; export class CreateProjectDto { @IsString() organizationId: string; @IsString() title: string; @IsString() description: string; @IsString() @IsOptional() locationId: string; @IsDateString() startDate: Date; @IsDateString() endDate: Date; @IsEnum(TimePreference) timeCommitment: TimePreference; @IsBoolean() provideCertificate: boolean; @IsEnum(ProjectStatus) @IsOptional() status?: ProjectStatus; @IsOptional() @IsBoolean() isActive?: boolean; }
# CleanCode ## Introduction CleanCode is a repository demonstrating best practices for writing clean, maintainable, and efficient code using the Swift programming language. The repository features practical examples of MVVM architecture with coordinators, clean code principles, and comprehensive unit testing. ## Features - **MVVM Architecture**: Implements the Model-View-ViewModel architecture, promoting a clear separation of concerns and enhancing testability. - **Coordinators**: Uses the coordinator pattern to handle navigation, improving modularity and readability. - **Clean Code Practices**: Adheres to principles outlined in Robert C. Martin's "Clean Code," including meaningful names, small functions, and avoiding duplication. - **Unit Tests**: Comprehensive unit tests ensure code reliability and correctness, with examples demonstrating testable code structure. ## Getting Started ### Prerequisites - Xcode 12.5 or later - Swift 5.3 or later ### Installation 1. Clone the repository: ```bash git clone https://github.com/ricardocostasilva/CleanCode.git ``` 2. Open the project in Xcode: ```bash open CleanCode/CleanCodeTest.xcodeproj ``` ### Running the Application - Select the `CleanCodeTest` scheme. - Press `Cmd+R` to run the application. - Can be an issue with the database. delete the one present in the Persistent folder and import it again. ### Running the Tests - Select the `CleanCodeTest` scheme. - Press `Cmd+U` to run the tests. ## Best Practices Demonstrated - **Code Organization**: Clear separation of concerns with distinct directories for models, views, and controllers. - **Naming Conventions**: Descriptive names for variables, functions, and classes. - **Testing**: Comprehensive unit tests to ensure code reliability and correctness. ## License This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
import axios from 'axios' import * as API from '@/api/app' /** * 文件上传 * @param {Object} file file对象 */ export function upload(file) { const formData = new FormData() formData.append('file', file) return API.upload(formData) } export function base64ToFile(data, filename = 'untitled') { try { const arr = data.split(',') const mimeMatch = arr[0].match(/:(.*?);/) if (!mimeMatch) { throw new Error('Invalid base64 data') } const mime = mimeMatch[1] const extensionMatch = mime.match(/\/([a-zA-Z]+)/) const extension = extensionMatch ? `.${extensionMatch[1]}` : '' const bstr = atob(arr[1]) let n = bstr.length const u8arr = new Uint8Array(n) while (n--) { u8arr[n] = bstr.charCodeAt(n) } // Append the file extension to the filename const filenameWithExtension = `${filename}${extension}` // Convert to a File object return new File([u8arr], filenameWithExtension, { type: mime }) } catch (e) { console.error(e) } } export function pathToFile(filePath, accept) { if (!(accept instanceof RegExp) && typeof accept !== 'string') { return Promise.reject(new Error('accept 参数必须是正则表达式或字符串')) } const filename = filePath.split('/').pop() return fetch(filePath) .then((response) => response.blob()) .then((blob) => { if ( (accept instanceof RegExp && accept.test(blob.type)) || (typeof accept === 'string' && blob.type.startsWith(accept)) ) { const file = new File([blob], filename, { type: blob.type }) return file } else { return Promise.reject(new Error('文件类型不符合要求或指定文件未找到')) } }) }
import React, {useState, useEffect} from 'react'; import { Modal, Text, Button, StyleSheet, View, TextInput, ScrollView, Pressable, Alert, } from 'react-native'; import DatePicker from 'react-native-date-picker'; export const Formulario = props => { //STATE DE LOS INPUTS const [id, setId] = useState(''); const [pacienteForm, setPacienteForm] = useState(''); const [propietarioForm, setPropietarioForm] = useState(''); const [emailForm, setEmailForm] = useState(''); const [telefonoForm, setTelefonoForm] = useState(''); const [sintomasForm, setSintomasForm] = useState(''); const [fechaForm, setFechaForm] = useState(new Date()); const { modalVisible, cerrarModal, setListadoPacientes, listadoPacientes, pacienteEdit: pacienteObjEditable, setPacienteEdit, } = props; // si muestran en el formulario, los datos del paciente si el valor de pacienteObjEditable cambia, es decir cuando aplaste el boton editar, useEffect(() => { if (Object.keys(pacienteObjEditable).length > 0) { setId(pacienteObjEditable.id); setPacienteForm(pacienteObjEditable.pacienteForm); setPropietarioForm(pacienteObjEditable.propietarioForm); setEmailForm(pacienteObjEditable.emailForm); setFechaForm(pacienteObjEditable.fechaForm); setTelefonoForm(pacienteObjEditable.telefonoForm); setSintomasForm(pacienteObjEditable.sintomasForm); } }, [pacienteObjEditable]); //lOGICA PARA ALMACENAR UNA CITA const guardarNuevaCita = () => { //validar antes de guardar: valida que todos los campos del formualrio estén llenos if ( [ pacienteForm, propietarioForm, emailForm, fechaForm, sintomasForm, ].includes('') ) { // esta línea verifica que el arreglo tenga una cadena vacía como elemento - si lo tiene lo evaluá como true //alertas nativas Alert.alert('Error', 'Todos los campos son obligatorios', [ {text: 'Cancelar', style: 'cancel'}, {text: 'Entendido'}, ]); //Retorna la alerta si todos los campos no están llenos return; } //SI TODOS LOS CAMPOS ESTÁN LLENOS //CREA UN OBJETO con todos los valores del state que almacenan el valor de los inputs del form, donde como las variables son iguales a los nombre de las propiedades se escribe directamente, el nombre de la variable---> pacienteForm: pacienteForm const nuevoPaciente = { pacienteForm, propietarioForm, emailForm, telefonoForm, fechaForm, sintomasForm, }; //Revisar si es un nuevo registro o edición, revisando si el id existe o no, si no existe, es porque aún no ha sido creado el paciente if (id) { //editando //le agrega el mismo id DEL STATE: idForm, al objeto: nuevoPaciente nuevoPaciente.id = id; //este id es el del state que también tiene el mismo nombre que la propiedad del objeto nuevoPaciente //itera sobre el state pacientes de app (contiene la lista de objetos de los nuevosPacitens), comparando el id de cada objeto, de esa lista de objetos con el del objeto nuevopaciente que se crea con un nuevo registro y reescribiendo el valor actual del input y por tanto del state asignado a ese input en el objeto--->nuevoPaciente const pacientesActualizados = listadoPacientes.map(pacienteState => pacienteState.id === nuevoPaciente.id ? nuevoPaciente : pacienteState, ); //.map retorna un nuevo arreglo con la modificación de la edición, por eso no se usa spread operator setListadoPacientes(pacientesActualizados); //setear el obj del state que utilizamos para mostrar en los inputs los datos de ese paciente setPacienteEdit({}); } else { //nuevo registro //si es nuevo registro se asigna un id nuevoPaciente.id = Date.now(); //AGREGA UN NUEVO PACIENTE AL RESTO setListadoPacientes([...listadoPacientes, nuevoPaciente]); //toma una copia del arreglo con los pacientes previos en el estado (con los elementos de este arreglo) y se le agrega un nuevo paciente al arreglo, que es también es un objeto console.log(nuevoPaciente); } //cuando llena el formulario se cierra la ventana emergente cerrarModal(); //Dejar los campos vacíos de los formularios al guardar la cita setId(''); setPacienteForm(''); setPropietarioForm(''); setEmailForm(''); setSintomasForm(''); setTelefonoForm(''); setFechaForm(new Date()); }; return ( <Modal animationType="slide" visible={modalVisible}> <View style={styles.contenido}> <ScrollView> <Text style={styles.titulo}>{pacienteObjEditable.id? 'Editar':'Nueva'}{' '}<Text style={styles.tituloBold}>Cita</Text> </Text> <Pressable style={styles.btnCancelar} onLongPress={() => { cerrarModal() setPacienteEdit({}); // al dar click en cancelar que también se reseté los inputs del form de tal forma que solo al presinar editar se mostraran los valores en los inputs setId(''); setPacienteForm(''); setPropietarioForm(''); setEmailForm(''); setSintomasForm(''); setTelefonoForm(''); setFechaForm(new Date()); }}> <Text style={styles.btnCancelarTexto}>X Cancelar</Text> </Pressable> <View style={styles.campo}> <Text style={styles.label}>Nombre Paciente</Text> <TextInput style={styles.input} placeholder="Nombre Paciente" placeholderTextColor={'#666'} value={pacienteForm} onChangeText={setPacienteForm} /> </View> <View style={styles.campo}> <Text style={styles.label}>Nombre Propietario</Text> <TextInput style={styles.input} placeholder="Nombre Propietario" placeholderTextColor={'#666'} value={propietarioForm} onChangeText={setPropietarioForm} /> </View> <View style={styles.campo}> <Text style={styles.label}>Email Propietario</Text> <TextInput style={styles.input} placeholder="Email Propietario" keyboardType={'email-address'} placeholderTextColor={'#666'} value={emailForm} onChangeText={setEmailForm} /> </View> <View style={styles.campo}> <Text style={styles.label}>Teléfono Propietario</Text> <TextInput style={styles.input} placeholder="Teléfono Propietario" keyboardType={'number-pad'} placeholderTextColor={'#666'} value={telefonoForm} onChangeText={setTelefonoForm} maxLength={10} /> </View> <View style={styles.campo}> <Text style={styles.label}>Fecha Alta</Text> <View style={styles.fechaContenedor}> <DatePicker date={fechaForm} locale="es" onDateChange={date => setFechaForm(date)} /> </View> </View> <View style={styles.campo}> <Text style={styles.label}>Síntomas Paciente</Text> <TextInput style={[styles.input, styles.sintomasInput]} placeholder="Síntomas" placeholderTextColor={'#666'} value={sintomasForm} onChangeText={setSintomasForm} multiline={true} numberOfLines={4} /> </View> <Pressable style={styles.btnNuevaCita} onPress={guardarNuevaCita}> <Text style={styles.btnNuevaCitaTexto}>{pacienteObjEditable.id? 'Editar':'Agregar'} Paciente</Text> </Pressable> </ScrollView> </View> </Modal> ); }; const styles = StyleSheet.create({ contenido: { backgroundColor: '#6D28D9', flex: 1, }, titulo: { fontSize: 30, fontWeight: '600', textAlign: 'center', marginTop: 30, color: '#FFF', }, tituloBold: { fontWeight: '900', }, btnCancelar: { marginTop: 20, marginBottom: 11, backgroundColor: '#5827A4', marginHorizontal: 30, padding: 15, borderRadius: 10, }, btnCancelarTexto: { color: '#FFF', textAlign: 'center', fontWeight: '900', fontSize: 16, textTransform: 'uppercase', }, campo: { marginTop: 10, marginHorizontal: 30, }, label: { color: '#FFF', marginBottom: 10, marginTop: 15, fontSize: 20, fontWeight: '600', }, input: { backgroundColor: '#FFF', padding: 15, borderRadius: 10, }, sintomasInput: { height: 100, }, fechaContenedor: { backgroundColor: '#FFF', borderRadius: 10, }, btnNuevaCita: { marginVertical: 50, backgroundColor: '#F59E0B', paddingVertical: 15, marginHorizontal: 30, borderRadius: 10, }, btnNuevaCitaTexto: { color: '#5827A4', textAlign: 'center', fontWeight: '900', fontSize: 16, textTransform: 'uppercase', }, });
<?php /** * Aufbaustudiengang.php * Model class for postgraduate study courses (table mvv_aufbaustudiengang) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * @author Peter Thienel <thienel@data-quest.de> * @license http://www.gnu.org/licenses/gpl-2.0.html GPL version 2 * @category Stud.IP * @since 4.4 */ class Aufbaustudiengang extends ModuleManagementModel { protected static function configure($config = []) { $config['db_table'] = 'mvv_aufbaustudiengang'; $config['belongs_to']['grund_studiengang'] = array( 'class_name' => 'Studiengang', 'assoc_foreign_key' => 'studiengang_id', 'foreign_key' => 'grund_stg_id' ); $config['has_one']['aufbau_studiengang'] = array( 'class_name' => 'Studiengang', 'assoc_foreign_key' => 'studiengang_id', 'foreign_key' => 'aufbau_stg_id' ); $config['i18n_fields']['kommentar'] = true; parent::configure($config); } public function getDisplayName($options = self::DISPLAY_DEFAULT) { return $this->aufbau_studiengang->getDisplayName($options); } public function validate() { $ret = parent::validate(); $types = $GLOBALS['MVV_AUFBAUSTUDIENGANG']['TYP']['values']; /* if (!$types[$this->typ]) { $ret['typ'] = true; $messages = array(_('Unbekannter Typ des Aufbaustudiengangs')); throw new InvalidValuesException(join("\n", $messages), $ret); } * */ return $ret; } /** * Inherits the status of the parent study course. * * @return string The status (see mvv_config.php) */ public function getStatus() { if ($this->aufbau_studiengang) { return $this->aufbau_studiengang->getStatus(); } elseif ($this->isNew()) { return $GLOBALS['MVV_STUDIENGANG']['STATUS']['default']; } return parent::getStatus(); } }
# Lighting Lighting is the setting to configure all settings related to light, however, some light settings are in **Project Setting→Graphics, URP/HDRP setting** in the Assets folder. Even **Preferences→GI Cache is also related** to light. Another setting named **Lighting Explore** is also used for all lighting settings in the scene. It would not be obvious when beginners try to learn Unity lighting. To understand **Lighting** Settings in Unity, you can think they are static settings for the project, once you set them, you will not likely touch them anymore. ## SCENE <picture><img src="https://github.com/qinbatista/UnityLightSetting/blob/master/Images/lightsetting.png" width = 1000px align="center"></picture> Used to set the lighting type of **GI**, there are **Baked GI** and **Realtime GI**. Depending on your project, you can choose Baked GI for better performance, while Realtime GI for better Graphic quality but lower performance. ### Light Settings Save all your light configurations into prefab, so you can save your settings and reuse them later. ### Realtime Lighting (Realtime Global Illumination Lighting) <picture><img src="https://github.com/qinbatista/UnityLightSetting/blob/master/Images/GISetting.png" width = 900px align="center"></picture> This setting is specific for the **light type of** **Directional Light** to generate the **Indirect light(GI)**, once it is opened, Directional Light can generate indirect light in realtime. It is not free and your scene must be satisfied: - Only **static objects** can contribute to GI from Directional Light - **Directional Light** setting→**Indirect Multiplier** must be bigger than 1(light will bounce at least once) *Here is an example of GI did not succeed because objects are not static or the Indirect Multiplier is 0* <picture><img src="https://github.com/qinbatista/UnityLightSetting/blob/master/Images/GIFailed.png" width = 900px align="center"></picture> *Here is an example of GI that was successful because objects are static and the indirect multiplier is 70.5* <picture><img src="https://github.com/qinbatista/UnityLightSetting/blob/master/Images/GISuccess.png" width = 900px align="center"></picture> | Option | Description | | ------ | ----------- | | Realtime Global Illumination | Open Realtime GI for Directional Light | | Realtime environment Light | If **Mixed Lighting->Baked Global Illumination** is opened, open realtime GI or not | | Indirect Resolution | Quality of GI or light baking map, higher value leads to high quality but longer baking time. Bake once every time the indirect resolution changes, after baking a real-time light map, the scene can use real-time GI for all static objects, and all the values will be saved to real-time Lightmaps | <picture><img src="https://github.com/qinbatista/UnityLightSetting/blob/master/Images/lightingmap.png" width = 900px align="center"></picture> *Here are examples of different Indirect Resolutions, open in **Scene->Draw Model->Realtime Global Illumination**.* <picture><img src="https://github.com/qinbatista/UnityLightSetting/blob/master/Images/GIResolution2.png" width = 900px align="center"></picture> <picture><img src="https://github.com/qinbatista/UnityLightSetting/blob/master/Images/GIResolution8.png" width = 900px align="center"></picture> #### Real GI showcase - Scene Location`Assets->Scene->1RealtimeGI` ![Minion](https://github.com/qinbatista/UnityLightSetting/blob/master/Images/ShowGI.gif)
// // Theme.swift // StyleGuide // // Created by Phong Vo on 14/08/2023. // import SwiftUI public class Theme: ObservableObject, Decodable { public enum CodingKeys: String, CodingKey { case primaryColor = "primary_color" case secondaryColor = "secondary_color" case errorColor = "error_color" } required public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) // TODO: this just for debugging, need an extension to convert these string to SwiftUI.Color and set them to Color type instance below primaryColorStr = try container.decode(String.self, forKey: .primaryColor) secondaryColorStr = try container.decode(String.self, forKey: .secondaryColor) errorColorStr = try container.decode(String.self, forKey: .errorColor) // Just for testing primaryColor = .white secondaryColor = .white errorColor = .white } // TODO: this just for debugging, need an extension to convert these string to SwiftUI.Color and set them to Color type instance below public var primaryColorStr: String = "" public var secondaryColorStr: String = "" public var errorColorStr: String = "" @Published public var primaryColor: Color @Published public var secondaryColor: Color @Published public var errorColor: Color init(primaryColor: Color, secondaryColor: Color, errorColor: Color) { self.primaryColor = primaryColor self.secondaryColor = secondaryColor self.errorColor = errorColor } } extension Theme { static let `default` = Theme( primaryColor: .black, secondaryColor: .black.opacity(0.5), errorColor: .red ) }
/* eslint-disable react/prop-types */ import React, {useContext, useImperativeHandle} from "react"; import { KeyboardAvoidingView, Platform, Pressable, SafeAreaView, ScrollView, View, } from "react-native"; import {ThemeContext, UnifiedTheme} from "."; import {AlignContent, AlignItems, AlignSelf, BoxProps, JustifyContent, SPACING} from "./Common"; import {mediaQueryLargerThan} from "./MediaQuery"; import {Unifier} from "./Unifier"; const ALIGN_CONTENT = { start: "flex-start", end: "flex-end", center: "center", between: "space-between", around: "space-around", stretch: "stretch", }; const ALIGN_ITEMS = { start: "flex-start", end: "flex-end", center: "center", baseline: "baseline", stretch: "stretch", }; const ALIGN_SELF = { auto: "auto", baseline: "baseline", start: "flex-start", end: "flex-end", center: "center", between: "space-between", around: "space-around", stretch: "stretch", }; const BORDER_WIDTH = 1; // eslint-disable-next-line react/display-name export const Box = React.forwardRef((props: BoxProps, ref) => { const {theme} = useContext(ThemeContext); useImperativeHandle(ref, () => ({ scrollToEnd: () => { if (scrollRef && scrollRef.current) { // HACK HACK HACK...but it works. Probably need to do some onContentSizeChange or onLayout to // avoid this, but it works well enough. setTimeout(() => { scrollRef && scrollRef.current && (scrollRef.current as any).scrollToEnd(); }, 50); } }, scrollTo: (y: number) => { if (scrollRef && scrollRef.current) { // HACK HACK HACK...but it works. Probably need to do some onContentSizeChange or onLayout to // avoid this, but it works well enough. setTimeout(() => { scrollRef && scrollRef.current && (scrollRef.current as any).scrollTo({y}); }, 50); } }, })); const BOX_STYLE_MAP: { [prop: string]: ( value: any, all: {[prop: string]: any} ) => {[style: string]: string | number} | {}; } = { alignItems: (value: AlignItems) => ({alignItems: ALIGN_ITEMS[value]}), alignContent: (value: AlignContent) => ({alignContent: ALIGN_CONTENT[value]}), alignSelf: (value: AlignSelf) => ({alignSelf: ALIGN_SELF[value]}), color: (value: keyof UnifiedTheme) => ({backgroundColor: theme[value]}), direction: (value: any) => ({flexDirection: value, display: "flex"}), // eslint-disable-next-line @typescript-eslint/no-unused-vars smDirection: (value: any) => mediaQueryLargerThan("sm") ? {flexDirection: value, display: "flex"} : {}, // eslint-disable-next-line @typescript-eslint/no-unused-vars mdDirection: (value: any) => mediaQueryLargerThan("md") ? {flexDirection: value, display: "flex"} : {}, // eslint-disable-next-line @typescript-eslint/no-unused-vars lgDirection: (value: any) => mediaQueryLargerThan("lg") ? {flexDirection: value, display: "flex"} : {}, display: (value: any) => { return value === "flex" ? {flex: undefined} : {flex: 0, flexDirection: "row"}; }, flex: (value: string) => { if (value === "grow") { return {flexGrow: 1, flexShrink: 1, display: "flex"}; } else if (value === "shrink") { return {flexShrink: 1, display: "flex"}; } else { return {flex: 0, display: "flex"}; } }, justifyContent: (value: JustifyContent) => ({justifyContent: ALIGN_CONTENT[value]}), height: (value) => { if (props.border && !isNaN(Number(value))) { return {height: Number(value) + 2 * 2}; } else { return {height: value}; } }, margin: (value) => ({margin: value * SPACING}), marginRight: (value) => ({marginRight: value * SPACING}), marginLeft: (value) => ({marginLeft: value * SPACING}), marginTop: (value) => ({marginTop: value * SPACING}), marginBottom: (value) => ({marginBottom: value * SPACING}), paddingX: (value) => ({paddingLeft: value * SPACING, paddingRight: value * SPACING}), paddingY: (value) => ({paddingTop: value * SPACING, paddingBottom: value * SPACING}), padding: (value) => ({padding: value * SPACING}), zIndex: (value) => ({zIndex: value ? value : undefined}), position: (value) => ({position: value}), top: (top) => ({top: top ? 0 : undefined}), bottom: (bottom) => ({bottom: bottom ? 0 : undefined}), right: (right) => ({right: right ? 0 : undefined}), left: (left) => ({left: left ? 0 : undefined}), rounding: (rounding, allProps) => { if (rounding === "circle") { if (!allProps.height && !allProps.width) { console.warn("Cannot use Box rounding='circle' without height or width."); return {borderRadius: undefined}; } return {borderRadius: allProps.height || allProps.width}; } if (rounding === "pill") { return {borderRadius: 999}; } if (typeof rounding === "number") { return {borderRadius: rounding * 4}; } return {borderRadius: undefined}; }, overflow: (value) => { if (value === "scrollY" || value === "scroll") { return {overflow: "scroll"}; } return {overflow: value}; }, width: (value) => { if (props.border && !isNaN(Number(value))) { return {width: Number(value) + 2 * 2}; } else { return {width: value}; } }, wrap: (value) => ({flexWrap: value ? "wrap" : "nowrap", alignItems: "flex-start"}), shadow: (value) => { if (!value) { return {}; } if (Platform.OS === "ios" || Platform.OS === "web") { return { shadowColor: "#999", shadowOffset: { width: 2, height: 2, }, shadowRadius: 2, shadowOpacity: 1.0, }; } else { return {elevation: 4}; } }, border: (value: keyof UnifiedTheme) => { if (!value) { return {}; } return {borderColor: theme[value], borderWidth: BORDER_WIDTH}; }, borderBottom: (value: keyof UnifiedTheme) => { if (!value) { return {}; } return {borderBottomColor: theme[value], borderBottomWidth: BORDER_WIDTH}; }, borderTop: (value: keyof UnifiedTheme) => { if (!value) { return {}; } return {borderTopColor: theme[value], borderTopWidth: BORDER_WIDTH}; }, borderRight: (value: keyof UnifiedTheme) => { if (!value) { return {}; } return {borderRightColor: theme[value], borderRightWidth: BORDER_WIDTH}; }, borderLeft: (value: keyof UnifiedTheme) => { if (!value) { return {}; } return {borderLeftColor: theme[value], borderLeftWidth: BORDER_WIDTH}; }, }; const scrollRef = props.scrollRef ?? React.createRef(); const propsToStyle = (): any => { let style: any = {}; for (const prop of Object.keys(props)) { const value = (props as any)[prop]; if (BOX_STYLE_MAP[prop]) { Object.assign(style, BOX_STYLE_MAP[prop](value, props)); } else if (prop !== "children" && prop !== "onClick") { style[prop] = value; // console.warn(`Box: unknown property ${prop}`); } } if (props.wrap && props.alignItems) { console.warn("React Native doesn't support wrap and alignItems together."); } // Finally, dangerously set overrides. if (props.dangerouslySetInlineStyle) { style = {...style, ...props.dangerouslySetInlineStyle.__style}; } return style; }; const onHoverIn = () => { props.onHoverStart?.(); }; const onHoverOut = () => { props.onHoverEnd?.(); }; let box; if (props.onClick) { box = ( <Pressable style={propsToStyle()} testID={props.testID ? `${props.testID}-clickable` : undefined} onLayout={props.onLayout} onPointerEnter={onHoverIn} onPointerLeave={onHoverOut} onPress={() => { Unifier.utils.haptic(); props.onClick!(); }} > {props.children} </Pressable> ); } else { box = ( <View style={propsToStyle()} testID={props.testID} onPointerEnter={onHoverIn} onPointerLeave={onHoverOut} > {props.children} </View> ); } if (props.scroll) { const {justifyContent, alignContent, alignItems, ...scrollStyle} = propsToStyle(); box = ( <ScrollView ref={props.scrollRef || scrollRef} contentContainerStyle={{justifyContent, alignContent, alignItems}} horizontal={props.overflow === "scrollX"} keyboardShouldPersistTaps="handled" nestedScrollEnabled scrollEventThrottle={50} style={scrollStyle} onScroll={(event) => { if (props.onScroll && event) { props.onScroll(event.nativeEvent.contentOffset.y); } }} > {box} </ScrollView> ); } if (props.avoidKeyboard) { box = ( <KeyboardAvoidingView behavior={Platform.OS === "ios" ? "padding" : "height"} keyboardVerticalOffset={props.keyboardOffset} style={{flex: 1, display: "flex"}} > <SafeAreaView style={{flex: 1, display: "flex"}}>{box}</SafeAreaView> </KeyboardAvoidingView> ); } return box; });
import { Link } from "react-router-dom"; import { MagnifyingGlassIcon, BellIcon, AdjustmentsHorizontalIcon, AdjustmentsVerticalIcon, } from "@heroicons/react/24/outline"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "../ui/tooltip"; import { ModeToggle } from "../ModeToggler"; import MobileNav from "./MobileNav"; import userAvatar from "../../assets/images/user-avatar.jpg"; const TopNav = ({ openNav, setOpenNav, }: { openNav: boolean; setOpenNav: (nav: boolean) => void; }) => { return ( <main className={`w-full h-20 border-b border-black border-opacity-5 flex lg:hidden items-center px-4 justify-between overflow-hidden bg-[#EFF6E0] bg-opacity-20 dark:border-[#F87E0D] dark:border-opacity-40 dark:bg-black`} > <div className=""> <Link to="/"> <h1 className="text-4xl text-[#F87E0D] font-bold">FairShop</h1> </Link> </div> <section className="hidden lg:flex items-center justify-end gap-16 xl:gap-28"> {/* Input con */} <div className=" "> <div className="flex items-center gap-1 border dark:border-white border-black border-opacity-30 px-4 rounded-xl w-64 xl:w-96 justify-between h-12"> <input type="text" className="p-6 focus:outline-none w-full bg-transparent dark:placeholder:text-white" placeholder="Search" /> <span className="hover:cursor-pointer"> <MagnifyingGlassIcon className="h-4 w-4" /> </span> </div> </div> {/* Avatar & Icons con */} <div className=" flex-1 flex items-center gap-4 justify-end "> <TooltipProvider> <Tooltip> <TooltipTrigger> <ModeToggle /> </TooltipTrigger> <TooltipContent className="bg-none"> <p>change theme</p> </TooltipContent> </Tooltip> </TooltipProvider> <TooltipProvider> <Tooltip> <TooltipTrigger> <span className="cursor-pointer hover:bg-gray-100 hover:scale-150 h-8 w-8 flex items-center justify-center rounded-full dark:hover:bg-slate-50"> <BellIcon className="w-6 h-6 dark:hover:text-black" /> </span> </TooltipTrigger> <TooltipContent className="bg-none"> <p> notifications</p> </TooltipContent> </Tooltip> </TooltipProvider> {/* <SettingMenu /> */} <div className="h-10 w-10 rounded-full hover:cursor-pointer"> <img src={userAvatar} alt="user-avatar" className="rounded-full" /> </div> </div> </section> {/* Mobile Nav */} <div className="lg:hidden"> <div className="border border-opacity-50 w-12 h-12 flex items-center justify-center rounded-lg cursor-pointer"> {openNav ? ( <AdjustmentsVerticalIcon className="h-8 w-8" onClick={() => setOpenNav(false)} /> ) : ( <AdjustmentsHorizontalIcon className="h-8 w-8" onClick={() => setOpenNav(true)} /> )} </div> </div> <MobileNav openNav={openNav} setOpenNav={setOpenNav} /> </main> ); }; export default TopNav;
import { useMaterial3Theme } from '@pchmn/expo-material3-theme'; import AsyncStorage from '@react-native-async-storage/async-storage'; import { StatusBar } from 'expo-status-bar'; import { useEffect, useMemo, useState } from 'react'; import { Appearance } from 'react-native'; import { adaptNavigationTheme, MD3DarkTheme, MD3LightTheme, PaperProvider } from 'react-native-paper'; import { PERSISTENCE_KEY, PREFERENCES_KEY, UserThemeType } from './utils/def'; import { InitialState, NavigationContainer, DarkTheme as NavigationDarkTheme, DefaultTheme as NavigationDefaultTheme, } from '@react-navigation/native'; import { navigationRef } from './utils/navigate'; import { I18nextProvider } from 'react-i18next'; import i18n from './i18n'; import { ConfigurationContext } from './context/Configuration'; import Root from './root'; import SnackbarContainer from './components/SnackbarAPI'; import { DialogProvider } from './context/DialogProvider'; import ConnectorContainer from './components/Connector'; export default function App() { const [initialState, setInitialState] = useState< InitialState | undefined >(); const { LightTheme, DarkTheme } = adaptNavigationTheme({ reactNavigationLight: NavigationDefaultTheme, reactNavigationDark: NavigationDarkTheme, }); const [userThemeMode, setUserThemeMode] = useState<UserThemeType>("system"); const colorScheme = Appearance.getColorScheme(); const { theme } = useMaterial3Theme(); const isDarkTheme = userThemeMode === "system" ? colorScheme === "dark" ? true : false : userThemeMode === "dark" ? true : false; const paperTheme = useMemo( () => isDarkTheme ? { ...MD3DarkTheme, colors: theme.dark } : { ...MD3LightTheme, colors: theme.light }, [colorScheme, theme, userThemeMode]); const preferences = useMemo( () => ({ changeTheme: (mode: UserThemeType) => setUserThemeMode(mode), currentUserTheme: userThemeMode }), [theme, userThemeMode]); const CombinedDefaultTheme = { ...MD3LightTheme, ...LightTheme, colors: { ...MD3LightTheme.colors, ...LightTheme.colors, }, }; const CombinedDarkTheme = { ...MD3DarkTheme, ...DarkTheme, colors: { ...MD3DarkTheme.colors, ...DarkTheme.colors, }, }; const combinedTheme = isDarkTheme ? CombinedDarkTheme : CombinedDefaultTheme; useEffect(() => { (async () => { try { const prefString = await AsyncStorage.getItem(PREFERENCES_KEY); const preferences = JSON.parse(prefString || ''); if (preferences) { setUserThemeMode(preferences.theme as UserThemeType); } } catch (e) { } })(); }, []); useEffect(() => { (async () => { try { await AsyncStorage.setItem( PREFERENCES_KEY, JSON.stringify({ theme: userThemeMode, }) ); } catch (e) { } })(); }, [userThemeMode]); return ( <I18nextProvider i18n={i18n} defaultNS={'translation'}> <PaperProvider theme={paperTheme} settings={{ rippleEffectEnabled: true }}> <StatusBar style={isDarkTheme ? 'light' : 'dark'} translucent /> <ConfigurationContext.Provider value={preferences}> <NavigationContainer theme={combinedTheme} initialState={initialState} ref={navigationRef} onStateChange={(state) => AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(state)) } > <SnackbarContainer> <DialogProvider> <ConnectorContainer> <Root /> </ConnectorContainer> </DialogProvider> </SnackbarContainer> </NavigationContainer> </ConfigurationContext.Provider> </PaperProvider> </I18nextProvider> ); }
C4: Media & Interactivity for iOS Travis Kirton :toc: :theme: c4tutorial :source-highlighter: pygments :language: objective-c :icons: :numbered: :email: tutorials@c4ios.com Thanks for joining the newest workshop on C4 at link:http://www.vivomediaarts.com[VIVO]! I'm pretty excited to be hosting this workshop because it's the first one in Vancouver, and the first one at VIVO too. Intro ----- I've designed this workshop to be a solid foundation for getting started with C4 as an API for building creative and expressive applications. There is really _too much_ to teach in a single session or a single workshop but, because of its design, there are fundamentals common to almost everything in C4 that are important to understand right at the very beginning. This workshop is meant to teach just that. In doing so, I've split up the workshop into 4 main sections. 3 of these tackle an important concept and highlight examples of code that will get you rolling along. The fourth session will be for open questions and the chance to work on anything that might interest you. Gestalt ------- The first session will focus on working with shapes to create gestalt imagery. The shapes and images we'll be creating will be fairly simple, but they'll also be designed in a way that highlights some of the important characteristics of working with objects in C4. image::gestalt/gestaltHeader.png["Four Gestalt Images"] Date ~~~~ Monday May 6th, 7-10pm Content ~~~~~~~ Here's a link to the link:gestalt.php[GESTALT] workshop tutorial. Media Mashup ------------ In this session participants will be challenged to integrate images, audio and video into the gestalt works they created and build upon what they learned in the previous session. At the end of the session participants will be asked to think about a directed project they want to create. Date ~~~~ Wednesday May 9th, 7-10pm. Content ~~~~~~~ n/a Interactivity ------------- The focus for this session will be on integrating touch and gestural interaction with the objects and media that were introduced in Sessions 1 & 2. participants will choose and begin working their own directed projects. Date ~~~~ Monday May 13th, 7-10pm Content ~~~~~~~ Here's a link to the link:interaction.php[INTERACTION] workshop tutorial Directed Projects ----------------- In this session participants will continue working on their directed projects. New concepts and specific techniques that arise through their experimentation will be discussed. Participants will also be introduced to some pretty fresh new content for the C4 site. We just finished working on *125* new examples and *20* new tutorials. Date ~~~~ Wednesday May 16th, 7-10pm Content ~~~~~~~ n/a
import { FC, useEffect } from 'react'; import { Link } from 'react-router-dom'; import CartSvg from '../../assets/CartSvg'; import { useAppDispatch, useAppSelector } from '../../store/hooks/redux'; import { clearCarts, selectCart } from '../../store/reducers/CartSlice'; import BackSvg from './BackSvg'; import style from './Cart.module.scss'; import Carts from './Carts'; import Empty from './Empty'; import TrashSvg from './TrashSvg'; const Cart: FC = () => { const { totalCount, totalPrise, carts } = useAppSelector(selectCart); const dispatch = useAppDispatch(); useEffect(() => { localStorage.setItem( 'cartReducer', JSON.stringify({ totalCount, totalPrise, carts }) ); }); return ( <div className={style.wrapper}> <div className={style.container}> {totalCount === 0 && <Empty />} {totalCount !== 0 && ( <> <div className={style.top}> <div className={style.title}> <CartSvg /> <h2>Корзина</h2> </div> <div className={style.clearCart}> <TrashSvg /> <button onClick={() => { dispatch(clearCarts()); }} > Очистить корзину </button> </div> </div> <Carts /> <div className={style.sum}> <p className={style.sumAll}> Всего пицц:{' '} <span className={style.sumAllBold}>{`${totalCount} шт.`}</span>{' '} </p> <p> Сумма заказа:{' '} <span className={style.sumAllPrise}>{`${totalPrise} ₽`}</span> </p> </div> <div className={style.controls}> <Link className={style.back} to="/"> <BackSvg /> Вернуться назад </Link> <button className={style.buy}>Оплатить сейчас</button> </div> </> )} </div> </div> ); }; export default Cart;
import React, { useEffect, useState } from 'react' import { useWindowSize } from '@uidotdev/usehooks' import { Link, useNavigate } from 'react-router-dom' import { images } from '../../../../constants' import {AiFillDashboard, AiOutlineClose, AiOutlineMenu} from 'react-icons/ai' import { FaComments } from 'react-icons/fa' import {MdDashboard} from 'react-icons/md' import NavItem from './NavItem' import NavItemCollapse from './NavItemCollapse' import { useMutation, useQueryClient } from '@tanstack/react-query' import toast from 'react-hot-toast' import { useSelector } from 'react-redux' import { createPost } from '../../../../services/index/posts' const Header = () => { const navigate = useNavigate() const queryClient = useQueryClient() const userState = useSelector((state) => state.user) const [isMenuActive, setIsMenuActive] = useState(false) const [activeNavName, setActiveNavName] = useState('dashboard') const windowSize = useWindowSize() const { mutate: mutateCreatePost, isLoading: isLoadindCreatePost } = useMutation({ mutationFn: ({slug, token }) => { return createPost({ token }); }, onSuccess: (data) => { queryClient.invalidateQueries(["posts"]) toast.success("New Poast is created, edit that now"); navigate(`/admin/posts/manage/edit/${data.slug}`) }, onError: (error) => { toast.error(error.message); console.log(error); }, }); const toggleMenuHandler =()=>{ setIsMenuActive((prevState)=> !prevState) } useEffect(()=>{ if(windowSize.width<1024) { setIsMenuActive(false) } else{ setIsMenuActive(true) } },[windowSize.width]) const handleCreateNewPost =({token})=>{ mutateCreatePost({token}) } return ( <header className='flex h-fit w-full items-center justify-between p-4 lg:h-full lg:max-w-[300px] lg:flex-col lg:items-start lg:justify-start lg:p-0'> {/*logo*/} <Link to={'/'}> <img src={images.Logo} alt="logo" className='w-16 lg:hidden' /> </Link> {/*menu burger item*/} <div className='cursor-pointer lg:hidden'> {isMenuActive ? ( <AiOutlineClose className='w-6 h-6' onClick={toggleMenuHandler}/> ): <AiOutlineMenu className='w-6 h-6' onClick={toggleMenuHandler}/>} </div> {/* sidebar container */} {isMenuActive &&( <div className='fixed inset-0 lg:static lg:h-full lg:w-full'> {/* underlay */} <div className='fixed inset-0 bg-black opacity-50 lg:hidden' onClick={toggleMenuHandler} /> {/* sidebar */} <div className='fixed top-0 bottom-0 left-0 z-50 w-3/4 overflow-y-auto bg-white p-4 lg:static lg:h-full lg:p-6'> <Link to={'/'}> <img src={images.Logo} alt="logo" className='w-16'/> </Link> <h4 className='mt-10 font-bold text-[#c7c7c7]'>Main menu</h4> {/* menu items */} <div className='mt-6 flex flex-col gap-y-[0.563rem]'> <NavItem title="Dashboard" icon={<AiFillDashboard className='text-xl'/>} link="/admin" name="dashboard" activeNavName={activeNavName} setActiveNavName={setActiveNavName} /> <NavItem title="Comments" icon={<FaComments className='text-xl'/>} link="/admin/comments" name="comments" activeNavName={activeNavName} setActiveNavName={setActiveNavName} /> <NavItemCollapse title="Posts" icon={<MdDashboard className='text-xl'/>} name="posts" activeNavName={activeNavName} setActiveNavName={setActiveNavName} > <Link to="/admin/posts/manage">Manage all posts</Link> <button disabled={isLoadindCreatePost} className='text-start disabled:opacity-70 disabled:cursor-not-allowed' onClick={()=>handleCreateNewPost({token: userState.userInfo.token})}>Add New Post</button> </NavItemCollapse> </div> </div> </div> )} </header> ) } export default Header
package com.example.performancetest.ui.examples.example5 import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshots.SnapshotStateList import androidx.compose.runtime.toMutableStateList import com.example.performancetest.ui.examples.TitleScreenColumn @Composable fun Example5CScreen( title: String, viewModel: Example5CViewModel ) { var count by remember { mutableStateOf(0) } TitleScreenColumn(title = title) { Text(text = "count: $count") Button(onClick = { count++ }) { Text(text = "count++") } StableText(list = viewModel.list) } } @Composable private fun StableText(list: SnapshotStateList<String>) { Text(text = "list: ${ list.toList() }") } class Example5CViewModel() { private val _list = mutableListOf("1", "2", "3") // Solution: snapshot state list is a stable parameter now val list: SnapshotStateList<String> = _list.toMutableStateList() }
package com.zcc.study.review.thread; import com.mysql.cj.util.TimeUtil; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; /** * 线程测试方法: * * @author: zcc * @version: 1.0 * @date: 2023/4/23 13:36 */ @Slf4j(topic = "c.ThreadTest") public class ThreadTest { /** * 线程不安全演示 1000个线程同事操作共享数据 * <p> * 结果:961 小于1000 */ @Test public void test1() throws InterruptedException { int threadSize = 1000; ThreadUnsafeExample threadUnsafeExample = new ThreadUnsafeExample(); ExecutorService executorService = Executors.newCachedThreadPool(); CountDownLatch countDownLatch = new CountDownLatch(threadSize); for (int i = 0; i < threadSize; i++) { executorService.execute(() -> { threadUnsafeExample.add(); countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); System.out.println(threadUnsafeExample.get()); } /** * 线程创建的多种方式: */ @Test public void createThread() { //第一种:继承Thread new MyThread().start(); //第二种: 实现Runnable 无返回值 new Thread(new MyRunnable()).start(); //第三种:实现Callable 有返回值 new Thread(new FutureTask<>(new MyCallable())).start(); //使用线程池 ExecutorService executorService = Executors.newCachedThreadPool(); executorService.submit(new Thread(() -> System.out.println("hhh"))); } /** * 守护线程: */ @Test public void daemonThread() throws InterruptedException { log.debug("运行开始..."); Thread damoThread = new Thread(() -> { log.debug("start"); try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { throw new RuntimeException(e); } log.debug("end"); }, "daemon"); //设置为守护线程 damoThread.setDaemon(true); damoThread.start(); TimeUnit.SECONDS.sleep(2); log.debug("运行结束..."); } /** * 停止当前运行的线程 */ @Test public void stopThread() throws InterruptedException { Thread thread = new Thread(()->{ log.debug("start"); boolean flag =true; while (flag){ } log.debug("start"); },"thread1"); thread.start(); TimeUnit.SECONDS.sleep(3); thread.stop(); log.debug("{}",thread.getState()); //当前线程休眠1秒 TimeUnit.SECONDS.sleep(1); //输出线程thread1的状态 log.info("{}", thread.getState()); } /** * 线程中断: * 方式一:使用标志 * 方式二:打断线程: interrupt() */ @Test public void interruptThread() throws InterruptedException { useFlag(); useInterrupt(); } /** * 线程通信: * wait() notify() */ @Test public void threadCommunication() throws InterruptedException { Object obj = new Object(); Thread t1 = new Thread(()->{ synchronized (obj){ log.debug("t1 start"); log.debug("t1 wait"); try { obj.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } log.debug("t1 end"); } },"t1"); Thread t2 = new Thread(()->{ synchronized(obj){ log.debug("t2 start"); log.debug("t2 wait"); try { obj.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } log.debug("t2 end"); } },"t2"); Thread t3 = new Thread(()->{ synchronized(obj){ log.debug("t3 start"); log.debug("t3 notify"); //obj.notify(); obj.notifyAll(); log.debug("t3 end"); } },"t3"); t1.start(); t2.start(); TimeUnit.SECONDS.sleep(2); t3.start(); } /** * Executor的中断操作 */ @Test public void threadExecutorsInterrupt(){ ExecutorService executorService = Executors.newCachedThreadPool(); executorService.execute(()->{ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("thread running"); }); executorService.shutdownNow(); System.out.println("main end"); } private static volatile boolean isStop =false; public void useFlag() throws InterruptedException { Thread isStopThread = new Thread(()->{ while (true){ if (isStop){ System.out.println("线程停止"); break; } } },"isStop"); isStopThread.start(); TimeUnit.SECONDS.sleep(1); isStop=true; } public void useInterrupt() throws InterruptedException { Thread interruptThread = new Thread(){ @Override public void run() { while (true){ try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { //异常会清除中断标志 所以需要在这边再次打上中断标志 this.interrupt(); } if (this.isInterrupted()) { System.out.println("我要退出了!"); break; } } } }; interruptThread.setName("interruptThread"); interruptThread.start(); TimeUnit.SECONDS.sleep(4); //线程打断 interruptThread.interrupt(); } }