text
stringlengths
184
4.48M
<?php namespace littlemissrobot\craftsearchable; use Craft; use craft\base\Plugin as BasePlugin; use craft\events\RegisterUserPermissionsEvent; use craft\events\TemplateEvent; use craft\services\UserPermissions; use craft\web\View; use yii\base\Event; /** * Searchable plugin * * @method static Plugin getInstance() * @author Little Miss Robot <craft@littlemissrobot.com> * @copyright Little Miss Robot * @license MIT */ class Plugin extends BasePlugin { public static $instance; public string $schemaVersion = '1.0.0'; // Public Methods /** * @inheritdoc */ public function __construct($id, $parent = null, array $config = []) { // Set this as the global instance static::setInstance($this); parent::__construct($id, $parent, $config); } public static function config(): array { return [ 'components' => [ // Define component configs here... ], ]; } public function init(): void { parent::init(); self::$instance = $this; // Defer most setup tasks until Craft is fully initialized Craft::$app->onInit(function() { $this->attachEventHandlers(); }); Craft::info( Craft::t( 'searchable', '{name} plugin loaded', ['name' => $this->name] ), __METHOD__ ); } private function attachEventHandlers(): void { // Register event handlers here ... // (see https://craftcms.com/docs/4.x/extend/events.html to get started) $this->installCpEventListeners(); // $this->installElementEventHandlers(); } protected function installElementEventHandlers() { // ... } protected function installCpEventListeners() { // Searchable: UserPermissions::EVENT_REGISTER_PERMISSIONS // Register custom user permissions Event::on( UserPermissions::class, UserPermissions::EVENT_REGISTER_PERMISSIONS, function(RegisterUserPermissionsEvent $event) { // Add permission for viewing and setting the searchable label $event->permissions[] = [ 'heading' => Craft::t('searchable', 'Searchable'), 'permissions' => [ 'viewSearchable' => [ 'label' => Craft::t('searchable', 'Can see searchable label in field labels'), ], ], ]; } ); // Searchable: View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE // Register Asset Bundle on TemplateEvent Event::on( View::class, View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE, function (TemplateEvent $event) { if ($event->templateMode !== View::TEMPLATE_MODE_CP) { return; } if (Craft::$app->user->checkPermission('viewSearchable')) { $this->registerAssetBundle(); } } ); } /** * @return void * @throws \yii\base\Exception * @throws \yii\base\InvalidConfigException */ protected function registerAssetBundle(): void { // Create a data object with the search label $data = [ 'searchLabel' => Craft::t('searchable', 'This field\'s values are used as search keywords.'), ]; // Get all available fields $fields = Craft::$app->getFields()->getAllFields('global'); // Add the id and their searchable attribute foreach ($fields as $field) { $fieldType = get_class($field); $data['fields'][$field->handle] = [ "id" => $field->id, "searchable" => $field->searchable ?? false, "type" => $fieldType, ]; switch ($fieldType) { case "craft\\fields\\Matrix": $data = $this->processField($data, $field, 'matrix-', $fieldType); break; default: break; } } // Register the asset bundle and pass data object Craft::$app->getView()->registerAssetBundle(SearchableBundleAsset::class, \yii\web\View::POS_END); Craft::$app->getView()->registerJs('Craft.SearchablePlugin.init(' . \json_encode($data) . ');', \yii\web\View::POS_END); } function processField($data, $field, $blockFieldPrefix = '', $fieldType = '') { $blockFields = $field->getBlockTypeFields(); foreach ($blockFields as $blockField) { $data['fields'][$blockFieldPrefix . $blockField->handle] = [ "id" => $blockField->id, "searchable" => $blockField->searchable ?? false, "type" => $fieldType, ]; } return $data; } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!--Website title and icon image--> <title>Twitter Clone</title> <link rel="icon" href="logo.png" type="image/png"> <!--CSS Stylesheet--> <link rel="stylesheet" href="style.css" type="text/css"> <!--Google font icon image links--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@20..48,100..700,0..1,-50..200" /> </head> <body> <!-------Whole Body area of Website - which is divided in 3 sub-parts--------> <div class="mainbody"> <!----Leftside Options menu-----> <div class="leftsection"> <!--Website logo/icon--> <div class="logo"> <img src="logo.png" alt="No image"> </div> <!--List of options to navigate--> <div class="navbar"> <span class="material-icons">home</span> <a class="options-name" href="#">Home</a> </div> <div class="navbar"> <span class="material-icons">search</span> <a class="options-name" href="#">Explore</a> </div> <div class="navbar"> <span class="material-icons">notifications</span> <a class="options-name" href="#">Notifications</a> </div> <div class="navbar"> <span class="material-icons">mail_outline</span> <a class="options-name" href="#">Messages</a> </div> <div class="navbar"> <div class="material-icons">bookmark_border</div> <a class="options-name" href="#">Bookmarks</a> </div> <div class="navbar"> <div class="material-icons">view_list</div> <a class="options-name" href="#">List</a> </div> <div class="navbar"> <span class="material-icons">person_outline</span> <a class="options-name" href="#">Profile</a> </div> <div class="navbar"> <span class="material-icons">more_horiz</span> <a class="options-name" href="#">More</a> </div> </div> <!-----Middlebar Section Starts-----> <div class="middlebar"> <!--Feed Section--> <div class="feed"> <div class="feed_heading"> <p>Home</p> </div> <!-- --> <!-- Feed input Section --> <div class="feed_input_section"> <div class="usericon"> <img src="usericon.png" alt="No image"> </div> <div class="feed-input"> <input type="text" placeholder="What's happening ?"> </div> <br> <div class="tweet-button"> <button type="button">Tweet</button> </div> </div> </div> <!------ Post input section-------> <!-- New Post starts --> <div class="post_section"> <div class="post_section_image"> <img src="usericon.png" alt="No image"> </div> <!-- Information about post--> <div class="post_info"> <div class="post_infoall"> <div class="profile_name"><h3>Prafull Kuwar</h3></div> <span class="verify_badge"> <img src="verify_badge.png" alt="no image"> </span> <div class="twitter_id"><h4>@prafullk101</h4></div> </div> <!-- Post content / description --> <div class="post_content"> <div class="post_description"> <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Lorem ipsum dolor sit amet consectetur, adipisicing elit. In ea at unde aperiam officia perspiciatis sapiente provident magnam error praesentium! </p> </div> <!-- Post Photo will appear heare --> <div class="post_photo"> <img src="car.jpg" alt="No Image"> </div> <div class="post_replies"> <div class="retweet"> <img src="retweet.svg" alt="retweet"> </div> <div class="like"> <img src="like_blank.svg" alt="like"> </div> <div class="publish"> <img src="publish.svg" alt="publish"> </div> </div> </div> </div> </div> <!---- New Post Ends ----> <!---- New Post starts ----> <div class="post_section"> <div class="post_section_image"> <img src="usericon.png" alt="No image"> </div> <!-- Information about post--> <div class="post_info"> <div class="post_infoall"> <div class="profile_name"><h3>Prafull Kuwar</h3></div> <div class="verify_badge"> <img src="verify_badge.png" alt="no image"> </div> <div class="twitter_id"><h4>@prafullk101</h4></div> </div> <!-- Post content / description --> <div class="post_content"> <div class="post_description"> <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Lorem ipsum dolor sit amet consectetur, adipisicing elit. In ea at unde aperiam officia perspiciatis sapiente provident magnam error praesentium! </p> </div> <!-- Post Photo will appear heare --> <div class="post_photo"> <img src="car.jpg" alt="No Image"> </div> <div class="post_replies"> <div class="retweet"> <img src="retweet.svg" alt="retweet"> </div> <div class="like"> <img src="like_blank.svg" alt="like"> </div> <div class="publish"> <img src="publish.svg" alt="publish"> </div> </div> </div> </div> </div> <!---- New Post Ends ----> </div> <!-----Middlebar Section Ends-----> <!--Rightside Section--> <div class="rightsection"> <!-- Search bar --> <div class="search_bar"> <div class="material-icons">search</div> <div class="Search_bar_input"><input type="text" placeholder="Search Twitter"></div> </div> <!-- Your widgets section --> <div class="widgets"> <h3>What's happening?</h3> <div class="news_section"> <div class="widget_section_logo"> <img src="news_logo.png" alt="No image"> </div> <!-- Profile name logo and other information --> <div class="profile_name_widgets"><h4>US Department of the Interior</h4> <div class="verify_badge"> <img src="verify_badge.png" alt="no image"> <span class="twitter_logo"><img src="logo.png" alt="logo"></span> <span class="twitter_id_widgets">@Interior.</span> <span class="highlights">Follow</span> </div> </div> <!-- Post content / description --> <div class="post_content"> <div class="post_description"> <p>Sunsets don't get much better than this one over <span class="highlights">.@GrandTetonNPS.</span> <span class="highlights">#nature</span> <span class="highlights">#sunset</span> </p> </div> <div class="post_photo"> <img src="sunset.jpg" alt="No Image" style="width: 100%;"> </div> <div class="post_publish_info"> <div class="time_date"><p>3:39 AM . May 6, 2014</p></div> <div class="post_publish_info"> <img src="info_icon.svg" alt="no image"> </div> </div> <!-- Post Reactions options --> <div class="post_reactions"> <div class="like"> <span><img src="like.png" alt="like"></span><a href="#">6.3K</a> </div> <div class="reply"> <span><img src="comment.svg" alt="reply"></span><a href="#">Reply</a> </div> <div class="share"> <span><img src="share_icon.svg" alt="share"></span><a href="#">Share</a> </div> </div> <!-- No. of reply's received --> <div class="reply_numbers"> <button>Read 2K replies</button> </div> </div> </div> </div> </div> </div> </body> </html>
import axios from 'axios' import { Prettify } from '../types' import createHooks from './createHooks' import { HTTPOptions } from './types.t' import { httpDefaultConfig } from '../config' import createBaseMethods from './createMethods' /** * * @param options - This is the config of axios and 'formatError' and 'formatData' functions * @returns - Everything you need to make HTTP requests * * ## Basic usage * * ```ts * import ReactHTTP from 'react-net-kit' * export const { useApi, useApiOnce, createSuspense } = ReactHTTP() * ``` */ export default function <O extends HTTPOptions>(options?: O) { type FallBack = Prettify< (undefined extends O['formatData'] ? {} : { data: ReturnType<Exclude<O['formatData'], undefined>> }) & (undefined extends O['formatError'] ? {} : { error: ReturnType<Exclude<O['formatError'], undefined>> }) > const { formatData, formatError, ...axiosOptions } = { ...httpDefaultConfig, ...(options ?? {}), } const axiosInstance = axios.create(axiosOptions) const baseConfig = { formatData, formatError } const baseMethods = createBaseMethods<FallBack>(axiosInstance, baseConfig) const hooks = createHooks<typeof baseMethods, FallBack>(baseMethods) return { ...hooks, ...baseMethods, axios: axiosInstance, } }
@RestResource(urlMapping ='/MyRestClassEP/*') Global class MyRestClass { @httpGet global static void getData(){ RestRequest req = Restcontext.request; // to handle the request we created this restrequest instance from extenal site // Restcontext.request; we are storing the request from third party and handling the request // RestRequest res = we have created and RestRequest instance ie 'res' to hold all req string urlid = req.requestURI; string uid = urlid.substring(urlid.lastIndexOf('/')+1); list<Contact> conlist = [SELECT id,Name,Department,Phone from Contact where AccountId =:uid]; // querying Contact Info to send postman // best practice to use TRY AND Catch block while sending data to external site to handle the exception if occures try{ RestResponse res = RestContext.response; string JASONbody = JSON.serialize(conlist); // here we are serialize all data which present in the" conlist " in from of JSON like "KEY" :" Value ", // blob = is use to convert response body in base64 to Encrypted for security porpose res.responseBody = Blob.valueOf(JASONbody); res.statusCode= 200; } catch (Exception e) { RestResponse res = RestContext.response; string JASONbody = JSON.serialize(e.getMessage()); res.responseBody = Blob.valueOf(JASONbody); res.statusCode = 200; } //return 'get method run successfully...!!!'; } @httpPost global static void postData() { try{ //created RestRequest instance .. to store whaterver request coming from external site RestRequest req = Restcontext.request; // as we are getting data in base64 formate we have to convert that into the Json, so we have used body.tostring(); Blob blobbody = req.requestBody; // as datatype is blob so we have used the blob here to store response string jsonData = blobbody.toString(); // here converting that into string List<Sobject> AccToInsert = (List<Sobject>) JSON.deserialize(jsonData, List<Sobject>.class); insert AccToInsert; } catch(Exception e){ RestResponse res = RestContext.response; string JASONbody = JSON.serialize(e.getMessage()); res.responseBody = Blob.valueOf(JASONbody); res.statusCode = 200; } } }
from magpie import MagpieModel from sklearn import metrics from sklearn.preprocessing import LabelEncoder from glob import glob import logging import os log = logging.getLogger(__name__) class Predict: def __init__(self, config): self.config = config embeddings_path = os.path.join(self.config["save_path"], "embeddings", "embeddings") scaler_path = os.path.join(self.config["save_path"], "scaler", "scaler") model_path = os.path.join(self.config["save_path"], "model", "model.h5") if os.path.exists(embeddings_path) and os.path.exists(scaler_path) and os.path.exists(model_path): self.magpie = MagpieModel( keras_model=model_path, word2vec_model=embeddings_path, scaler=scaler_path, labels=['Affirmed', 'Reversed'] ) else: raise Exception("Model, scaler and embedded must be generated before predicting") def predict(self): test_path = os.path.join(self.config['test_path'], "**", "*.txt") files = glob(test_path, recursive=True) y = [] predicted = [] for fname in files: lab = fname[:-4] + ".lab" with open(lab, "r") as f: status = f.read() prediction = self.magpie.predict_from_file(fname)[0][0] predicted.append(prediction) y.append(status) encoder = LabelEncoder() y = encoder.fit_transform(y) predicted = encoder.transform(predicted) fpr, tpr, thresholds = metrics.roc_curve(y, predicted) log.info(metrics.f1_score(y, predicted, average="weighted")) log.info(metrics.accuracy_score(y, predicted)) log.info(metrics.confusion_matrix(y, predicted))
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #ifndef COMMON_COSINETABLES_H #define COMMON_COSINETABLES_H namespace Common { class CosineTable { public: /** * Construct a cosine table with the specified bit precision * * @param bitPrecision Precision of the table, which must be in range [4, 16] */ CosineTable(int bitPrecision); ~CosineTable(); /** * Get pointer to table. * * This table contains 2^bitPrecision/2 entries. * The layout of this table is as follows: * - Entries 0 up to (excluding) 2^bitPrecision/4: * cos(0) till (excluding) cos(1/2*pi) * - Entries 2^bitPrecision/4 up to (excluding) 2^bitPrecision/2: * cos(3/2*pi) till (excluding) cos(2*pi) */ const float *getTable() { return _table; } /** * Get pointer to table */ int getPrecision() { return _bitPrecision; } private: float *_table; int _bitPrecision; }; } // End of namespace Common #endif // COMMON_COSINETABLES_H
package com.dx.facade.merchant.req; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import com.dx.facade.common.PageRequest; @Data @ApiModel(value="查询德州操作记录入参", description="查询德州操作记录入参") public class DzCardLogParamReqDTO extends PageRequest { @ApiModelProperty(value = "商户编号") private String merchantCode; @ApiModelProperty(value = "查询起始时间,13位时间戳") private Long startTime; @ApiModelProperty(value = "查询结束时间,13位时间戳") private Long endTime; @ApiModelProperty(value = "操作栏目1游戏管理2俱乐部管理") private Integer operationMenu; @ApiModelProperty(value = "操作页面1游戏规则-德州扑克2游戏规则-短牌3保险赔率-德州扑克4保险赔率-短牌5牌桌详情6俱乐部申请列表7通用俱乐部管理") private Integer operationPage; @ApiModelProperty(value = "操作人") private String operator; @ApiModelProperty(value = "操作IP") private String ip; }
<!DOCTYPE HTML> <html lang=""> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Pattern editor</title> <style> body { margin: 0px; padding: 0px; } canvas { background-color: #fff; width: 640px; height: 640px; margin: 20px 40px; } p { margin: 0; } </style> <!-- p5 --> <script src="../p5.js"></script> <script src="../addons/p5.dom.min.js"></script> <script src="../addons/p5.sound.min.js"></script> <script type="module" src="sketch.js"></script> </head> <body> <!-- <audio controls> <source src="../song.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> --> <table> <tr> <td align="center" valign="top"> <canvas id="canvas" width="640" height="640"></canvas> <br/> <button id="save-image">Save hi-res image</button> </td> <td> <p>Offset: <span id="offs0_val"></span></p> <input type="range" min="-1000" max="1000" class="slider" id="offs0_x"/> <p>Rotation: PI*<span id="rot0_val"></span></p> <input type="range" min="-360" max="360" class="slider" id="rot0"/> <hr/> <button id="save-preset">Save preset</button> <label for="load-preset">Open preset</label><input id="load-preset" type="file" accept="application/json"/> </td> </tr> </table> <script type="text/javascript"> /****************************** ******************************* Begin Mic Code **************** ******************************* *******************************/ let mic, fft, writer, fps; var timestamp = 0; let volumes = []; let frequencies = []; let vol_avg = 0.0; let hz_avg = 0.0; function preload() { soundFormats('mp3', 'ogg'); mySound = loadSound('../Satellite.mp3'); } function setup() { createCanvas(710, 400); noFill(); mySound.setVolume(0.1); mySound.play(); //mic = new p5.AudioIn(); //mic.start(); fft = new p5.FFT(); fft.setInput(mySound); userStartAudio().then(function(){}); // Create a new file in the sketch directory writer = createWriter("freqs_vols.txt"); } function draw() { background(200); fps = frameRate(); let spectrum = fft.analyze(); beginShape(); for (i = 0; i < spectrum.length; i++) { vertex(i, map(spectrum[i], 0, 255, height, 0)); } endShape(); var waveform = fft.waveform(); beginShape(); stroke(255,0,0); // waveform is red strokeWeight(1); for (var i = 0; i< waveform.length; i++){ var x = map(i, 0, waveform.length, 0, width); var y = map( waveform[i], -1, 1, 0, height); vertex(x,y); } endShape(); var volume = 0; for (var i = 0; i< waveform.length; i++){ if(volume < Math.abs(waveform[i])) { volume = Math.abs(waveform[i]); } } //print('volume : ' + volume); var HzPerBin = 22072.8888889 / waveform.length; var imax = 0; for (var i = 0; i < spectrum.length; ++i){ if (spectrum[imax] < spectrum[i]) imax = i; } var hzMax = imax * HzPerBin; //print ('hzMax : ' + hzMax); if (millis() - timestamp >=100) { timestamp = millis(); //print('volume : ' + volume); //print ('hzMax : ' + hzMax); //print ('hz per bin : ' + HzPerBin); //print ('imax : ' + imax); volumes.push(volume); frequencies.push(round(hzMax)); vol_write = map(volume, 0.00, 0.10, 0, 100); writer.print(round(hzMax) + ", " + round(vol_write)); // print('frameRate: '+fps); hz_map = map(hzMax, 215.0, 800.0, -8.0, 8.0); vol_map = map(volume, 0.00, 0.10, -(Math.PI), Math.PI); console.log('map_hz: ' + Math.round(hzMax) + " vol: " + Math.ceil(volume * 100) / 100); // console.log('map_hz: ' + hz_map + " vol: " + vol_map); //console.log('map_vol: ' + vol_map); //state.offs0[0] = hz_map; //state.rot0 = vol_map; // update the sliders /*var rotVal=*/ //document.getElementById("rot0").value = state.rot0 * (ROT_SLIDER_RANGE/ROT_SCALE); //console.log("input rot0 value: "+rotVal); /*var offsVal=*/ //document.getElementById("offs0_x").value = (state.offs0[0] / OFFS_SCALE) * OFFS_SLIDER_RANGE; //console.log("input offs0_x value: "+offsVal); //generate(); //updateLabels(); } if (millis() >= 60 * 1000){ // saveStrings(frequencies, 'frequencies', 'txt'); writer.close(); writer.clear(); exit(); // Stops the program } // if (millis() >= 8000){ // console.log('volumes: ' + volumes); // console.log('frequencies: ' + frequencies); // console.log('avg_hz: ' + average(frequencies)); // console.log('avg_vol: ' + average(volumes)); // hz_map = map(average(frequencies), 0.0, 12000.0, -8.0, 8.0); // vol_map = map(average(volumes), 0.0, 0.1, -(Math.PI), Math.PI); // console.log('map_hz: ' + hz_map); // console.log('map_vol: ' + vol_map); // //state.rot0 = document.getElementById("rot0").value / (ROT_SLIDER_RANGE/ROT_SCALE); // //state.offs0_x = document.getElementById("offs0_x").value / OFFS_SLIDER_RANGE * OFFS_SCALE; // // if already mapped, then dont need to do the above, simply set the state // state.offs0[0] = hz_map; // state.rot0 = vol_map; // // update the sliders // /*var rotVal=*/ document.getElementById("rot0").value = state.rot0 * (ROT_SLIDER_RANGE/ROT_SCALE); // //console.log("input rot0 value: "+rotVal); // /*var offsVal=*/ document.getElementById("offs0_x").value = (state.offs0[0] / OFFS_SCALE) * OFFS_SLIDER_RANGE; // //console.log("input offs0_x value: "+offsVal); // //console.log('value_hz: ' + document.getElementById("offs0_x").value ); // //console.log('value_vol ' + document.getElementById("rot0").value ); // console.log('state_hz: ' + state.offs0[0]); // console.log('state_vol: ' + state.rot0); // generate(); // updateLabels(); // remove(); // } }/* end mic code */ function average(arr){ let sum = arr.reduce((previous, current) => current += previous); return sum / arr.length; } /****************************** ******************************* Begin Mandala ***************** ******************************* *******************************/ // const PI = Math.PI; // var imgw = 640; // var imgh = 640; // var canvas = document.getElementById('canvas'); // var ctx = canvas.getContext('2d'); // var imgData = ctx.createImageData(imgw, imgh); // var state = { // zoomPre: 24.5, // zoomPost: 12.3, // zoom0: 0.3, // zoom1: 0.9, // amodPre: 6, // amod0: 1, // amod1: 1, // amod2: 1, // offs0: [0.88, 2.272], // offs1: [4.504, 6.056], // offs2: [0.936, 0.432], // rot0: 1.0471975511965976, // rot1: 0.41015237421866746, // rot2: -1.0471975511965976, // symm0: true, // symm1: true, // symm2: false, // yPos: 0, // yScale: 1, // bgMode: "min(abs())" // } // function putPixel(imgData, w, x, y, val) { // var buf = imgData.data; // var idx = (y*w+x)*4; // buf[idx] = buf[idx+1] = buf[idx+2] = val; // buf[idx+3] = 255; // } // function mod(x, y) { // return x - y * Math.floor(x/y); // } // function fract(x) { // return x - Math.floor(x); // } // function amod(x, y, c) { // if (c <= 1.001) // return [x, y] // var m = 2.0*PI / c; // var a = mod(Math.atan2(x, y)-m*.5, m) - m*.5; // var len = Math.sqrt(x*x+y*y); // return [Math.cos(a)*len, Math.sin(a)*len]; // } // function mo(p, d, symm) { // p[0] = Math.abs(p[0]) - d[0]; // p[1] = Math.abs(p[1]) - d[1]; // if (symm && p[1]>p[0]) { // var z = p[1]; p[1] = p[0]; p[0] = z; // } // } // function r2d(a) { // var c = Math.cos(a), s = Math.sin(a); // return [c, s, -s, c]; // } // function mul(vec, mat) { // var x = vec[0]*mat[0] + vec[1]*mat[1]; // var y = vec[0]*mat[2] + vec[1]*mat[3]; // vec[0] = x; // vec[1] = y; // } // function smoothstep(lo, hi, x) { // x = (x-lo) / (hi-lo) // if (x <= 0) // return lo; // if (x >= 1) // return hi; // return x * x * (3. - 2. * x) * (hi-lo) + lo; // } // function calcPixel(rx, ry) { // var uv = [rx, ry]; // uv[1] += state.yPos; // uv[0] *= state.zoomPre; // uv[1] *= state.zoomPre * state.yScale; // uv = amod(uv[0], uv[1], state.amodPre); // mo(uv, state.offs0, state.symm0); // mul(uv, r2d(state.rot0)); // uv = amod(uv[0], uv[1], state.amod0); // uv[0] *= state.zoom0; // uv[1] *= state.zoom0; // mo(uv, state.offs1, state.symm1); // mul(uv, r2d(state.rot1)); // uv = amod(uv[0], uv[1], state.amod1); // uv[0] *= state.zoom1; // uv[1] *= state.zoom1; // mo(uv, state.offs2, state.symm2); // mul(uv, r2d(state.rot2)); // uv = amod(uv[0], uv[1], state.amod2); // uv[0] *= state.zoomPost; // uv[1] *= state.zoomPost; // var d = 0.5; // if (state.bgMode == "min(abs())") { // var l = Math.min(Math.abs(uv[0]), Math.abs(uv[1])) + PI/2; // d = (Math.sin(l) - .6)*2.; // d = smoothstep(0.0, 1.0, d); // } else if (state.bgMode == "abs()+abs()") { // var l = Math.abs(uv[0]) + Math.abs(uv[1]); // d = (Math.sin(l + PI/2) - .6)*2.; // d = smoothstep(0.0, 1.0, d); // } else if (state.bgMode == "horiz") { // var l = uv[1]; // d = (Math.sin(l + PI/2) - .6)*2.; // d = smoothstep(0.0, 1.0, d); // } else if (state.bgMode == "vert") { // var l = uv[0]; // d = (Math.sin(l + PI/2) - .6)*2.; // d = smoothstep(0.0, 1.0, d); // } else if (state.bgMode == "length") { // l = Math.sqrt(uv[0]*uv[0]+uv[1]*uv[1]) // d = (Math.sin(l) - .6)*2.; // d = smoothstep(0.0, 1.0, d); // } // return Math.sqrt(d) * 0.7 + 0.3; // } // var clearCircle = function(x, y, radius){ // ctx.save(); // ctx.globalCompositeOperation = 'destination-in'; // ctx.beginPath(); // ctx.arc(x, y, radius, 0, 2 * Math.PI, false); // ctx.fill(); // ctx.restore(); // }; // function generate() { // for (var y=0; y<imgh; ++y) { // for (var x=0; x<imgw; ++x) { // var rx = (x - 0.5*imgw) / imgh // var ry = (y - 0.5*imgh) / imgh // var v = smoothstep(0, 255, 255*calcPixel(rx, ry)) // putPixel(imgData, imgw, x, y, v); // } // } // ctx.putImageData(imgData, 0, 0); // ctx.fillStyle = '#fff'; // clearCircle(320, 320, 320); // } // function generateAndSaveHiRes() { // var imgw = 2048 // var imgh = 2048 // var canvas = document.createElement('canvas'); // canvas.width = imgw // canvas.height = imgh // var ctx = canvas.getContext('2d'); // var imgData = ctx.createImageData(imgw, imgh); // for (var y=0; y<imgh; ++y) { // for (var x=0; x<imgw; ++x) { // var rx = (x - 0.5*imgw) / imgh // var ry = (y - 0.5*imgh) / imgh // var v = smoothstep(0, 255, 255*calcPixel(rx, ry)) // putPixel(imgData, imgw, x, y, v); // } // } // ctx.putImageData(imgData, 0, 0); // ctx.fillStyle = '#fff'; // ctx.save(); // ctx.globalCompositeOperation = 'destination-in'; // ctx.beginPath(); // ctx.arc(1024, 1024, 1024, 0, 2 * Math.PI, false); // ctx.fill(); // ctx.restore(); // var element = document.createElement('a'); // element.setAttribute('href', canvas.toDataURL("image/png")); // element.setAttribute('download', "mandala.png"); // element.style.display = 'none'; // document.body.appendChild(element); // element.click(); // document.body.removeChild(element); // document.body.removeChild(canvas); // } // const OFFS_SLIDER_RANGE = 1000.0; // const OFFS_SCALE = 8.0; // const ROT_SLIDER_RANGE = 360.0; // const ROT_SCALE = PI; // const ZOOM_SLIDER_K = 10.0; // function setupControls() { // for (var i=0; i<1; ++i) { // document.getElementById("offs"+i+"_x").value = state["offs"+i][0] / OFFS_SCALE * OFFS_SLIDER_RANGE; // document.getElementById("rot"+i).value = state["rot"+i] / ROT_SCALE * ROT_SLIDER_RANGE; // } // } // function updateLabels() { // for (var i=0; i<1; ++i) { // document.getElementById("offs"+i+"_val").innerText = (""+state["offs"+i][0]).slice(0, 4); // document.getElementById("rot"+i+"_val").innerText = (""+(state["rot"+i] / PI)).slice(0,6); // } // } // setupControls(); // updateLabels(); // function makeSliderHandler(field, elem_id, scale) { // document.getElementById(elem_id).addEventListener("input", function(e) { // // console.log("before: "+state[field]); // // console.log(e.target.value); // // console.log(ROT_SLIDER_RANGE/ROT_SCALE); // state[field] = e.target.value / scale; // //console.log("after: "+state[field]); // generate(); // updateLabels(); // }) // } // function makeOffsHandler(field, idx) { // document.getElementById(field+"_x").addEventListener("input", function(e) { // // console.log("before: "+state[field][idx]); // // console.log(e.target.value); // // console.log(OFFS_SLIDER_RANGE); // // console.log(OFFS_SCALE); // state[field][idx] = e.target.value / OFFS_SLIDER_RANGE * OFFS_SCALE; // //console.log("after: "+state[field][idx]); // generate(); // updateLabels(); // }) // } // for (var i=0; i<1; ++i) { // makeOffsHandler("offs"+i, 0); // makeSliderHandler("rot"+i, "rot"+i, ROT_SLIDER_RANGE / ROT_SCALE); // } // document.getElementById("save-preset").onclick = savePreset // document.getElementById("load-preset").oninput = loadPreset // document.getElementById("save-image").onclick = generateAndSaveHiRes // generate() // function deep_copy(aObject) { // if (!aObject) { // return aObject; // } // var bObject, v, k; // bObject = Array.isArray(aObject) ? [] : {}; // for (k in aObject) { // v = aObject[k]; // bObject[k] = (typeof v === "object") ? deep_copy(v) : v; // } // return bObject; // } // function savePreset() { // var element = document.createElement('a'); // var data = deep_copy(state); // element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(JSON.stringify(data, null, 2))); // element.setAttribute('download', "preset.json"); // element.style.display = 'none'; // document.body.appendChild(element); // element.click(); // document.body.removeChild(element); // } // function loadPreset(evt) { // var file = evt.target.files[0]; // var reader = new FileReader(); // reader.onload = function() { // var text = reader.result; // state = JSON.parse(text); // updateLabels(); // setupControls(); // generate(); // } // reader.readAsText(file); // } // console.log("offs0_x: "+document.getElementById("offs0_x").value); // console.log("rot0: "+document.getElementById("rot0").value ); </script> </body> </html>
## 题目描述 最近 n+e 发现了一个好玩的游戏,他打算和萌妹子们一起来玩,以便在玩的过程中他们可以谈笑风生。这个游戏的规则十分简单,因此妹子萌也很愿意玩:最开始 n+e 有 $m$ 张牌,妹子萌有 $n$ 张牌,并且还有一张牌盖在桌子上。因此,在最开始有 $n+m+1$ 张牌。除此之外,游戏的玩家知道所有牌的组成,也就是他们知道这些牌都是什么,玩家们也能看见自己的牌,当然玩家们是看不见对方的牌和桌子上的牌的。现在 n+e 和妹子萌轮流玩游戏,从 n+e 先开始。在每一个回合,他们可以干这两件事中的一件: 1. 猜测桌子上的牌是什么。如果猜对,那么这个玩家获胜,游戏结束。如果猜错,游戏同样结束,不过对方获胜; 2. 指定一张牌。如果对方手上有这一张牌,那么把它亮出来并且放在一边(之后的游戏中这张牌就被除外,不能再被指定),如果对方手上没有,那么什么都不做。 n+e 自然是十分的聪明,他为了能够一直能和萌妹子们谈笑风生,早已计算出了最优的策略和胜利的概率,这样他就可以自由决定每一局到底是赢还是输。但是萌妹子最近得到了一片粉色药片,这种药片是很神奇的,吃下它你会变得和 n+e 一样聪明,这样萌妹子每次都可以以最优的策略来玩游戏,n+e 只好也用最优策略来应对。 由于 n+e 忙着和妹子萌谈笑风生,他想让你帮他算一算,在妹子萌吃下那个药片后,他们都用最厉害的方法玩游戏,n+e 获胜的概率和妹子萌获胜的概率有多大? ## 输入格式 包含一行,包含两个整数 $n,m$,表示 n+e 和妹子萌最开始有的牌数。 ## 输出格式 包含一行,表示 n+e 获胜的概率和妹子萌获胜的概率,你的答案要保留到小数点后 $6$ 位。 ## 样例 #1 ```input1 0 3 ``` ```output1 0.250000 0.750000 ``` ## 样例说明 #1 由于 n+e 手上没有牌,也就是说妹子萌知道桌上的牌是什么了,所以 n+e 只能直接猜,因此猜对的概率是 $0.25$。 ## 样例 #2 ```input2 2 2 ``` ```output2 0.555556 0.444444 ``` ## 样例说明 #2 对于第二个样例,有一个伟大的人给了我们一个解释,十分可惜他现在已经不在了,这个解释也跟着消失在历史中了,但是十分聪明的 n+e 和妹子萌却早已了解,不信去问他们。 ## 数据规模与约定 对于 $100\%$ 的数据:$0 \le n,m \le 10^3$。
'use client'; import React, { useEffect } from 'react'; import styles from './orders.module.css'; import { useGetVentasQuery } from '../../../redux/services/ventasApi'; import Link from 'next/link'; function Page() { const { data, refetch } = useGetVentasQuery(null); const ventas = data?.result; useEffect(() => { refetch(); }, [refetch]); return ( <div> <Link href='/admin' className={styles.link}> Volver </Link> <div className={styles.contenedorTitulo}> <h1 className={styles.titulo}>Lista de Ventas</h1> </div> <div className={styles.addButtonContainer}></div> <div className={styles.tabla}> <table className={styles.userTable}> <thead> <tr> <th>EMAIL VENDEDOR</th> <th>EMAIL COMPRADOR</th> <th>PRECIO</th> <th>FECHA</th> </tr> </thead> {ventas?.map((venta, index) => ( <tr key={index}> <td>{venta.vendedor.correo}</td> <td>{venta.comprador.correo}</td> <td>{venta.monto}</td> <td>{new Date(venta.fecha).toLocaleDateString('es-ES')}</td> </tr> ))} </table> </div> </div> ); } export default Page;
<!DOCTYPE html> <html> <div class="container"> <app-header></app-header> <div class="signup-container"> <div class="title-container"> <h2>Konto Erstellen</h2> <img src="assets\img\studylink_II_logo.svg" alt="Logo"> </div> <form [formGroup]="loginForm" (keydown.enter)="directToLogin()" (mouseup)="onButtonReleased()" (mouseup)="onButtonCReleased()"> <div class="form-group"> <label for="email" [class.active]="isEmailActive">E-Mail</label> <input type="text" id="email" (focus)="onInputFocus('email')" (blur)="onInputBlur('email')" name="email" formControlName="email" required> </div> <div class="form-group"> <label for="passwort" [class.active]="isPasswordActive">Passwort</label> <input type="{{ isPasswordVisible ? 'text' : 'password' }}" id="passwort" (focus)="onInputFocus('password')" (blur)="onInputBlur('password')" name="passwort" formControlName="password" required> <button type="button" class="btn-show-password" (mousedown)="onButtonPressed()"><img [src]=" isPasswordVisible ? 'assets/img/eye.png' : 'assets/img/eye.png'" alt="themIcon"></button> </div> <div class="form-group"> <label for="confirmPassword" [class.active]="isConfirmPasswordActive">Passwort bestätigen</label> <input type="{{ isConfirmPasswordVisible ? 'text' : 'password' }}" id="confirmPassword" (focus)="onInputFocus('confirmPassword')" (blur)="onInputBlur('confirmPassword')" name="confirmPassword" formControlName="confirmPassword" required> <button type="button" class="btn-show-password" (mousedown)="onButtonCPressed()"><img [src]=" isConfirmPasswordVisible ? 'assets/img/eye.png' : 'assets/img/eye.png'" alt="themIcon"></button> </div> <div class="form-btn-container"> <div class="text">Bereits ein Konto?</div> <button type="button" routerLink="/login" class="btn-directTo-login">Anmelden</button> </div> </form> <div class="btn-container" > <button type="button" (click)="onSubmit()" class="btn-confirm btn-propertys">Konto Erstellen</button> </div> </div> <app-footer></app-footer> </div> </html>
import { HttpErrorResponse } from '@angular/common/http'; import { Component, Input } from '@angular/core'; import { FormControl } from '@angular/forms'; import { MatDatepicker } from '@angular/material/datepicker'; import { MatDialog } from '@angular/material/dialog'; import { ChartConfiguration, ChartData, ChartEvent, ChartTypeRegistry } from 'chart.js'; import { addMonths, endOfMonth, startOfMonth, subMonths } from 'date-fns'; import { ConfirmModalComponent } from '../modals/confirm-modal/confirm-modal.component'; import { Expense } from '../model/Expense'; import { Label } from '../model/Label'; import { ErrorHandlerService } from '../services/error.handler.service'; import { ExpenseService } from '../services/expense.service/expense.service'; import { LabelService } from '../services/label.service/label.service'; import { DIALOG_SMALL_HEIGHT, DIALOG_SMALL_WIDTH } from '../utils/Constants'; @Component({ selector: 'app-expense-list-by-month', templateUrl: './expense-list-by-month.component.html', styleUrls: ['./expense-list-by-month.component.scss'] }) export class ExpenseListByMonthComponent { @Input() public labels: Label[] = []; public expenses: Expense[] = []; public monthsWithExpenses: string[] = []; public selectedMonthFormControl = new FormControl(startOfMonth(new Date())); public expensesByLabelChart: | ChartData<keyof ChartTypeRegistry, number[], string> | undefined = undefined; public barChartOptions: ChartConfiguration['options'] = { responsive: true, plugins: { legend: { display: true } } }; private currentSelectedMonth = startOfMonth(new Date()); private ERROR_DELETING_LABEL = 'Erreur lors de la suppression du label.'; private ERROR_GETTING_EXPENSES = 'Erreur lors de la récupération des dépenses.'; private EXPENSES_CHART_LABEL = 'Dépenses'; constructor( public dialog: MatDialog, private labelService: LabelService, private expenseService: ExpenseService, private errorHandlerService: ErrorHandlerService ) { const startIntervalDate = this.currentSelectedMonth; const endIntervalDate = endOfMonth(this.currentSelectedMonth); this.getExpenses(startIntervalDate, endIntervalDate); // Get total expenses, et switch avec la liste des expense par mois } public deleteLabel(labelId: number): void { this.labelService.deleteLabel(labelId).subscribe({ next: () => { this.labels = this.labels.filter((label) => label.id !== labelId); this.expenses = this.expenses.filter( (expense) => expense.labelId !== labelId ); this.refreshExpensesChart(); }, error: (error: HttpErrorResponse) => this.errorHandlerService.handleError(error, this.ERROR_DELETING_LABEL) }); } public handleExpenseCreation(newExpense: Expense): void { this.expenses = [...this.expenses, newExpense]; this.refreshExpensesChart(); } public openDeleteExpenseModal(expenseId: number): void { const dialogRef = this.dialog.open(ConfirmModalComponent, { height: DIALOG_SMALL_HEIGHT, width: DIALOG_SMALL_WIDTH, data: { title: "Suppression d'une dépense", message: 'Êtes-vous sûr de vouloir supprimer cette dépense ?' } }); dialogRef.afterClosed().subscribe((result) => { if (result === 'validate') { this.deleteExpense(expenseId); } }); } public getLabelFromId(labelId: number): Label | undefined { return this.labels.find((label) => label.id === labelId); } public getTotalForMonth(): number { return parseFloat( this.expenses .map((expense) => expense.amount) .reduce((total, amount) => total + amount, 0) .toFixed(10) ); } public handleChartClickedEvent({ event, active }: { event?: ChartEvent; active?: object[]; }): void { console.log(event, active); } public selectPreviousMonth(): void { this.selectMonth(subMonths(this.currentSelectedMonth, 1)); } public selectNextMonth(): void { this.selectMonth(addMonths(this.currentSelectedMonth, 1)); } public setMonthAndYear( normalizedMonthAndYear: Date, datepicker: MatDatepicker<Date> ): void { const selectedMonth = new Date( normalizedMonthAndYear.getFullYear(), normalizedMonthAndYear.getMonth(), 1 ); this.selectMonth(selectedMonth); datepicker.close(); } private selectMonth(selectedMonth: Date): void { this.selectedMonthFormControl.setValue(selectedMonth); this.handleSelectExpensesForMonth(selectedMonth); } private deleteExpense(expenseId: number) { this.expenseService.deleteExpense(expenseId).subscribe({ next: () => { this.expenses = this.expenses.filter( (expense) => expense.id !== expenseId ); this.refreshExpensesChart(); } }); } private getExpensesByLabel(expenses: Expense[]): Record<string, number[]> { return expenses.reduce( (expensesByLabel: Record<string, number[]>, currentExpense: Expense) => { const labelId = currentExpense.labelId; expensesByLabel[labelId] = expensesByLabel[labelId] ?? []; expensesByLabel[labelId].push(currentExpense.amount); return expensesByLabel; }, {} ); } private handleSelectExpensesForMonth(month: Date): void { if (this.currentSelectedMonth.getTime() !== startOfMonth(month).getTime()) { this.currentSelectedMonth = startOfMonth(month); this.getExpenses(this.currentSelectedMonth, endOfMonth(month)); } } private getExpenses(startIntervalDate: Date, endIntervalDate: Date) { this.expenseService .getExpensesAtMonth(startIntervalDate, endIntervalDate) .subscribe({ next: (expenses) => { this.expenses = expenses; this.refreshExpensesChart(); }, error: (error: HttpErrorResponse) => this.errorHandlerService.handleError( error, this.ERROR_GETTING_EXPENSES ) }); } private refreshExpensesChart() { const expensesByLabel = this.getExpensesByLabel(this.expenses); this.expensesByLabelChart = { labels: [this.EXPENSES_CHART_LABEL], datasets: Object.keys(expensesByLabel).map((labelId) => { const labelName = this.labels.filter( (label) => label.id.toString() === labelId )[0]; if (!labelId || labelName === undefined) { return { label: '', data: [] }; } return { label: labelName.label, data: [ expensesByLabel[labelId].reduce((total, amount) => total + amount) ] }; }) }; } }
/* Section 2 Roll No. - 22CS30016 Name - Omkar Vijay Bhandare Assignment No. - 08 Description - Matrices and Structure */ #include<stdio.h> #include<stdlib.h> struct matrix { int **ptr }a,b,c; void readMatrix(int a[][10], int m, int n) { for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { scanf("%d", &a[i][j]); } } } void printMatrix(int a[][10], int m, int n) { for(int i=0; i<m; i++) { for(int j=0; j<n; j++) { printf("%d ", a[i][j]); } printf("\n"); } } void matrixMultiplication(int a[][10], int b[][10], int c[][10], int m, int n, int p) { int sum = 0; for(int i=0; i<m; i++) { for(int j=0; j<p; j++) { for(int k=0; k<n; k++) { sum = sum + a[i][k]*b[k][j]; } c[i][j] = sum; sum = 0; } } } int main() { int arow,acol,brow,bcol; printf("Enter number of rows for matrix A : "); scanf("%d", &arow); printf("Enter number of columns for matrix A : "); scanf("%d", &acol); printf("Enter number of rows for matrix B : "); scanf("%d", &brow); printf("Enter number of columns for matrix B : "); scanf("%d", &bcol); a.ptr = (int **)malloc(arow*sizeof(int *)); for(int i=0; i<arow; i++) { a.ptr[i] = (int *)malloc(acol*sizeof(int)); } printf("Enter the values for Matrix A : \n"); readMatrix(a.ptr,arow,acol); b.ptr = (int **)malloc(brow*sizeof(int *)); for(int i=0; i<brow; i++) { b.ptr[i] = (int *)malloc(bcol*sizeof(int)); } printf("Enter the values for Matrix B : \n"); readMatrix(b.ptr,brow,bcol); printf("Matrices before multiplication : \n"); printf("Matrix A : \n"); printMatrix(a.ptr,arow,acol); printf("\n"); printf("Matrix B : \n"); printMatrix(b.ptr,brow,bcol); printf("\n"); if(acol!=brow) { printf("Error : Invalid matrix sizes for multiplication!"); } else { c.ptr = (int **)malloc(arow*sizeof(int *)); for(int i=0; i<arow; i++) { c.ptr[i] = (int *)malloc(bcol*sizeof(int)); } matrixMultiplication(a.ptr,b.ptr,c.ptr,arow,acol,bcol); printf("Matrices after multiplication : \n"); printf("Matrix A : \n"); printMatrix(a.ptr,arow,acol); printf("\n"); printf("Matrix B : \n"); printMatrix(b.ptr,brow,bcol); printf("\n"); printf("Resultant Matrix : \n"); printMatrix(c.ptr,arow,bcol); printf("\n"); } return 0; }
<div class="container" id="factura" #factura> <div class="card"> <div class="card-body"> <div id="invoice"> <div class="invoice overflow-auto"> <div style="min-width: 600px"> <header> <div class="row"> <div class="col"> <a href="javascript:;"> <img src="assets/img/logo.png" width="120" alt=""> </a> </div> <div class="col company-details"> <h2 class="name"> Dulce Heladería S.R.L </h2> <div>Illia 1234, X5000, Córdoba</div> <div>(351) 123-456</div> <div>CUIL 23-6540650-3</div> <div>dulce@heladeria.com.ar</div> </div> </div> </header> <main> <div class="row contacts"> <div class="col invoice-to"> <div class="text-gray-light">Cliente:</div> <h2 class="to">{{Factura.Cliente!.businessName}}</h2> <div class="address">{{Factura.Cliente!.homeAdress}}</div> <div class="address">{{TiposIdentifiers[Factura.Cliente!.identifierTypeId!]}} {{Factura.Cliente!.identifier}}</div> <div class="email"><a href="mailto:{{Factura.Cliente!.email}}">{{Factura.Cliente!.email}}</a> </div> </div> <div class="col invoice-details"> <h1 class="invoice-id">Comprobante #{{Factura.id}}</h1> <div class="date">Fecha: {{Factura.fecha}}</div> <div class="fp">Forma de Pago: {{Factura.formaPago}}</div> </div> </div> <table> <thead> <tr> <th>#</th> <th class="text-left">Descripción</th> <th class="text-right">Precio Unitario</th> <th class="text-right">Cantidad</th> <th class="text-right">Subtotal</th> </tr> </thead> <tbody> <tr *ngFor="let prod of Factura.producto; let i = index"> <td class="no">{{i+1}}</td> <td class="text-left"> <h3> {{prod.nombre}} </h3> <span *ngFor="let art of prod.articulos"> {{art.nombre}} </span> </td> <td class="unit">{{prod.precio | currency}}</td> <td class="qty">{{prod.cantidad}}</td> <td class="total">{{prod.precio*prod.cantidad | currency}}</td> </tr> </tbody> <tfoot> <tr> <td colspan="2"></td> <td colspan="2">TOTAL</td> <td>{{Factura.total | currency}}</td> </tr> </tfoot> </table> <div class="thanks">Muchas Gracias por su compra!</div> </main> <footer>Comprobante no valido como factura.</footer> </div> <!--DO NOT DELETE THIS div. IT is responsible for showing footer always at the bottom--> <div></div> </div> </div> </div> </div> </div> <div class="toolbar hidden-print"> <hr> <div class="text-center"> <button type="button" class="btn btn-primary" (click)="generatePDF()"><i class="fa fa-print"></i> Descargar PDF</button> <button type="button" class="btn btn-primary mx-3" (click)="openPDF()"><i class="fa fa-print"></i> Abrir PDF</button> </div> </div>
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FireGun : MonoBehaviour, IItem { public ParticleSystem fireParticleSystem; private Color fireColor = Color.red; private bool isShooting = false; private bool isHeld = false; private Rigidbody rb; private void Start() { fireParticleSystem.Stop(); rb = GetComponent<Rigidbody>(); } public void Pickup(Transform hand) { if (!isHeld) { Debug.Log("Picking up Fire Gun"); isHeld = true; // Disable Rigidbody to prevent movement while held rb.isKinematic = true; rb.velocity = Vector3.zero; // Ensure no residual velocity // Set the trigger to play the pickup animation if needed // animator.SetTrigger("PickupTrigger"); transform.SetParent(hand); transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; Collider col = GetComponent<Collider>(); if (col != null) { col.enabled = false; } } } public void Drop() { Debug.Log("Dropping Fire Gun"); isHeld = false; // Enable Rigidbody to allow movement when not held rb.isKinematic = false; rb.AddRelativeForce(Vector3.forward * 10, ForceMode.Impulse); transform.SetParent(null); Collider col = GetComponent<Collider>(); if (col != null) { col.enabled = true; } } public void PrimaryAction() { Debug.Log("Shooting fire with color: " + fireColor); if (isHeld && !isShooting) { isShooting = true; StartCoroutine(ShootFire()); } } public void SecondaryAction() { Debug.Log("Change fire color"); ChangeFireColor(); } private void ChangeFireColor() { fireColor = new Color(Random.value, Random.value, Random.value); Debug.Log("Fire color changed to: " + fireColor); } private IEnumerator ShootFire() { fireParticleSystem.Play(); while (isShooting) { var mainModule = fireParticleSystem.main; mainModule.startColor = fireColor; yield return null; } fireParticleSystem.Stop(); } public void StopShooting() { isShooting = false; } }
import axios from "axios"; import { useState, useEffect } from "react"; import { BsArchive, BsFile } from "react-icons/bs"; import { toast } from "react-toastify"; import AdminLayout from "../../../src/components/admin/AdminLayout"; import styles from "../../../styles/admin/Facility.module.css"; import { Input, Loader } from ".././../../src/components/ui/ui"; const Term = () => { const [loading, setloading] = useState(false); const [termName, setTermName] = useState(""); const [terms, setTerms] = useState([]); const addTerm = async (e) => { e.preventDefault(); try { const res = await axios.post("/api/term", { name: termName, }); if (res.status == 201) { toast.success("Successfully submitted your quotation"); setloading(false); getTerms(); } } catch (error) { setloading(false); toast.error("Something went wrong"); } }; const getTerms = async () => { setloading(true); const res = await axios.get("/api/term"); if (res.status == 200) { setTerms(res.data.terms); } setloading(false); }; const deleteTerm = async (id) => { try { const res = await axios.delete(`/api/term/${id}`); setTerms(terms.filter((item) => item._id !== id)); toast.success("Successfully deleted"); } catch (error) { console.log(error); toast.error("Something went wrong"); } }; useEffect(() => { getTerms(); }, []); if (loading) return <Loader />; return ( <AdminLayout> <div className={styles.wrapper}> <h1>Terms</h1> <div className={styles.addItem}> <Input label={"Name"} onChange={(e) => setTermName(e.target.value)} value={termName} /> <button className={styles.button} onClick={addTerm}> Add Term </button> </div> <div className={styles.items}> {terms.map((item, index) => ( <div className={styles.item} key={index}> <p>{item.name}</p> <div> <span onClick={() => deleteTerm(item._id)}> <BsArchive /> </span> </div> </div> ))} </div> </div> </AdminLayout> ); }; export default Term;
package vn.edu.iuh.fit.Back_End.entities; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import jakarta.persistence.*; import vn.edu.iuh.fit.Back_End.enums.EmployeeStatus; import java.io.Serializable; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "employee") @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id") @JsonIgnoreProperties(value = {"hibernateLazyInitializer", "handler"}) public class Employee implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "emp_id", columnDefinition = "bigint(20)") private long id; @Column(columnDefinition = "nvarchar(250)") private String address; @Column(columnDefinition = "datetime(6)") @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") @JsonSerialize(using = LocalDateSerializer.class) private LocalDate dob; @Column(columnDefinition = "nvarchar(150)") private String email; @Column(columnDefinition = "nvarchar(150)") private String fullName; @Column(columnDefinition = "nvarchar(15)") private String phone; @Column(columnDefinition = "int(11)") private EmployeeStatus status; @OneToMany(mappedBy = "employee") private List<Order> orderList= new ArrayList<Order>(); public Employee() { } public Employee(String address, LocalDate dob, String email, String fullName, String phone, EmployeeStatus status) { this.address = address; this.dob = dob; this.email = email; this.fullName = fullName; this.phone = phone; this.status = status; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public LocalDate getDob() { return dob; } public void setDob(LocalDate dob) { this.dob = dob; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public EmployeeStatus getStatus() { return status; } public void setStatus(EmployeeStatus status) { this.status = status; } public List<Order> getOrderList() { return orderList; } public void setOrderList(List<Order> orderList) { this.orderList = orderList; } @Override public String toString() { return "Employee{" + "id=" + id + ", address='" + address + '\'' + ", dob=" + dob + ", email='" + email + '\'' + ", fullName='" + fullName + '\'' + ", phone='" + phone + '\'' + ", status=" + status + '}'; } }
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package astutil contains common utilities for working with the Go AST. package astutil // import "llvm.org/llgo/third_party/gotools/go/ast/astutil" import ( "fmt" "go/ast" "go/token" "strconv" "strings" ) // AddImport adds the import path to the file f, if absent. func AddImport(fset *token.FileSet, f *ast.File, ipath string) (added bool) { return AddNamedImport(fset, f, "", ipath) } // AddNamedImport adds the import path to the file f, if absent. // If name is not empty, it is used to rename the import. // // For example, calling // AddNamedImport(fset, f, "pathpkg", "path") // adds // import pathpkg "path" func AddNamedImport(fset *token.FileSet, f *ast.File, name, ipath string) (added bool) { if imports(f, ipath) { return false } newImport := &ast.ImportSpec{ Path: &ast.BasicLit{ Kind: token.STRING, Value: strconv.Quote(ipath), }, } if name != "" { newImport.Name = &ast.Ident{Name: name} } // Find an import decl to add to. // The goal is to find an existing import // whose import path has the longest shared // prefix with ipath. var ( bestMatch = -1 // length of longest shared prefix lastImport = -1 // index in f.Decls of the file's final import decl impDecl *ast.GenDecl // import decl containing the best match impIndex = -1 // spec index in impDecl containing the best match ) for i, decl := range f.Decls { gen, ok := decl.(*ast.GenDecl) if ok && gen.Tok == token.IMPORT { lastImport = i // Do not add to import "C", to avoid disrupting the // association with its doc comment, breaking cgo. if declImports(gen, "C") { continue } // Match an empty import decl if that's all that is available. if len(gen.Specs) == 0 && bestMatch == -1 { impDecl = gen } // Compute longest shared prefix with imports in this group. for j, spec := range gen.Specs { impspec := spec.(*ast.ImportSpec) n := matchLen(importPath(impspec), ipath) if n > bestMatch { bestMatch = n impDecl = gen impIndex = j } } } } // If no import decl found, add one after the last import. if impDecl == nil { impDecl = &ast.GenDecl{ Tok: token.IMPORT, } if lastImport >= 0 { impDecl.TokPos = f.Decls[lastImport].End() } else { // There are no existing imports. // Our new import goes after the package declaration and after // the comment, if any, that starts on the same line as the // package declaration. impDecl.TokPos = f.Package file := fset.File(f.Package) pkgLine := file.Line(f.Package) for _, c := range f.Comments { if file.Line(c.Pos()) > pkgLine { break } impDecl.TokPos = c.End() } } f.Decls = append(f.Decls, nil) copy(f.Decls[lastImport+2:], f.Decls[lastImport+1:]) f.Decls[lastImport+1] = impDecl } // Insert new import at insertAt. insertAt := 0 if impIndex >= 0 { // insert after the found import insertAt = impIndex + 1 } impDecl.Specs = append(impDecl.Specs, nil) copy(impDecl.Specs[insertAt+1:], impDecl.Specs[insertAt:]) impDecl.Specs[insertAt] = newImport pos := impDecl.Pos() if insertAt > 0 { // Assign same position as the previous import, // so that the sorter sees it as being in the same block. pos = impDecl.Specs[insertAt-1].Pos() } newImport.Path.ValuePos = pos newImport.EndPos = pos // Clean up parens. impDecl contains at least one spec. if len(impDecl.Specs) == 1 { // Remove unneeded parens. impDecl.Lparen = token.NoPos } else if !impDecl.Lparen.IsValid() { // impDecl needs parens added. impDecl.Lparen = impDecl.Specs[0].Pos() } f.Imports = append(f.Imports, newImport) return true } // DeleteImport deletes the import path from the file f, if present. func DeleteImport(fset *token.FileSet, f *ast.File, path string) (deleted bool) { var delspecs []*ast.ImportSpec // Find the import nodes that import path, if any. for i := 0; i < len(f.Decls); i++ { decl := f.Decls[i] gen, ok := decl.(*ast.GenDecl) if !ok || gen.Tok != token.IMPORT { continue } for j := 0; j < len(gen.Specs); j++ { spec := gen.Specs[j] impspec := spec.(*ast.ImportSpec) if importPath(impspec) != path { continue } // We found an import spec that imports path. // Delete it. delspecs = append(delspecs, impspec) deleted = true copy(gen.Specs[j:], gen.Specs[j+1:]) gen.Specs = gen.Specs[:len(gen.Specs)-1] // If this was the last import spec in this decl, // delete the decl, too. if len(gen.Specs) == 0 { copy(f.Decls[i:], f.Decls[i+1:]) f.Decls = f.Decls[:len(f.Decls)-1] i-- break } else if len(gen.Specs) == 1 { gen.Lparen = token.NoPos // drop parens } if j > 0 { lastImpspec := gen.Specs[j-1].(*ast.ImportSpec) lastLine := fset.Position(lastImpspec.Path.ValuePos).Line line := fset.Position(impspec.Path.ValuePos).Line // We deleted an entry but now there may be // a blank line-sized hole where the import was. if line-lastLine > 1 { // There was a blank line immediately preceding the deleted import, // so there's no need to close the hole. // Do nothing. } else { // There was no blank line. Close the hole. fset.File(gen.Rparen).MergeLine(line) } } j-- } } // Delete them from f.Imports. for i := 0; i < len(f.Imports); i++ { imp := f.Imports[i] for j, del := range delspecs { if imp == del { copy(f.Imports[i:], f.Imports[i+1:]) f.Imports = f.Imports[:len(f.Imports)-1] copy(delspecs[j:], delspecs[j+1:]) delspecs = delspecs[:len(delspecs)-1] i-- break } } } if len(delspecs) > 0 { panic(fmt.Sprintf("deleted specs from Decls but not Imports: %v", delspecs)) } return } // RewriteImport rewrites any import of path oldPath to path newPath. func RewriteImport(fset *token.FileSet, f *ast.File, oldPath, newPath string) (rewrote bool) { for _, imp := range f.Imports { if importPath(imp) == oldPath { rewrote = true // record old End, because the default is to compute // it using the length of imp.Path.Value. imp.EndPos = imp.End() imp.Path.Value = strconv.Quote(newPath) } } return } // UsesImport reports whether a given import is used. func UsesImport(f *ast.File, path string) (used bool) { spec := importSpec(f, path) if spec == nil { return } name := spec.Name.String() switch name { case "<nil>": // If the package name is not explicitly specified, // make an educated guess. This is not guaranteed to be correct. lastSlash := strings.LastIndex(path, "/") if lastSlash == -1 { name = path } else { name = path[lastSlash+1:] } case "_", ".": // Not sure if this import is used - err on the side of caution. return true } ast.Walk(visitFn(func(n ast.Node) { sel, ok := n.(*ast.SelectorExpr) if ok && isTopName(sel.X, name) { used = true } }), f) return } type visitFn func(node ast.Node) func (fn visitFn) Visit(node ast.Node) ast.Visitor { fn(node) return fn } // imports returns true if f imports path. func imports(f *ast.File, path string) bool { return importSpec(f, path) != nil } // importSpec returns the import spec if f imports path, // or nil otherwise. func importSpec(f *ast.File, path string) *ast.ImportSpec { for _, s := range f.Imports { if importPath(s) == path { return s } } return nil } // importPath returns the unquoted import path of s, // or "" if the path is not properly quoted. func importPath(s *ast.ImportSpec) string { t, err := strconv.Unquote(s.Path.Value) if err == nil { return t } return "" } // declImports reports whether gen contains an import of path. func declImports(gen *ast.GenDecl, path string) bool { if gen.Tok != token.IMPORT { return false } for _, spec := range gen.Specs { impspec := spec.(*ast.ImportSpec) if importPath(impspec) == path { return true } } return false } // matchLen returns the length of the longest path segment prefix shared by x and y. func matchLen(x, y string) int { n := 0 for i := 0; i < len(x) && i < len(y) && x[i] == y[i]; i++ { if x[i] == '/' { n++ } } return n } // isTopName returns true if n is a top-level unresolved identifier with the given name. func isTopName(n ast.Expr, name string) bool { id, ok := n.(*ast.Ident) return ok && id.Name == name && id.Obj == nil } // Imports returns the file imports grouped by paragraph. func Imports(fset *token.FileSet, f *ast.File) [][]*ast.ImportSpec { var groups [][]*ast.ImportSpec for _, decl := range f.Decls { genDecl, ok := decl.(*ast.GenDecl) if !ok || genDecl.Tok != token.IMPORT { break } group := []*ast.ImportSpec{} var lastLine int for _, spec := range genDecl.Specs { importSpec := spec.(*ast.ImportSpec) pos := importSpec.Path.ValuePos line := fset.Position(pos).Line if lastLine > 0 && pos > 0 && line-lastLine > 1 { groups = append(groups, group) group = []*ast.ImportSpec{} } group = append(group, importSpec) lastLine = line } groups = append(groups, group) } return groups }
package Day02 import println import readInput fun main() { fun List<String>.findMaxValueOfColor(color: String): Int { return this.filter { it.contains(color) }.maxOf { it.replace(color, "").toInt() } } fun part1(input: List<String>): Int { return input.map { it.replace(" ", "").split(":|;|,".toRegex()) } .filter { val greenMax = it.findMaxValueOfColor("green") val blueMax = it.findMaxValueOfColor("blue") val redMax = it.findMaxValueOfColor("red") greenMax <= 13 && redMax <= 12 && blueMax <= 14 } .sumOf { it[0].replace("Game", "").toInt() } } fun part2(input: List<String>): Int { return input.sumOf { val subValue = it.replace(" ", "").split(":|;|,".toRegex()) val greenMax = subValue.findMaxValueOfColor("green") val blueMax = subValue.findMaxValueOfColor("blue") val redMax = subValue.findMaxValueOfColor("red") greenMax * blueMax * redMax } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 8) val testInputPartTwo = readInput("Day02_test") check(part2(testInputPartTwo) == 2286) val input = readInput("Day02") part1(input).println() part2(input).println() }
<template> <div class="container"> <div class="card"> <div class="card-header"> <h3>Editar Funcionário</h3> </div> <div class="card-body"> <form v-on:submit.prevent="updateFormEmployee()"> <div class="form-group"> <label class="font-weight-bold">Nome do Funcionário</label> <input type="text" id="name" class="form-control" v-model="employeeForm.name_employee"> </div> <div class="form-group"> <label class="font-weight-bold">Função do Funcionário</label> <input type="text" id="role" class="form-control" v-model="employeeForm.role_employee"> </div> <div class="form-group"> <label class="font-weight-bold">Salário do Funcionário</label> <input type="number" id="salary" class="form-control" v-model="employeeForm.salary_employee"> </div> <div class="form-group"> <label class="font-weight-bold">Número de Registro do Funcionário</label> <input type="number" id="registration" class="form-control" v-model="employeeForm.registration_employee"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary"><font-awesome-icon icon="fa-solid fa-pen" /> Update </button> </div> </form> </div> </div> </div> </template> <script> import ServiceUser from '../../services/user' export default { data() { return { employeeForm: {} } }, mounted() { this.getEmployeeById() }, methods: { async getEmployeeById() { const {registration_employee} = this.$route.params; const response = await ServiceUser.updateEmployee(registration_employee) this.employeeForm = {...response} }, async updateFormEmployee() { await ServiceUser.updateEmployee(this.employeeForm); this.$router.push ({name: 'list'}) }, } } </script> <style> .employee { display: flex; align-items: center; justify-content: center; } </style>
use std::f32::consts::FRAC_PI_2; use ambient_api::{ core::{ ecs::components::{children, parent}, physics::concepts::make_character_controller, player::components::is_player, prefab::components::prefab_from_url, transform::{ components::{local_to_parent, local_to_world, rotation, translation}, concepts::make_transformable, }, }, prelude::*, }; use packages::unit_schema::components::{health, run_direction}; use packages::{ basic_character_animation::components::basic_character_animations, this::{assets, components}, }; #[main] pub async fn main() { let chars = [ assets::url("Zombiegirl W Kurniawan.fbx"), assets::url("copzombie_l_actisdato.fbx"), assets::url("Yaku J Ignite.fbx"), ]; fn anim_url(name: &str) -> String { assets::url(&format!("{name}.fbx/animations/mixamo.com.anim")) } run_async(async move { for character_url in chars { let zombie = Entity::new().spawn(); let model = make_transformable() .with(prefab_from_url(), character_url) .with(parent(), zombie) .with(local_to_parent(), Default::default()) .with(rotation(), Quat::from_rotation_z(-FRAC_PI_2)) .spawn(); entity::add_components( zombie, make_transformable() .with_merge(make_character_controller()) .with( translation(), vec3(-8.0 * random::<f32>(), -8.0 * random::<f32>(), 1.3), ) .with(children(), vec![model]) .with(local_to_world(), Default::default()) .with(components::zombie_model_ref(), model) .with(health(), 100.) .with(run_direction(), -Vec2::Y) .with(components::is_zombie(), ()) .with(basic_character_animations(), model) .with( packages::basic_character_animation::components::idle(), anim_url("Zombie Idle"), ) .with( packages::basic_character_animation::components::walk_forward(), anim_url("Zombie Walk"), ) .with( packages::basic_character_animation::components::run_forward(), anim_url("Zombie Run"), ) .with( packages::basic_character_animation::components::death(), anim_url("Zombie Death"), ), ); sleep(random::<f32>()).await; } }); let player_query = query(translation()).requires(is_player()).build(); query((translation(), components::is_zombie())).each_frame(move |zombies| { for (zombie, (pos, _)) in zombies { let players: Vec<(EntityId, Vec3)> = player_query.evaluate(); let zombie_pos = vec2(pos.x, pos.y); let mut min_distance = 50.; let mut nearest_player_pos: Option<Vec2> = None; for (_player, pos) in players { let player_pos = vec2(pos.x, pos.y); let distance = (zombie_pos - player_pos).length(); if distance < min_distance { let mut wall_blocking = false; for hit in physics::raycast( zombie_pos.extend(0.5), (player_pos - zombie_pos).normalize().extend(0.), ) { if entity::has_component(hit.entity, components::is_zombie()) { continue; // other zombies cant block my sight } else if entity::has_component(hit.entity, is_player()) { break; // great! i see you } else { wall_blocking = true; // aww, a walls in the way break; } } if wall_blocking { continue; // can't see this player; good bye. } min_distance = distance; nearest_player_pos = Some(player_pos); } } if let Some(nearest_player_pos) = nearest_player_pos { let displace = nearest_player_pos - zombie_pos; // if displace.length() > 5.0 { // break; // } let zb_speed = 0.03; // If you want the zombie to move at a constant speed regardless of distance to the player, // you may want to normalize the displacement vector before feeding it to `move_character` let displace = displace.normalize_or_zero() * zb_speed; // normalize to get a unit vector let angle = displace.y.atan2(displace.x); let rot = Quat::from_rotation_z(angle); let _collision = physics::move_character( zombie, vec3(displace.x, displace.y, -0.1), 0.01, delta_time(), ); entity::set_component(zombie, rotation(), rot); entity::set_component(zombie, run_direction(), -Vec2::Y); // println!("collision: {} {} {}", collision.up, collision.down, collision.side); } else { entity::set_component(zombie, run_direction(), Vec2::ZERO); } } }); }
package com.ecureuill.rpgbattle.application.services; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; import org.springframework.stereotype.Service; import org.springframework.util.MultiValueMap; import com.ecureuill.rpgbattle.application.dtos.BattleCreateRequest; import com.ecureuill.rpgbattle.application.dtos.BattleSelectCharacterRequest; import com.ecureuill.rpgbattle.application.exceptions.BattleNotFoundException; import com.ecureuill.rpgbattle.application.exceptions.BattleStateException; import com.ecureuill.rpgbattle.application.exceptions.CharacterNotFoundException; import com.ecureuill.rpgbattle.application.exceptions.InvalidBattleParametersException; import com.ecureuill.rpgbattle.application.exceptions.NoTurnActiveException; import com.ecureuill.rpgbattle.application.exceptions.PlayerNotFoundException; import com.ecureuill.rpgbattle.application.exceptions.TurnNotFoundException; import com.ecureuill.rpgbattle.application.services.specifications.QueryParamsSpecification; import com.ecureuill.rpgbattle.domain.battle.Battle; import com.ecureuill.rpgbattle.domain.battle.Player; import com.ecureuill.rpgbattle.domain.battle.SelectedCharacter; import com.ecureuill.rpgbattle.domain.battle.Turn; import com.ecureuill.rpgbattle.domain.battle.states.battlestate.CreatedBattleState; import com.ecureuill.rpgbattle.domain.battle.states.battlestate.EndBattleState; import com.ecureuill.rpgbattle.domain.battle.states.battlestate.InitiativeBattleState; import com.ecureuill.rpgbattle.domain.battle.states.battlestate.NotCreatedBattleState; import com.ecureuill.rpgbattle.domain.battle.states.battlestate.TurnsBattleState; import com.ecureuill.rpgbattle.domain.battle.states.turnstate.EndTurnState; import com.ecureuill.rpgbattle.domain.battle.states.turnstate.TurnStateType; import com.ecureuill.rpgbattle.infrastructure.repositories.BattleRepository; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; @Service @RequiredArgsConstructor public class BattleService { private final BattleRepository battleRepository; private final UserService userService; private final CharacterService characterService; private final List<QueryParamsSpecification> specifications; public Battle createBattle(BattleCreateRequest battleUsers) throws InvalidBattleParametersException, BattleStateException { if(battleUsers.playerOne().equals(battleUsers.playerTwo())){ throw new InvalidBattleParametersException("Player One and Player Two should not be the same"); } try { Player playerOne = new Player(null, userService.findByUsername(battleUsers.playerOne()).getUsername(), null, null); Player playerTwo = new Player(null, userService.findByUsername(battleUsers.playerTwo()).getUsername(), null, null); Battle battle = new Battle( ); try { ((NotCreatedBattleState)battle.getState()).createBattle(battle, playerOne, playerTwo); } catch (ClassCastException e) { throw new BattleStateException("This operation is not allowed while battle is in " + battle.getStage().getName()); } return battleRepository.save(battle); } catch (PlayerNotFoundException e) { throw new InvalidBattleParametersException(e.getMessage()); } } public List<Battle> getAllBattles(MultiValueMap<String, String> queryParams) { if(queryParams.isEmpty()){ return battleRepository.findAll(); } for (QueryParamsSpecification specification : specifications) { if(specification.isSatisfiedBy(queryParams)) { return specification.getResults(queryParams); } } return new ArrayList<>(); } public Battle getBattleById(UUID uuid) throws BattleNotFoundException { return battleRepository.findById(uuid).orElseThrow(() -> new BattleNotFoundException(uuid)); } public Battle selectCharacter(UUID battleId, String playerUsername, @Valid BattleSelectCharacterRequest data) throws BattleNotFoundException, PlayerNotFoundException, CharacterNotFoundException, BattleStateException { Battle battle = findBattleById(battleId); SelectedCharacter character = new SelectedCharacter(characterService.getCharacterBySpecie(data.specie())); try { ((CreatedBattleState)battle.getState()).addCharacter(battle, playerUsername, character); } catch (ClassCastException e) { throw new BattleStateException("This operation is not allowed while battle is in " + battle.getStage().getName()); } battleRepository.save(battle); return battle; } public Battle determineInitiative(UUID battleId) throws BattleStateException, BattleNotFoundException{ Battle battle = findBattleById(battleId); try { ((InitiativeBattleState)battle.getState()).determineInitiative(battle); } catch (ClassCastException e) { throw new BattleStateException("This operation is not allowed while battle is in " + battle.getStage().getName()); } battleRepository.save(battle); return battle; } public Battle takeTurns(UUID battleId) throws BattleNotFoundException, BattleStateException, NoTurnActiveException, TurnNotFoundException { Battle battle = findBattleById(battleId); validateBattleState(battle); TurnsBattleState state = (TurnsBattleState) battle.getState(); if(isTurnNotInitiated(battle)){ startNewTurn(battle); } if(isTurnOver(battle)){ startNewTurn(battle); battle.setLastTurnTime(LocalDateTime.now()); } state.turnAction(battle); battleRepository.save(battle); if(isBattleOver(battle)){ endedBattle(battle); } battleRepository.save(battle); return battle; } private Boolean isBattleOver(Battle battle){ return battle.getState() instanceof EndBattleState; } private void endedBattle(Battle battle){ battle.setEndTime(LocalDateTime.now()); } private void startNewTurn(Battle battle){ Turn turn = new Turn(); turn.setTurnSequence(battle.getTurnsSequence() + 1); battle.getTurns().add(turn); battle.setTurnsSequence(battle.getTurnsSequence() + 1); battle = battleRepository.save(battle); battle.setCurrentTurnId(findActiveTurn(battle)); } private Boolean isTurnNotInitiated(Battle battle){ return battle.getCurrentTurnId() == null; } private Boolean isTurnOver(Battle battle){ Optional<Turn> optionalTurn = battle.getCurrentTurn(); if(optionalTurn.isEmpty()){ return false; } return optionalTurn.get().getState() instanceof EndTurnState; } private void validateBattleState(Battle battle) throws BattleStateException{ if(!(battle.getState() instanceof TurnsBattleState)){ throw new BattleStateException("This operation is not allowed while battle is in " + battle.getStage().getName()); } } private Battle findBattleById(UUID battleId) throws BattleNotFoundException { return battleRepository.findById(battleId).orElseThrow(() -> new BattleNotFoundException(battleId)); } private UUID findActiveTurn(Battle battle) { return battle.getTurns().stream().filter(t -> t.getStateType() != TurnStateType.IS_END).findFirst().get().getId(); } }
# Shop Keeper example This project is a short simple example of test driven example in the context of games development. It was designed to be used as part of an example for presentations/talks for educational purposes to encourage people to learn the practice. **This project is coded in C# using the Rider platform and should open in Jet Brains Rider and Visual Studio** ## How to Start This project is designed as a starting point for people unsure about Test Driven Development. Download this project and try out the practice! 1. Download [GitHub Desktop](https://desktop.github.com/) and Login 2. Clone this Repository 3. Open in [Visual Studio](https://visualstudio.microsoft.com/) or [Jet Brains Rider](https://www.jetbrains.com/rider/) 4. Press play and use some of the commands 5. Look through some of the code, in particular the Game Elements project **[Never heard of Git, GitHub or GitHub Desktop until now? See this.](https://blog.scottgarryfoster.com/easy-source-control-for-your-game-project-10af6f0331f2)** ### What is here? This project is a starting point, therefore there is already some code to make it a little easier to expand. * Command Manager - This project handles the console level of the project * Shop Game Loop - The actual command code runs from here. At the bottom you'll see the Give, SetPrice and Buy commands hooked up to ShopKeeper! * ShopKeeper - This is the substance, the logic behind a shop keeper. * This is incomplete however, buy is not finished. That'll be the task! * ShopKeeperExample - This is just the very top level application. It kicks off the command manager. ### How did we get here? As in Test Driven Development, everything is primarily driven by requirements. Below are the requirements and then the design of the application for the existing parts. **Give** To get to the point of buy, give is required to setup the Shop Keeper. These were the requirements and then below the design to meet them. ![Give Design](https://github.com/ScottGarryFoster/EXAMPLE-ShopKeeperTDD/blob/main/ReadmeImages/GiveRequirements.png?raw=true) The give command is hooked up to the top level as, **Give** *item* *quanity* and may be previewed below. ![](https://github.com/ScottGarryFoster/EXAMPLE-ShopKeeperTDD/blob/main/ReadmeImages/GiveCommandInUse.PNG?raw=true) **Set Price Get Price** Price is required before we can buy otherwise we cannot look at the wallet value. This is the design: ![](https://github.com/ScottGarryFoster/EXAMPLE-ShopKeeperTDD/blob/main/ReadmeImages/SetPriceRequirements.png?raw=true) Set Price and Get Price are both simple methods to store the value ready for buy. Below is it being used. ![](https://github.com/ScottGarryFoster/EXAMPLE-ShopKeeperTDD/blob/main/ReadmeImages/PriceCommand.PNG?raw=true) ### What is the Task? Buy is the last piece of the puzzle. This is a method within Shop Keeper which is entirely hooked up to the commands but with no implementation. Below are the requirements and existing code: ![](https://github.com/ScottGarryFoster/EXAMPLE-ShopKeeperTDD/blob/main/ReadmeImages/BuyRequirements.png?raw=true) Within ShopKeeper.cs ```c# /// <summary> /// Buy an item from the shop. /// </summary> /// <param name="item">The item to buy. </param> /// <param name="quantity">How many to buy. </param> /// <param name="wallet">Your wallet value. </param> /// <returns>Information about the trade. </returns> public InventoryAnswer Buy(Item item, int quantity, int wallet) { throw new NotImplementedException(); } ``` This is hooked up already in the command manager: HandleBuyCommand within ShopGameLoop: ```c# int price = this.shopKeeper.GetPrice(item); InventoryAnswer answer = this.shopKeeper.Buy(item, quantity, wallet); switch (answer.Answer) { case ShopInventoryAnswer.OutOfStock: this.userExchange.WriteText( $"Buy: You did not trade because they are out of stock of {item}"); break; case ShopInventoryAnswer.NotEnoughFunds: this.userExchange.WriteText( $"Buy: You did not trade because you do not have enough funds. " + $"Your wallet: {answer.NewWalletValue}, price of {item} {price}."); break; case ShopInventoryAnswer.SuccessfulTrade: this.userExchange.WriteText( $"Buy: You traded successfully. Your new wallet value is {answer.NewWalletValue}."); break; } ``` ![](https://github.com/ScottGarryFoster/EXAMPLE-ShopKeeperTDD/blob/main/ReadmeImages/BuyCommand.PNG?raw=true) ## Your task is to Implement Buy using Test Driven Development! # Key Items to Remember Test Driven Development key aspects to remember: 1. Red, Green, Clean! 2. Arrange, Act, Assert 3. Test Public Behaviour ![](https://github.com/ScottGarryFoster/EXAMPLE-ShopKeeperTDD/blob/main/ReadmeImages/TDDFlow-OnWhite.drawio.png?raw=true) Red Green Clean is the loop for TDD. Write a failing Test, make it pass then ensure your code is clean using your tests to verify everything still works. ![](https://github.com/ScottGarryFoster/EXAMPLE-ShopKeeperTDD/blob/main/ReadmeImages/ArrangeActAssert-OnWhite.drawio.png?raw=true) The triple A structure might help you write the tests. Arrange the state you would like to test under, perform the test and then check the results. You also may end up writing these in a different order but in the method naturally these will occur in this order. # Good Luck and Links below **Links** * [Introduction to Test Driven Development using examples by Scott Foster](https://blog.scottgarryfoster.com/introduction-to-test-driven-development-using-examples-372f3ea0b571) * [Test code once by arranging behaviours — using mocks](https://blog.scottgarryfoster.com/test-code-once-by-arranging-behaviours-using-mocks-7416d647b992) * [Stop pressing play- Unity Test Driven Development](https://blog.scottgarryfoster.com/stop-pressing-play-unity-test-driven-development-1e6ee4cde656) * [Ian Cooper (2017). TDD, Where Did It All Go Wrong.](https://www.youtube.com/watch?v=EZ05e7EMOLM) * [David Whitney (2022). Test Driven Development in JavaScript](https://www.youtube.com/watch?v=D7LKslgwxmQ) * [Unreal 4 Unit Testing](https://benui.ca/unreal/unreal-testing-introduction) * [From 0-1000: A Test Driven Approach to Tools Development by David Paris](https://www.gdcvault.com/play/1026631/Tools-Summit-From-0-1000) * [How Rare Tests Sea of Thieves to Stop Bugs Reaching Players](https://www.youtube.com/watch?v=Bu4YV4be6IE) * [Test Driven Game Development Experiences](https://www.gamedeveloper.com/programming/test-driven-game-development-experiences) * [GDC: Backwards is Forward: Making Better Games with Test-Driven Development - High Moon Studio developers](https://www.gamedeveloper.com/programming/gdc-backwards-is-forward-making-better-games-with-test-driven-development) **Books** * Working effectively with legacy code by Michael Feathers, M.C. (2013) * Test-driven development : by example by Kent Beck (2003) * Learning Test-Driven Development: A Polyglot Guide to Writing Uncluttered Code by Saleem Siddiqui (2021) * Art of Clean Code, The: Best Practices to Eliminate Complexity and Simplify Your Life by Christian Mayer (2022) * 97 Things Every Programmer Should Know: Collective Wisdom from the Experts by Kevlin Henney (2010)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Grafo de Red Dinámico</title> <script src="https://d3js.org/d3.v6.min.js"></script> </head> <body> <svg id="grafico"></svg> <script> const nodos = [ { id: 0, cercania: 1 }, { id: 1, cercania: 2 }, { id: 2, cercania: 3 }, { id: 3, cercania: 1 }, { id: 4, cercania: 3 }, { id: 5, cercania: 2 } ]; const conexiones = [ { source: 0, target: 1 }, { source: 1, target: 2 }, { source: 2, target: 3 }, { source: 3, target: 0 }, { source: 2, target: 4 }, { source: 4, target: 5 }, { source: 5, target: 1 } ]; const svg = d3.select("#grafico") .attr("width", 250) .attr("height", 150); const simulacion = d3.forceSimulation(nodos) .force("enlace", d3.forceLink(conexiones).distance(40)) .force("carga", d3.forceManyBody().strength(-100)) .force("centro", d3.forceCenter(125, 75)) .force("cercania", d3.forceRadial(d => d.cercania * 25, 125, 75)); const nodos_sel = svg.selectAll(".nodo") .data(nodos) .enter() .append("circle") .attr("class", "nodo") .attr("r", 10) .style("fill", "red"); const conexiones_sel = svg.selectAll(".conexion") .data(conexiones) .enter() .append("line") .attr("class", "conexion") .style("stroke", "black"); simulacion.on("tick", () => { nodos_sel.attr("cx", d => d.x) .attr("cy", d => d.y); conexiones_sel.attr("x1", d => d.source.x) .attr("y1", d => d.source.y) .attr("x2", d => d.target.x) .attr("y2", d => d.target.y); }); </script> </body> </html>
# Writer The writer takes your token collection and writes them to the disk. Theemo can write to multiple `targets`, like so: ```ts import { styleDictionaryWriter } from '@theemo/style-dictionary'; import { defineConfig } from '@theemo/cli'; export default defineConfig({ sync: { writer: { targets: styleDictionaryWriter({ ... }) } } }); ``` All these `targets` are writer plugins. Theemo provides some, but you can write your own, too. ## Available Writer Plugins - [Style Dictionary Writer](./style-dictionary/writer.md) ## Write your own Writer Plugin The plugin should implement the `WriterTool` interface, with only one `write()` function to keep the API fairly minimal. Here is the minimal starter code: ::: code-group ```ts [index.ts] import YourWriter from './reader'; import type { YourWriterConfig } from './config'; import type { TokenCollection } from '@theemo/tokens'; import type { WriterTool } from '@theemo/sync'; export function yourWriter(config: YourWriterConfig): WriterTool { return { write(tokens: TokenCollection) { const writer = new YourWriter(config); const tokens = writer.write(tokens); } }; } ``` ```ts [writer.ts] import type { YourWriterConfig } from './config'; import type { TokenCollection } from '@theemo/tokens'; export default class YourWriter { #config: YourWriterConfig; constructor(#config: YourWriterConfig) { } write(tokens: TokenCollection): void { // do your work here } } ``` ```ts [config.ts] export interface YourWriterConfig { // place your config options here } ``` ::: Use your reader aside to the figma reader: ```js import { styleDictionaryWriter } from '@theemo/style-dictionary'; import { yourWriter } from '<see-above>'; import { defineConfig } from '@theemo/cli'; export default defineConfig({ sync: { writer: { targets: [ styleDictionaryWriter({ ... }), yourWriter({ ... }) ] } } }); ```
<!DOCTYPE html> <html> <!-- WARNING! Make sure that you match all Quasar related tags to the same version! (Below it's "@2.3.2") --> <head> <!-- <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900|Material+Icons" rel="stylesheet" type="text/css" /> --> <link href="https://unpkg.com/quasar/dist/quasar.prod.css" rel="stylesheet" type="text/css" /> </head> <body> <!-- example of injection point where you write your app template --> <div id="q-app"> <q-btn>按钮</q-btn> <q-card class="my-card"> <q-card-section> {{ lorem }} </q-card-section> </q-card> </div> <!-- Add the following at the end of your body tag --> <script src="https://unpkg.com/vue"></script> <script src="https://unpkg.com/quasar/dist/quasar.umd.prod.js"></script> <script src="https://unpkg.com/quasar/dist/lang/zh-CN.umd.prod.js"></script> <script> /* Example kicking off the UI. Obviously, adapt this to your specific needs. Assumes you have a <div id="q-app"></div> in your <body> above */ const app = Vue.createApp({ setup() { return { lorem: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", }; }, }); app.use(Quasar); Quasar.lang.set(Quasar.lang.zhCN); app.mount("#q-app"); </script> </body> </html>
require('dotenv').config(); const express = require('express'); const mongoose = require('mongoose'); const helmet = require('helmet'); const cors = require('cors'); const { errors } = require('celebrate'); const { router } = require('./routes/index'); const errorHandler = require('./middlewares/error-handler'); const limiter = require('./middlewares/limiter'); const { requestLogger, errorLogger } = require('./middlewares/logger'); const { dataMovies, PORT } = require('./utils/config'); const app = express(); app.use(cors()); app.use(helmet()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); mongoose.connect(dataMovies); app.use(requestLogger); app.use(limiter); app.get('/crash-test', () => { setTimeout(() => { throw new Error('Сервер сейчас упадёт'); }, 0); }); app.use(router); app.use(errorLogger); app.use(errors()); app.use(errorHandler); app.listen(PORT, () => PORT);
/* Copyright 2023 The MediaPipe Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. #include "mediapipe/tasks/c/components/containers/embedding_result_converter.h" #include <algorithm> #include <cstdint> #include <cstdlib> #include "mediapipe/tasks/c/components/containers/embedding_result.h" #include "mediapipe/tasks/cc/components/containers/embedding_result.h" namespace mediapipe::tasks::c::components::containers { void CppConvertToEmbeddingResult( const mediapipe::tasks::components::containers::EmbeddingResult& in, EmbeddingResult* out) { out->has_timestamp_ms = in.timestamp_ms.has_value(); out->timestamp_ms = out->has_timestamp_ms ? in.timestamp_ms.value() : 0; out->embeddings_count = in.embeddings.size(); out->embeddings = out->embeddings_count ? new Embedding[out->embeddings_count] : nullptr; for (uint32_t i = 0; i < out->embeddings_count; ++i) { auto embedding_in = in.embeddings[i]; auto& embedding_out = out->embeddings[i]; if (!embedding_in.float_embedding.empty()) { // Handle float embeddings embedding_out.values_count = embedding_in.float_embedding.size(); embedding_out.float_embedding = new float[embedding_out.values_count]; std::copy(embedding_in.float_embedding.begin(), embedding_in.float_embedding.end(), embedding_out.float_embedding); embedding_out.quantized_embedding = nullptr; } else if (!embedding_in.quantized_embedding.empty()) { // Handle quantized embeddings embedding_out.values_count = embedding_in.quantized_embedding.size(); embedding_out.quantized_embedding = new char[embedding_out.values_count]; std::copy(embedding_in.quantized_embedding.begin(), embedding_in.quantized_embedding.end(), embedding_out.quantized_embedding); embedding_out.float_embedding = nullptr; } embedding_out.head_index = embedding_in.head_index; embedding_out.head_name = embedding_in.head_name.has_value() ? strdup(embedding_in.head_name->c_str()) : nullptr; } } void CppConvertToCppEmbedding( const Embedding& in, // C struct as input mediapipe::tasks::components::containers::Embedding* out) { // Handle float embeddings if (in.float_embedding != nullptr) { out->float_embedding.assign(in.float_embedding, in.float_embedding + in.values_count); } // Handle quantized embeddings if (in.quantized_embedding != nullptr) { out->quantized_embedding.assign(in.quantized_embedding, in.quantized_embedding + in.values_count); } out->head_index = in.head_index; // Copy head_name if it is present. if (in.head_name) { out->head_name = std::string(in.head_name); } } void CppCloseEmbeddingResult(EmbeddingResult* in) { for (uint32_t i = 0; i < in->embeddings_count; ++i) { auto embedding_in = in->embeddings[i]; delete[] embedding_in.float_embedding; delete[] embedding_in.quantized_embedding; embedding_in.float_embedding = nullptr; embedding_in.quantized_embedding = nullptr; free(embedding_in.head_name); } delete[] in->embeddings; in->embeddings = nullptr; } } // namespace mediapipe::tasks::c::components::containers
/** * VALUES AND PROMISES * Please, make sure to read the "05-Values-and-promises.md" file form exercise-info folder * @task * Create a function `attachTitle` which follows the requirements: * * prepends `'DR. '` to its first argument and returns the result. * Example: export const attachTitle = (arg) => {<Your_code>} * export const Promise */ export const attachTitle = (someName) => { return `DR. ${someName}`; }; /** * @task * Create a function that follows the requirements: * * Returns a fulfilled promise with a value of `'MANHATTAN'`. * * Build a promise chain off the promise we just constructed that first calls `attachTitle` then calls `console.log`. * If your program runs successfully, it should print out and return “DR. MANHATTAN” which is extremely exciting. */ export const getPromise = () => { return new Promise((resolve) => { resolve("MANHATTAN"); }) .then((data) => { console.log(data); return attachTitle(data); }) .then((value) => { console.log(value); return value; }); }; // === TEST YOURSELF === // Once you're finished run the test with "npm run test-5" // If the test has all tests passed, switch to the next exercise file // If any of the tests fails, refactor the code and run the test command after you've fixed the function
export interface TimeEntryBase { client: string; project: string; title: string; } export type TimerStatus = { isRunning: false } | { isRunning: true; entry: TimeEntryBase; runningForMs: number }; export abstract class TimeTracker { protected _status: TimerStatus = { isRunning: false }; public abstract syncStatus(): Promise<void>; public abstract getStatus(): Promise<TimerStatus>; public abstract stop(): Promise<void>; /** * Resume / restart the very last time entry * * If a timer is already running, or there is no previous entry to resume, * this method should throw an error */ public abstract resumeLastEntry(): Promise<void>; }
import React from 'react'; import renderer, {act} from 'react-test-renderer'; import StartScreen from '../../src/screens/StartScreen'; import settingsImage from '../../src/assets/settings-cog.png'; let component, settingsButton, settingsDisabled, startButton, text; describe('Given StartScreen component', () => { describe('When the component renders with a message', () => { const props = { navigation: { navigate: jest.fn() } }; beforeEach(() => { component = renderer.create(<StartScreen {...props}/>); startButton = component.root.findByProps({'data-testing': 'start-button'}); text = component.root.findByProps({'data-testing': 'litebike-title'}); settingsButton = component.root.findByProps({'data-testing': 'settings-button'}); settingsDisabled = component.root.findByProps({'data-testing': 'settings-disabled'}); }); it('Then the component matches the snapshot', () => { expect(component.toJSON()).toMatchSnapshot(); }); it('Then LiteBike appears on the screen', () => { expect(text.props.children).toBe('LiteBike'); }); it('Then the start button is blue', () => { expect(startButton.props.color).toBe('#add8e6'); }); it('Then the settings button exists', () => { expect(settingsButton.props.source).toBe(settingsImage); }); it('Then the settings button is disabled', () => { expect(settingsDisabled.props.disabled).toBe(true); }); describe('When the start button is clicked', () => { beforeEach(() => { act(() => { startButton.props.onPress(); }); }); it('Then navigate to the map screen', () => { expect(props.navigation.navigate).toHaveBeenCalled(); }); }); }); });
package com.hrtools.www.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.hrtools.www.controller.request.DepartmentRequest; import com.hrtools.www.controller.response.DepartmentResponse; import com.hrtools.www.etl.DepartmentETL; import com.hrtools.www.model.Company; import com.hrtools.www.model.Department; import com.hrtools.www.repository.CompanyRepository; import com.hrtools.www.repository.DepartmentRepository; import jakarta.transaction.Transactional; @Service public class DepartmentService { @Autowired private DepartmentRepository departmentRepository; @Autowired private CompanyRepository companyRepository; public DepartmentResponse createDepartment(DepartmentRequest departmentRequest) throws Exception { try { // Logic to get Company and Owner objects should be added here Company company = null; Optional<Company> companyOpitional = companyRepository.findById(departmentRequest.getCompany()); if(companyOpitional.isPresent()) { company = companyOpitional.get(); } return DepartmentETL.convertDepartmentToDepartmentResponse(departmentRepository.save(DepartmentETL .convertDepartmentRequestToDepartment(departmentRequest, new Department(), company, null)), true); } catch (Exception e) { throw new Exception("Method: createDepartment | Reason: " + e.getMessage(), e); } } @Transactional public DepartmentResponse updateDepartment(DepartmentRequest departmentRequest, Long id) throws Exception { try { Optional<Department> departmentOptional = departmentRepository.findById(id); if (departmentOptional.isPresent()) { Department department = departmentOptional.get(); // Logic to get Company and Owner objects should be added here Company company = null; Optional<Company> companyOpitional = companyRepository.findById(departmentRequest.getCompany()); if(companyOpitional.isPresent()) { company = companyOpitional.get(); } DepartmentETL.convertDepartmentRequestToDepartment(departmentRequest, department, company, null); return DepartmentETL.convertDepartmentToDepartmentResponse(department, true); } throw new Exception("Department not found"); } catch (Exception e) { throw new Exception("Method: updateDepartment | Reason: " + e.getMessage(), e); } } public List<DepartmentResponse> listDepartments() throws Exception { try { return departmentRepository.findAll().stream().map(department -> { try { return DepartmentETL.convertDepartmentToDepartmentResponse(department, true); } catch (Exception e) { e.printStackTrace(); } return null; }).toList(); } catch (Exception e) { throw new Exception("Method: listDepartments | Reason: " + e.getMessage(), e); } } public DepartmentResponse findDepartment(Long id) throws Exception { try { Optional<Department> departmentOptional = departmentRepository.findById(id); if (departmentOptional.isPresent()) { return DepartmentETL.convertDepartmentToDepartmentResponse(departmentOptional.get(), true); } throw new Exception("Department not found"); } catch (Exception e) { throw new Exception("Method: findDepartment | Reason: " + e.getMessage(), e); } } }
/* * Copyright 2012-2016 Dmitri Pisarenko * * WWW: http://altruix.cc * E-Mail: dp@altruix.co * Skype: dp118m (voice calls must be scheduled in advance) * * Physical address: * * 4-i Rostovskii pereulok 2/1/20 * 119121 Moscow * Russian Federation * * This file is part of econsim-tr01. * * econsim-tr01 is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * econsim-tr01 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with econsim-tr01. If not, see <http://www.gnu.org/licenses/>. * */ package cc.altruix.econsimtr01.ch03 import org.fest.assertions.Assertions import org.junit.Test import java.util.* /** * Created by pisarenko on 16.05.2016. */ class EnoughSeedsAtTheStartValidatorTests { @Test fun validate() { validateTestLogic( sizeOfField = "250000", seedsPerSquareMeter = "0.0629", initialSeedQuantity = "15725.0", expectedValidity = true, expectedMessage = "") validateTestLogic( sizeOfField = "250000", seedsPerSquareMeter = "0.0449", initialSeedQuantity = "11225.0", expectedValidity = true, expectedMessage = "") validateTestLogic( sizeOfField = "250000", seedsPerSquareMeter = "0.0629", initialSeedQuantity = "15724.9", expectedValidity = false, expectedMessage = "We need 15725.0 kg of seeds, but only have 15724.9" ) } private fun validateTestLogic( sizeOfField: String, seedsPerSquareMeter: String, initialSeedQuantity: String, expectedValidity: Boolean, expectedMessage: String) { // Prepare val data = Properties() data["SizeOfField"] = sizeOfField data["Process1QuantityOfSeeds"] = seedsPerSquareMeter data["InitialSeedQuantity"] = initialSeedQuantity val scenario = PropertiesFileSimParametersProviderWithPredefinedData(data) scenario.initAndValidate() val out = EnoughSeedsAtTheStartValidator() // Run method under test val res = out.validate(scenario) // Verify Assertions.assertThat(res.message).isEqualTo(expectedMessage) Assertions.assertThat(res.valid).isEqualTo(expectedValidity) } }
import { ProgrammingLanguage } from 'src/constants/programming-languages'; export abstract class RunnableCode { constructor( protected readonly identifier: string, protected readonly programmingLanguage: ProgrammingLanguage, protected readonly sourceCode: string, ) {} abstract getFileExtension(): string; abstract needCompilation(): boolean; abstract compilationCommand(): string; abstract runCommand(): string; getFileName() { return `${this.identifier}${this.getFileExtension()}`; } getProgrammingLanguage() { return this.programmingLanguage; } getSourceCode() { return this.sourceCode; } }
package com.example.cardealershipapp.web.controller; import com.example.cardealershipapp.model.Car; import com.example.cardealershipapp.model.User; import com.example.cardealershipapp.service.ApplicationService; import com.example.cardealershipapp.service.CarService; import com.example.cardealershipapp.service.UserService; import jakarta.servlet.http.HttpServletRequest; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; @Controller @RequestMapping("/application") public class ApplicationController { public final CarService carService; public final UserService userService; public final ApplicationService applicationService; public ApplicationController(CarService carService, UserService userService, ApplicationService applicationService) { this.carService = carService; this.userService = userService; this.applicationService = applicationService; } @GetMapping public String showRentalsPage(Model model) { model.addAttribute("rentals", this.applicationService.listActiveRentals()); return ""; } @PostMapping("/rent/{id}") public String rent(@PathVariable Long id, @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDateTime rentedFrom, @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDateTime rentedTo, HttpServletRequest req) { String username = req.getRemoteUser(); User user = this.userService.findUserByEmail(username); Car car = this.carService.findById(id); this.applicationService.create(user, car, rentedFrom, rentedTo); return "redirect:/home"; } }
import React from 'react'; import {Text, StyleSheet, View, TextInput} from 'react-native'; import { Feather } from '@expo/vector-icons'; const SearchBar = ({term, onTermChange, onTermSubmit}) =>{ return ( <View style = {styles.backgroundStyle}> <Feather name="search" style = {styles.iconStyle} /> <TextInput style = {styles.inputStyle} placeholder = 'Search' autoCapitalize = 'none' autoCorrect = {false} value = {term} onChangeText = {onTermChange} onEndEditing = {onTermSubmit} /> </View> ) }; const styles = StyleSheet.create({ backgroundStyle: { marginTop: 10, backgroundColor: 'lightgray', height: 50, marginHorizontal: 15, borderRadius: 10, flexDirection: 'row', marginBottom:10 }, inputStyle: { fontSize: 18, flex: 1, }, iconStyle: { fontSize: 35, alignSelf: "center", marginHorizontal: 15, } }); export default SearchBar;
package three.stone.algorithm.leetcode; /** * Suppose an array of length n sorted in ascending order is rotated between 1 and n times. * For example, the array nums = [0,1,2,4,5,6,7] might become: * * Given the sorted rotated array nums of unique elements, return the minimum element of this array. * * You must write an algorithm that runs in O(log n) time. * * Input: nums = [3,4,5,1,2] * Output: 1 * Explanation: The original array was [1,2,3,4,5] rotated 3 times. * */ public class _0153_FindMinimumInRotatedSortedArray { public int findMin(int[] nums) { int low = 0, high = nums.length - 1; while (low < high) { int mid = low + (high - low) / 2; int cur = nums[mid]; if (cur >= nums[low] && cur > nums[high]) { low = mid + 1; } else { high = mid; } } return nums[low]; } }
package urlProcessor; import org.junit.Test; import migrator.BlogType; import urlprocessor.UrlProcessor; import static org.junit.Assert.assertEquals; public class UrlProcessorTest { UrlProcessor urlProcessor = new UrlProcessor(); String naverRawUrl1 = "https://blog.naver.com/jhi990823/222848946417"; String naverRawUrl2 = "http://blog.naver.com/jhi990823/222848946417"; String naverProcessedUrl1 = "https://blog.naver.com/PostView.naver?blogId=jhi990823&logNo=222848946417"; String naverProcessedUrl2 = "http://blog.naver.com/PostView.naver?blogId=jhi990823&logNo=222848946417"; String naverInvalidUrl = "https://blog.naver.com/invalidUrl"; String unsupportedUrl = "http://hyelie.com"; @Test public void testNaverUrlType() throws Exception{ // when BlogType naverProcessedUrl1Type = urlProcessor.process(naverProcessedUrl1).getUrlType(); BlogType naverProcessedUrl2Type = urlProcessor.process(naverProcessedUrl2).getUrlType(); BlogType naverRawUrl1Type = urlProcessor.process(naverRawUrl1).getUrlType(); BlogType naverRawUrl2Type = urlProcessor.process(naverRawUrl2).getUrlType(); // then assertEquals(BlogType.NAVER, naverProcessedUrl1Type); assertEquals(BlogType.NAVER, naverProcessedUrl2Type); assertEquals(BlogType.NAVER, naverRawUrl1Type); assertEquals(BlogType.NAVER, naverRawUrl2Type); } @Test public void testNaverRawUrl() throws Exception { // when String processedNaverRawUrl1 = urlProcessor.process(naverRawUrl1).getUrl(); String processedNaverRawUrl2 = urlProcessor.process(naverRawUrl2).getUrl(); // then assertEquals(naverProcessedUrl1, processedNaverRawUrl1); assertEquals(naverProcessedUrl1, processedNaverRawUrl2); } @Test public void testNaverProcessedUrl() throws Exception { // when String processedNaverProcessedUrl1 = urlProcessor.process(naverProcessedUrl1).getUrl(); String processedNaverProcessedUrl2 = urlProcessor.process(naverProcessedUrl2).getUrl(); // then assertEquals(naverProcessedUrl1, processedNaverProcessedUrl1); assertEquals(naverProcessedUrl2, processedNaverProcessedUrl2); } @Test(expected = Exception.class) public void testInvalidUrl() throws Exception { urlProcessor.process(naverInvalidUrl); } @Test(expected = Exception.class) public void testUnsupportedUrl() throws Exception { urlProcessor.process(unsupportedUrl); } }
#!/usr/bin/env node import { createReadStream } from "fs"; import { parse } from "fast-csv"; import { resolve as pathResolve } from "path"; import { StringCSVHeaders } from "./types/csv.types"; import { parseCSVValues } from "./helpers/csv-value-parser"; import { mutateGeojsonValues } from "./helpers/geojson-to-string-convert"; import { createObjectCsvWriter } from "csv-writer"; import { errorHelperFunction } from "./helpers/error"; const clear = require('clear'); async function main() { clearConsole(); const importedData = await csvImport(); const parsedImportedData = parseCSVValues(importedData); const mutatedGeomValues = mutateGeojsonValues(parsedImportedData); writeCSV(mutatedGeomValues); } function csvImport(): Promise<StringCSVHeaders[]> { const csvValues: StringCSVHeaders[] = []; return new Promise((resolve, reject) => { createReadStream(pathResolve(__dirname, '../assets', 'parse.csv'), 'utf8') .pipe(parse({ headers: true })) .on('error', error => console.error(error)) .on('data', row => csvValues.push(row)) .on('end', (rowCount: number) => { console.log(`Parsed ${rowCount} of CSV rows`); resolve(csvValues); }); }); } async function writeCSV(csvValues: StringCSVHeaders[]) { const csvWriter = createObjectCsvWriter({ path: pathResolve(__dirname, '../assets', 'parsed.csv'), header: [ {id: "name", title: "name"}, {id: "geom", title: "geom"}, {id: "bounds", title: "bounds"}, {id: "address", title: "address"}, {id: "siteid", title: "siteid"}, ], }); await csvWriter.writeRecords(csvValues); }; function clearConsole() { clear(); } export default main;
/* Simulopolis * Copyright (C) 2018 Pierre Vigier * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <SFML/Graphics.hpp> #include "game/GameState.h" #include "city/City.h" #include "gui/Gui.h" #include "game/WindowManager.h" class ImmigrantsWindow; class CitizensWindow; class RentalMarketWindow; class LaborMarketWindow; class GoodsMarketWindow; class PoliciesWindow; class NewspaperWindow; enum class ActionState{NONE, PANNING, SELECTING}; class GameStateEditor : public GameState { public: GameStateEditor(); virtual ~GameStateEditor(); virtual void enter() override; virtual void handleMessages() override; virtual void update(float dt) override; virtual void draw() override; virtual void exit() override; void newGame(std::string cityName, uint64_t seed); void loadGame(const std::string& cityName); const sf::Texture& getCityTexture() const; private: sf::RenderTexture mRenderTexture; sf::View mGameView; sf::Sprite mBackground; City mCity; ActionState mActionState; sf::Vector2i mPanningAnchor; float mZoomLevel; sf::Vector2i mSelectionStart; sf::Vector2i mSelectionEnd; Tile::Type mCurrentTile; // Gui std::unique_ptr<Gui> mGui; std::vector<WindowManager> mWindowManagers; ImmigrantsWindow* mImmigrantsWindow; CitizensWindow* mCitizensWindow; RentalMarketWindow* mRentalMarketWindow; LaborMarketWindow* mLaborMarketWindow; GoodsMarketWindow* mGoodsMarketWindow; PoliciesWindow* mPoliciesWindow; NewspaperWindow* mNewspaperWindow; std::vector<std::unique_ptr<sf::RenderTexture>> mMenuTextures; void drawCity(sf::RenderTexture& renderTexture, const sf::View& view, bool background); void generatePreview(sf::Vector2u size, sf::Texture& texture); // Gui void createGui(); void generateMenuTextures(); void openPersonWindow(const Person& person); void openBuildingWindow(const Building& building); void openImmigrantsWindow(); void openCitizensWindow(); void openRentalMarketWindow(); void openLaborMarketWindow(); void openGoodsMarketWindow(); void openPoliciesWindow(); void openNewspaperWindow(); void updateWindows(); bool updateTabs(const std::string& name); bool updateTile(const std::string& name); // Editor void startPanning(sf::Vector2i mousePosition); void pan(sf::Vector2i mousePosition); void startSelecting(sf::Vector2f gamePosition); void stopSelecting(); void zoom(float factor); Money getCost(Tile::Type type) const; Money computeCostOfSelection() const; Id extractId(const std::string& name, const std::string& prefix) const; // Events void onNewYear(); };
Prácticas para desarrolladores ****************************** Instalación .[#toc-installation] La mejor manera de instalar Latte es utilizar un Compositor: ```shell composer require latte/latte ``` Versiones PHP soportadas (se aplica a las últimas versiones del parche Latte): | versión | compatible con PHP |-----------------|------------------- | Latte 3.0 | PHP 8.0 - 8.2 Cómo renderizar una plantilla .[#toc-how-to-render-a-template] ¿Cómo renderizar una plantilla? Utilice este sencillo código: ```php $latte = new Latte\Engine; // directorio caché $latte->setTempDirectory('/path/to/tempdir'); $params = [ /* template variables */ ]; // o $params = new TemplateParameters(/* ... */); // renderizar a la salida $latte->render('template.latte', $params); // o renderizar a variable $output = $latte->renderToString('template.latte', $params); ``` Los parámetros pueden ser matrices o incluso mejor [objeto |#Parameters as a class], que proporcionará la comprobación de tipo y sugerencia en el editor. .[note] También puedes encontrar ejemplos de uso en el repositorio [Latte examples |https://github.com/nette-examples/latte]. Rendimiento y caché .[#toc-performance-and-caching] Las plantillas Latte son extremadamente rápidas, porque Latte las compila directamente en código PHP y las almacena en caché en disco. Por lo tanto, no tienen sobrecarga adicional en comparación con las plantillas escritas en PHP puro. La caché se regenera automáticamente cada vez que se modifica el fichero fuente. Así que puede editar cómodamente sus plantillas Latte durante el desarrollo y ver los cambios inmediatamente en el navegador. Puede desactivar esta característica en un entorno de producción y ahorrar un poco de rendimiento: ```php $latte->setAutoRefresh(false); ``` Cuando se despliega en un servidor de producción, la generación inicial de caché, especialmente para aplicaciones grandes, puede tardar un poco. Latte tiene incorporada una prevención contra la "estampida de caché":https://en.wikipedia.org/wiki/Cache_stampede. Esta es una situación en la que el servidor recibe un gran número de peticiones concurrentes y debido a que la caché de Latte aún no existe, todas ellas la generarían al mismo tiempo. Lo que dispara la CPU. Latte es inteligente, y cuando hay múltiples peticiones concurrentes, sólo el primer hilo genera la caché, los demás esperan y luego la usan. Parámetros como clase .[#toc-parameters-as-a-class] Mejor que pasar variables a la plantilla como arrays es crear una clase. Obtienes [notación de tipo seguro |type-system], [buena sugerencia en IDE |recipes#Editors and IDE] y una forma de [registrar filtros |extending-latte#Filters Using the Class] y [funciones |extending-latte#Functions Using the Class]. ```php class MailTemplateParameters { public function __construct( public string $lang, public Address $address, public string $subject, public array $items, public ?float $price = null, ) {} } $latte->render('mail.latte', new MailTemplateParameters( lang: $this->lang, subject: $title, price: $this->getPrice(), items: [], address: $userAddress, )); ``` Deshabilitando Auto-Escaping de Variable .[#toc-disabling-auto-escaping-of-variable] Si la variable contiene una cadena HTML, puede marcarla para que Latte no la escape automáticamente (y por tanto doblemente). Esto evita la necesidad de especificar `|noescape` en la plantilla. La forma más sencilla es envolver la cadena en un objeto `Latte\Runtime\Html`: ```php $params = [ 'articleBody' => new Latte\Runtime\Html($article->htmlBody), ]; ``` Latte tampoco escapa todos los objetos que implementan la interfaz `Latte\HtmlStringable`. Así que puedes crear tu propia clase cuyo método `__toString()` devuelva código HTML que no será escapado automáticamente: ```php class Emphasis extends Latte\HtmlStringable { public function __construct( private string $str, ) { } public function __toString(): string { return '<em>' . htmlspecialchars($this->str) . '</em>'; } } $params = [ 'foo' => new Emphasis('hello'), ]; ``` .[warning] El método `__toString` debe devolver HTML correcto y proporcionar escapado de parámetros, ¡de lo contrario puede producirse una vulnerabilidad XSS! Cómo extender Latte con filtros, etiquetas, etc. .[#toc-how-to-extend-latte-with-filters-tags-etc] ¿Cómo añadir un filtro personalizado, función, etiqueta, etc. a Latte? Descúbrelo en el capítulo [Extendiendo |extending Latte] Latte. Si quieres reutilizar tus cambios en diferentes proyectos o si quieres compartirlos con otros, entonces debes [crear una extensión |creating-extension]. Cualquier código en la plantilla `{php ...}` .{toc: RawPhpExtension} Dentro de la etiqueta [`{do}` |tags#do] por lo que no puede, por ejemplo, insertar construcciones como `if ... else` o sentencias terminadas en punto y coma. Sin embargo, puede registrar la extensión `RawPhpExtension`, que añade la etiqueta `{php ...}`. Puede utilizarla para insertar cualquier código PHP. No está sujeta a ninguna regla del modo sandbox, por lo que su uso es responsabilidad del autor de la plantilla. ```php $latte->addExtension(new Latte\Essential\RawPhpExtension); ``` Comprobación del código generado .[#toc-checking-generated-code]{data-version:3.0.7} Latte compila plantillas en código PHP. Por supuesto, se asegura de que el código generado es sintácticamente válido. Sin embargo, cuando se usan extensiones de terceros o RawPhpExtension, Latte no puede garantizar la corrección del fichero generado. Además, en PHP, puede escribir código que sea sintácticamente correcto pero que esté prohibido (por ejemplo, asignar un valor a la variable $this) y cause un Error de Compilación PHP. Si escribe una operación de este tipo en una plantilla, también se incluirá en el código PHP generado. Dado que existen más de doscientas operaciones prohibidas diferentes en PHP, Latte no pretende detectarlas. El propio PHP las marcará al renderizar, lo que normalmente no es un problema. Sin embargo, hay situaciones en las que se desea saber durante la compilación de la plantilla que no contiene errores de compilación de PHP. Especialmente cuando las plantillas pueden ser editadas por usuarios, o usted usa [Sandbox |Sandbox]. En tal caso, haga que las plantillas se comprueben durante la compilación. Puede activar esta funcionalidad usando el método Engine::enablePhpLint(). Ya que necesita llamar al binario PHP para la comprobación, pase su ruta como parámetro: ```php $latte = new Latte\Engine; $latte->enablePhpLinter('/path/to/php'); try { $latte->compile('home.latte'); } catch (Latte\CompileException $e) { // atrapa errores Latte y también Compile Error en PHP echo 'Error: ' . $e->getMessage(); } ``` Modo estricto .[#toc-strict-mode]{data-version:3.0.8} En el modo de análisis sintáctico estricto, Latte comprueba si faltan etiquetas HTML de cierre y también desactiva el uso de la variable `$this`. Para activarlo ```php $latte = new Latte\Engine; $latte->setStrictParsing(); ``` Para generar plantillas con la cabecera `declare(strict_types=1)`, haga lo siguiente: ```php $latte = new Latte\Engine; $latte->setStrictTypes(); ``` Traducción en plantillas .{toc: TranslatorExtension} Utilice la extensión `TranslatorExtension` para añadir [`{_...}` |tags#_], [`{translate}` |tags#translate] y filtrar [`translate` |filters#translate] a la plantilla. Se utilizan para traducir valores o partes de la plantilla a otros idiomas. El parámetro es el método (PHP callable) que realiza la traducción: ```php class MyTranslator { public function __construct(private string $lang) {} public function translate(string $original): string { // crear $traducido a partir de $original según $this->lang return $translated; } } $translator = new MyTranslator($lang); $extension = new Latte\Essential\TranslatorExtension( $translator->translate(...), // [$translator, 'translate'] en PHP 8.0 ); $latte->addExtension($extension); ``` El traductor es llamado en tiempo de ejecución cuando la plantilla es renderizada. Sin embargo, Latte puede traducir todos los textos estáticos durante la compilación de la plantilla. Esto ahorra rendimiento porque cada cadena se traduce sólo una vez y la traducción resultante se escribe en el archivo compilado. Esto crea múltiples versiones compiladas de la plantilla en el directorio caché, una para cada idioma. Para ello, sólo tiene que especificar el idioma como segundo parámetro: ```php $extension = new Latte\Essential\TranslatorExtension( $translator->translate(...), $lang, ); ``` Por texto estático entendemos, por ejemplo, `{_'hello'}` o `{translate}hello{/translate}`. El texto no estático, como `{_$foo}`, seguirá traduciéndose en tiempo de ejecución. La plantilla también puede pasar parámetros adicionales al traductor a través de `{_$original, foo: bar}` o `{translate foo: bar}`, que recibe como matriz `$params`: ```php public function translate(string $original, ...$params): string { // $params['foo'] === 'bar' } ``` Depuración y Tracy .[#toc-debugging-and-tracy] Latte intenta que el desarrollo sea lo más agradable posible. A efectos de depuración, existen tres etiquetas [`{dump}` |tags#dump], [`{debugbreak}` |tags#debugbreak] y [`{trace}` |tags#trace]. Obtendrás la mayor comodidad si instalas la gran [herramienta de depuración Tracy |tracy:] y activas el plugin Latte: ```php // activa Tracy Tracy\Debugger::enable(); $latte = new Latte\Engine; // activa la extensión de Tracy $latte->addExtension(new Latte\Bridges\Tracy\TracyExtension); ``` Ahora verás todos los errores en una pulcra pantalla roja, incluidos los errores en plantillas con resaltado de filas y columnas ([vídeo |https://github.com/nette/tracy/releases/tag/v2.9.0]). Al mismo tiempo, en la esquina inferior derecha, en la llamada Tracy Bar, aparece una pestaña para Latte, donde puedes ver claramente todas las plantillas renderizadas y sus relaciones (incluyendo la posibilidad de hacer clic en la plantilla o en el código compilado), así como las variables: [* latte-debugging.webp *] Dado que Latte compila las plantillas en código PHP legible, puede recorrerlas cómodamente en su IDE. Linter: Validando la Sintaxis de la Plantilla .{toc: Linter} La herramienta Linter le ayudará a revisar todas las plantillas y comprobar si hay errores de sintaxis. Se ejecuta desde la consola: ```shell vendor/bin/latte-lint <path> ``` Utilice el parámetro `--strict` para activar el modo [estricto|#strict mode]. Si utiliza etiquetas personalizadas, cree también su Linter personalizado, por ejemplo `custom-latte-lint`: ```php #!/usr/bin/env php <?php // introduzca la ruta real al archivo autoload.php require __DIR__ . '/vendor/autoload.php'; $path = $argv[1] ?? '.'; $linter = new Latte\Tools\Linter; $latte = $linter->getEngine(); // añada aquí sus extensiones individuales $latte->addExtension(/* ... */); $ok = $linter->scanDirectory($path); exit($ok ? 0 : 1); ``` Alternativamente, puede pasar su propio objeto `Latte\Engine` al Linter: ```php $latte = new Latte\Engine; // aquí configuramos el objeto $latte $linter = new Latte\Tools\Linter(engine: $latte); ``` Carga de plantillas desde una cadena .[#toc-loading-templates-from-a-string] ¿Necesita cargar plantillas a partir de cadenas en lugar de archivos, quizás con fines de prueba? [StringLoader |extending-latte#stringloader] le ayudará: ```php $latte->setLoader(new Latte\Loaders\StringLoader([ 'main.file' => '{include other.file}', 'other.file' => '{if true} {$var} {/if}', ])); $latte->render('main.file', $params); ``` Manejador de Excepciones .[#toc-exception-handler] Puede definir su propio manejador para las excepciones esperadas. Las excepciones que se produzcan dentro de [`{try}` |tags#try] y en el [sandbox |sandbox] se le pasan. ```php $loggingHandler = function (Throwable $e, Latte\Runtime\Template $template) use ($logger) { $logger->log($e); }; $latte = new Latte\Engine; $latte->setExceptionHandler($loggingHandler); ``` Búsqueda automática de diseños .[#toc-automatic-layout-lookup] Mediante la etiqueta [`{layout}` |template-inheritance#layout-inheritance] la plantilla determina su plantilla padre. También es posible que el diseño se busque automáticamente, lo que simplificará la escritura de plantillas, ya que no tendrán que incluir la etiqueta `{layout}`. Esto se consigue de la siguiente manera: ```php $finder = function (Latte\Runtime\Template $template) { if (!$template->getReferenceType()) { // devuelve la ruta al archivo de plantilla padre return 'automatic.layout.latte'; } }; $latte = new Latte\Engine; $latte->addProvider('coreParentFinder', $finder); ``` Si la plantilla no debe tener diseño, lo indicará con la etiqueta `{layout none}`.
import { getOnCaretMoveEvents } from "@/src/app/components/recipe/steps/step/description/ContentEditable/getCaretMoveEvents"; import { getCaretPosition } from "@/src/app/components/recipe/steps/step/description/ContentEditable/getCaretPosition"; import userEvent from "@testing-library/user-event"; import { test, expect, vi, Mock } from "vitest"; test("Should exists", () => { expect(getOnCaretMoveEvents).toBeDefined(); }); const user = userEvent.setup(); const getElement = (onCaretMove: Mock) => { const element = document.createElement("div"); element.setAttribute("contenteditable", "true"); document.body.appendChild(element); const { onclick, oninput, onkeydown } = getOnCaretMoveEvents(onCaretMove); element.onclick = onclick; element.oninput = oninput; element.onkeydown = onkeydown; return element; }; test("Should return an event that fires when user click", async () => { const onCaretMove = vi.fn(); const element = getElement(onCaretMove); await user.click(element); expect(onCaretMove.mock.calls).toHaveLength(1); }); test("Should return an event that fires when user changes input", async () => { const onCaretMove = vi.fn(); const element = getElement(onCaretMove); await user.click(element); await user.keyboard("test"); expect(onCaretMove.mock.calls).toHaveLength(5); }); test("Should return an event that fires after the caret has moved", async () => { const onCaretMove = vi.fn(() => getCaretPosition(element)); const element = getElement(onCaretMove); await user.click(element); await user.keyboard("1234"); await user.keyboard("{ArrowLeft}"); expect( onCaretMove.mock.results[onCaretMove.mock.results.length - 1]?.value, ).toBe(3); });
<!DOCTYPE html> <html> <head> <title>iTWATCHER API</title> <!-- Add your CSS and JS files here --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'styles.css' %}"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <a class="navbar-brand" href="http://127.0.0.1:8000/my-url/">iTWatcher</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="navbar-nav ml-auto"> <li class="nav-item"> <a class="nav-link" href="{% url 'downloadrequest-list-create' %}">Download Video From NVR</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'upload-video' %}">Upload Video</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'train' %}">Train</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'lpr-view' %}">LPR</a> </li> <li class="nav-item"> <span class="navbar-text mr-2">Welcome, {{ user.username }}</span> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Logout</a> </li> <!-- Add more links for other views here --> </ul> </div> </nav> <div class="container mt-4"> <!-- Track and Count Section --> <h2>Track and Count</h2> <form method="post" enctype="multipart/form-data" id="track-count-form"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <label for="selection">Choose Input Type:</label> <select name="selection" id="selection" class="form-control"> <option value="video-path">Video File</option> <option value="camera-feed">Camera Feed URL</option> </select> </div> </div> <div class="row mt-3" id="video-path-input"> <div class="col-md-6"> <label for="video_path">Video file:</label> <select name="video_path" id="video_path" class="form-control"> {% for video in videos %} <option value="{{ video.id }}">{{ video.file.path }}</option> {% endfor %} </select> </div> </div> <div class="row mt-3" id="camera-feed-input" style="display: none;"> <div class="col-md-6"> <label for="livestream_url">Live stream URL:</label> <input type="text" name="livestream_url" id="livestream_url" class="form-control"> </div> </div> <div class="row mt-3"> <div class="col-md-6"> <label for="vehicle_type_lpr">Model Type:</label> <select name="vehicle_type" id="vehicle_type_tc" class="form-control"> <option value="tricycle">Tricycle</option> <option value="all_vehicle">Catch All</option> <option value="combi">iTWatcher</option> </select> </div> </div> <div class="row mt-3"> <div class="col-md-6"> <input type="submit" value="Process" class="btn btn-primary"> </div> </div> </form> <div class="row mt-3"> <div class="col-md-6"> <a href="{% url 'vehicle_log_list' %}" class="btn btn-primary">View Track and Count List</a> </div> </div> </div> <script> $(document).ready(function() { $('#selection').on('change', function() { var selectedOption = $(this).val(); if (selectedOption === 'video-path') { $('#video-path-input').show(); $('#camera-feed-input').hide(); } else if (selectedOption === 'camera-feed') { $('#video-path-input').hide(); $('#camera-feed-input').show(); } }); // Your existing AJAX code here $('#track-count-form').on('submit', function(event) { event.preventDefault(); var formData = new FormData(this); var selectedOption = $('#selection').val(); var selectedAction = $('#vehicle_type_tc').val(); // Remove irrelevant field based on the selected option if (selectedOption === 'video-path') { formData.delete('livestream_url'); // Remove livestream_url if video-path is selected } else if (selectedOption === 'camera-feed') { formData.delete('video_path'); // Remove video_path if camera-feed is selected } // Dynamically set the form action based on the selected option if (selectedAction === 'tricycle') { $(this).attr('action', 'http://127.0.0.1:8000/tracking/tric/'); } else if (selectedAction === 'all_vehicle') { $(this).attr('action', 'http://127.0.0.1:8000/tracking/catchall/'); } else if (selectedAction === 'combi') { $(this).attr('action', 'http://127.0.0.1:8000/tracking/combi/'); } $.ajax({ url: $(this).attr('action'), method: 'POST', data: formData, processData: false, contentType: false, success: function(response) { // Handle success response }, error: function(xhr, status, error) { console.log('Error:', xhr.responseText); console.log('Selected Option:', selectedOption); console.log('FormData:', formData); // Handle error response } }); }); }); </script> </body> </html>
import 'package:e_racing_app/core/ext/access_extension.dart'; import 'package:e_racing_app/core/model/classes_model.dart'; import 'package:e_racing_app/core/model/team_model.dart'; import 'package:e_racing_app/core/tools/session.dart'; import 'package:e_racing_app/core/ui/component/state/loading_shimmer.dart'; import 'package:e_racing_app/core/ui/component/ui/card_widget.dart'; import 'package:e_racing_app/core/ui/component/ui/text_widget.dart'; import 'package:e_racing_app/login/legacy/domain/model/user_model.dart'; import 'package:flutter/material.dart'; import 'button_widget.dart'; import 'icon_widget.dart'; import 'spacing_widget.dart'; class TeamsWidget extends StatefulWidget { final bool isHost; final List<TeamModel?>? teams; final List<UserModel?>? users; final List<ClassesModel?>? classes; final int? maxCrew; final Function(String?) onLeave; final Function(String?) onJoin; final Function(String?) onDelete; const TeamsWidget( {required this.isHost, required this.teams, required this.users, required this.classes, required this.maxCrew, required this.onLeave, required this.onJoin, required this.onDelete, Key? key}) : super(key: key); Widget loading(BuildContext context) { return const Card(child: LoadingShimmer()); } @override _TeamsWidgetState createState() => _TeamsWidgetState(); } class _TeamsWidgetState extends State<TeamsWidget> { @override void initState() { super.initState(); } @override Widget build(BuildContext context) { if (widget.teams == null) { return Container(); } else { return Padding( padding: const EdgeInsets.only(left: 8.0, right: 8.0), child: Column( children: [ Wrap( crossAxisAlignment: WrapCrossAlignment.start, alignment: WrapAlignment.start, direction: Axis.horizontal, spacing: 5.0, children: widget.teams! .map((team) { return CardWidget( ready: true, arrowed: true, onPressed: () { details(team); }, child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Padding( padding: const EdgeInsets.only(left: 16, right: 16), child: Row( children: [ const Padding( padding: EdgeInsets.all(8), child: IconWidget( icon: Icons.sports_motorsports), ), TextWidget( text: "(${team?.crew?.length.toString()}/${widget.maxCrew.toString()})", style: Style.paragraph), ], ), ), TextWidget( text: "${team?.name}", style: Style.paragraph), ], ), ); }) .toList() .cast<Widget>(), ), const SpacingWidget(LayoutSize.size16), ], ), ); } } details(TeamModel? team) { var alreadyInTeam = team?.crew ?.where((element) => element == Session.instance.getUser()?.id) .isNotEmpty ?? false; showModalBottomSheet( isScrollControlled: true, context: context, builder: (context) => Padding( padding: const EdgeInsets.all(48.0), child: SizedBox( child: Wrap( children: [ Column( children: [ const SpacingWidget(LayoutSize.size24), Row( children: [ TextWidget(text: team?.name, style: Style.title), ], ), const SpacingWidget(LayoutSize.size24), Wrap( crossAxisAlignment: WrapCrossAlignment.start, alignment: WrapAlignment.start, direction: Axis.horizontal, spacing: 5.0, children: team!.crew! .map((crew) { return Padding( padding: const EdgeInsets.all(16.0), child: Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.start, children: [ const IconWidget( icon: Icons.sports_motorsports, ), const SpacingWidget(LayoutSize.size16), TextWidget( text: getName(crew), style: Style.paragraph), ], ), ); }) .toList() .cast<Widget>(), ), const SpacingWidget(LayoutSize.size48), Row( crossAxisAlignment: CrossAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center, children: [ alreadyInTeam ? ButtonWidget( label: "Leave", type: ButtonType.icon, icon: Icons.exit_to_app, onPressed: () { widget.onLeave(team.id); }, enabled: true, ) : Container(), !alreadyInTeam && isSubscriber(widget.classes) ? ButtonWidget( label: "Join", type: ButtonType.icon, icon: Icons.person_add, onPressed: () { widget.onJoin(team.id); }, enabled: true, ) : Container(), const SpacingWidget(LayoutSize.size16), widget.isHost || alreadyInTeam ? ButtonWidget( label: "Delete", type: ButtonType.icon, icon: Icons.delete, onPressed: () { widget.onDelete(team.id); }, enabled: true, ) : Container(), ], ), ], ) ], ), ), ), ); } String getName(String? id) { var user = widget.users?.firstWhere((element) => element?.id == id)?.profile; return "${user?.firstName} ${user?.surName}"; } }
import { computed, defineComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'; import type { PropType, Ref, ComputedRef } from 'vue'; import { Table as ATable, type TablePaginationConfig } from 'ant-design-vue'; import { usePaginationConfig } from './hooks/tableHooks'; import { deepClone, inDevMode } from '../utils'; import { v4 as uuidv4 } from 'uuid'; import tableStyle from './style/index.module.less'; if (inDevMode()) { console.log('AlphaTable Version v0.1.0'); } interface ScrollConfig { x: number | string | true | undefined; y: number | string | undefined; scrollToFirstRowOnChange: boolean | undefined; } export interface TableConfig { rowKey: string; whereis?: string | string[]; fetchTableData: ((queryParams: Object | undefined, additionalParam?: any) => Promise<any>) | undefined | null; paginationSize?: 'small'; pageSizeOptions?: string[]; additionalParam?: any; queryParams?: { [key: string]: any }; scrollConfig?: ScrollConfig; rowSelection?: { preserveSelectedRowKeys?: boolean; selectedRowKeys: any[]; onChange?: (selectedRowKeys: any, selectedRows: any) => any; getCheckboxProps?: (record: any) => { disabled: boolean; name: string }; onSelect?: (record: any, selected?: boolean, selectedRows?, nativeEvent?) => any; onSelectAll?: (selected: boolean, selectedRows?, changeRows?) => any; }; before?: (dataSource: any[]) => any[]; //前置钩子,必须要有返回值, 返回值可以影响列表数据 after?: (dataSource) => void; //后置钩子, 在完成数据获取之后会将数据当作参数传给后置钩子 } interface TableMatirials { dataSource: Ref<any[]>; pagination: Ref<TablePaginationConfig>; columns: ComputedRef<any>; scrollConfig: Ref<ScrollConfig | undefined>; tableLoading: Ref<Boolean>; } export default defineComponent({ name: 'AlphaTable', props: { columns: { type: Array, required: true, }, tableConfig: { type: Object as PropType<TableConfig>, required: true, }, }, emits: ['afterDataFetched'], setup(props, { attrs, slots, emit, expose }) { const uuid = uuidv4(); const tableMatirials = { dataSource: ref<any[]>([]), pagination: usePaginationConfig(props.tableConfig.paginationSize, props.tableConfig.pageSizeOptions), columns: computed<any[]>(() => { return props.columns; }), scrollConfig: ref<ScrollConfig | undefined>(deepClone(props.tableConfig.scrollConfig)), tableLoading: ref(false), rowSelection: computed(() => { if (!props.tableConfig.rowSelection) { return undefined; } const result = deepClone(props.tableConfig.rowSelection); if (result.preserveSelectedRowKeys === undefined) { result.preserveSelectedRowKeys = true; } result.selectedRowKeys = ref(result.selectedRowKeys); result.customOnChange = result.onChange; result.onChange = function (selectedRowKeys, selectedRows) { result.selectedRowKeys.value = selectedRowKeys; if (result.customOnChange && typeof result.customOnChange === 'function') { result.customOnChange(selectedRowKeys, selectedRows); } }; return result; }), }; const table = ref(); let adapting = false; function adaptParentHeight(dataLength, scrollConfig, tScrollConfig) { function getElementOuterHeight(el: HTMLElement) { if (!el) { return 0; } let result = 0; const computedStyle = window.getComputedStyle(el); const marginTop = Number(computedStyle.marginTop.match(/[0-9]+/g)?.[0] || 0); const marginBottom = Number(computedStyle.marginBottom.match(/[0-9]+/g)?.[0] || 0); result = el.clientHeight + marginTop + marginBottom; return result; } if (adapting) { console.log('adapting, adapt aborted'); return; } adapting = true; const antTableCellHeight = document.querySelectorAll(`[id='${uuid}'] [data-row-key] .ant-table-cell`)?.[0]?.clientHeight || 57; const totalHeight = dataLength * antTableCellHeight; //表格每一行的高度是antTableCellHeight if (table.value && totalHeight) { const parentNode = table.value.parentNode; const parentComputedStyle = window.getComputedStyle(parentNode); const parentPaddingTop = Number(parentComputedStyle.paddingTop.match(/[0-9]+/g)?.[0] || 0); const parentPaddingBottom = Number(parentComputedStyle.paddingBottom.match(/[0-9]+/g)?.[0] || 0); const parentClientHeight = parentNode.clientHeight - parentPaddingBottom - parentPaddingTop; const children: HTMLElement[] = Array.from(parentNode.children); const childrenHeight = children.reduce((accumulator, v) => { if (v !== table.value) { return (accumulator + getElementOuterHeight(v as HTMLElement)) as number; } return accumulator; }, 0); const targetHeight = Number(parentClientHeight) - childrenHeight - 114.14; if (targetHeight < totalHeight) { scrollConfig.value.y = targetHeight; } else { scrollConfig.value.y = undefined; } } else { if (scrollConfig.value) { scrollConfig.value.y = tScrollConfig.y; if (scrollConfig.value.y && totalHeight <= scrollConfig.value.y) { scrollConfig.value.y = undefined; //防止最右边出现垂直空隙 } } } adapting = false; } function getTableData( current: number | undefined, pageSize: number | undefined, tableConfig: TableConfig, tableMatirials: TableMatirials ): Promise<any> { if (!tableConfig.fetchTableData) { return Promise.reject('未传递获取表格数据API调用函数'); } const { fetchTableData, queryParams, additionalParam, before, after } = tableConfig; const { tableLoading, dataSource, pagination, scrollConfig } = tableMatirials; tableLoading.value = true; return fetchTableData({ ...queryParams, current, pageSize }, additionalParam) .then((response) => { const whereis = props.tableConfig.whereis || 'rows'; pagination.value.current = current; pagination.value.pageSize = pageSize; // pagination.value.total = response.total; let tableData; if (whereis) { if (typeof whereis === 'object' && whereis instanceof Array) { tableData = whereis.reduce((lastLayer, curKey) => { if (lastLayer) { return lastLayer[curKey]; } return undefined; }, response); } else if (typeof whereis === 'string') { tableData = response[whereis]; } } else { tableData = response['rows']; } if (!tableData) { console.error(`AlphaTable: 无法从指定位置(${whereis || 'rows'})找到列表数据`); return; } if (before) { tableData = before(tableData); } pagination.value.total = (function getTotal(src: any[]) { let result: any = src.length; src.forEach((v) => { if (v.children?.length) { result += getTotal(v.children); } }); return result; })(tableData); dataSource.value.splice(0); tableData.forEach((v) => { dataSource.value.push(v); }); if (after) { after(deepClone(tableData)); } const length = dataSource.value.length; //throw adapt method into next tick nextTick(() => { adaptParentHeight(length, scrollConfig, tableConfig.scrollConfig); }); return dataSource.value; }) .catch(() => { return Promise.reject(undefined); }) .finally(() => { tableLoading.value = false; }); } function reloadTableData() { getTableData(tableMatirials.pagination.value.current, tableMatirials.pagination.value.pageSize, props.tableConfig, tableMatirials).then( (tableData) => { emit('afterDataFetched', deepClone(tableData)); } ); } function handlePaginationChange(pagination) { getTableData(pagination.current, pagination.pageSize, props.tableConfig, tableMatirials).then((tableData) => { emit('afterDataFetched', deepClone(tableData)); }); } function getDataSource() { return deepClone(tableMatirials.dataSource.value); } function getSelectedRowKeys() { return deepClone(tableMatirials.rowSelection.value?.selectedRowKeys.value); } function clearSelectedRowKeys() { if (tableMatirials.rowSelection.value) { tableMatirials.rowSelection.value.selectedRowKeys.value.splice(0); } } reloadTableData(); expose({ reloadTableData, getDataSource, getSelectedRowKeys, clearSelectedRowKeys, }); watch(props.tableConfig.queryParams!, () => { getTableData(1, tableMatirials.pagination.value.pageSize, props.tableConfig, tableMatirials).then((tableData) => { emit('afterDataFetched', deepClone(tableData)); }); }); /** * window resize event listener */ function adaptWrapper() { adaptParentHeight(tableMatirials.dataSource.value.length, tableMatirials.scrollConfig, props.tableConfig.scrollConfig); } onMounted(() => { window.addEventListener('resize', adaptWrapper); }); onBeforeUnmount(() => { window.removeEventListener('resize', adaptWrapper); }); function realStr(text) { return typeof text === 'string' && text && text.length; } function handleEmptyStr(text) { if (realStr(text)) { return text; } return '-'; } return () => ( <div ref={table} id={uuid} class={tableStyle.transition}> <ATable rowKey={props.tableConfig.rowKey} columns={tableMatirials.columns.value} dataSource={tableMatirials.dataSource.value} loading={tableMatirials.tableLoading.value} pagination={tableMatirials.pagination.value} scroll={tableMatirials.scrollConfig.value} onChange={handlePaginationChange} rowSelection={tableMatirials.rowSelection.value}> {{ bodyCell: ({ text, record, index, column }) => { let result: any = text; if (slots?.default) { result = slots.default({ text, column, record, reloadTableData }); if (typeof result[0].children !== 'object') { result = handleEmptyStr(text); } } return result; }, }} </ATable> </div> ); }, });
<template> <div> <div class="d-flex justify-content-center table-wrap "> <!-- <div class="per-page bg-dark rounded-top d-flex align-items-center px-3 justify-content-end"> <div class="wrap-select d-flex"> <p class="text-select">Per page</p> <select v-model="todosPerPage" class="form-select form-select-sm my-1 select-custom bg-dark text-white" style="width: auto;border: none;padding: 0 25px 0 10px;margin-top: 0px !important;"> <option value="20">20</option> <option value="50">50</option> <option value="100">100</option> <option value="all">All</option> </select> </div> </div> --> <div class="d-flex justify-content-end" style="margin:10px 0 -15px 0"> <a class="btn btn-primary " href="/create">create</a> </div> <table class="table table-striped text-white custom-table" style="max-width: 94%;"> <thead> <tr> <th scope="col">No</th> <th scope="col">Judul</th> <th scope="col"></th> </tr> </thead> <tbody> <tr v-for="(todo, index) in paginatedTodos" :key="todo.id"> <th scope="row">{{ ((currentPage - 1) * perPage) + index + 1 }}</th> <td>{{ todo.title }}</td> <td> <button class="btn btn-primary btn-sm mx-2" @click="editTodo(todo)"><i class="bi bi-pencil-square"></i></button> <button class="btn btn-danger btn-sm" @click="confirmDelete(todo.id)"><i class="bi bi-trash-fill"></i></button> </td> </tr> </tbody> </table> <b-pagination v-model="currentPage" :total-rows="todos.length" :per-page="perPage" first-text="⏮" prev-text="⏪" next-text="⏩" last-text="⏭" class="mt-3" ></b-pagination> </div> </div> </template> <style> .table-wrap{ flex-direction: column; flex-wrap: wrap; align-content: center; border-bottom-left-radius: 10px !important; border-bottom-right-radius: 10px !important; } .per-page{ display: flex; border-top-left-radius: 10px !important; border-top-right-radius: 10px !important; } .text-select{ margin-top: 14px; color: gray; } .active>.page-link, .page-link.active{ color: white !important; } </style> <script> import { mapState, mapActions } from "vuex"; import { BPagination } from 'bootstrap-vue-3'; export default { components: { BPagination }, data() { return { currentPage: 1, perPage: 10, } }, computed: { ...mapState(["todos"]), paginatedTodos() { if (this.todosPerPage === 'all') { return this.todos; } else { const start = (this.currentPage - 1) * parseInt(this.perPage); const end = start + parseInt(this.perPage); return this.todos.slice(start, end); } }, totalPages() { if (this.todosPerPage === 'all') { return 1; } else { return Math.ceil(this.todos.length / parseInt(this.todosPerPage)); } }, }, watch: { todosPerPage() { this.currentPage = 1; }, }, methods: { ...mapActions(["fetchTodos", "deleteTodo"]), confirmDelete(todoId) { if (window.confirm("Anda yakin ingin menghapus todo ini?")) { this.deleteTodoItem(todoId); } }, editTodo(todo) { const todoId = todo.id; this.$router.push({ name: 'update', params: { id: todoId } }); }, deleteTodoItem(todoId) { this.deleteTodo(todoId) .then(() => { this.fetchTodos(); }) .catch((error) => { console.error("Gagal menghapus todo:", error); }); }, setPage(pageNumber) { this.currentPage = pageNumber; }, }, created() { this.fetchTodos(); }, }; </script>
import db from "../db/conn.mjs"; import { ObjectId } from "mongodb"; const getUsers = async (req, res) => { try { const users = await db.users .find() .project({ password: 0 }) .sort({ username: 1 }) .toArray(); // Fetch only username and _id fields console.log(users); res.status(200).json(users); } catch (error) { console.error(error); res.status(500).json({ message: "Error retrieving users" }); } }; const getFriendsList = async (req, res) => { const { userId } = req.body; try { const result = await db.users.findOne( { _id: new ObjectId(userId), }, { friends: 1, _id: 0 } // Returns only the friends array ); if (!result || !result.friends) { return res.status(200).json([]); } const friendsIds = result.friends.map((stringId) => new ObjectId(stringId)); const friends = await db.users .find( { _id: { $in: friendsIds } }, { projection: { password: 0 } } // specify projection in an options object ) .sort({ username: 1 }) .toArray(); return res.status(200).json(friends); } catch (error) { console.log(error); res.status(500).send({ message: error }); } }; const checkFriend = async (req, res) => { const { friendId } = req.params; const { userId } = req.body; db.users .findOne({ $and: [{ _id: new ObjectId(userId) }, { friends: friendId }], }) .then((result) => { if (result) { console.log("true"); res.status(200).json(true); } else { console.log("false"); res.status(200).json(false); } }) .catch((error) => { console.log(error); res.status(500).send({ message: error }); }); }; const addFriend = async (req, res) => { const { userId, friendId } = req.body; db.users .updateOne( { _id: new ObjectId(userId), }, { $push: { friends: friendId } } ) .then((result) => { console.log("Friend added successfully!"); res.status(200).send({ message: `Friend added successfully!` }); }) .catch((error) => { console.log(error); res.status(500).send({ message: error }); }); }; export { getUsers, getFriendsList, checkFriend, addFriend };
package com.gs.cache.config; import com.gs.cache.CacheProxy; import com.gs.cache.impl.LocalCacheProxyImpl; import com.gs.cache.impl.RedisCacheProxyImpl; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedisPool; import java.util.Arrays; import java.util.stream.Collectors; /** * Created by linjuntan on 2017/10/29. * email: ljt1343@gmail.com */ @Configuration @Slf4j public class CacheConfiguration { @Value("${redis.maxActive:16}") private int maxActive; @Value("${redis.maxIdle:16}") private int maxIdle; @Value("${redis.minIdle:8}") private int minIdle; @Value("${redis.maxWait:1000}") private int maxWait; @Value("${redis.lifo:false}") private boolean lifo; @Value("${redis.testOnBorrow:false}") private boolean testOnBorrow; @Value("${redis.shared.url:redis://@127.0.0.1:6579/0}") private String jedisSharedInfo; @Bean("jedisPoolConfig") public JedisPoolConfig jedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxTotal(maxActive); jedisPoolConfig.setMinIdle(minIdle); jedisPoolConfig.setMaxWaitMillis(maxWait); jedisPoolConfig.setLifo(lifo); jedisPoolConfig.setTestOnBorrow(testOnBorrow); return jedisPoolConfig; } @Bean("shardedJedisPool") @DependsOn("jedisPoolConfig") public ShardedJedisPool shardedJedisPool(@Autowired JedisPoolConfig jedisPoolConfig) { try { ShardedJedisPool jedisPool = new ShardedJedisPool(jedisPoolConfig, Arrays.stream(jedisSharedInfo.split(",")).map(JedisShardInfo::new).collect(Collectors.toList())); return jedisPool; } catch (Exception e) { log.error(" >>> init redis pool error", e); log.error(" >>> will be use local cache"); } return null; } @Bean @DependsOn("shardedJedisPool") public CacheProxy cacheProxy(@Autowired(required = false) ShardedJedisPool shardedJedisPool) { if (shardedJedisPool == null) { log.info(" >>> create local cache"); return new LocalCacheProxyImpl(); } log.info(" >>> create redis cache"); RedisCacheProxyImpl cacheProxy = new RedisCacheProxyImpl(); cacheProxy.setShardedJedisPool(shardedJedisPool); return cacheProxy; } }
--- title: Personnaliser l'étiquette des données du graphique linktitle: Personnaliser l'étiquette des données du graphique second_title: API de traitement de documents Aspose.Words description: Découvrez comment ajouter et personnaliser des étiquettes de données dans un graphique à l'aide d'Aspose.Words for .NET pour fournir des informations supplémentaires sur les points de données. type: docs weight: 10 url: /fr/net/programming-with-charts/chart-data-label/ --- Ce didacticiel explique comment ajouter et personnaliser des étiquettes de données dans un graphique à l'aide d'Aspose.Words for .NET. Les étiquettes de données fournissent des informations supplémentaires sur les points de données d'un graphique. ## Conditions préalables Pour suivre ce tutoriel, vous devez disposer des éléments suivants : - Bibliothèque Aspose.Words pour .NET installée. - Connaissance de base de C# et du traitement de mots avec des documents Word. ## Étape 1 : configurer le répertoire de documents Commencez par configurer le chemin d’accès à votre répertoire de documents. Remplacer`"YOUR DOCUMENT DIRECTORY"` avec le chemin réel du répertoire dans lequel vous souhaitez enregistrer le document. ```csharp string dataDir = "YOUR DOCUMENT DIRECTORY"; ``` ## Étape 2 : Créer un nouveau document et DocumentBuilder Créez une nouvelle instance du`Document` classe et un`DocumentBuilder` s'opposer à travailler avec le document. ```csharp Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); ``` ## Étape 3 : Insérer et configurer un graphique Insérez un graphique dans le document à l'aide du`InsertChart` méthode du`DocumentBuilder` objet. Définissez le type de graphique et les dimensions souhaités. ```csharp Shape shape = builder.InsertChart(ChartType.Bar, 432, 252); Chart chart = shape.Chart; ``` ## Étape 4 : Personnaliser les étiquettes de données Accédez à la collection d'étiquettes de données de la série de graphiques et modifiez diverses propriétés pour personnaliser l'apparence des étiquettes de données. ```csharp ChartSeries series0 = shape.Chart.Series[0]; ChartDataLabelCollection labels = series0.DataLabels; labels.ShowLegendKey = true; labels.ShowLeaderLines = true; labels.ShowCategoryName = false; labels.ShowPercentage = false; labels.ShowSeriesName = true; labels.ShowValue = true; labels.Separator = "/"; ``` ## Étape 5 : Enregistrez le document Enregistrez le document dans le répertoire spécifié à l'aide du`Save` méthode. Fournissez le nom de fichier souhaité avec l'extension de fichier appropriée. Dans cet exemple, nous enregistrons le document sous le nom « WorkingWithCharts.ChartDataLabel.docx ». ```csharp doc.Save(dataDir + "WorkingWithCharts.ChartDataLabel.docx"); ``` ### Exemple de code source pour l'étiquette de données de graphique utilisant Aspose.Words pour .NET ```csharp // Chemin d'accès à votre répertoire de documents string dataDir = "YOUR DOCUMENT DIRECTORY"; Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); Shape shape = builder.InsertChart(ChartType.Bar, 432, 252); Chart chart = shape.Chart; ChartSeries series0 = shape.Chart.Series[0]; ChartDataLabelCollection labels = series0.DataLabels; labels.ShowLegendKey = true; // Par défaut, lorsque vous ajoutez des étiquettes de données aux points de données dans un graphique à secteurs, des lignes de repère s'affichent pour les étiquettes de données qui sont // positionné bien en dehors de la fin des points de données. Les lignes de repère créent une connexion visuelle entre une étiquette de données et son // point de données correspondant. labels.ShowLeaderLines = true; labels.ShowCategoryName = false; labels.ShowPercentage = false; labels.ShowSeriesName = true; labels.ShowValue = true; labels.Separator = "/"; labels.ShowValue = true; doc.Save(dataDir + "WorkingWithCharts.ChartDataLabel.docx"); ``` C'est ça! Vous avez ajouté et personnalisé avec succès des étiquettes de données dans un graphique à l'aide d'Aspose.Words pour .NET. ## Conclusion Dans ce didacticiel, vous avez appris à ajouter et à personnaliser des étiquettes de données dans un graphique à l'aide d'Aspose.Words for .NET. En suivant le guide étape par étape, vous pouvez insérer un graphique, accéder à la collection d'étiquettes de données et modifier les propriétés pour personnaliser l'apparence des étiquettes de données. Aspose.Words for .NET fournit une API puissante pour le traitement de mots avec des documents et des graphiques Word, vous permettant de créer des graphiques visuellement attrayants et informatifs avec des étiquettes de données personnalisées. ### FAQ #### T1. Que sont les étiquettes de données dans un graphique ? Les étiquettes de données dans un graphique fournissent des informations supplémentaires sur les points de données représentés dans le graphique. Ils peuvent afficher des valeurs, des catégories, des noms de séries, des pourcentages ou d'autres détails pertinents en fonction du type de graphique et de la configuration. #### Q2. Puis-je personnaliser l’apparence des étiquettes de données ? Oui, vous pouvez personnaliser l'apparence des étiquettes de données dans un graphique. Aspose.Words for .NET fournit des options pour modifier diverses propriétés des étiquettes de données, telles que l'affichage des clés de légende, des lignes de repère, des noms de catégories, des noms de séries, des valeurs, etc. Vous pouvez également définir des séparateurs et formater les étiquettes pour répondre à vos besoins spécifiques. #### Q3. Puis-je ajouter des étiquettes de données à n’importe quel type de graphique ? Oui, vous pouvez ajouter des étiquettes de données à différents types de graphiques, notamment des graphiques à barres, des diagrammes circulaires, des graphiques linéaires, etc. Le processus d'ajout et de personnalisation des étiquettes de données peut varier légèrement en fonction du type de graphique et de la bibliothèque ou de l'outil que vous utilisez.
package org.example.Others; /** * Represents an item type in the inventory. */ public class ItemType { Integer itemTypeID; String itemTypeName; Integer totalItems; // Total items of this type /** * Constructs an ItemType object with the specified attributes. * @param itemTypeID The ID of the item type. * @param itemTypeName The name of the item type. * @param totalItems The total items of this type. */ public ItemType(Integer itemTypeID, String itemTypeName, Integer totalItems) { this.itemTypeID = itemTypeID; this.itemTypeName = itemTypeName; this.totalItems = totalItems; } /** * Retrieves the ID of the item type. * @return The ID of the item type. */ public Integer getItemTypeID() { return itemTypeID; } /** * Sets the ID of the item type. * @param itemTypeID The ID to set. */ public void setItemTypeID(Integer itemTypeID) { this.itemTypeID = itemTypeID; } /** * Retrieves the name of the item type. * @return The name of the item type. */ public String getItemTypeName() { return itemTypeName; } /** * Sets the name of the item type. * @param itemTypeName The name to set. */ public void setItemTypeName(String itemTypeName) { this.itemTypeName = itemTypeName; } /** * Retrieves the total items of this type. * @return The total items of this type. */ public Integer getTotalItems() { return totalItems; } /** * Sets the total items of this type. * @param totalItems The total items to set. */ public void setTotalItems(Integer totalItems) { this.totalItems = totalItems; } }
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/html" xmlns:sec="http://www.w3.org/1999/xhtml"> <head th:insert="fragments/fragments :: head-content"> </head> <body> <nav th:insert="fragments/fragments :: nav-bar-fragment(${user})"> </nav> <div class="user-info-container"> <div class="user-info-content"> <div th:style="'background:url(' + ${user.avatarImgUrl} + '); background-position: center; background-size: cover;'" class="user-image-block"> </div> <div class="article-preview-content-block user-info-position"> <div class="user-info-content-row"> <h5 th:object="${user}" class="text-white" th:text="${user.getUsername()}">USER</h5> <h5 class="card-title text-white" th:text="${user.getId()}" id="content">Title</h5> </div> <div class="user-info-content-row"> <label class="text-white" for="username" th:text="#{lang.name}">Name:</label> <b class="card-title text-white" th:text="${user.getName()}" id="username"></b> </div> <div class="user-info-content-row"> <label class="text-white" for="roleName" th:text="#{lang.role}">User roles:</label> <b class="card-title text-white" th:each="userRole : ${user.getRoles()}"th:text="${userRole} + ' '" id="roleName"></b> <p><a th:href="@{/profile/edit}"> <button type="button" class="btn btn-primary w-100" id="profile-edit-button" th:text="#{lang.edit.profile}">Edit profile</button> </a> </p> </div> </div> </div> </div> </body> </html>
import { Button, Icon, useColorModeValue } from "@chakra-ui/react"; import { IconType } from "react-icons"; interface ExternalLinkProps { href: string; title: string; solid?: boolean; icon?: IconType; } export const ExternalLink = ({ href, title, solid: main, icon, }: ExternalLinkProps) => { let button; const iconColor = useColorModeValue("gray.700", "gray.300"); const backgroundColor = useColorModeValue("gray.200", "gray.800"); if (main) { button = ( <Button size="md" fontWeight="700" color="white" bgGradient="linear(to-r, hsla(27, 84%, 55%, 1), hsla(17, 84%, 55%, 0.8))" w="full" _hover={{ bgGradient: "linear(to-r, hsla(27, 84%, 45%, 1), hsla(17, 84%, 45%, 0.8))", }} > {title} </Button> ); } else { button = ( <Button size="md" variant="ghost" fontWeight="400" w="full" _hover={{ backgroundColor, }} > <Icon as={icon} boxSize="5" color={iconColor} /> </Button> ); } return ( <a href={href} target="_blank" rel="noopener noreferrer"> {button} </a> ); };
package algorithm.dfs.boj_4963_섬의_개수; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.time.Duration; import java.time.LocalDateTime; import java.util.StringTokenizer; public class Main { static int w, h; static int[][] map; static boolean[][] visit; static int[] dr = {0, -1, -1, -1, 0, 1, 1, 1}; static int[] dc = {-1, -1, 0, 1, 1, 1, 0, -1}; static int count; static void dfs(int r, int c) { for (int i = 0; i < 8; i++) { int nr = r + dr[i]; int nc = c + dc[i]; if (nr < 0 || nc < 0 || nr >= h || nc >= w) { continue; } if (map[nr][nc] == 0 || visit[nr][nc]) { continue; } visit[nr][nc] = true; dfs(nr, nc); } } public static void main(String args[]) throws IOException { // LocalDateTime start = LocalDateTime.now(); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); StringTokenizer st; while (true) { st = new StringTokenizer(br.readLine()); w = Integer.parseInt(st.nextToken()); h = Integer.parseInt(st.nextToken()); if (w == 0 && h == 0) { break; } map = new int[h][w]; visit = new boolean[h][w]; for (int r = 0; r < h; r++) { st = new StringTokenizer(br.readLine()); for (int c = 0; c < w; c++) { map[r][c] = Integer.parseInt(st.nextToken()); } } count = 0; for (int r = 0; r < h; r++) { for (int c = 0; c < w; c++) { if (map[r][c] == 1 && !visit[r][c]) { count++; visit[r][c] = true; dfs(r, c); } } } bw.write(String.valueOf(count)); bw.newLine(); } bw.flush(); // LocalDateTime end = LocalDateTime.now(); // System.out.println(); // System.out.println("[Elapsed time: " + Duration.between(start, end).getSeconds() + " sec]"); bw.close(); br.close(); } }
open Globals; open LetOps; open StakerHelpers; open Mocha; let test = ( ~contracts: ref(Helpers.coreContracts), ~accounts: ref(array(Ethers.Wallet.t)), ) => { describe("_stake", () => { let token = Helpers.randomAddress(); let (userAmountStaked, userAmountToStake) = Helpers.Tuple.make2(Helpers.randomTokenAmount); // will be at least two let user = Helpers.randomAddress(); let marketIndex = Helpers.randomJsInteger(); let promiseRef: ref(JsPromise.t(ContractHelpers.transaction)) = ref(None->Obj.magic); let setup = (~userLastRewardIndex, ~latestRewardIndex) => { let%Await _ = deployAndSetupStakerToUnitTest( ~functionName="_stake", ~contracts, ~accounts, ); StakerSmocked.InternalMock.mock_mintAccumulatedFloatToReturn(); let%AwaitThen _ = contracts^.staker ->Staker.Exposed.set_stakeParams( ~user, ~marketIndex, ~latestRewardIndex, ~token, ~userAmountStaked, ~userLastRewardIndex, ); let promise = contracts^.staker ->Staker.Exposed._stakeExposed( ~user, ~token, ~amount=userAmountToStake, ); promiseRef := promise; promise; }; describe("case user has outstanding float to be minted", () => { let latestRewardIndex = Js.Math.random_int(2, Js.Int.max)->Ethers.BigNumber.fromInt; let randomRewardIndexBelow = num => Js.Math.random_int(1, num->Ethers.BigNumber.toNumber) ->Ethers.BigNumber.fromInt; before_once'(() => setup( ~userLastRewardIndex=randomRewardIndexBelow(latestRewardIndex), ~latestRewardIndex, ) ); it("calls mintAccumulatedFloat with correct args", () => { StakerSmocked.InternalMock._mintAccumulatedFloatCalls() ->Array.getExn(0) ->Chai.recordEqualFlat({marketIndex, user}) }); it("mutates userAmountStaked", () => { let%Await amountStaked = contracts^.staker->Staker.userAmountStaked(token, user); amountStaked->Chai.bnEqual( userAmountStaked->Ethers.BigNumber.add(userAmountToStake), ); }); it("mutates userIndexOfLastClaimedReward", () => { let%Await lastClaimedReward = contracts^.staker ->Staker.userIndexOfLastClaimedReward(marketIndex, user); lastClaimedReward->Chai.bnEqual(latestRewardIndex); }); it("emits StakeAdded", () => Chai.callEmitEvents( ~call=promiseRef^, ~contract=contracts^.staker->Obj.magic, ~eventName="StakeAdded", ) ->Chai.withArgs4(user, token, userAmountToStake, latestRewardIndex) ); }); // next two cases still do everything except call mintFloat but unwieldy to test describe("case user has last claimed index of 0", () => { before_once'(() => setup( ~userLastRewardIndex=CONSTANTS.zeroBn, ~latestRewardIndex=Helpers.randomInteger(), ) ); it("doesn't call mintAccumulatedFloat", () => { StakerSmocked.InternalMock._mintAccumulatedFloatCalls() ->Array.length ->Chai.intEqual(0) }); }); describe( "case users last claimed index == latestRewardIndex for market", () => { let index = Helpers.randomInteger(); before_once'(() => setup(~userLastRewardIndex=index, ~latestRewardIndex=index) ); it("doesn't call mintAccumulatedFloat", () => { StakerSmocked.InternalMock._mintAccumulatedFloatCalls() ->Array.length ->Chai.intEqual(0) }); }); }); };
import React from "react"; import { Pie } from "react-chartjs-2"; import { Chart, registerables } from "chart.js"; Chart.register(...registerables); const PieChart = () => { const state = { labels: [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", "Anjayday", ], datasets: [ { label: "Class Strength", backgroundColor: [ "Black", "Purple", "Yellow", "Teal", "Red", "Navy", "Brown", "Pink", ], data: [10, 14, 17, 16, 19, 16, 14, 3], }, ], }; return ( <> <div className="card"> <Pie data={state} options={{ title: { display: true, text: "Class Strength", fontSize: 20, }, legend: { display: true, position: "right", }, }} /> </div> </> ); }; export default PieChart;
<script setup lang="ts"> definePageMeta({ middleware: 'shop-owner' }) const file = ref() const BASE_URL = 'https://localhost:7124' const authStore = useAuthStore() const userId = computed(() => authStore.user.id) const marketName = ref() const isDragging = ref(false) const toast = useToast() async function submitUpload() { let formData = new FormData() formData.append('userId', userId.value) formData.append('marketName', marketName.value) formData.append('file', file.value) const {data} = await useFetch(BASE_URL + '/api/Upload/Csv', { method: 'POST', body: formData, headers: { Authorization: localStorage.getItem('token') } }) toast.add({severity: 'custom', summary: 'Datei erfolgreich hochgeladen', group: 'auth', life: 2000}) file.value = null marketName.value = '' } function dropFile(e: any) { isDragging.value = false file.value = e.dataTransfer.files[0] } function dragOver() { isDragging.value = true } function dragLeave() { isDragging.value = false } function chooseFile(e: any) { file.value = e.target.files[0] } </script> <template> <div class="flex justify-center"> <form @submit.prevent="submitUpload" class="w-[330px] p-5 bg-white shadow-2xl rounded-2xl border-0"> <div class="mx-auto mt-3"> <span class="p-float-label"> <PrimeInputText id="marketName" v-model="marketName" class="rounded-3xl" /> <label for="marketName">Marktname</label> </span> </div> <label for="dropzone-file" class="mt-5 flex flex-col items-center justify-center w-full aspect-square border-2 border-gray-300 border-dashed rounded-3xl cursor-pointer bg-gray-50 hover:bg-gray-100" @drop.prevent="dropFile($event)" @dragover.prevent="dragOver" @dragleave="dragLeave" > <template v-if="file"> <PrimeCard class="bg-white p-5 rounded-2xl shadow w-44 relative" unstyled> <template #header> <PrimeBadge unstyled class="absolute -top-2 -right-2 rounded-full bg-red-600 w-7 h-7 flex justify-center items-center" @click.prevent="file = null"> <Icon name="fa6-solid:xmark" class="text-white"/> </PrimeBadge> </template> <template #content> <PrimeImage src="https://upload.wikimedia.org/wikipedia/commons/3/3d/Logo_CSV.svg" alt="Image"/> <span class="text-xs">{{ file.name }}</span> </template> </PrimeCard> </template> <template v-else> <div v-if="!isDragging" class="flex flex-col items-center justify-center pt-5 pb-6"> <Icon name="fa6-solid:cloud-arrow-up" size="50" class="mb-5"/> <p class="mb-2 text-sm text-gray-500 font-semibold"> Klicken um Produktliste hochzuladen </p> <p class="text-xs text-gray-500">oder Produktliste ins Feld ziehen</p> </div> <div v-else class="flex flex-col items-center justify-center pt-5 pb-6"> <Icon name="fa6-solid:cloud-arrow-down" size="50" class="mb-5"/> <p class="mb-2 text-sm text-gray-500"> Produktliste zum hochladen hier loslassen </p> <p></p> </div> </template> <input id="dropzone-file" type="file" class="hidden" @change="chooseFile($event)"/> </label> <PrimeButton type="submit" label="Hochladen" size="small" class="float-right mt-5 bg-trolley-primary border-trolley-primary rounded-3xl" /> </form> </div> </template> <style scoped> </style>
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:sm_bloc_cubit/Business_logic/cubit/counter_cubit.dart'; import '../../Business_logic/cubit/counter_state.dart'; class SecondScreen extends StatelessWidget { const SecondScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return SafeArea( child: Scaffold( appBar: AppBar( title: Text('Second Page'), ), backgroundColor: Colors.lightGreen, body: Center( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ FloatingActionButton( heroTag: 'h3', onPressed: () { BlocProvider.of<CounterCubit>(context).decrement(); }, child: const Icon(Icons.remove), ), const SizedBox( width: 10, ), BlocConsumer<CounterCubit, CounterState>( builder: (context, state) { return Text(state.counterValue.toString()); }, listener: (context, state) { if (state.wasIncremented == true) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Incremented'), duration: Duration(milliseconds: 300), ), ); ScaffoldMessenger.of(context).hideCurrentSnackBar(); } else if (state.wasIncremented == false) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Decremented'), duration: Duration(milliseconds: 300), ), ); ScaffoldMessenger.of(context).hideCurrentSnackBar(); } }, ), const SizedBox( width: 10, ), FloatingActionButton( heroTag: 'h4', onPressed: () { BlocProvider.of<CounterCubit>(context).increment(); }, child: const Icon(Icons.add), ), ], ), ), ), ); } }
from django.contrib.syndication.views import Feed from .models import Post class AllPostsRssFeed(Feed): # 显示在聚合阅读器的标签 title = "黑与白的个人博客网站" # 通过聚合阅读器跳转到网站的地址 link = "/" # 显示在聚合阅读器上的描述信息 description = "关于黑与白的全部文章" # 需要显示的内容条目 def items(self): return Post.objects.all() # 聚合器中显示的内容条的标题 def item_title(self, item): return "[%s] %s" % (item.category, item.title) # 聚合器显示的内容条目的描述 def item_description(self, item): return item.body_html
package com.example.myhearing import android.Manifest import android.app.AlertDialog import android.content.BroadcastReceiver import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.IntentFilter import android.content.SharedPreferences import android.content.pm.PackageManager import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.media.AudioRecord import android.net.Uri import android.os.Build import android.os.Bundle import android.provider.Settings import android.util.Log import android.view.View import android.widget.Button import android.widget.ProgressBar import android.widget.TextView import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.content.ContextCompat import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.lifecycleScope import androidx.localbroadcastmanager.content.LocalBroadcastManager import com.example.myhearing.data.MyHearingDatabaseHelper import com.example.myhearing.services.LocationAndNoiseService import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.components.XAxis import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import com.github.mikephil.charting.formatter.DefaultValueFormatter import com.google.android.material.navigation.NavigationView import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainActivity : AppCompatActivity() { private lateinit var drawerLayout: DrawerLayout private lateinit var navigationView: NavigationView private lateinit var toolbar: Toolbar private lateinit var chart: LineChart private var dataEntries: ArrayList<Entry> = ArrayList() private var audioRecord: AudioRecord? = null private lateinit var noiseLevelTextView: TextView private lateinit var settingsButton: Button private var currentMode = Mode.NUMBER private lateinit var progressBar: ProgressBar private lateinit var horizontalProgressBar: ProgressBar private lateinit var prefs: SharedPreferences private lateinit var dbHelper: MyHearingDatabaseHelper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) prefs = getSharedPreferences("com.example.myhearing", Context.MODE_PRIVATE) requestPermissions() dbHelper = MyHearingDatabaseHelper(this) // Initialize UI components drawerLayout = findViewById(R.id.drawerLayout) navigationView = findViewById(R.id.navigationView) toolbar = findViewById(R.id.toolbar) chart = findViewById(R.id.chart) setSupportActionBar(toolbar) // Drawer toggle val toggle = ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close ) drawerLayout.addDrawerListener(toggle) toggle.syncState() navigationView.itemIconTintList = null navigationView.setNavigationItemSelectedListener { menuItem -> when (menuItem.itemId) { R.id.nav_item1 -> { startActivity(Intent(this, MainActivity::class.java)) true } R.id.nav_item2 -> { startActivity(Intent(this, HeatmapActivity::class.java)) true } R.id.nav_item3 -> { startActivity(Intent(this, TestHearingActivity::class.java)) true } R.id.nav_item4 -> { startActivity(Intent(this, CalibrationActivity::class.java)) true } else -> false } } noiseLevelTextView = findViewById(R.id.tvDecibelLevel) settingsButton = findViewById(R.id.settingsButton) val intentMode = intent.getStringExtra("selectedMode") currentMode = convertStringToMode(intentMode ?: "Number") Log.d("MainActivity", currentMode.toString()) setLayoutForCurrentMode() settingsButton.setOnClickListener { val intent = Intent(this, SettingsActivity::class.java) startActivity(intent) } initChart() lifecycleScope.launch { while (true) { withContext(Dispatchers.Main) { updateChartData() } delay(500) } } } /** Service implementation, transferred over from DecibelMeterActivity */ private val noiseLevelReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { val noiseLevel = intent?.getFloatExtra("noise_level", 0.0f) ?: 0.0f Log.d("MainActivity", "Received Decibel Level: $noiseLevel dB") if (noiseLevel.toInt() >= 0) { noiseLevelTextView.text = getString(R.string.tvDecibelLevel_text, noiseLevel.toInt()) } val progress = noiseLevel.toInt().coerceIn(0, 100) // Update db meter in UI progressBar.progress = progress horizontalProgressBar.progress = progress } } private fun startLocationAndNoiseService() { val serviceIntent = Intent(this, LocationAndNoiseService::class.java) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { startForegroundService(serviceIntent) } else { startService(serviceIntent) } } override fun onPause() { super.onPause() LocalBroadcastManager.getInstance(this).unregisterReceiver(noiseLevelReceiver) } override fun onResume() { super.onResume() lifecycleScope.launch { withContext(Dispatchers.IO) { if (prefs.getBoolean("app_info_return", false)) { prefs.edit().putBoolean("app_info_return", false).apply() delay(100L) requestPermissions() } } } if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START, false) } val filter = IntentFilter("com.example.myhearing.NOISE_LEVEL_UPDATE") LocalBroadcastManager.getInstance(this).registerReceiver(noiseLevelReceiver, filter) } private fun initChart() { val dataSet = LineDataSet(dataEntries, "Decibel Level") val lineData = LineData(dataSet) chart.data = lineData val xAxis = chart.xAxis xAxis.position = XAxis.XAxisPosition.BOTTOM xAxis.setDrawGridLines(false) xAxis.granularity = 1f xAxis.setDrawLabels(false) val yAxis = chart.axisLeft yAxis.axisMinimum = 0f yAxis.axisMaximum = 100f yAxis.granularity = 10f chart.axisLeft.setDrawGridLines(false) chart.axisRight.isEnabled = false chart.description.isEnabled = false } private fun updateChartData() { val records = dbHelper.getRecentDecibelRecords() val startColor = Color.argb(128, 255, 0, 0) val endColor = Color.argb(128, 0, 255, 0) val gradientDrawable = GradientDrawable( GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(startColor, endColor) ) dataEntries.clear() var maxY = 0f records.forEachIndexed { index, pair -> if (pair.second >= 0) { dataEntries.add(Entry(index.toFloat(), pair.second)) if (pair.second > maxY) { maxY = pair.second } } } val dataSet = LineDataSet(dataEntries, "Decibel Level") dataSet.setDrawFilled(true) dataSet.fillDrawable = gradientDrawable dataSet.valueFormatter = DefaultValueFormatter(0) chart.axisLeft.axisMaximum = maxY.coerceIn(100f, 300f) chart.data = LineData(dataSet) chart.data.notifyDataChanged() chart.notifyDataSetChanged() chart.setVisibleXRange(20f, 20f) chart.invalidate() } private fun requestPermissions() { val baseFgPermissions = arrayOf( Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION ) val fgPermissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { baseFgPermissions + arrayOf( Manifest.permission.FOREGROUND_SERVICE, Manifest.permission.POST_NOTIFICATIONS ) } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { baseFgPermissions + arrayOf(Manifest.permission.FOREGROUND_SERVICE) } else { baseFgPermissions } fgPermissionLauncher.launch(fgPermissions) } private fun hasPermission(permission: String): Boolean { return ContextCompat.checkSelfPermission( this, permission ) == PackageManager.PERMISSION_GRANTED } private val fgPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { _ -> val hasAudio = hasPermission(Manifest.permission.RECORD_AUDIO) val hasCoarse = hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION) val hasFine = hasPermission(Manifest.permission.ACCESS_FINE_LOCATION) if (hasAudio && hasCoarse && hasFine) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { bgLocationPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } else { startLocationAndNoiseService() } } else if (hasAudio) { launchFineLocationDialog() } else if (hasCoarse && hasFine) { launchAudioDialog() } else { launchFgDialog() } } private fun launchFineLocationDialog() { val fgLocationPermissions = arrayOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION ) AlertDialog.Builder(this) .setTitle("Permission Required") .setMessage("This app won't work properly without your precise location!") .setPositiveButton("Ask Again") { dialog: DialogInterface, _: Int -> if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) { fgPermissionLauncher.launch(fgLocationPermissions) } else { launchAppInfo() } dialog.dismiss() } .setNegativeButton("Deny Anyway") { dialog: DialogInterface, _: Int -> if (hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { bgLocationPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } } dialog.dismiss() } .create() .show() } private fun launchAudioDialog() { AlertDialog.Builder(this) .setTitle("Permission Required") .setMessage("This app won't work properly without the \"record audio\" permission!") .setPositiveButton("Ask Again") { dialog: DialogInterface, _: Int -> if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO)) { fgPermissionLauncher.launch(arrayOf(Manifest.permission.RECORD_AUDIO)) } else { launchAppInfo() } dialog.dismiss() } .setNegativeButton("Deny Anyway") { dialog: DialogInterface, _: Int -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { bgLocationPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } dialog.dismiss() } .create() .show() } private fun launchFgDialog() { val fgPermissions = arrayOf( Manifest.permission.RECORD_AUDIO, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION ) AlertDialog.Builder(this) .setTitle("Permission Required") .setMessage("This app won't work properly without the requested permissions!") .setPositiveButton("Ask Again") { dialog: DialogInterface, _: Int -> if (shouldShowRequestPermissionRationale(Manifest.permission.RECORD_AUDIO) && shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION) ) { fgPermissionLauncher.launch(fgPermissions) } else { launchAppInfo() } dialog.dismiss() } .setNegativeButton("Deny Anyway") { dialog: DialogInterface, _: Int -> dialog.dismiss() } .create() .show() } private fun launchAppInfo() { val editor = getSharedPreferences("com.example.myhearing", Context.MODE_PRIVATE).edit() editor.putBoolean("app_info_return", true) editor.apply() val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) val uri: Uri = Uri.fromParts("package", packageName, null) intent.data = uri startActivity(intent) } private val bgLocationPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean -> if (isGranted) { startLocationAndNoiseService() } else { launchBgLocationDialog() } } private fun launchBgLocationDialog() { AlertDialog.Builder(this) .setTitle("Permission Required") .setMessage("This app won't work properly without knowing your location all the time!") .setPositiveButton("Ask Again") { dialog: DialogInterface, _: Int -> if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_BACKGROUND_LOCATION)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { bgLocationPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION) } else { startLocationAndNoiseService() } } else { launchAppInfo() } dialog.dismiss() } .setNegativeButton("Deny Anyway") { dialog: DialogInterface, _: Int -> startLocationAndNoiseService() dialog.dismiss() } .create() .show() } private enum class Mode { NUMBER, GAUGE, HORIZONTAL_GAUGE } private fun setLayoutForCurrentMode() { // Set the content view based on the current mode when (currentMode) { Mode.NUMBER -> { progressBar = findViewById(R.id.progressBar) horizontalProgressBar = findViewById(R.id.horizontalProgressBar) progressBar.visibility = View.GONE horizontalProgressBar.visibility = View.GONE } Mode.GAUGE -> { progressBar = findViewById(R.id.progressBar) horizontalProgressBar = findViewById(R.id.horizontalProgressBar) progressBar.visibility = View.VISIBLE horizontalProgressBar.visibility = View.GONE } Mode.HORIZONTAL_GAUGE -> { progressBar = findViewById(R.id.progressBar) horizontalProgressBar = findViewById(R.id.horizontalProgressBar) progressBar.visibility = View.GONE horizontalProgressBar.visibility = View.VISIBLE } } } private fun convertStringToMode(modeString: String): Mode { return when (modeString) { "Number" -> Mode.NUMBER "Circular Gauge" -> Mode.GAUGE "Horizontal Gauge" -> Mode.HORIZONTAL_GAUGE else -> throw IllegalArgumentException("Invalid mode: $modeString") } } override fun onDestroy() { super.onDestroy() audioRecord?.stop() audioRecord?.release() } }
import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:google_fonts/google_fonts.dart'; class LoginScreen extends StatefulWidget { final VoidCallback displayRegisterScreen; const LoginScreen({Key? key, required this.displayRegisterScreen}) : super(key: key); @override State<LoginScreen> createState() => _LoginScreenState(); } class _LoginScreenState extends State<LoginScreen> { final _usernameController = TextEditingController(); final _pwdController = TextEditingController(); Future signIn() async { await FirebaseAuth.instance.signInWithEmailAndPassword( email: _usernameController.text.trim(), password: _pwdController.text.trim(), ); } @override void dispose() { _usernameController.dispose(); _pwdController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.lightGreenAccent, body: SafeArea( child: Center( child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const DisplayLogo(), SizedBox(height: 60), Text( 'Welcome to OEV!', style: GoogleFonts.alice( fontSize: 45, ), ), SizedBox(height: 10), Text( 'Please login with your registered email', style: TextStyle( fontSize: 18, ), ), SizedBox(height: 40), Padding( padding: const EdgeInsets.symmetric(horizontal: 30.0), child: TextField( controller: _usernameController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.black), borderRadius: BorderRadius.circular(20), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.black), borderRadius: BorderRadius.circular(20), ), hintText: 'Email', fillColor: Colors.grey[100], filled: true, ), ), ), SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 30.0), child: TextField( obscureText: true, controller: _pwdController, decoration: InputDecoration( enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.black), borderRadius: BorderRadius.circular(20), ), focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Colors.black), borderRadius: BorderRadius.circular(20), ), hintText: 'Password', fillColor: Colors.grey[100], filled: true, ), ), ), SizedBox(height: 12), Padding( padding: const EdgeInsets.symmetric(horizontal: 30.0), child: GestureDetector( onTap: signIn, child: Container( padding: EdgeInsets.all(22), decoration: BoxDecoration( color: Colors.black, borderRadius: BorderRadius.circular(20), ), child: Center( child: Text( 'Log in', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 20, ), ), ), ), ), ), SizedBox(height: 20), //not a member? register now Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( 'Not a member?', style: TextStyle( fontWeight: FontWeight.bold, fontSize: 16, ), ), GestureDetector( onTap: widget.displayRegisterScreen, child: Text( ' Register now', style: TextStyle( color: Colors.blue, fontWeight: FontWeight.bold, fontSize: 16, ), ), ), ], ), ], ), ), ), ), ); } } class DisplayLogo extends StatelessWidget { const DisplayLogo({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return const Image(image: AssetImage('assets/images/oev_logo.png')); } }
import 'package:flutter/material.dart'; import 'package:world_time_app/style/colors.dart'; import 'package:world_time_app/services/world_time.dart'; import 'package:http/http.dart'; import 'dart:convert'; // for converting JSON import 'package:flutter_spinkit/flutter_spinkit.dart'; class Loading extends StatefulWidget { const Loading({super.key}); @override State<Loading> createState() => _LoadingState(); } class _LoadingState extends State<Loading> { String time = 'loading'; void setupWorldTime() async { WorldTime instance = WorldTime( location: 'Philippines', flag: 'philippines.png', url: 'Asia/Manila', ); await instance.getTime(); print(instance.time); setState( () { time = instance.time; }, ); Navigator.pushReplacementNamed( context, '/home', arguments: { 'location': instance.location, 'flag': instance.flag, 'time': instance.time, 'isDaytime': instance.isDaytime, }, ); // sends to /home route } @override void initState() { super.initState(); setupWorldTime(); } @override Widget build(BuildContext context) { return const Scaffold( backgroundColor: MyColors.gray, body: Center( child: SpinKitThreeBounce( color: MyColors.white, size: 64.0, ), ), ); } }
import React, { useState } from "react"; import { accordionData } from "../../accordionData"; import "../../accordion.css"; const Accordion = ({ defaultActiveKey, collapsible = true }) => { const [activeAccordionItem, setActiveAccordionItem] = useState(defaultActiveKey); return ( <div className="accordion-container"> {accordionData.map((item, index) => ( <> <div className="accordion-item" key={index}> <div className="accordion-toggle" onClick={() => collapsible && activeAccordionItem === index ? setActiveAccordionItem(null) : setActiveAccordionItem(index) } > <div className="accordion-toggle-header">{item.header}</div> <div className="accordion-toggle-icon"> {activeAccordionItem === index ? "-" : "+"} </div> </div> {activeAccordionItem === index && ( <div className="accordion-body"> {accordionData[activeAccordionItem].body} </div> )} </div> </> ))} </div> ); }; export default Accordion;
import { zodResolver } from '@hookform/resolvers/zod'; import { useEffect } from 'react'; import { useForm } from 'react-hook-form'; import { Form } from '@/components/ui/form'; import { type DateFieldPropertiesSchema, dateFieldPropertiesSchema, } from '@/lib/validations/dateFieldPropertiesSchema'; import { useBoundStore } from '@/store/useBoundStore'; import { PropertiesFormField } from '../PropertiesFormField'; import { PropertiesSwitch } from '../PropertiesSwitch'; import type { DateFieldInstance, DateFieldPropertiesFormProps } from './@types'; export function DateFieldProperties({ elementInstance, }: DateFieldPropertiesFormProps) { const element = elementInstance as DateFieldInstance; const { updateElementProperties } = useBoundStore((state) => state.actions); const form = useForm<DateFieldPropertiesSchema>({ resolver: zodResolver(dateFieldPropertiesSchema), mode: 'onBlur', defaultValues: element.properties, }); useEffect(() => { form.reset(element.properties); }, [element, form]); function applyChanges(values: DateFieldPropertiesSchema) { updateElementProperties(element.id, values); } return ( <Form {...form}> <form onBlur={form.handleSubmit(applyChanges)} onSubmit={(e) => e.preventDefault()} className="space-y-3" > <PropertiesFormField control={form.control} label="Label" name="label" description="The label of the field. This will be displayed above the field." /> <PropertiesFormField control={form.control} label="Helper Text" name="helperText" description="The helper text of the field. This will be displayed below the field." /> <PropertiesSwitch control={form.control} label="Required" name="required" description="Whether the field is required or not." /> </form> </Form> ); }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.shindig.protocol; import junit.framework.TestCase; /** * Test content type checks */ public class ContentTypesTest extends TestCase { @Override protected void setUp() throws Exception { } public void testAllowJson() throws Exception { ContentTypes.checkContentTypes(ContentTypes.ALLOWED_JSON_CONTENT_TYPES, ContentTypes.OUTPUT_JSON_CONTENT_TYPE, true); } public void testAllowJsonRpc() throws Exception { ContentTypes.checkContentTypes(ContentTypes.ALLOWED_JSON_CONTENT_TYPES, "application/json-rpc", true); } public void testAllowAtom() throws Exception { ContentTypes.checkContentTypes(ContentTypes.ALLOWED_ATOM_CONTENT_TYPES, ContentTypes.OUTPUT_ATOM_CONTENT_TYPE, true); } public void testAllowXml() throws Exception { ContentTypes.checkContentTypes(ContentTypes.ALLOWED_XML_CONTENT_TYPES, ContentTypes.OUTPUT_XML_CONTENT_TYPE, true); } public void testAllowMultipart() throws Exception { ContentTypes.checkContentTypes(ContentTypes.ALLOWED_MULTIPART_CONTENT_TYPES, ContentTypes.MULTIPART_FORM_CONTENT_TYPE, true); } public void testForbidden() throws Exception { try { ContentTypes.checkContentTypes(ContentTypes.ALLOWED_JSON_CONTENT_TYPES, "application/x-www-form-urlencoded", false); fail("Should fail as form encoded is forbidden"); } catch (ContentTypes.InvalidContentTypeException icte) { } } public void testStrictDisallowUnknown() throws Exception { try { ContentTypes.checkContentTypes(ContentTypes.ALLOWED_JSON_CONTENT_TYPES, "text/plain", true); fail("Should fail with strict content type checking enabled"); } catch (ContentTypes.InvalidContentTypeException icte) { } } public void testNonStrictAllowUnknown() throws Exception { ContentTypes.checkContentTypes(ContentTypes.ALLOWED_JSON_CONTENT_TYPES, "text/plain", false); } public void textExtractMimePart() throws Exception { assertEquals("text/xml", ContentTypes.extractMimePart("Text/Xml ; charset = ISO-8859-1;x=y")); } }
import { Component, OnInit, OnDestroy } from '@angular/core'; import Swal from 'sweetalert2'; import { Usuario } from '../../../models/usuario.model'; import { BusquedaService } from '../../../services/busqueda.service'; import { ModalImagenService } from 'src/app/services/modal-imagen.service'; import { UsuarioService } from '../../../services/usuario.service'; import { Subscription } from 'rxjs'; import { delay } from 'rxjs/operators'; @Component({ selector: 'app-usuarios', templateUrl: './usuarios.component.html', styleUrls: ['./usuarios.component.css'] }) export class UsuariosComponent implements OnInit, OnDestroy { public totalUsuarios: number = 0; public usuarios: Usuario[] = []; public usuariosTemp: Usuario[] = []; public imgSubs: Subscription; public desde: number = 0; public cargando: boolean = true; constructor( private usuarioService: UsuarioService, private busquedaService: BusquedaService, private modalImagenService: ModalImagenService ) { } ngOnDestroy(): void { this.imgSubs.unsubscribe(); } ngOnInit(): void { this.cargarUsuarios(); this.imgSubs = this.modalImagenService.imagenCambio.pipe(delay(100)).subscribe(img => this.cargarUsuarios() ); } cargarUsuarios() { this.cargando = true; this.usuarioService.cargarUsuarios(this.desde) .subscribe(({total, usuarios}) => { this.totalUsuarios = total; this.usuarios = usuarios; this.usuariosTemp = usuarios; this.cargando = false; }); } cambiarPagina(valor: number) { this.desde += valor if(this.desde < 0) { this.desde = 0; return; } else if (this.desde >= this.totalUsuarios) { this.desde -= valor; return; } this.cargarUsuarios(); } buscar(termino: string) { if ( termino.length === 0 ) { return this.usuarios = this.usuariosTemp; } this.busquedaService.buscar("usuarios", termino) .subscribe((resp: Usuario[]) => { this.usuarios = resp; }); } eliminarUsuario(usuario: Usuario) { if(usuario._id === this.usuarioService.uid){ return Swal.fire("Error", "No puedes borrarte a ti mismo", "error"); } Swal.fire({ title: 'Seguro quieres eliminar el usuario?', text: `El usuario ${usuario.nombre} será eliminado`, icon: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Si, eliminar' }).then((result) => { if (result.value) { this.usuarioService.eliminarUsuario(usuario) .subscribe(resp => { this.cargarUsuarios(); Swal.fire( 'Usuario eliminado', `${usuario.nombre} ha sido eliminado correctamente`, 'success' ); }); } }); } cambiarRole(usuario: Usuario) { this.usuarioService.guardarUsuario(usuario) .subscribe(resp => { console.log(resp); }) } abrirModal(usuario: Usuario) { this.modalImagenService.abrirModal("usuarios", usuario._id, usuario.img); } }
<!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <title>Challenge - Encriptador</title> <link rel="stylesheet" type="text/css" href="reset.css"> <link rel="stylesheet" type="text/css" href="style-enc.css"> </head> <body> <header> <div class="caja"> <h1> Encriptador y desencriptador </h1> </div> </header> <main> <div class="entrada"> <label for="mensaje">Entrada: </label> <textarea cols="70" rows="10" id="textoentrada" class="inp-padron" ></textarea> </div> <div class="salida"> <label for="mensaje">Salida: </label> <textarea cols="30" rows="10" id="textosalida" class="inp-padron" ></textarea> </div> <div class="opciones"> <input type="button" value="Encriptar" class="enviar" onClick="btnencriptar();"> <input type="button" value="Desencriptar" class="enviar" onClick="btndesencriptar()"> <input type="button" value="Limpiar" class="enviar" onClick="btnlimpiar()"> </div> </main> <footer> <label for="mensaje">Creado por: Oliver Fabian Garcia Vertiz </label> </footer> </body> </html> <script type="text/javascript"> function btnencriptar (){ const textoentrada = document.getElementById('textoentrada').value; const txtsalida = document.getElementById('textosalida').value; const textoencriptado = encriptar(textoentrada) document.getElementById('textosalida').value=textoencriptado ; } function btndesencriptar (){ const textoentrada = document.getElementById('textoentrada').value; const textodesencriptado = desencriptar(textoentrada) document.getElementById('textosalida').value=textodesencriptado ; } function encriptar (strtexto){ let matriz = [["e","enter"],["i","imes"],["a","ai"],["o","ober"],["u","ufat"]]; strtexto = strtexto.toLowerCase(); for (var i=0; i < matriz.length; i++) { if (strtexto.includes(matriz[i][0])) { strtexto = strtexto.replaceAll(matriz[i][0],matriz[i][1]) } } return strtexto } function desencriptar (strtexto){ let matriz = [["e","enter"],["i","imes"],["a","ai"],["o","ober"],["u","ufat"]]; strtexto = strtexto.toLowerCase(); for (var i=0; i < matriz.length; i++) { if (strtexto.includes(matriz[i][1])) { strtexto = strtexto.replaceAll(matriz[i][1],matriz[i][0]) } } return strtexto } function btnlimpiar (){ document.getElementById('textoentrada').value=""; document.getElementById('textosalida').value=""; } </script>
<!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Includes() Método String</title> </head> <body> <script> /** * * STRING JAVASCRIPT INCLUDES() MÉTODO * * Resumo : neste tutorial, você aprenderá como usar o includes()método JavaScript String para verificar se uma string contém outra string. * * * INCLUDES() - INCLUI - INTRODUÇÃO AO MÉTODO JS STRING * * O includes() método determina se uma string contém outra string: string.includes(searchString[, position]); * * O método includes() retorna true se o searchString encontrado no string; caso contrário false. * * O parâmetro opcional position especifica a posição string na qual começar a procurar o arquivo searchString. O position padrão é 0. * * A includes() string de correspondência faz distinção entre maiúsculas e minúsculas. * * * INCLUDES() EXEMPLOS DE STRING JS * * Este exemplo usa o includes()método para verificar se a string @está na string 'admin@example.com': * */ //declara uma variavel chamada email essa variavel e inicializada com uma string literal let email = 'admin@example.com'; //utilizando o metodo string.include() para verificar se a string literal email contem a string '@', se sim retorna true se não false console.log(`'${'admin@example.com'}' possui '${'@'}' = ${email.includes('@')}`);//true /** * Como mencionado anteriormente, o includes() corresponde à string diferenciando maiúsculas de minúsculas, portanto, o exemplo a seguir retorna false: * */ //declara uma variavel chamada str que e inicializada com uma string literal let str = 'JavaScript String'; //utilizando o metodo string.include() para verificar se a string literal str contem a string 'script' //aqui neste caso retornara false pois o include diferencia maiusculas de minusculas, o que procuro e string 'script' e o que contem na str string literl e 'Script' com letra maiuscula console.log(str.includes('script')); /** * O exemplo a seguir usa o includes() método com o segundo parâmetro: */ //declara uma variavel chamada str3 que e inicializada com uma string literal let str3 = 'JavaScript String'; //utilizando o metodo string.includes passando dois argumentos, o primeiro argumento e para verificar se a string literal str3 contem a string 'Script', lembrando que include diferencia maiusculas de minusculas, assim aqui retorna false, pois são diferentes oque procuro do que tenho, o segundo argumento e o valor 5 e indicando ao metodo a partir de qual posição deve procurar a string, aqui e a partir da 5 a partir do caractere c console.log(str3.includes('Script', 5)); //false /** * Neste tutorial, você aprendeu como usar o includes() método JavaScript String para determinar se uma string contém outra string. */ </script> </body> </html>
#' Estimate a survey-weighted ROC curve #' #' @param design survey.design object specifying the complex survey design #' @param prediction character value specifying the name of the variable containing the predicted value #' @param label character value specifying the name of the binary response encoded 0 (control) and 1 (cases) #' @param fpr_grid NULL (default) or numeric vector ranging from 0 to 1 specifying the desired cutpoints for the FPR. #' If set to NULL, the cutpoints are defined by the unique values of the predictor #' #' This function estimates the ROC curve non-parametrically while accounting for the complex sampling design #' #' @return A list containing the ROC curve and the corresponding AUC #' @export svyroc_estimate <- function(design, prediction, label, fpr_grid = NULL) { data <- design$variables D <- pull(data, label) X <- pull(data, prediction) #if(unique(D) != c(0,1)) stop("label variable must be c(0,1)") wt <- 1/design$prob wt <- wt*(!is.na(X)) X.order <- order(X, decreasing = TRUE, na.last = NA) TTT <- X[X.order] TPF <- cumsum(wt[X.order]*(D[X.order] == 1))/sum(wt*(D == 1)) FPF <- cumsum(wt[X.order]*(D[X.order] == 0))/sum(wt*(D == 0)) dups <- rev(duplicated(rev(TTT))) tp <- TPF[!dups] fp <- FPF[!dups] cutoffs <- TTT[!dups] tp <- ifelse(tp > 1, 1, tp) fp <- ifelse(fp > 1, 1, fp) roc <- data.frame(fpr = c(0,fp), tpr = c(0,tp), cutoff = c(Inf, cutoffs)) ################ # COMPUTING AUC ################ auc <- svyroc_auc(roc$fpr, roc$tpr) ########################################## # COMPUTING ROC VALUES FOR SPECIFIED GRID ########################################## if(!is.null(fpr_grid)) { roc <- roc %>% mutate(fpr_grid = cut(fpr, c(-Inf,{{fpr_grid}}), include.lowest = TRUE, labels = {{fpr_grid}})) %>% group_by(fpr_grid) %>% summarise(tpr = max(tpr), cutoff = min(cutoff)) %>% rename(fpr = fpr_grid) %>% mutate(fpr = as.numeric(as.character(fpr))) } return(list(roc = roc, auc = auc)) }
<template> <div class="allContainer"> <!-- アイコン 始まり --> <section class="icon"> <h1 class="profileTitle">アイコン</h1> <div class="icon_Container"> <img class="icon_Container_user" :src="inputUserImage" /> </div> </section> <!-- アイコン 終わり --> <!-- ユーザーネーム 始まり --> <section class="userName"> <h1 class="profileTitle">ユーザーネーム(10文字まで)</h1> <div class="userName_Container"> <input class="inputContainer" type="text" maxlength="10" v-model="inputUserName" :placeholder="inputPlaceholder" /> </div> <div class="transparentCode">{{ getuserName }}</div> </section> <!-- ユーザーネーム 終わり --> <!-- コース 始まり --> <section class="courseArea"> <h1 class="profileTitle">コース</h1> <div class="courseContainer"> <select class="courseSelect" v-model="inputUserCourse"> <option value="IPhone">iPhoneアプリ開発コース</option> <option value="Game">Gameアプリ開発コース</option> <option value="Web">webサービス開発コース</option> <option value="WebExpert">WebExpertコース</option> <option value="VideoEditor">VideoEditorコース</option> <option value="UIUX">UI/UXコース</option> <option value="AI">AIコース</option> <option value="Python">Pythonコース</option> </select> </div> </section> <!-- コース 終わり --> <!-- ボタン 始まり --> <section class="Savebutton"> <button class="Savebutton_button" @click="allSave"> <span>決定</span> </button> </section> <!-- ボタン 終わり --> </div> </template> <script> import { getAuth, // signInWithPopup, // GoogleAuthProvider, onAuthStateChanged, // signOut, } from "firebase/auth" import { // setDoc, doc, updateDoc, collection, // addDoc, // deleteField, getDoc, getDocs, query, where, } from "firebase/firestore" import { db } from "@/firebase" export default { name: "ProfilePage", data() { return { inputUserCourse: "", getuserName: "", geetusercourse: "", inputPlaceholder: "名無し", inputUserName: "", inputUserImage: "", } }, created() { const auth = getAuth() // ログイン後のユーザー情報を取得するには,onAuthStateChangedが最初に必要 onAuthStateChanged(auth, async (user) => { // プロフィール設定している場合 if (user) { const user = auth.currentUser const userID = user.uid const docRef = doc(db, "users", userID) const docSnap = await getDoc(docRef) // console.log("Profile => docSnap" + ":" + docSnap.data()) if (docSnap.exists()) { this.inputUserName = docSnap.data().userName this.inputUserCourse = docSnap.data().userCourse this.inputUserImage = docSnap.data().userImg } else { // console.log("Profile => ユーザー情報がないよ!") } } }) }, methods: { async allSave() { if (this.inputUserName !== "" && this.inputUserCourse !== "") { const auth = getAuth() const user = auth.currentUser await updateDoc(doc(db, "users", user.uid), { userName: this.inputUserName, userCourse: this.inputUserCourse, }) // -------------------------------------------------------- // 更新したとき、過去に投稿したメモのユーザー名も更新するコード // ------------------------------------------------------------ const a = query( collection(db, "userMemos"), where("userID", "==", user.uid) ) const querySnapshot = await getDocs(a) let idBoxes = [] querySnapshot.forEach(async (doc) => { idBoxes.push(doc.id) }) for (let i = 0; i < idBoxes.length; i++) { const userMemosRef = doc(db, "userMemos", idBoxes[i]) updateDoc(userMemosRef, { userName: this.inputUserName, }) } // 初めてアカウントを作った場合、リロードすることで画像が表示される仕組みにする const firstCreateData = user.metadata.creationTime const lastCreateData = user.metadata.lastSignInTime if (firstCreateData === lastCreateData) { location.reload() } alert("変更しました!") } else { alert("どっちも入力してね!") } }, }, } </script> <style lang="scss" scoped> @import "@/assets/css/_reset.scss"; $containerMargin-top: 40px; .allContainer { // border: 2px solid red; height: 100vh; padding-top: 30px; background-color: rgba(253, 244, 232, 0.747); user-select: none; section { // border: 2px solid red; margin: 30px auto; } .profileTitle { // border: 2px solid green; text-align: center; font-weight: bold; font-size: 1.3em; border-bottom: 2px solid #000; } /* アイコン 始まり */ .icon { // border: 2px solid indianred; max-width: 80%; .icon_Container { // border: 2px solid greenyellow; display: flex; justify-content: center; } .icon_Container_user { // border: 2px solid red; margin: auto; width: 130px; height: 130px; border-radius: 50%; color: black; margin: 20px auto 0px; } } // ------------------------- /* ユーザーネーム 始まり */ // --------------------------- .userName { /* border: 2px solid blue; */ max-width: 80%; } .userName_Container { /* border: 2px solid red; */ margin: 0 auto; display: flex; justify-content: center; input { text-align: center; width: 60%; height: 40px; border: 2px solid rgb(73, 72, 72); background-color: white; font-size: 30px; font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif; margin-top: $containerMargin-top; } } // ----------------------------- /* コース 始まり */ // ------------------------------- .courseArea { // border: 2px solid brown; max-width: 80%; } .courseContainer { // border: 2px solid red; margin: 0 auto; display: flex; justify-content: center; } .courseSelect { margin-top: $containerMargin-top; height: 40px; width: 60%; border: 2px solid rgb(73, 72, 72); background-color: white; font-size: 20px; font-weight: bold; border: 2px solid black; font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif; letter-spacing: 2px; -moz-appearance: menulist; -webkit-appearance: menulist; option { text-align: center; } } // ------------------------------- /* 決定ボタン 始まり */ // -------------------------------- .Savebutton { // border: 2px solid red; text-align: center; .Savebutton_button { background-color: #c7887fdd; border: 2px solid #645856dd; border-radius: 10px; font-size: 40px; font-weight: 900; font-family: "Franklin Gothic Medium", "Arial Narrow", Arial, sans-serif; padding: 7px 20px; margin-top: 40px; &:hover { cursor: pointer; filter: brightness(115%); } &:active { transform: scale(0.98); } } } } </style>
<?php namespace Acioina\UserManagement\Http\Controllers; use Symfony\Component\Finder\Finder; use Symfony\Component\Mime\MimeTypes; use Symfony\Component\Finder\SplFileInfo; use Symfony\Component\HttpFoundation\BinaryFileResponse; use Illuminate\Support\Arr; /** * Class ResourceController. */ class ResourceController { /** * @var MimeTypes */ private $mimeTypes; /** * @var Finder */ private $finder; /** * ResourceController constructor. * * @param Finder $finder */ public function __construct(Finder $finder, MimeTypes $mimeTypes) { $this->finder = $finder; $this->mimeTypes = $mimeTypes; } /** * Serve the requested resource. * * @param string $package * @param string $path * @param Dashboard $dashboard * * @return BinaryFileResponse */ public function getIndex($path) { //Accessing The Current Route //$route = Route::current(); //$name = Route::currentRouteName(); //$action = Route::currentRouteAction(); $dir = $GLOBALS['CIOINA_Config']->get('AssetsDir'); abort_if($dir === null, 404); $resources = $this->finder ->ignoreUnreadableDirs() ->followLinks() ->in($dir) ->files() ->path(dirname($path)) ->name(basename($path)); $iterator = tap($resources->getIterator())->rewind(); /* Changing the separator for Windows operating systems */ $path = str_replace('/', DIRECTORY_SEPARATOR, $path); $resource = collect($iterator) ->filter(static function (SplFileInfo $file) use ($path) { return $file->getRelativePathname() === $path; }) ->first(); abort_if($resource === null, 404); $mimeType = $this->getMimeType($resource->getExtension()); return response()->file($resource->getRealPath(), [ 'Content-Type' => $mimeType ?? 'text/plain', 'Cache-Control' => 'public, max-age=31536000', ]); } /** * @param string $mimeType * @param mixed|null $default * * @return string|null */ private function getExtension(string $mimeType, string $default = null): ?string { return Arr::first($this->mimeTypes->getExtensions($mimeType), null, $default); } /** * @param string $ext * @param string|null $default * * @return string|null */ private function getMimeType(string $ext, string $default = null): ?string { return Arr::first($this->mimeTypes->getMimeTypes($ext), null, $default); } }
package main import "fmt" //现在你总共有 numCourses 门课需要选,记为 0 到 numCourses - 1。给你一个数组 prerequisites ,其中 //prerequisites[i] = [ai, bi] ,表示在选修课程 ai 前 必须 先选修 bi 。 // // // 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示:[0,1] 。 // // // 返回你为了学完所有课程所安排的学习顺序。可能会有多个正确的顺序,你只要返回 任意一种 就可以了。如果不可能完成所有课程,返回 一个空数组 。 // // // // 示例 1: // // //输入:numCourses = 2, prerequisites = [[1,0]] //输出:[0,1] //解释:总共有 2 门课程。要学习课程 1,你需要先完成课程 0。因此,正确的课程顺序为 [0,1] 。 // // // 示例 2: // // //输入:numCourses = 4, prerequisites = [[1,0],[2,0],[3,1],[3,2]] //输出:[0,2,1,3] //解释:总共有 4 门课程。要学习课程 3,你应该先完成课程 1 和课程 2。并且课程 1 和课程 2 都应该排在课程 0 之后。 //因此,一个正确的课程顺序是 [0,1,2,3] 。另一个正确的排序是 [0,2,1,3] 。 // // 示例 3: // // //输入:numCourses = 1, prerequisites = [] //输出:[0] // // // //提示: // // // 1 <= numCourses <= 2000 // 0 <= prerequisites.length <= numCourses * (numCourses - 1) // prerequisites[i].length == 2 // 0 <= ai, bi < numCourses // ai != bi // 所有[ai, bi] 互不相同 // // Related Topics 深度优先搜索 广度优先搜索 图 拓扑排序 👍 639 👎 0 func main() { value := 1 no210Print("%+v", value) } func no210Print(format string, params ...interface{}) { println(fmt.Sprintf(format, params...)) } //leetcode submit region begin(Prohibit modification and deletion) func findOrder(numCourses int, prerequisites [][]int) []int { var ( edges = make([][]int, numCourses) deep = make([]int, numCourses) result []int q []int ) for _, p := range prerequisites { edges[p[1]] = append(edges[p[1]], p[0]) deep[p[0]]++ } for _, d := range deep { if d == 0 { q = append(q, d) } } if len(q) > 0 { u := q[0] q = q[1:] result = append(result, u) for _, v := range edges[u] { deep[v]-- if deep[v] == 0 { q = append(q, v) } } } if len(result) != numCourses { return []int{} } return result } func findOrder1(numCourses int, prerequisites [][]int) []int { var ( edges = make([][]int, numCourses) visited = make(map[int]int, numCourses) valid = true result []int findOrderFunc func(u int) ) findOrderFunc = func(u int) { visited[u] = 1 for _, v := range edges[u] { if visited[v] == 0 { findOrderFunc(v) if !valid { return } } else if visited[v] == 1 { valid = false return } } visited[u] = 2 result = append(result, u) } // 把边整理出来 for _, info := range prerequisites { edges[info[1]] = append(edges[info[1]], info[0]) } for i := 0; i < numCourses && valid; i++ { if visited[i] == 0 { findOrderFunc(i) } } if !valid { return []int{} } left := 0 right := len(result) - 1 for left < right { result[left], result[right] = result[right], result[left] left++ right-- } return result } //leetcode submit region end(Prohibit modification and deletion)
import React, { Fragment } from "react"; import useVisualMode from "../../hooks/useVisualMode"; import "./styles.scss"; import Header from "./Header"; import Show from "./Show"; import Empty from "./Empty"; import Form from "./Form"; import Status from "./Status"; import Confirm from "./Confirm"; import Error from "./Error"; const Appointment = (props) => { const EMPTY = "EMPTY"; const SHOW = "SHOW"; const CREATE = "CREATE"; const SAVING = "SAVING"; const CONFIRM = "CONFIRM"; const DELETING = "DELETING"; const EDIT = "EDIT"; const ERROR_SAVE = "ERROR_SAVE"; const ERROR_DELETE = "ERROR_DELETE"; const { mode, transition, back } = useVisualMode( props.interview ? SHOW : EMPTY ); const onAdd = () => { transition(CREATE); }; const onCancel = () => { back(); }; const save = (name, interviewer) => { const interview = { student: name, interviewer, }; transition(SAVING); Promise.resolve(props.bookInterview(props.id, interview)) .then(() => transition(SHOW, true)) .catch((error) => { transition(ERROR_SAVE, true); console.log("SAVE ERROR: ", error); }); }; const deleteAppointment = (id) => { transition(DELETING); Promise.resolve(props.cancelInterview(props.id)) .then(() => transition(EMPTY, true)) .catch((error) => { transition(ERROR_SAVE, true); console.log("SAVE ERROR: ", error); }); }; return ( <article className="appointment"> <Header time={props.time} /> {mode === EMPTY && <Empty onAdd={onAdd} />} {mode === SHOW && ( <Show student={props.interview.student} interviewer={props.interview.interviewer} onDelete={() => transition(CONFIRM)} onEdit={() => transition(EDIT)} /> )} {mode === CREATE && ( <Form interviewers={props.interviewers} onCancel={onCancel} onSave={save} /> )} {mode === SAVING && <Status message="Saving" />} {mode === CONFIRM && ( <Confirm message="Are you sure you want to delete?" onConfirm={deleteAppointment} onCancel={onCancel} /> )} {mode === DELETING && <Status message="Deleting" />} {mode === EDIT && ( <Form name={props.interview.student} interviewer={props.interview.interviewer.id} interviewers={props.interviewers} onCancel={back} onSave={save} /> )} {mode === ERROR_SAVE && ( <Error message="Error: Unable to save" onClose={back} /> )} {mode === ERROR_DELETE && ( <Error message="Error: Unable to delete" onClose={back} /> )} </article> ); } export default Appointment;
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <meta name="format-detection" content="email=no,telephone=no,address=no"> <title>=^.^=</title> <style> body {margin: 0;} </style> </head> <body> <div style="position: absolute; color: #fff"> <label><input type="checkbox" onchange="cameraControls.verticalDragToForward = this.checked">vertical drag to move forward</label> <br> <label><input type="checkbox" onchange="cameraControls.dollyToCursor = this.checked">dolly to cursor</label> <br> <label><input type="checkbox" onchange="cameraControls.infinityDolly = this.checked">infinity dolly</label> <br> <br> <button onclick="cameraControls.rotate( 45 * THREE.MathUtils.DEG2RAD, 0, true )">rotate theta 45deg</button> <button onclick="cameraControls.rotate( -90 * THREE.MathUtils.DEG2RAD, 0, true )">rotate theta -90deg</button> <button onclick="cameraControls.rotate( 360 * THREE.MathUtils.DEG2RAD, 0, true )">rotate theta 360deg</button> <button onclick="cameraControls.rotate( 0, 20 * THREE.MathUtils.DEG2RAD, true )">rotate phi 20deg</button> <br> <button onclick="cameraControls.truck( 1, 0, true)">truck( 1, 0 )</button> <button onclick="cameraControls.truck( 0, 1, true)">truck( 0, 1 )</button> <button onclick="cameraControls.truck( -1, -1, true )">truck( -1, -1 )</button> <br> <button onclick="cameraControls.dolly( 1, true )">dolly 1</button> <button onclick="cameraControls.dolly( -1, true )">dolly -1</button> <br> <button onclick="cameraControls.zoom( cameraControls.camera.zoom / 2, true )">zoom `cameraControls.camera.zoom / 2`</button> <button onclick="cameraControls.zoom( -cameraControls.camera.zoom / 2, true )">zoom `- cameraControls.camera.zoom / 2`</button> <br> <button onclick="cameraControls.moveTo( 3, 5, 2, true )">move to( 3, 5, 2 )</button> <button onclick="cameraControls.fitToBox( mesh, true )">fit to the bounding box of the mesh</button> <br> <button onclick="cameraControls.setPosition( -5, 2, 1, true )">move to ( -5, 2, 1 )</button> <button onclick="cameraControls.setTarget( 3, 0, -3, true )">look at ( 3, 0, -3 )</button> <button onclick="cameraControls.setLookAt( 1, 2, 3, 1, 1, 0, true )">move to ( 1, 2, 3 ), look at ( 1, 1, 0 )</button> <br> <button onclick="cameraControls.reset( true )">reset</button> <button onclick="cameraControls.saveState()">saveState</button> <br> <button onclick="cameraControls.enabled = false;">disable mouse/touch controls</button> <button onclick="cameraControls.enabled = true;">enable mouse/touch controls</button> </div> <script type="module"> import * as THREE from 'https://cdn.skypack.dev/three@0.134.0/build/three.module.js'; import CameraControls from 'https://cdn.skypack.dev/camera-controls'; CameraControls.install( { THREE } ); const clock = new THREE.Clock(); const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setAnimationLoop( animation ); document.body.appendChild( renderer.domElement ); const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.01, 10 ); camera.position.set( 0, 1, 3 ); const controls = new CameraControls( camera, renderer.domElement ); const gridHelper = new THREE.GridHelper( 5, 10 ); scene.add( gridHelper ); const geometry = new THREE.BoxGeometry( 0.5, 0.5, 0.5 ); const material = new THREE.MeshNormalMaterial(); const mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); function animation() { const delta = clock.getDelta(); controls.update( delta ); renderer.render( scene, camera ); } window.THREE = THREE; window.mesh = mesh; window.cameraControls = controls; </script> </body> </html>
package org.example; /*-------------------------------------*/ /* SID: 2267684 - TEAM: TECH ACHIEVERS */ /*-------------------------------------*/ import java.io.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; public class RegistrationManager { // Define private fields to store user registration information private final String firstname; private final String lastname; private final String email; private final String username; private final String password; // Constructor to initialize user registration information public RegistrationManager(String firstName, String lastName, String email, String username, String password) { this.firstname = firstName; this.lastname = lastName; this.email = email; this.username = username; this.password = password; } // Getter methods for accessing user registration information public String getFirstName() { return firstname; } public String getLastName() { return lastname; } public String getEmail() { return email; } public String getUsername() { return username; } public String getPassword() { return password; } // Static inner class to handle user registration data public static class UserRegistration { // Map to store user accounts (username -> account type) public static final Map<String, Integer> userAccounts = new HashMap<>(); // Static map to store user accounts // Static variable to store the currently logged-in user's username private static String currentUser; // Variable to store the currently logged-in user's username // Method to retrieve currently logged-in user's username public static String getCurrentUser() { return currentUser; // Returning the currently logged-in user's username } // Method to set the currently logged-in user's username public static void setCurrentUser(String username) { currentUser = username; // Setting the currently logged-in user's username } } public static RegistrationManager registerUser() { LoginManager loginManager = new LoginManager(); // Creating an instance of LoginManager System.out.println("\n-- REGISTRATION --"); Scanner sc = new Scanner(System.in); // Creating Scanner object for user input System.out.print("Enter Firstname: "); // Prompting user to enter first name String firstname = getStringOnly(sc); // Calling method to get only letters for first name System.out.print("Enter Lastname: "); // Prompting user to enter last name String lastname = getStringOnly(sc); // Calling method to get only letters for last name String email; do { System.out.print("Enter email: "); // Prompting user to enter email email = sc.nextLine(); // Reading user input for email if (!isValidEmail(email)) { // Checking if the entered email is valid System.out.println("Invalid email format. Please enter a valid email."); // Displaying error message for invalid email format } } while (!isValidEmail(email)); // Loop until a valid email is entered System.out.print("Enter username: "); // Prompting user to enter username String username = sc.nextLine(); System.out.print("Enter password: "); // Prompting user to enter password String password = sc.nextLine(); // Select account type for the user int accountType = TypeOfAccount.accountSelection(); // Calling method to select account type System.out.println("Registration successful!"); // Displaying registration success message RegistrationManager newUser = new RegistrationManager(firstname, lastname, email, username, password); // Creating a new user instance RegistrationManager.saveProfile(newUser); // Saving user profile // Set the current user before saving profile and login data UserRegistration.setCurrentUser(username); // Setting the current user // Save user data and login credentials LoginManager.users.put(username, password); // Saving username and password to users map UserRegistration.userAccounts.put(username, accountType); // Saving username and account type to userAccounts map LoginManager.saveUserData(); // Saving user data // Provide options to go back to the menu or exit int selection; do { System.out.println("\n\n1. Go back to menu\n2. Exit"); // Displaying menu options System.out.println("Enter Input: "); // Prompting user to enter input // Check if the input is a number while (!sc.hasNextInt()) { // Loop until user enters a number System.out.println("Please enter a number."); // Displaying error message for non-numeric input sc.next(); // Consume the invalid input } selection = sc.nextInt(); // Reading user input sc.nextLine(); // Consume newline character if (selection == 1) { // If user chooses to go back to the menu Main main = new Main(); // Creating an instance of Main main.Menu(loginManager); // Displaying the menu } else if (selection != 2) { // If user chooses an invalid option System.out.println("Invalid input. Please enter 1 or 2."); // Displaying error message for invalid input } } while (selection != 2); // Loop until user chooses to exit System.out.println("Thank you for using our System!"); // Exit the program System.exit(0); // Exiting the program return newUser; // Returning the newly registered user } // Method to validate email format public static boolean isValidEmail(String email) { String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,7}$"; // Regular expression for email validation return email.matches(emailRegex); // Checking if email matches the regex pattern } // Method to input string only public static String getStringOnly(Scanner sc) { String input; do { input = sc.nextLine(); // Reading user input if (!input.matches("^[a-zA-Z\\s]+$")) { // Checking if input contains only letters and spaces System.out.print("Please enter only letters and spaces: "); // Displaying error message for non-letter/space input } } while (!input.matches("^[a-zA-Z\\s]+$")); // Loop until input contains only letters and spaces return input; // Returning the validated input } // Method to save user profile data to a text file public static void saveProfile(RegistrationManager user) { // Get the current working directory Path userPath = Paths.get(System.getProperty("user.dir")); // Getting current working directory // Write user profile data to a text file if (user != null) { // Checking if user object is not null try (PrintWriter writer = new PrintWriter(new FileWriter(userPath + "\\src\\main\\java\\org\\example\\Profile_UserData\\" + user.getUsername() + "_RegistrationData.txt"))) { // Creating PrintWriter to write to file writer.println("Username: " + user.getUsername()); // Writing username to file writer.println("First Name: " + user.getFirstName()); // Writing first name to file writer.println("Last Name: " + user.getLastName()); // Writing last name to file writer.println("Email: " + user.getEmail()); // Writing email to file writer.println("Password: " + user.getPassword()); // Writing password to file writer.println(); // Adding an empty line for separation System.out.println("Profile saved for username: " + user.getUsername()); // Displaying success message } catch (IOException e) { // Handling IO exception System.err.println("Error saving profile: " + e.getMessage()); // Displaying error message } } } // Method to load user profile data from a text file public static void loadProfile() { // Get the current working directory Path userPath = Paths.get(System.getProperty("user.dir")); // Getting current working directory String username = UserRegistration.getCurrentUser(); // Getting current user's username StringBuilder profileData = new StringBuilder(); // Creating StringBuilder to store profile data // Read user profile data from a text file try (BufferedReader br = new BufferedReader(new FileReader(userPath + "\\src\\main\\java\\org\\example\\Profile_UserData\\" + username + "_RegistrationData.txt"))) { // Creating BufferedReader to read from file String line; while ((line = br.readLine()) != null) { // Looping through each line in the file profileData.append(line).append("\n"); // Appending each line to StringBuilder } } catch (FileNotFoundException e) { // Handling file not found exception System.out.println("Profile not found for username: " + username); // Displaying message for profile not found } catch (IOException e) { // Handling IO exception System.err.println("Error reading profile: " + e.getMessage()); // Displaying error message } // Display user profile data if (profileData.length() > 0) { // Checking if profile data exists System.out.println("\nRegistration details for " + username + ":"); // Displaying username System.out.println(profileData); // Displaying profile data } } }
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <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>jhkimblog - main index</title> <th:block th:replace="main/index-head::header"></th:block> </head> <body> <!-- Navigation --> <th:block th:replace="main/index-nav::nav"></th:block> <!-- Page Header --> <header class="masthead" style="background-image: url('../img/home-bg.jpg')"> <div class="overlay"></div> <div class="container"> <div class="row"> <div class="col-lg-8 col-md-10 mx-auto"> <div class="site-heading"> <h1>Blog List</h1> <span class="subheading">블로그 목록</span> </div> </div> </div> </div> </header> <!-- Main Content --> <div class="container"> <form class="form" th:action="@{'/blogs/list/search'}" th:method="get"> <div class="form-group row justify-content-left"> <div class="form-group" style="padding-right:10px"> <select class="form-control form-control-sm" name="searchType"> <option value="title">제목</option> <option value="name">작성자</option> </select> </div> <div class="form-group w-auto" style="padding-right:10px"> <input type="text" class="form-control form-control-sm" name="search" id="search"/> </div> <div> <button class="btn btn-sm btn-primary" type="submit">검색</button> </div> </div> </form> </div> <div class="row"> <div class="col-lg-8 col-md-10 mx-auto"> <th:block th:unless="${session.name == null}"> <div class="text-right"> <a class="btn btn-primary float-right" th:href="@{'/blogs/create-form'}">New Post</a> </div> </th:block> <div th:each="blog : ${blogList}"> <div class="post-preview"> <a th:href="@{'/blogs/{id}'(id=${blog.id})}"> <h2 class="post-title"> <th:block th:text="${blog.title}"></th:block> </h2> <h3 class="post-subtitle"> <th:block th:text="${blog.content}"></th:block> </h3> </a> <p class="post-meta">Posted by <a href="#"><th:block th:text="${blog.b201712015ger}"></th:block></a> on <th:block th:text="${blog.reg_date_time}"></th:block></p> </div> <hr> </div> <div class="pagination"> <a th:href="@{'/blogs/list?page=1'}">&laquo;</a> <th:block th:with="start = ${pagination.startPage}, end = ${pagination.endPage}"> <div th:each = "pageButton : ${#numbers.sequence(start, end)}"> <a th:href="@{'/blogs/list?page={page}' (page = ${pageButton})}" th:text="${pageButton}"></a> </div> </th:block> <!-- <a class="active" href="#">2</a>--> <a th:href="@{'/blogs/list?page={page}'(page=${pagination.totalPageCnt})}">&raquo;</a> </div> <!-- Pager <div class="clearfix"> <a class="btn btn-primary float-right" href="#">Older Posts &rarr;</a> </div> --> </div> </div> </div> <hr> <!-- Footer --> <th:block th:replace="main/index-footer::footer"></th:block> </body> <style> /* Pagination links */ .pagination a { color: black; float: left; padding: 8px 16px; text-decoration: none; transition: background-color .3s; } /* Style the active/current link */ .pagination a.active { background-color: dodgerblue; color: white; } /* Add a grey background color on mouse-over */ .pagination a:hover:not(.active) {background-color: #ddd;} </style> </html>
import React, { useState } from 'react'; import { useForm } from "react-hook-form"; import { yupResolver } from '@hookform/resolvers/yup'; import * as yup from "yup"; import { useNavigate } from 'react-router-dom' import { Alert, Avatar, Box, Button, Container, CssBaseline, Grid, Link, TextField, Typography } from '@mui/material'; import LockOutlinedIcon from '@mui/icons-material/LockOutlined'; import * as Constants from "../shared/constants"; import { forgotPassword } from '../supabaseClient'; interface IFormInputs { email: string, }; const schema = yup.object({ email: yup.string().required('Email is required').email('Email not valid'), }) export default function ForgotPassword() { const navigate = useNavigate(); const [error, setError] = useState(''); const { register, handleSubmit, formState: { errors } } = useForm<IFormInputs>({ resolver: yupResolver(schema) }); const onSubmit = async (formData: IFormInputs) => { const { email } = formData; const { data, error } = await forgotPassword(email); if (error) { setError(error.message); } else { navigate('/forgot-password-submit'); } } return ( <Container component="main" maxWidth="xs"> <CssBaseline /> <Box sx={{ marginTop: 8, display: 'flex', flexDirection: 'column', alignItems: 'center', }} > <Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}> <LockOutlinedIcon /> </Avatar> <Typography component="h1" variant="h5"> {Constants.FORGOT_PASSWORD} </Typography> <Box component="form" noValidate onSubmit={handleSubmit(onSubmit)} sx={{ mt: 1 }}> <TextField error={!!errors.email} required fullWidth id="email" label="Email Address" autoComplete="email" helperText={errors.email?.message} {...register("email")} /> {error && <Alert severity="error" sx={{ mt: 3 }}>{error}</Alert>} <Button type="submit" fullWidth variant="contained" sx={{ mt: 3, mb: 2 }} > {Constants.FORGOT_PASSWORD} </Button> <Grid container justifyContent="flex-end"> <Grid item> <Link href="/login" variant="body2"> {"Back to Login"} </Link> </Grid> </Grid> </Box> </Box> </Container> ); }
const path = require('path'); // 운영체제 마다 표현되는 경로가 다름 console.log(__dirname); console.log(__filename); console.log(path.sep); // 경로 구분자 console.log(path.delimiter); // 환경변수 구분자 // basename console.log(path.basename(__filename)); console.log(path.basename(__filename, '.js')); // dirname console.log(path.dirname(__filename)); // extension console.log(path.extname(__filename)); // parse const parsed = path.parse(__filename); console.log(parsed); const str = path.format(parsed); console.log(str); // isAbsolute console.log('isAbsolute?', path.isAbsolute(__dirname)); console.log('isAbsolute?', path.isAbsolute('../')); // normalize console.log(path.normalize('./folder//////sub')); // join console.log(__dirname + path.sep + 'image'); console.log(path.join(__dirname, 'image'));
import { html, render } from 'lit'; import type { LifeCycleFn } from 'single-spa'; // Ideally these types and the getMountPoint function would be factored into some shared JavaScript // package. type CustomAppProps = { appBaseUri: string; }; type MicroFrontendLifecycleFn = LifeCycleFn<CustomAppProps>; function getMountPoint(appName: string) { return document.getElementById(`single-spa-application:${appName}`); } function getResourceBaseUri() { // Build the resource base URI from this JavaScript module's URL. Note that Blazor requires base // URIs to have a trailing slash in order for the Blazor runtime to correctly resolve relative // resource URLs referenced by the Blazor startup script. const iLastSlash = import.meta.url.lastIndexOf('/'); return import.meta.url.substring(0, iLastSlash + 1); } function getDocumentStyleSheet() { // Adapted from: https://developer.mozilla.org/en-US/docs/Web/API/StyleSheetList#get_all_css_rules_for_the_document_using_array_methods // Doesn't include additional error handling for brevity sake. // // Arguably a smarter and more resource efficient way of handling this would be for the app shell // to construct the CSSStyleSheet object representing the app's "global" styles that can be merged // in with a micro frontend via adoptedStyleSheets. The app shell could then pass that sheet down // as a custom prop in the single-spa lifecycle callbacks. const sheetContents = Array.from(document.styleSheets) .flatMap((sheet) => Array.from(sheet.cssRules)) .map((rule) => rule.cssText) .join(''); const sheet = new CSSStyleSheet(); sheet.replaceSync(sheetContents); return sheet; } async function getBlazorStyleSheet(sheetResourceName: string) { // NOTE: Error handling deliberately removed for brevity sake. const resourceBaseUri = getResourceBaseUri(); const sheetUri = new URL(sheetResourceName, resourceBaseUri).href; const sheet = new CSSStyleSheet(); const sheetContents = await fetch(sheetUri); sheet.replaceSync(await sheetContents.text()); return sheet; } // .NET and Blazor runtime objects created by this micro frontend's startup script. let blazor: any = undefined; // @ts-ignore 'dotnet' is declared but its value is never read. let dotnet: any = undefined; // The actual single-spa lifecycle callbacks. export const bootstrap: MicroFrontendLifecycleFn = async ({ name: appName, appBaseUri, }) => { const resourceBaseUri = getResourceBaseUri(); // Import the Blazor startup script responsible for loading the .NET runtime in the browser along // with the actual Blazor runtime. Both runtime objects are encapsulated within the startup // script and are exposed on the window object after the script has executed. We will want to // capture a reference to these objects after the script has loaded. // // NOTE: There is quite possibly a race condition here if more than one Blazor-based micro // frontend is loading at the same time using this approach. Consider if two different // Blazor-based micro frontends (M1 and M2) have their bootstrap callback invoked back-to-back. M1 // will start its import of its Blazor startup script, and its continuation will be set to run // sometime after the script has been imported and executed. // // While M1 is importing, M2 could have the initial part of its bootstrap callback scheduled and // executed. It, too, will start the import of its Blazor startup script. // // Suppose the following sequence occurs: // // 1. M1 fetches its startup script // 2. M2 fetches its startup script // 3. M1 executes its startup script, writing to the window.Blazor and window.DotNet objects. // 4. M2 executes its startup script, writing to the window.Blazor and window.DotNet objects. // 5. M1's bootstrap continuation executes, capturing the window.Blazor and window.DotNet objects. // // In this case, M1 ends up with references to the wrong objects. // // It is unclear to me if this behavior would actually occur given current browser or JavaScript // engine implementations. However, it seems plausible and would highlight a constraint currently // present with Blazor-based micro frontends using this approach. However, this seems like it // should be something that could be addressed relatively easily on the Blazor side by making it // possible to retrieve the DotNet and Blazor objects through some mechanism other than the global // window object. const blazorStartupScriptUrl = new URL( '_framework/blazor.webassembly.js', resourceBaseUri ).href; await import(blazorStartupScriptUrl); blazor = window.Blazor; dotnet = window.DotNet; // Technically we could probably return the Promise returned by start, but awaiting here would // allow us to do some additional one-time initialization inside our Blazor micro frontend, such // as calling static methods that capture references to JavaScript objects we want to reference // from Blazor's JSInterop. console.log(appBaseUri); await blazor.start({ appBaseUri, resourceBaseUri, resourceCacheName: appName, // Assume the resources are served from a different origin that allows access to any origin via // a wildcard. In that case, we CANNOT send credentials to the resource origin. resourceFetchCredentialMode: 'omit', }); }; export const mount: MicroFrontendLifecycleFn = async ({ name: appName }) => { // Enable the Blazor micro frontend's navigation listeners and force the Blazor to resync with the // page's current URL before mounting the application. blazor.addNavigationEventListeners(); blazor.navigateTo(document.location.href, { replaceHistoryEntry: true, forceLoad: false, }); const mountPoint = getMountPoint(appName); if (mountPoint) { // In order to incorporate the Blazor micro frontend's styles, we fetch them from the resource // origin. We then create a new shadow root within our mount point and add the fetched styles to // the shadow root's adopted style sheets. In order to easily incorporate any "global" styles // the app shell defines within the created shadow DOM, we also pull in the document's styles. // We then render the Blazor micro frontend within the mount point's shadow root. // // NOTE: Safari users will need to be on 16.4 or later as supported for the adoptedStyleSheets // API and constructible style sheets was only recently implemented. // // NOTE 2: This approach presumes the Blazor micro frontend defined its styles using Blazor's // CSS isolation. That's not strictly necessary, and almost any style sheet that can be fetched // from the resource origin can be adopted (limits like not being to use @import rules in the // fetched style sheet exist currently). That said, use whatever approach makes sense for your // project. const shadowRoot = mountPoint.attachShadow({ mode: 'open' }); shadowRoot.adoptedStyleSheets = [ getDocumentStyleSheet(), await getBlazorStyleSheet('CatalogApp.styles.css'), ]; render(html`<mfe-catalog-app></mfe-catalog-app>`, shadowRoot); } }; export const unmount: MicroFrontendLifecycleFn = async ({ name: appName }) => { const mountPoint = getMountPoint(appName); if (mountPoint) { mountPoint.innerHTML = ''; } // Disable Blazor's navigation event listeners so that they don't try to process routes meant for // other micro frontends. blazor.removeNavigationEventListeners(); };
1. **You**: I want my shopping cart that when I click on it opens on the left side of the page like other online store sites such as skatedeluxe 2. **ChatGPT**: To create a shopping cart that opens on the left side of the page when clicked, you'll need to use HTML, CSS, and JavaScript. Here's a step-by-step guide on how you can achieve this: 1. First, create an HTML structure for your shopping cart. You can use a `<div>` element to contain the cart items. ``` <div class="cart"> <h3>Shopping Cart</h3> <ul class="cart-items"> <!-- List of cart items will be displayed here --> </ul> <p class="total">Total: $0</p> </div> ``` 2. Next, use CSS to position the shopping cart on the left side of the page and hide it by default. You can use the `transform` property to move the cart off the screen. ``` .cart { position: fixed; top: 0; left: -100%; width: 300px; height: 100%; background-color: #fff; transform: translateX(-100%); transition: transform 0.3s ease-in-out; z-index: 9999; } .cart.active { transform: translateX(0); } ``` 3. Now, you need to add JavaScript code to toggle the shopping cart. You can add a click event listener to the cart icon, and toggle a CSS class to show or hide the cart. ``` const cart = document.querySelector('.cart'); const cartIcon = document.querySelector('.cart-icon'); cartIcon.addEventListener('click', () => { cart.classList.toggle('active'); }); ``` 4. Finally, you can add some logic to display the cart items and update the total price. You can use JavaScript to add and remove cart items, and update the total price based on the selected items. ``` const cartItems = document.querySelector('.cart-items'); const total = document.querySelector('.total'); function addToCart(item) { // Add the item to the list of cart items const li = document.createElement('li'); li.textContent = item.name + ': $' + item.price; cartItems.appendChild(li); // Update the total price const currentTotal = parseFloat(total.textContent.slice(7)); total.textContent = 'Total: $' + (currentTotal + item.price); } function removeFromCart(item) { // Remove the item from the list of cart items const itemToRemove = Array.from(cartItems.children).find(li => li.textContent.startsWith(item.name)) if (itemToRemove) { cartItems.removeChild(itemToRemove); } // Update the total price const currentTotal = parseFloat(total.textContent.slice(7)); total.textContent = 'Total: $' + (currentTotal - item.price); } ``` This is the basic implementation of a shopping cart that opens on the left side of the page. You can customize the styling and add more functionality based on your requirements. 3. **You**: o meu projeto é em reac 4. **ChatGPT**: Entendi, React é uma biblioteca JavaScript muito utilizada no desenvolvimento de aplicações web. Com ela, é possível criar interfaces de usuário de forma mais fácil e eficiente através da manipulação do DOM (Document Object Model) de maneira mais conveniente. Para começar a trabalhar com React, é importante entender alguns conceitos básicos, como: 1. Componentes: são blocos de código que representam partes de uma interface de usuário. Podem ser reutilizados em diferentes partes da aplicação. 2. Propriedades: são atributos que um componente recebe. Permitem que as informações sejam passadas entre componentes. 3. Estado: é onde as informações são armazenadas e gerenciadas dentro de um componente. 4. Renderização: é o processo de exibição de um componente na interface do usuário. Com esses conceitos em mente, você pode começar a desenvolver seu projeto em React. Para criar um novo projeto, você pode utilizar o Create React App, que é uma ferramenta que automatiza a criação de uma estrutura básica de um projeto React. Uma vez que o projeto esteja criado, você pode começar a desenvolver seus componentes, definindo suas propriedades e estados, e criando as funções necessárias para manipular o DOM e renderizar o resultado na tela. Para ajudar na organização do código, é possível utilizar Hooks, que são funções que permitem utilizar o estado e outras funcionalidades do React em componentes funcionais. Além disso, é importante conhecer outras bibliotecas e ferramentas que podem ser utilizadas em conjunto com o React, como React Router para navegação entre páginas, styled-components para estilização dos componentes, e Redux para gerenciamento de estados de forma mais avançada. Espero que essas informações te ajudem a começar seu projeto em React. Caso tenha alguma dúvida específica ou precise de ajuda em algum ponto do desenvolvimento, não hesite em perguntar. 5. **You**: import { Offcanvas, Stack } from "react-bootstrap" import { useShoppingCart } from "../context/ShoppingCartContext" import { formatCurrency } from "../utilities/formatCurrency" import { CartItem } from "./CartItem" import storeItems from "../data/items.json" type ShoppingCartProps = { isOpen: boolean } export function ShoppingCart({ isOpen }: ShoppingCartProps) { const { closeCart, cartItems } = useShoppingCart() return ( <Offcanvas show={isOpen} onHide={closeCart} placement="end"> <Offcanvas.Header closeButton> <Offcanvas.Title>Cart</Offcanvas.Title> </Offcanvas.Header> <Offcanvas.Body> <Stack gap={3}> {cartItems.map(item => ( <CartItem key={item.id} {...item} /> ))} <div className="ms-auto fw-bold fs-5"> Total{" "} {formatCurrency( cartItems.reduce((total, cartItem) => { const item = storeItems.find(i => i.id === cartItem.id) return total + (item?.price || 0) * cartItem.quantity }, 0) )} </div> </Stack> </Offcanvas.Body> </Offcanvas> ) faz com que esse codigo funcione para javascript 6. **ChatGPT**: To convert the given code to JavaScript, you simply have to remove the type definitions and import statements using the following syntax: ``` function ShoppingCart({ isOpen }) { const { closeCart, cartItems } = useShoppingCart(); return ( <Offcanvas show={isOpen} onHide={closeCart} placement="end"> <Offcanvas.Header closeButton> <Offcanvas.Title>Cart</Offcanvas.Title> </Offcanvas.Header> <Offcanvas.Body> <Stack gap={3}> {cartItems.map((item) => ( <CartItem key={item.id} {...item} /> ))} <div className="ms-auto fw-bold fs-5"> Total{" "} {formatCurrency( cartItems.reduce((total, cartItem) => { const item = storeItems.find((i) => i.id === cartItem.id); return total + (item?.price || 0) * cartItem.quantity; }, 0) )} </div> </Stack> </Offcanvas.Body> </Offcanvas> ); } ``` Note: You also need to make sure that the required dependencies and packages are installed and imported correctly in your project before running the code. 7. **You**: export 'default' (imported as 'Carrinho') was not found in './Carrinho' (module has no exports) ERROR [eslint] src\Carrinho.js Line 2:36: 'useShoppingCart' is not defined no-undef Line 5:6: 'Offcanvas' is not defined react/jsx-no-undef Line 6:8: 'Offcanvas' is not defined react/jsx-no-undef Line 7:10: 'Offcanvas' is not defined react/jsx-no-undef Line 9:8: 'Offcanvas' is not defined react/jsx-no-undef Line 10:10: 'Stack' is not defined react/jsx-no-undef Line 12:14: 'CartItem' is not defined react/jsx-no-undef Line 16:14: 'formatCurrency' is not defined no-undef 8. **ChatGPT**: The error message is informing us that there is a problem with the exports in the './Carrinho' module. It seems that you are trying to import the default export from this module using the syntax `import Carrinho from './Carrinho'` and it's not working. To solve this issue, first, you have to make sure that the './Carrinho' module actually exports something as the default export. If it doesn't, you can either change the import statement to import a named export or add a default export to the './Carrinho' module. Regarding the eslint errors, the first one is telling us that `useShoppingCart` is not defined, meaning that it's probably not imported from its correct module. You can try to import it using `import { useShoppingCart } from 'use-shopping-cart'` if you haven't done it already. The other eslint errors are telling us that some variables are not defined, meaning that you should import or define them before using them, for example: `Offcanvas`, `Stack`, `CartItem`, and `formatCurrency`. Make sure they are imported from their correct modules or defined before being used. 9. **You**: nao funciona, vou mandar uma pagina que leva para o carrinho e tente arranjar o problema da pagina de carrinhos import React, { useState } from 'react'; import { useParams, useNavigate } from 'react-router-dom'; import ProdutosData from './Produto.json'; import './App.css'; import { Col, Row, Button } from 'react-bootstrap'; function ProductDetails() { const { id } = useParams(); const navigate = useNavigate(); const product = ProdutosData.Produtos.find(skateboard => skateboard.id === parseInt(id)); const [isAddedToCart, setIsAddedToCart] = useState(false); const handleAddToCart = () => { const cartItem = { id: product.id, name: product.model, price: product.price, img: product.imgsrc }; const existingCartItems = JSON.parse(localStorage.getItem('carrinho')) || []; const updatedCartItems = [...existingCartItems, cartItem]; localStorage.setItem('carrinho', JSON.stringify(updatedCartItems)); setIsAddedToCart(true); navigate('/carrinho'); }; return ( <div> <div className="product-container"> {product && ( <Row className="row-2"> <Col> <div className="product-image product-details"> <img src={product.imgsrc} alt={product.model} /> </div> </Col> <Col> <div className="product-info"> <h1>{product.brand}</h1> <h2>{product.model}</h2> <p>{product.price}</p> <p>{product.description}</p> {!isAddedToCart ? ( <Button variant="primary" onClick={handleAddToCart}> <i class='bx bx-cart'></i> </Button> ) : ( <p>Adicionado ao Carrinho</p> )} </div> </Col> </Row> )} </div> <section class="contact"> <div class="contact-info"> <div class="first-info"> <img src='/imagens/EspoSkate.png' /> <br></br> <a href='https://www.google.com/maps/place/C%C3%A2mara+Municipal+de+Esposende/@41.5314358,-8.7801767,18.96z/data=!4m14!1m7!3m6!1s0xd244bba6d8c44a1:0xd3bfe8a5d9eb0d42!2sC%C3%A2mara+Municipal+de+Esposende!8m2!3d41.531351!4d-8.7806344!16s%2Fg%2F1tfjmdhm!3m5!1s0xd244bba6d8c44a1:0xd3bfe8a5d9eb0d42!8m2!3d41.531351!4d-8.7806344!16s%2Fg%2F1tfjmdhm'>Praça do Município,<br />4740-223 Esposende</a> <p>966 597 688</p> <p>esposkate05@gmail.com</p> <div class="social-icon"> <a href="https://www.facebook.com/profile.php?id=100092639252098"><i class='bx bxl-facebook'></i></a> <a href="https://www.instagram.com/esposendeskate/"><i class='bx bxl-instagram-alt' ></i></a> <a href="https://twitter.com/EsposendeSkate"><i class='bx bxl-twitter' ></i></a> </div> </div> <div class="second-info"> <h4>Suporte</h4> <a href='./Contact'>Contacta-nos</a> <p> </p> <a href='./Privacidade'>Privacidade</a> </div> <div class="fourth-info"> <h4>Empresa</h4> <a href='./AboutUs'>Sobre</a> <p> </p> <a href='./Login'>Login</a> </div> <div class="five"> <h4>Subscreve</h4> <p>Receba atualizações,Descontos, altas promoções no seu email</p> <p>Receive updates, discounts, high promotions in your email</p> <p>Recevez des mises à jour, des réductions, des promotions élevées dans votre e-mail</p> </div> </div> </section> </div> ); } export default ProductDetails; 10. **ChatGPT**: It's hard to identify the problem without knowing what errors or issues you're experiencing. However, here are a few suggestions to help you debug the page: 1. Check if you have imported the necessary dependencies (e.g., React, React Router, React Bootstrap) in your file. Make sure that you have installed them through npm or yarn. 2. Verify that the `ProdutosData` JSON file is being imported correctly and contains the necessary data. You can add a `console.log` statement to inspect the value of `ProdutosData.Produtos`. 3. Make sure that the `id` parameter is being passed correctly to the `ProductDetails` component. You can add a `console.log` statement to see the value of `id`. 4. Check if the `handleAddToCart` function is being called when the "Adicionar ao Carrinho" button is clicked. You can add a `console.log` statement inside the function to test it. 5. Ensure that the `localStorage` API is being used correctly to store and retrieve cart items. You can use the developer tools in your browser to inspect the local storage data. Hope these tips help you identify and fix the issues on your cart page. 11. **You**: import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import Button from 'react-bootstrap/Button'; function Carrinho() { const [items, setItems] = useState([]); useEffect(() => { const carrinho = JSON.parse(localStorage.getItem('carrinho')); if (carrinho) { setItems(carrinho); } }, []); const handleClearCart = () => { setItems([]); localStorage.removeItem('carrinho'); }; const renderCartItems = () => { return items.map(item => ( <div key={item.id} className="cart-item"> <Link to={`/produto/${item.id}`}> <img src={item.img} alt={item.name} /> </Link> <div className="cart-item-details"> <h3>{item.name}</h3> <p>{item.price}</p> </div> </div> )); }; return ( <div> <h1>Carrinho de compras</h1> {items.length > 0 ? ( <div className="cart-items-container">{renderCartItems()}</div> ) : ( <p>O carrinho está vazio.</p> )} <Button variant="danger" onClick={handleClearCart}> Limpar Carrinho </Button> </div> ); } export default Carrinho; personalix 12. **You**: import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import Button from 'react-bootstrap/Button'; function Carrinho() { const [items, setItems] = useState([]); useEffect(() => { const carrinho = JSON.parse(localStorage.getItem('carrinho')); if (carrinho) { setItems(carrinho); } }, []); const handleClearCart = () => { setItems([]); localStorage.removeItem('carrinho'); }; const renderCartItems = () => { return items.map(item => ( <div key={item.id} className="cart-item"> <Link to={`/produto/${item.id}`}> <img src={item.img} alt={item.name} /> </Link> <div className="cart-item-details"> <h3>{item.name}</h3> <p>{item.price}</p> </div> </div> )); }; return ( <div> <h1>Carrinho de compras</h1> {items.length > 0 ? ( <div className="cart-items-container">{renderCartItems()}</div> ) : ( <p>O carrinho está vazio.</p> )} <Button variant="danger" onClick={handleClearCart}> Limpar Carrinho </Button> </div> ); } export default Carrinho; personaliza esta pagina com css, é uma pagina de carrinho de compras, quero que a imagem fique no lado esquerdo, no meio o nome do produto, e depois no lado direito o preço e tambem a opçao de eleminar o produto 13. **ChatGPT**: Para personalizar essa página com css, você pode seguir os seguintes passos: 1. Adicione uma classe para a div de cada item no carrinho, para que possa ser facilmente estilizada: ``` <div key={item.id} className="cart-item"> ``` 2. Use Flexbox para alinhar os elementos dentro da div `.cart-item`. Adicione o seguinte código de css ao seu arquivo .css: ``` .cart-item { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; } .cart-item img { width: 100px; margin-right: 20px; } .cart-item-details { flex: 1; } .cart-item-details h3 { margin: 0; font-size: 20px; margin-bottom: 10px; } .cart-item-details p { margin: 0; } .cart-item button { background-color: red; color: white; border: none; padding: 5px 10px; cursor: pointer; } ``` 3. Adicione uma classe para o botão "Limpar Carrinho": ``` <Button className="clear-cart-btn" variant="danger" onClick={handleClearCart}> ``` 4. Adicione o seguinte código de css para o botão "Limpar Carrinho": ``` .clear-cart-btn { margin-top: 20px; } ``` Dessa forma, a imagem ficará no lado esquerdo, o nome do produto ficará no centro e o preço e botão de eliminação ficarão no lado direito. Além disso, a página agora está personalizada com cores e estilos, tornando-a mais atraente para o usuário. 14. **You**: a imagem ficou muito para o lado esquerdo e os texto nao estao separados, usas table ou rows faz da maneira que achares mais eficaz 15. **ChatGPT**: Não entendi bem a sua solicitação. Você poderia fornecer mais informações ou contexto sobre o que precisa ser feito na imagem e no texto? Isso me ajudaria a fornecer uma resposta mais precisa e útil para você. 16. **You**: a imagem ficou colada a margem do lado esquerdo e queria ela mais distancia quanto da linha do site e dos textos 17. **ChatGPT**: Para adicionar espaço entre a imagem e a margem do site e dos textos, você pode usar a propriedade CSS `margin`. Por exemplo, se você quiser adicionar 10 pixels de espaço em torno da imagem, você pode usar o seguinte código: ```css img { margin: 10px; } ``` Você também pode especificar a margem em cada lado da imagem separadamente, usando a propriedade `margin-top`, `margin-right`, `margin-bottom` e `margin-left`. Por exemplo: ```css img { margin-top: 20px; margin-bottom: 20px; margin-left: 50px; margin-right: 50px; } ``` Nesse exemplo, a imagem terá 20 pixels de espaço acima e abaixo e 50 pixels de espaço à esquerda e à direita. Lembre-se de que você precisará ajustar os valores das margens de acordo com o layout do seu site e com o tamanho da imagem. 18. **You**: .cart-item { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; } .cart-item img { width: 100px; margin-right: 20px; } .cart-item-details { flex: 1; } .cart-item-details h3 { margin: 0; font-size: 20px; margin-bottom: 10px; } .cart-item-details p { margin: 0; } .cart-item button { background-color: red; color: white; border: none; padding: 5px 10px; cursor: pointer; } agora faz nisto e mete os textos maiores 19. **ChatGPT**: O código apresentado é um estilo CSS que define o layout visual de uma seção de carrinho de compras em um site ou aplicativo. O seletor .cart-item define as propriedades visuais do item individual no carrinho. Nesse caso, ele é exibido como um contêiner flexível com alinhamento centralizado e espaço uniforme entre os elementos. O seletor .cart-item img define a aparência da imagem do item no carrinho, definindo sua largura e margem direita. O seletor .cart-item-details define as propriedades do contêiner de detalhes do item. Nesse caso, ele ocupa todo o espaço disponível dentro do contêiner flexível pai. O seletor .cart-item-details h3 define a aparência do título do item, definindo sua fonte, tamanho e margem inferior. O seletor .cart-item-details p define a aparência da descrição do item, definindo sua margem. Por fim, o seletor .cart-item button define a aparência do botão de exclusão do item no carrinho, definindo sua cor de fundo, cor do texto, borda, preenchimento e cursor. Para ajustar o tamanho do texto em todo o layout, você pode adicionar a propriedade font-size ao seletor pai ou individualmente aos elementos conforme necessário. Por exemplo: .cart-item { font-size: 16px; /* tamanho do texto para o contêiner pai */ } .cart-item-details h3 { font-size: 24px; /* tamanho do texto para o título do item */ } .cart-item-details p { font-size: 18px; /* tamanho do texto para a descrição do item */ } .cart-item button { font-size: 16px; /* tamanho do texto para o botão de exclusão */ } 20. **You**: import React, { useState, useEffect } from 'react'; import { Link } from 'react-router-dom'; import Button from 'react-bootstrap/Button'; function Carrinho() { const [items, setItems] = useState([]); useEffect(() => { const carrinho = JSON.parse(localStorage.getItem('carrinho')); if (carrinho) { setItems(carrinho); } }, []); const handleClearCart = () => { setItems([]); localStorage.removeItem('carrinho'); }; const renderCartItems = () => { return items.map(item => ( <div key={item.id} className="cart-item"> <Link to={`/produto/${item.id}`}> <img src={item.img} alt={item.name} /> </Link> <div className="cart-item-details"> <h3>{item.name}</h3> <p>{item.price}</p> </div> </div> )); }; return ( <div> <h1>Carrinho de compras</h1> {items.length > 0 ? ( <div className="cart-items-container">{renderCartItems()}</div> ) : ( <p>O carrinho está vazio.</p> )} <Button variant="danger" onClick={handleClearCart}> Limpar Carrinho </Button> </div> ); } export default Carrinho; faz com que o item.img, item.name e o item.price fiquem distantes uma das outras na mesma linha como uma loja online 21. **ChatGPT**: Para que os elementos item.img, item.name e item.price fiquem na mesma linha, você pode usar CSS e definir as propriedades display: flex e align-items: center no elemento que contém esses três elementos, que é a div com a classe cart-item-details. A propriedade display: flex tornará os elementos filhos como um conjunto flexível de elementos, permitindo que se ajustem a diferentes tamanhos de tela, enquanto a propriedade align-items: center centralizará verticalmente os elementos na div. Portanto, você pode atualizar o seu código adicionando o seguinte CSS: .cart-item-details { display: flex; align-items: center; margin-left: 20px; //opcional para dar uma margem entre a imagem e os detalhes } Dessa forma, o item.img, item.name e o item.price ficarão na mesma linha e centralizados verticalmente, como em uma loja online. Certifique-se de adicionar esse estilo em um arquivo CSS separado ou em um bloco de estilo no cabeçalho HTML. 22. **You**: faz o codigo 23. **ChatGPT**: Claro, com prazer! Qual é a linguagem de programação que você precisa do código? E qual é o problema específico que você está tentando resolver? Por favor, forneça mais detalhes para que eu possamos começar. 24. **You**: isso é react 25. **ChatGPT**: Não, essa é uma linguagem natural, não é uma sintaxe de código. O React é uma biblioteca JavaScript usada para criar interfaces de usuário em aplicativos da web. Ele permite que os desenvolvedores criem componentes reutilizáveis ​​e dinâmicos que podem ser atualizados automaticamente quando os dados mudam. O React usa uma sintaxe especial chamada JSX, que permite que os desenvolvedores escrevam HTML-like em JavaScript. 26. **You**: faz logo o codigo ostia 27. **ChatGPT**: Peço desculpas, mas preciso entender qual é sua dúvida ou problema específico para poder ajudá-lo a escrever o código apropriado. Poderia por favor fornecer mais informações sobre seu problema ou o que precisa ser feito?
const express = require('express'); const Razorpay = require('razorpay'); const cors = require('cors'); const crypto = require('crypto') const bodyParser = require('body-parser'); const nodemailer = require('nodemailer') require("dotenv").config(); const app = express(); const PORT = process.env.PORT || '8000'; app.use(cors()); app.use(bodyParser.json()); app.post('/createOrder', (req, res) => { const razorpayInstance = new Razorpay({ key_id: process.env.RAZORPAY_ID, key_secret: process.env.RAZORPAY_SECRET }); const options = { amount: Number(req.body.money * 100), currency: "INR", } razorpayInstance.orders.create(options, (err, order) => { if (!err) res.json(order) else res.send(err); } ) }); app.post('/verifyOrder', (req, res) => { const { razorpay_payment_id, razorpay_order_id, razorpay_signature } = req.body.response; const key_secret = process.env.RAZORPAY_SECRET; let hmac = crypto.createHmac('sha256', key_secret); hmac.update(razorpay_order_id + "|" + razorpay_payment_id); const generated_signature = hmac.digest('hex'); if (razorpay_signature === generated_signature) { res.json({ success: true, message: "Payment has been verified" }) } else res.json({ success: false, message: "Payment verification failed" }) }); app.post('/sendMail', (req, res) => { let transporter = nodemailer.createTransport({ service: 'gmail', auth: { user: process.env.EMAIL, pass: process.env.PASSWORD } }); const mailOptions = { from: process.env.EMAIL, to: req.body.formData.email, subject: 'Thank You for Your Generous Donation!', text: `Dear ${req.body.formData.name},\n\n` + `Thank you so much for your generous donation of ₹${req.body.formData.money} to Unity Foundation. ` + 'Your support is instrumental in helping us achieve our mission. ' + 'We truly appreciate your commitment to making a positive impact in the community.\n\n' + 'Best regards,\n' + 'Unity Foundation Team' }; transporter.sendMail(mailOptions, function (error, info) { if (error) { console.log(error); } else { res.send(transporter.id) console.log('Email sent: ' + info.response); } }); }); app.listen(PORT, () => { console.log("Server is Listening on Port ", PORT); });
import logging from fastapi import Request from telegram import Update, Bot from telegram.ext import Application, CallbackContext, CommandHandler from configs import config from handlers import all_handlers from registries import config_registry logger = logging.getLogger(__name__) async def start(update: Update, context) -> None: logger.info(f"Update START for user: {update.effective_user}") await context.bot.send_message(chat_id=update.effective_chat.id, text="Hello!") class TelegramBot: def __init__(self): self.tg_bot: Bot | None = None self.tg_app: Application | None = None async def config(self): tokens = await config_registry.get_bot_tokens() if len(tokens) > 1: raise Exception("Too many bot tokens, Multiple bot tokens are currently not supported") if len(tokens) == 0: raise Exception("No bot token found") token = tokens[0] self.tg_bot = Bot(token.token) await self.tg_bot.initialize() self.tg_app = Application.builder().token(token.token).build() self.tg_app.add_handler(CommandHandler("start", start)) self.tg_app.add_handlers(all_handlers) await self.tg_bot.set_webhook(f"https://{config.external_url}/tapi/") await self.tg_app.initialize() await self.tg_app.start() async def put_update(self, request: Request) -> None: update = Update.de_json(await request.json(), self.tg_bot) await self.tg_app.update_queue.put(update) tg_bot = TelegramBot()
import React from "react"; import prdList from "./data.json"; import ProductList from "./ProductList"; import ProductDetail from "./ProductDetail"; import { useState } from "react"; import Cart from "./Cart"; const BTShoeShop = () => { const [productDetail, setProductDetail] = useState(prdList[0]); const [carts, setCarts] = useState([]); const handleProductDetail = (product) => { setProductDetail(product); }; const handleCarts = (product) => { console.log(product); setCarts((currentState) => { // kiểm tra lại xem trong cart đã tồn tại sp hay chưa const index = currentState.findIndex((item) => item.id === product.id); console.log(index); if (index !== -1) { //sp đã tồn tại trong carts currentState[index].cartQuantity += 1; } else { currentState.push({ ...product, cartQuantity: 1 }); // currentState.push(product); } return [...currentState]; }); }; const handleCartQuantity = (id, quantity) => { // quantity: +1 => button + // quantity: -1 => button - setCarts((currentState) => { const index = currentState.findIndex((item) => item.id === id); currentState[index].cartQuantity += quantity || 1; if (currentState[index].cartQuantity < 1) { currentState[index].cartQuantity = 1; } return [...currentState]; }); }; const handleDeleteCart = (id) => { setCarts((currentState) => { return currentState.filter((item) => item.id != id); }); }; return ( <div className="container mt-5"> <div className="d-flex justify-content-between"> <h1>BTShoeShop</h1> <button className="btn btn-outline-success" data-bs-toggle="modal" data-bs-target="#cart" > cart </button> </div> <ProductList prdList={prdList} handleProductDetail={handleProductDetail} handleCarts={handleCarts} /> {/* modal detail */} {/* <ProductDetail /> */} <ProductDetail productDetail={productDetail} /> {/* modal giỏ hàng */} <Cart carts={carts} handleCartQuantity={handleCartQuantity} handleDeleteCart={handleDeleteCart} /> </div> ); }; export default BTShoeShop;
--- title: Learn HTML. permalink: learn-html/index.html message: "I love your website but looking at the markup makes me sad. Please (re)learn HTML and make the web a better place." num: 1 --- Wait! Hear me out! I know that you can write HTML, but there’s a difference between understanding the language and being able to write semantic markup that’s beneficial to a variety of users. ### Refresh your HTML-Skills * [Beginners’ Guide To Writing Good HTML](https://websitesetup.org/html-tutorial-beginners/) (Not just for beginners) * [HTMHell](https://www.htmhell.dev/) * [Upgrade Your HTML](https://leanpub.com/upgrade-your-html)
--- hide_title: false hide_table_of_contents: false pagination_next: null pagination_prev: null --- # Date.prototype.setMinutes() The **`setMinutes()`** method sets the minutes for a specified date according to local time. ## Syntax ```js setMinutes(minutesValue) setMinutes(minutesValue, secondsValue) setMinutes(minutesValue, secondsValue, msValue) ``` ### Parameters - `minutesValue` - : An integer between 0 and 59, representing the minutes. - `secondsValue` - : Optional. An integer between 0 and 59, representing the seconds. If you specify the `secondsValue` parameter, you must also specify the `minutesValue`. - `msValue` - : Optional. A number between 0 and 999, representing the milliseconds. If you specify the `msValue` parameter, you must also specify the `minutesValue` and `secondsValue`. ### Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date. ## Description If you do not specify the `secondsValue` and `msValue` parameters, the values returned from [`Date.prototype.getSeconds()`](./getSeconds.mdx) and [`Date.prototype.getMilliseconds()`](./getMilliseconds.mdx) methods are used. If a parameter you specify is outside of the expected range, `setMinutes()` attempts to update the date information in the `Date` object accordingly. For example, if you use 100 for `secondsValue`, the minutes will be incremented by 1 (`minutesValue + 1`), and 40 will be used for seconds.
from abc import ABCMeta, abstractmethod class Appliance(metaclass=ABCMeta): @abstractmethod def enabled(self): pass @abstractmethod def start(self): pass @abstractmethod def stop(self): pass class AC(Appliance): def __init__(self): self.enabled = False @property def enabled(self): return self._enabled @enabled.setter def enabled(self, enabled: bool): self._enabled = enabled def start(self): print('AC is ON successfully!!!') self.enabled = True def stop(self): print('AC is OFF successfully!!!') self.enabled = False class Refrigerator(Appliance): def __init__(self): self.enabled = False @property def enabled(self): return self._enabled @enabled.setter def enabled(self, enabled: bool): self._enabled = enabled def start(self): print('Refrigerator is ON successfully!!!') self.enabled = True def stop(self): print('Refrigerator is OFF successfully!!!') self.enabled = False class Fan(Appliance): def __init__(self): self.enabled = False @property def enabled(self): return self._enabled @enabled.setter def enabled(self, enabled: bool): self._enabled = enabled def start(self): print('Fan is ON successfully!!!') self.enabled = True def stop(self): print('Fan is OFF successfully!!!') self.enabled = False class TV(Appliance): def __init__(self): self.enabled = False @property def enabled(self): return self._enabled @enabled.setter def enabled(self, enabled: bool): self._enabled = enabled def start(self): print('TV is ON successfully!!!') self.enabled = True def stop(self): print('TV is OFF successfully!!!') self.enabled = False class GateOpener(Appliance): def __init__(self): self.enabled = False @property def enabled(self): return self._enabled @enabled.setter def enabled(self, enabled: bool): self._enabled = enabled def start(self): print('Gate is OPENED successfully!!!') self.enabled = True def stop(self): print('AC is CLOSED successfully!!!') self.enabled = False class Switch(metaclass=ABCMeta): def __init__(self, appliance: Appliance): self.appliance = appliance @abstractmethod def turn_on(self): pass @abstractmethod def turn_off(self): pass class AutomaticRemoteController(Switch): def __init__(self, appliance: Appliance): super().__init__(appliance) def turn_on(self): print('Automatic Remote Controller has just worked') print('The one is trying to turn on an appliance . . .') if self.appliance.enabled: print('SOMETHING WENT WRONG!!!') else: self.appliance.start() def turn_off(self): print('Automatic Remote Controller has just worked') print('The one is trying to turn off an appliance . . .') if self.appliance.enabled: self.appliance.start() else: print('SOMETHING WENT WRONG!!!') class ManualRemoteController(Switch): def __init__(self, appliance): super().__init__(appliance) def turn_on(self): print('Manual Remote Controller has just worked') print('The one is trying to turn on an appliance . . .') if self.appliance.enabled: print('SOMETHING WENT WRONG!!!') else: self.appliance.start() def turn_off(self): print('Manual Remote Controller has just worked') print('The one is trying to turn off an appliance . . . ') if self.appliance.enabled: self.appliance.start() else: print('SOMETHING WENT WRONG!!!') # The client code tv = TV() ARC = AutomaticRemoteController(tv) ARC.turn_off() refrigerator = Refrigerator() MRC = ManualRemoteController(refrigerator) MRC.turn_on()
const User = require("../models/User"); // can be written as // import User from "../models/User"; const jwt = require("jsonwebtoken"); // to be used for signup // handle errors const handleErrors = (err) => { console.log(err.message, err.code); let errors = { email: '', password: '' }; // duplicate email error if (err.code === 11000) { errors.email = 'that email is already registered'; return errors; } // validation errors if (err.message.includes('user validation failed')) { // console.log(err); Object.values(err.errors).forEach(({ properties }) => { // console.log(val); // console.log(properties); errors[properties.path] = properties.message; }); // incorrect email if (err.message === "Incorrect Email Address Entered") { errors.email = "That email is not registered" } // incorrect password if (err.message === "Incorrect Passoword") { err.password = "Your Password is Incorrect." } } return errors; } const maxAge = 3 * 24 * 60 * 60; //setting maxage to 3 days as the values of jwt "expiresIn " must be in seconds // create jwt const createToken = (id) => { // the jwt.sign method takes in the payload and a secret, the secret should be long return jwt.sign({id}, 'my name is jp', { expiresIn: maxAge }); //the id is the payload and it is the only required value for the jwt creation } // controller actions module.exports.signup_get = (req, res) => { res.render('signup'); } module.exports.login_get = (req, res) => { res.render('login'); } module.exports.signup_post = async (req, res) => { const { email, password } = req.body; // extract values of email and password from req.body, using body-parser module try { const user = await User.create({ email, password }); const token = createToken(user._id); // create token using user id from database res.cookie('jwt', token, { httpOnly: true, maxAge: maxAge * 1000 }); //cookie maxAges are in milliseconds // res.status(201).json(user); res.status(201).json({user: user._id}); // to send the user id instead of returning all the user's information } catch(err) { const errors = handleErrors(err); res.status(400).json({ errors }); } } module.exports.login_post = async (req, res) => { const { email, password } = req.body; try { const user = await User.login(email, password); const token = createToken(user._id); // create user token using jwt // return cookie with jwt, token and options passed in. res.cookie('jwt', token, { maxAge: maxAge * 1000, httpOnly: true }); res.status(200).json({user: user._id}); } catch (err) { const errors = handleErrors(err); res.status(400).json({ errors }); } } module.exports.logout_get = async (req, res) => { res.cookie('jwt', '', {maxAge: 1 }); // rewriting the jwt cookie value to blank and giving it a maxAge of 1 millisecond res.redirect('/'); }
class Cart { constructor() { this.items = []; } add(product) { this.items.push(product); } remove(productId) { this.items = this.items.filter(item => item.id !== productId); } clear() { this.items = []; } getTotal() { return this.items.reduce((total, item) => total + item.price, 0).toFixed(2); } } const cart = new Cart(); // Fetch all products and display them on the site const loadProducts = async () => { try { const response = await fetch('https://fakestoreapi.com/products'); const products = await response.json(); createProducts(products); } catch (error) { console.error('Failed to fetch products:', error); } }; // Display products on the site const createProducts = (products) => { const productsContainer = document.getElementById('products'); productsContainer.innerHTML = ''; products.forEach(product => { const productDiv = document.createElement('div'); productDiv.className = 'product'; const image = document.createElement('img'); image.src = product.image; image.alt = product.title; image.onclick = () => createProductDetails(product); const title = document.createElement('h2'); title.textContent = product.title; const price = document.createElement('p'); price.textContent = `$${product.price.toFixed(2)}`; productDiv.appendChild(image); productDiv.appendChild(title); productDiv.appendChild(price); productsContainer.appendChild(productDiv); }); }; // Display product details when a product is clicked const createProductDetails = (product) => { const DetailsContainer = document.getElementById('product-details'); DetailsContainer.innerHTML = ''; const image = document.createElement('img'); image.src = product.image; image.alt = product.title; const title = document.createElement('h2'); title.textContent = product.title; const price = document.createElement('p'); price.textContent = `$${product.price.toFixed(2)}`; const description = document.createElement('p'); description.textContent = product.description; const addToCartButton = document.createElement('button'); addToCartButton.textContent = 'Add to Cart'; addToCartButton.onclick = () => { cart.add(product); console.log('Product added to cart:', product); console.log('Cart total:', cart.getTotal()); displayCart(); }; DetailsContainer.appendChild(image); DetailsContainer.appendChild(title); DetailsContainer.appendChild(price); DetailsContainer.appendChild(description); DetailsContainer.appendChild(addToCartButton); DetailsContainer.style.display = 'block'; document.getElementById('products').style.display = 'none'; }; // Filter products by category const filterProducts = async (category) => { try { const response = await fetch('https://fakestoreapi.com/products' + (category ? `/category/${category}` : '')); const products = await response.json(); displayProducts(products); } catch (error) { console.error('Failed to fetch products:', error); } }; // Display cart items and total const createCart = () => { const cartContainer = document.getElementById('cart'); const cartItemsContainer = document.getElementById('cart-items'); cartItemsContainer.innerHTML = ''; cart.items.forEach(item => { const cartItemDiv = document.createElement('div'); const title = document.createElement('span'); title.textContent = item.title; const price = document.createElement('span'); price.textContent = `$${item.price.toFixed(2)}`; const removeButton = document.createElement('button'); removeButton.textContent = 'Remove'; removeButton.onclick = () => { cart.remove(item.id); console.log('Product removed from cart:', item); console.log('Cart total:', cart.getTotal()); displayCart(); }; cartItemDiv.appendChild(title); cartItemDiv.appendChild(price); cartItemDiv.appendChild(removeButton); cartItemsContainer.appendChild(cartItemDiv); }); document.getElementById('cart-total').textContent = cart.getTotal(); cartContainer.style.display = 'block'; }; // Clear cart const clearCart = () => { cart.clear(); console.log('Cart cleared'); createCart(); }; // Load products when the site loads window.onload = loadProducts;
import type { Metadata } from "next"; import { Inter } from "next/font/google"; import "./globals.css"; import Navbar from "@/components/Navbar"; import { Provider } from "react-redux"; import ReduxProvider from "@/redux/ReduxProvider"; const inter = Inter({ subsets: ["latin"] }); export const metadata: Metadata = { title: "Dil Foods", description: "Generated by create next app", }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body className={inter.className}> <ReduxProvider> <Navbar /> {children} </ReduxProvider> </body> </html> ); }
import "./topbar.css" import React ,{useContext} from 'react'; import { Link } from "react-router-dom"; import {Context} from "../../context/Context"; export default function TopBar() { const {user,dispatch}= useContext(Context); const handleLogout= ()=>{ dispatch({type:"LOGOUT"}); }; const PF="http://localhost:5000/images/"; const placeholder = PF+ "placeholder.jpg"; return ( <div className="top"> <div className="topLeft"> <i className="topIcon fa-brands fa-facebook-square"/> <i className="topIcon fa-brands fa-instagram-square"/> <i className="topIcon fa-brands fa-twitter-square"/> <i className="topIcon fa-brands fa-pinterest-square"/> </div> <div className="topCenter"> <ul className="topList"> <li className="topListItem"><Link to="/" className="link" >HOME</Link></li> <li className="topListItem"><Link to="/" className="link" >ABOUT</Link></li> <li className="topListItem"><Link to="/" className="link" >CONTACT</Link></li> <li className="topListItem"><Link to="/write" className="link" >WRITE</Link></li> <li className="topListItem" onClick={handleLogout}> {user && "LOGOUT"} </li> </ul> </div> <div className="topRight"> { user ? ( <Link className="link" to="/settings"> {user.profilePic?(<img className="topImg" src={PF+user.profilePic} alt=""/>): (<img className="topImg" src={placeholder} alt=""/>)} </Link> ) : ( <ul className="topList"> <li className="topListItem"><Link to="/login" className="link" >LOGIN</Link></li> <li className="topListItem"><Link to="/register" className="link" >REGISTER</Link></li> </ul> ) } <i className="topSearchIcon fa-solid fa-magnifying-glass"/> </div> </div> ) }
// // ViewController.swift // MyInstaImagePicker // // Created by 구태호 on 2022/07/17. // import UIKit class ViewController: UIViewController { @IBOutlet weak var btMake: UIButton! @IBOutlet weak var btCenter: UIButton! @IBOutlet weak var btSize: UIButton! // imageView 들을 담을 배열 private var imageViews = [UIImageView]() private let IS_IMAGE_VIEW_LIMIT = 4 private var imageViewCount = 0 private let imageNames = ["jar1.jpg", "jar2.jpg", "jar3.jpg", "simple.jpg", "unknown.jpg"] override func viewDidLoad() { super.viewDidLoad() makeImageView() imageViewCount += 1 } private func makeImageView() { // view 좌표 및 크기 초기화 let roundImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 128)) // view 가운데 이동 roundImageView.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2) roundImageView.image = UIImage(named: "\(imageNames[imageViewCount])") roundImageView.contentMode = .scaleAspectFill roundImageView.clipsToBounds = true roundImageView.layer.borderWidth = 3 roundImageView.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) roundImageView.layer.cornerRadius = roundImageView.frame.height / 2 // 블러 효과 적용 // roundImageView.blur() // 드래그 이벤트 인식기 등록 let panGesture = CocobeanPanGestureRecognizer(target: self, action: #selector(self.drag)) // 이미지도 함께 저장 panGesture.imageView = roundImageView roundImageView.addGestureRecognizer(panGesture) // 줌 이벤트 인식기 등록 roundImageView.enableZoom() // 클릭 이벤트 등록 (애니메이션 등록됨) roundImageView.enableTap() view.addSubview(roundImageView) // 버튼 클릭 이벤트 등록 let onClickCenterButton = UIAction { _ in UIView.animate(withDuration: 0.5) { roundImageView.center = CGPoint(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2) } } btCenter.addAction(onClickCenterButton, for: .touchUpInside) imageViews.append(roundImageView) // 버튼 z index 조정 self.view.bringSubviewToFront(btCenter) self.view.bringSubviewToFront(btSize) } @IBAction func onClickMakeButton(_ sender: UIButton) { if imageViewCount <= IS_IMAGE_VIEW_LIMIT { makeImageView() imageViewCount += 1 } } @IBAction func onClickSizeButton(_ sender: UIButton) { if sender.isSelected { for imageView in imageViews { UIView.animate(withDuration: 0.5) { // 크기 1.75배 증가 imageView.transform = CGAffineTransform(scaleX: 1.75, y: 1.75) } } sender.isSelected = false } else { for imageView in imageViews { UIView.animate(withDuration: 0.5) { // 크기 원상태로 복구 imageView.transform = .identity } } sender.isSelected = true } } @objc func drag(sender: CocobeanPanGestureRecognizer) { // 부모 view 에서 sender(imageView)의 위치 출력 // print("\(sender.location(in: self.view))") // view 충돌 체크 (화면 밖으로 나가지 않도록) // imageView 좌표 출력 // print("\(roundImageView.frame.origin)") // imageView 데이터 검사 guard let roundImageView = sender.imageView else { return } let x = roundImageView.frame.origin.x let y = roundImageView.frame.origin.y let viewWidthSize = self.view.frame.width let viewHeightSize = self.view.frame.height let endX = x + roundImageView.frame.width let endY = y + roundImageView.frame.height if x < 0 { UIView.animate(withDuration: 0.2, animations: { roundImageView.frame.origin.x = 5 }) { _ in roundImageView.isUserInteractionEnabled = true } return } if y < 0 { UIView.animate(withDuration: 0.2) { roundImageView.frame.origin.y = 5 } return } if endX > viewWidthSize { UIView.animate(withDuration: 0.2) { roundImageView.frame.origin.x = viewWidthSize - roundImageView.frame.width } return } if endY > viewHeightSize { UIView.animate(withDuration: 0.2) { roundImageView.frame.origin.y = viewHeightSize - roundImageView.frame.height } return } // imageView의 현재 좌표 저장 let translation = sender.translation(in: self.view) // translation에 움직인 위치를 저장한다. // sender의 view는 sender가 바라보고 있는 circleView이다. 드래그로 이동한 만큼 circleView를 이동시킨다. sender.view!.center = CGPoint(x: sender.view!.center.x + translation.x, y: sender.view!.center.y + translation.y) // 0으로 움직인 값을 초기화 시켜준다. sender.setTranslation(.zero, in: self.view) } }
--- tags: [operating-system] --- # Pipe Pipe provides a one-way stream (no data size examination) flow of data, where the output of a process is directed into the input of another, which can be created using `pipe()` #[Unix System Call](202210062303.md). Pass in a file descriptor array (of type `int`) with a size of 2, the system call will return 2 file descriptors for use: `fd[0]` for reading and `fd[1]` for writing. A typical use case of Pipe is to establish a [communication channel](202210042126.md)# between two related processes. The maximum amount of data allowed in the pipe (OS treats it like a [Queue](202112101836.md)#) is usually 5120 bytes. In #unix, Pipe is implemented using #[Unix Domain Socket](202303232001.md) and shares the information that resides in the [Kernel](202210062254.md). **Note**: Since Pipe has no name, only processes that are related (having a common parent) can create a pipe between them. **Note**: Pipe cannot be used in [Network File System (NFS)](202302131659.md)-mounted filesystem as the data have to be passed between two different [File Systems](202202060057.md). **Note**: `socketpair()` allows the creation of full-duplex pipe. The following source code shows that a parent process initialised a Pipe then creates a child process which inherits the Pipe from its parent. The parent closes the read end of the Pipe whereas the child will close the write end of the Pipe: ```c int childipd, pipe[2] if (pipe(pipe1) < 0) < 0) { perror("pipe"); exit(1); } if ((childpid = fork()) < 0) { perror("fork"); exit(1); } else if (childpid > 0 { close(pipe[1]); // close write end of the pipe for child // Do stuffs... close(pipe[0]); // close pipe for child } else { close(pipe[0]); // close read end of the pipe for parent // Do stuffs... close (pipe[1]); // close pipe for parent } ``` **Note**: If the queue is empty or is full, the read or write operation will be blocked respectively until there is information coming in to the pipe. We can change the pipe's properties via the function `fcntl()` first obtain the current file status flags before the changing. We could get the flag with the function with the flag `F_GETFL`, and then add to the flag like `O_NONBLOCK` with bitwise-OR to the returned flag. Other than using POSIX interface, we could utilise the support of Pipe by using the function `popen()` and `pclose` from the standard I/O library (`stdio.h`) in C which could be used as follows: ```c FILE *fp; fp = popen(command, mode); // create pipe // mode as in "r" or "w", stand as read and write // respectively pclose(fp); // close pipe ```
import React, { useEffect, useState } from 'react'; import { useLocation, Link, NavLink } from 'react-router-dom'; import { useMediaQuery } from 'react-responsive'; import { useStyleContext } from '../components/StyleContext'; import Box from '../components/Box'; import logo from '../assets/images/logo.webp'; const Header = () => { const Desktop = () => { const isDesktop = useMediaQuery({ minWidth: 992 }) return isDesktop; } const Tablet = () => { const isTablet = useMediaQuery({ maxWidth: 768, maxWidth: 991 }) return isTablet; } const Mobile = () => { const isMobile = useMediaQuery({ maxWidth: 767 }) return isMobile; } const Default = () => { const isDefault = useMediaQuery({ minWidth: 768 }) return isDefault; } const [isHeaderOn, setIsHeaderOn] = useState(false); const location = useLocation(); const [isMenuOpen, setIsMenuOpen] = useState(false); const { isCropMode, setIsCropMode } = useStyleContext(); const handleMenuClick = () => { setIsMenuOpen(prevIsMenuOpen => !prevIsMenuOpen); setIsCropMode(prevIsCropMode => !prevIsCropMode); }; const handleMenuItemClick = () => { handleMenuClick(); // 메뉴 닫기 }; useEffect(() => { // 컴포넌트가 처음 렌더링될 때 실행되는 코드 //console.log('Component mounted'); const handleScroll = () => { const bodyOffsetTop = document.body.getBoundingClientRect().top; if (window.scrollY > bodyOffsetTop) { setIsHeaderOn(true); } else { setIsHeaderOn(false); } }; window.addEventListener('scroll', handleScroll); // 컴포넌트가 언마운트될 때 클린업 함수 설정 return () => { //console.log('Component unmounted'); window.removeEventListener('scroll', handleScroll); }; }, []); return ( <header className={isHeaderOn ? 'on' : ''}> <Box boxClassName="headerWrap"> <h1> <Link to="/" ><img src={process.env.PUBLIC_URL + logo} alt="케이뱅크" /></Link> </h1> <div className="gnbWrap"> <Link to="#" className={`m_menu ${isMenuOpen ? 'on' : ''}`} onClick={handleMenuClick}> <span>열기</span> </Link> <nav className={`${isMenuOpen ? 'on' : ''}`}> <ul className={`gnb ${location.pathname === '/' ? 'main' : ''}`}> <li><NavLink className={({ isActive }) => { return isActive ? 'on' : ''; }} to="/Recruit" onClick={handleMenuItemClick} >인재영입</NavLink></li> <li><NavLink className={({ isActive }) => { return isActive ? 'on' : ''; }} to="/Story" onClick={handleMenuItemClick}>사람들 이야기</NavLink></li> <li><NavLink className={({ isActive }) => { return isActive ? 'on' : ''; }} to="/Benefit" onClick={handleMenuItemClick}>복지와 혜택</NavLink></li> <li><NavLink className={({ isActive }) => { return isActive ? 'on' : ''; }} to="/Faq" onClick={handleMenuItemClick}>자주묻는 질문</NavLink></li> <li><NavLink className={({ isActive }) => { return isActive ? 'on' : ''; }} to={Desktop() ? "https://kbank.recruiter.co.kr/app/applicant/myPage/login" : "/MyApply"} onClick={handleMenuItemClick}>나의 지원현황</NavLink></li> <li><NavLink className={({ isActive }) => { return isActive ? 'on' : ''; }} to="https://kbank-recruit.tistory.com" onClick={handleMenuItemClick}>블로그</NavLink></li> {/* <li><NavLink className={({isActive})=>{return isActive ? 'on':'';}} to="ImageTest" onClick={handleMenuItemClick}>테스트</NavLink></li> */} </ul> </nav> </div> </Box> </header> ); } export default Header;
% This program calculates approximate solutions to the % Functionalized Cahn-Hilliard (FCH) equation using a first-order % IMEX scheme, with stabilization. The method was designed by Chen % and Shen in the paper % % Feng Chen, Jie Shen, "Efficient spectral-Galerkin methods for % systems of coupled second-order equations and their % applications," J. Comput. Phys. 231 (15) (2012) 5016-5028. % % A descprition of the model can be found in the paper % % C. Zhang, J. Ouyang, C. Wang, and S.M. Wise, "Numerical % Comparison of Modified-Energy Stable SAV-Type Schemes % and Classical BDF Methods on Benchmark Problems for the % Functionalized Cahn-Hilliard Equation," J. Comput. Phys. % 423 (2020) 109772 (35 pages). % % Most of the test problems below come from that 2020 paper. % % initType = 1 :: High accuracy benchmark % initType = 2 :: phiAve + random noise % initType = 3 :: S shape % initType = 4 :: S shape with smoothing filter % initType = 5 :: annulus 1 with smoothing filter % initType = 6 :: annulus 2 with smoothing filter % clear; clc; clf; initType = 2; % % Chen-Shen stabilization parameters: sig1 = 1.0; sig2 = 1.0; % % Time stepping and printout parameters: dt = 1e-4; stepsPerPlot = 10000; stepsPerScreenPlot = 1000; stepsPerReport = 100; plotFrames = 100; maxSteps = stepsPerPlot*plotFrames; phiAve = 0.0; % switch initType case 1 M = 1.0; L = 2*pi; N = 2^7; epsilon = 0.18; eta1 = epsilon^2; eta2 = epsilon^2; gamma = 0.00; case 2 M = 1.0; L = 2*pi; N = 2^8; epsilon = 0.04; eta1 = 5.0*epsilon; eta2 = 3.0*epsilon; gamma = 0.0; phiAve = 0.5; case {3, 4} M = 1.0; L = 12.8; N = 2^8; epsilon = 0.1; eta1 = 0.2; eta2 = 0.2; gamma = 0.00; case 5 M = 1.0; L = 2*pi; N = 2^8; epsilon = 0.04; eta1 = 2.0*epsilon; eta2 = 2.0*epsilon; gamma = 0.25; case 6 M = 1.0; L = 4*pi; N = 2^8; epsilon = 0.1; eta1 = 1.45*epsilon; eta2 = 2.0*epsilon; gamma = 0.25; otherwise error("Error in initType: No such initial conditon!") end % param.L = L; param.N = N; param.epsilon = epsilon; param.eta1 = eta1; param.eta2 = eta2; param.gamma = gamma; param.phiAve = phiAve; param.initType = initType; % % Grid and laplacian matrices: kx = 2.0*pi*[0:N/2-1 N/2 -N/2+1:-1]/L; ky = 2.0*pi*[0:N/2-1 N/2 -N/2+1:-1]/L; kx2 = kx.*kx; ky2 = ky.*ky; % h = L/N; xx = zeros(N,N); yy = zeros(N,N); lap = zeros(N,N); % for j = 1:N for i = 1:N xx(i,j) = h*i; yy(i,j) = h*j; lap(i,j) = -(kx2(i)+ky2(j)); end end % % Get initial condition [phi] = initialCondition(param); % % Print out initial frame: % printField('phi',phi,0,dt,0,param) % figure(1); pcolor(xx,yy,phi); axis equal shading interp; colormap('jet'); title('Initial Conditions'); colorbar; getframe; for k = 1:maxSteps % time = k*dt; % if (mod(k,stepsPerReport) == 0) fprintf('step : %6d time : %8.3f \n', k, time) end % fp = (phi-1.0).*(phi+1.0).*(phi+0.5*gamma); fpp = (phi+1.0).*(phi+0.5*gamma)+(phi-1.0).*(phi+0.5*gamma) ... +(phi-1.0).*(phi+1.0); % wt = epsilon*epsilon*real(ifft2(fft2(phi).*lap))-fp; q1 = (sig1-fpp).*wt+(eta1-eta2)*fp; q2 = sig2*phi-fp; q3 = epsilon*epsilon*real(ifft2(fft2(q2).*lap))-(sig1-eta1)*q2+q1; q4 = phi+dt*M*real(ifft2(fft2(q3).*lap)); % coef = 1.0-dt*M*epsilon^4*lap.^3 ... + dt*M*epsilon^2*(sig2+sig1-eta1)*lap.^2 ... - dt*M*(sig2*(sig1-eta1))*lap; % phi = real(ifft2(fft2(q4)./coef)); % if (mod(k,stepsPerScreenPlot) == 0) figure(1); pcolor(xx,yy,phi); axis equal shading interp; colormap(jet); colorbar; title(['FCH-IMEX: dt = ',num2str(dt),' time = ', ... num2str(time)]); getframe; end % if (mod(k,stepsPerPlot) == 0) % frame = round(k/stepsPerPlot); printField('phi',phi,frame,dt,time,param) % end end % disp('program done') % function [ ] = printField(fieldName,fieldArray,frame,dt,time,param) % N = param.N; L = param.L; % s1 = ['0000000' num2str(frame)]; s2 = s1((length(s1)-4):length(s1)); fid = fopen(['./OUT/',fieldName,s2,'.dat'],'w'); fprintf(fid,'%25.15e %25.15e %10i %25.15e\n',time,dt,N,L); for j = 1:N for i = 1:N fprintf(fid,'%25.15e\n',fieldArray(i,j)); end end fclose(fid); % end % function printField
namespace com.linkedin.policy import com.linkedin.common.Urn import com.linkedin.ownership.OwnershipTypeInfo /** * Information used to filter DataHub actors. */ record DataHubActorFilter { /** * A specific set of users to apply the policy to (disjunctive) */ users: optional array[Urn] /** * A specific set of groups to apply the policy to (disjunctive) */ groups: optional array[Urn] /** * Whether the filter should return true for owners of a particular resource. * Only applies to policies of type 'Metadata', which have a resource associated with them. */ resourceOwners: boolean = false /** * Define type of ownership for the policy */ resourceOwnersTypes: optional array[Urn] /** * Whether the filter should apply to all users. */ allUsers: boolean = false /** * Whether the filter should apply to all groups. */ allGroups: boolean = false /** * A specific set of roles to apply the policy to (disjunctive). */ @Relationship = { "/*": { "name": "IsAssociatedWithRole", "entityTypes": [ "dataHubRole" ] } } roles: optional array[Urn] }
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strmapi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: iet-tibi <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/20 20:48:46 by iet-tibi #+# #+# */ /* Updated: 2018/10/23 00:34:25 by iet-tibi ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" char *ft_strmapi(char const *s, char (*f)(unsigned int, char)) { char *str; size_t i; if (!s || !f) return (NULL); i = 0; if (!(str = (char*)malloc(ft_strlen(s) * sizeof(char) + 1))) return (NULL); while (s[i]) { str[i] = f(i, s[i]); i++; } str[i] = '\0'; return (str); }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Timesheet Calculator</title> <link rel="stylesheet" href="assets/styles/bulma.min.css"/> <link rel="icon" type="image/png" href="assets/images/favicomatic/favicon-32x32.png" sizes="32x32"/> <link rel="icon" type="image/png" href="assets/images/favicomatic/favicon-16x16.png" sizes="16x16"/> </head> <body> <section class="section mt-6"> <div class="columns"> <div class="column is-one-fifth is-offset-two-fifths"> <div class="box"> <div class="content is-size-5 has-text-centered has-text-weight-bold"> Enter Time and Hourly Rate </div> <div class="field"> <div class="control"> <input class="input is-link" type="text" id="time" placeholder="Time (hh:mm:ss)" onchange="calculate()"> </div> </div> <div class="field"> <div class="control"> <input class="input is-link" type="text" id="rate" placeholder="Hourly Rate" onchange="calculate()"> </div> </div> <div class="content is-size-5 has-text-centered has-text-weight-bold"> Hours </div> <div class="content is-size-6 has-text-centered" id="resultTime"></div> <div class="content is-size-5 has-text-centered has-text-weight-bold"> Price </div> <div class="content is-size-6 has-text-centered" id="resultRate"></div> </div> </div> </div> </section> <script> function timeToDecimal(t) { t = t.split(':'); return ((+t[0]) + (+t[1])/60 + (+t[2])/3600).toFixed(2); } function calculate() { var time = document.getElementById('time').value; var billingRate = document.getElementById('rate').value; hours = timeToDecimal(time); price = (hours * billingRate).toFixed(1); if (time != '') { document.getElementById("resultTime").innerHTML = hours; } if (time != '' && billingRate != '') { document.getElementById("resultRate").innerHTML = price; } } </script> </body> </html>
#ifndef OOP_CARTE_H #define OOP_CARTE_H #include <iostream> #include <string> #include <memory> #include <ctime> #include "EroareCarte.h" class Carte { protected: std::string numeCarte; std::string gen; int anAparitie; bool disponibilitate = true; public: Carte() = default; Carte(const std::string & numeCarte, const std::string & gen, int anAparitie); Carte(const Carte & copie); Carte & operator=(const Carte & copie); virtual ~Carte() = 0; friend std::ostream & operator<<(std::ostream & os, const Carte & carte); bool get_disponibilitate() const; void set_disponibilitate(bool disponibilitate); std::string get_numeCarte() const; std::string get_gen() const; int get_anAparitie() const; virtual std::shared_ptr<Carte> clone() const = 0; virtual void afis(std::ostream &os) const; }; #endif //OOP_CARTE_H
import { COMPUTED_PATH } from "../const"; import { computed } from "../inline"; import { getObserver, getObservers } from "../utils"; /** * @description `Computed` is a property decorator. * Changes in computed state values are also recognized according to changes in observers used within the getter function. * You can detect its status through `.subscribe`. * @hidden * @category Reactive-Decorator * @see ReactiveSubscribe * @example * ```ts const ob1 = observe(0); const ob2 = observe(1); // When @ReactiveSubscribe class TestComputed { @Computed get ob3() { return ob1.current + ob2.current; } } const inst = new TestComputed(); inst.subscribe("ob3", ob3 => { console.log(ob3); }); ob1.current = 1; ``` */ export function Computed(prototype: any, memberName: string, attributes: PropertyDescriptor): PropertyDescriptor { const get = attributes.get!; function getComputed() { const observers = getObservers(this); if (!(memberName in observers)) { observers[memberName] = computed(get.bind(this)); } return getObserver(this, memberName).current; } const nextAttributes: PropertyDescriptor = { configurable: true, get: getComputed, } if (COMPUTED_PATH in prototype) { prototype[COMPUTED_PATH] ||= []; const computedList = prototype[COMPUTED_PATH]; if (computedList.indexOf(memberName) === -1) { computedList.push(memberName); } } Object.defineProperty(prototype, memberName, nextAttributes); return nextAttributes; }
use std::sync::Arc; use async_trait::async_trait; use lazy_static::lazy_static; use tokio::sync::Mutex as AsyncMutex; use crate::account_deck::service::account_deck_service::AccountDeckService; use crate::account_deck::service::account_deck_service_impl::AccountDeckServiceImpl; use crate::account_deck_card::controller::account_deck_card_controller::AccountDeckCardController; use crate::account_deck_card::controller::request_form::account_deck_card_list_request_form::AccountDeckCardListRequestFrom; use crate::account_deck_card::controller::request_form::account_deck_card_modify_request_form::AccountDeckCardModifyRequestForm; use crate::account_deck_card::controller::request_form::account_deck_configuration_request_form::AccountDeckConfigurationRequestForm; use crate::account_deck_card::controller::response_form::account_deck_card_list_response_form::AccountDeckCardListResponseForm; use crate::account_deck_card::controller::response_form::account_deck_card_modify_response_form::AccountDeckCardModifyResponseForm; use crate::account_deck_card::controller::response_form::account_deck_configuration_response_form::AccountDeckConfigurationResponseForm; use crate::account_deck_card::service::account_deck_card_service::AccountDeckCardService; use crate::account_deck_card::service::account_deck_card_service_impl::AccountDeckCardServiceImpl; use crate::deck_configuration_validator::service::deck_configuration_validator_service::DeckConfigurationValidatorService; use crate::deck_configuration_validator::service::deck_configuration_validator_service_impl::DeckConfigurationValidatorServiceImpl; pub struct AccountDeckCardControllerImpl { account_deck_card_service: Arc<AsyncMutex<AccountDeckCardServiceImpl>>, deck_configuration_validator_service: Arc<AsyncMutex<DeckConfigurationValidatorServiceImpl>>, account_deck_service: Arc<AsyncMutex<AccountDeckServiceImpl>>, } impl AccountDeckCardControllerImpl { pub fn new(account_deck_card_service: Arc<AsyncMutex<AccountDeckCardServiceImpl>>, deck_configuration_validator_service: Arc<AsyncMutex<DeckConfigurationValidatorServiceImpl>>, account_deck_service: Arc<AsyncMutex<AccountDeckServiceImpl>>, ) -> Self { AccountDeckCardControllerImpl { account_deck_card_service, deck_configuration_validator_service, account_deck_service, } } pub fn get_instance() -> Arc<AsyncMutex<AccountDeckCardControllerImpl>> { lazy_static! { static ref INSTANCE: Arc<AsyncMutex<AccountDeckCardControllerImpl>> = Arc::new( AsyncMutex::new( AccountDeckCardControllerImpl::new( AccountDeckCardServiceImpl::get_instance(), DeckConfigurationValidatorServiceImpl::get_instance(), AccountDeckServiceImpl::get_instance()))); } INSTANCE.clone() } } #[async_trait] impl AccountDeckCardController for AccountDeckCardControllerImpl { async fn deck_configuration_register( &self, account_deck_configuration_request_form: AccountDeckConfigurationRequestForm) -> AccountDeckConfigurationResponseForm { println!("AccountDeckCardControllerImpl: deck_configuration_register()"); let account_deck_service_guard = self.account_deck_service.lock().await; let account_deck_owner_verification = account_deck_service_guard.account_deck_owner_verification( account_deck_configuration_request_form.account_session_id(), account_deck_configuration_request_form.deck_id_form()).await; if account_deck_owner_verification == false { return AccountDeckConfigurationResponseForm::new(false, "not your deck".to_string()); } let deck_configuration_validator_service_guard = self.deck_configuration_validator_service.lock().await; let validation_card_owner = deck_configuration_validator_service_guard .do_you_have_this_card( account_deck_configuration_request_form.card_id_list_form(), account_deck_configuration_request_form.account_session_id()).await; if validation_card_owner == false { return AccountDeckConfigurationResponseForm::new(false, "not your card".to_string()) } let validation_result = deck_configuration_validator_service_guard .validate_deck(&account_deck_configuration_request_form.card_id_list_form()).await; return match validation_result { Ok(()) => { let account_deck_card_service_guard = self.account_deck_card_service.lock().await; let response = account_deck_card_service_guard .deck_configuration_register( account_deck_configuration_request_form.to_account_deck_configuration_request()).await; response.to_account_deck_configuration_response_form() } Err(error_message) => { AccountDeckConfigurationResponseForm::new(false, error_message) } } } async fn deck_card_list(&self, account_deck_card_list_request_from: AccountDeckCardListRequestFrom) -> AccountDeckCardListResponseForm { println!("AccountDeckCardControllerImpl: deck_card_list()"); let account_deck_card_service_guard = self.account_deck_card_service.lock().await; let response = account_deck_card_service_guard .deck_card_list(account_deck_card_list_request_from.to_account_deck_card_list_request()).await; response.to_account_deck_card_list_response_form() } async fn deck_card_modify( &self, account_deck_card_modify_request_form: AccountDeckCardModifyRequestForm) -> AccountDeckCardModifyResponseForm { println!("AccountDeckCardControllerImpl: deck_card_modify()"); let account_deck_service_guard = self.account_deck_service.lock().await; let account_deck_owner_verification = account_deck_service_guard.account_deck_owner_verification( account_deck_card_modify_request_form.account_session_id(), account_deck_card_modify_request_form.deck_id_form()).await; if account_deck_owner_verification == false { return AccountDeckCardModifyResponseForm::new(false); } let deck_configuration_validator_service_guard = self.deck_configuration_validator_service.lock().await; let validation_card_owner = deck_configuration_validator_service_guard .do_you_have_this_card( account_deck_card_modify_request_form.card_id_list_form(), account_deck_card_modify_request_form.account_session_id()).await; if validation_card_owner == false { return AccountDeckCardModifyResponseForm::new(false) } let validation_result = deck_configuration_validator_service_guard .validate_deck(&account_deck_card_modify_request_form.card_id_list_form()).await; return match validation_result { Ok(()) => { let account_deck_card_service_guard = self.account_deck_card_service.lock().await; let _ = account_deck_card_service_guard.deck_card_delete(account_deck_card_modify_request_form.deck_id_form()).await; let response = account_deck_card_service_guard .deck_configuration_register( account_deck_card_modify_request_form.to_account_deck_configuration_request()).await; AccountDeckCardModifyResponseForm::new(response.get_is_success()) } Err(error_message) => { AccountDeckCardModifyResponseForm::new(false) } } } } #[cfg(test)] mod tests { use super::*; use tokio::test; #[test] async fn test_deck_configuration_register_in_controller() { let card_list = vec![ 19, 8, 8, 8, 9, 9, 25, 25, 25, 27, 27, 27, 151, 20, 20, 20, 2, 2, 2, 26, 26, 26, 30, 31, 31, 31, 32, 32, 32, 33, 33, 35, 35, 36, 36, 93, 93, 93, 130, 130 ]; let deck_configuration_request_form = AccountDeckConfigurationRequestForm::new(23, card_list, "qwer".to_string()); let account_deck_card_controller = AccountDeckCardControllerImpl::get_instance(); let account_deck_card_controller_guard = account_deck_card_controller.lock().await; let result = account_deck_card_controller_guard .deck_configuration_register(deck_configuration_request_form).await; println!("is_saved: {:?}", result.get_is_success()); } }
import React, { useState, useEffect } from "react"; import { useNavigate } from "react-router-dom"; import styled from "styled-components"; import Button from "react-bootstrap/Button"; import Form from "react-bootstrap/Form"; import editar from "../../images/editar.png"; import HeaderComponents from "../Headers/HeaderComponents"; import ClienteService from "../../services/ClienteService"; function ListClienteComponents() { const navigate = useNavigate(); const initialState = { rut: "", nombre: "", empresa: "", }; const [input, setInput] = useState(initialState); const [ClienteEntity, setClienteEntity] = useState([]); useEffect(() => { ClienteService.getClientes().then((res) => { setClienteEntity(res.data); }); }, []); const handleInputChange = (event) => { const { name, value } = event.target; setInput({ ...input, [name]: value }); }; const buscarRut = () => { ClienteService.getClienteByRut(input.rut).then((res) => { if (Array.isArray(res.data)) { setClienteEntity(res.data); } else if (res.data === "") { setClienteEntity([]); } else { setClienteEntity([res.data]); } }); }; const buscarNombre = () => { ClienteService.getClienteByNombre(input.nombre).then((res) => { setClienteEntity(res.data); }); }; const buscarEmpresa = () => { ClienteService.getClienteByEmpresa(input.empresa).then((res) => { setClienteEntity(res.data); }); }; const handleKeyPressRut = (event) => { if (event.key === "Enter") { event.preventDefault(); // Evita que el formulario se envíe si está dentro de un <form> buscarRut(); // Llama a la función que deseas ejecutar } }; const handleKeyPressNombre = (event) => { if (event.key === "Enter") { event.preventDefault(); // Evita que el formulario se envíe si está dentro de un <form> buscarNombre(); // Llama a la función que deseas ejecutar } }; const handleKeyPressEmpresa = (event) => { if (event.key === "Enter") { event.preventDefault(); // Evita que el formulario se envíe si está dentro de un <form> buscarEmpresa(); // Llama a la función que deseas ejecutar } }; const crearCliente = () => { navigate("crear"); }; const ChangeViendoCliente = (todoElDato) => { const datos = { rut: todoElDato.rut, nombre: todoElDato.nombre, email: todoElDato.email, empresa: todoElDato.empresa, telefono: todoElDato.telefono, }; const datosComoTexto = JSON.stringify(datos); navigate(`/clientes/mas info/${encodeURIComponent(datosComoTexto)}`); }; return ( <div> <NavStyle> <HeaderComponents /> <div className="container"> <div className="container-1"> <div className="inline-forms-container"> <Form className="inline-form"> <Form.Group controlId="rut"> <Form.Label className="agregar">Rut del Cliente:</Form.Label> <Form.Control className="agregar" type="text" name="rut" placeholder="12.345.678-9" value={input.rut} onChange={handleInputChange} onKeyPress={handleKeyPressRut} /> </Form.Group> <Button className="boton" onClick={buscarRut}> Buscar </Button> </Form> <Form className="inline-form"> <Form.Group controlId="nombre"> <Form.Label className="agregar">Nombre Cliente:</Form.Label> <Form.Control className="agregar" type="text" name="nombre" placeholder="Juan Perez" value={input.nombre} onChange={handleInputChange} onKeyPress={handleKeyPressNombre} /> </Form.Group> <Button className="boton" onClick={buscarNombre}> Buscar </Button> </Form> <Form className="inline-form"> <Form.Group controlId="empresa"> <Form.Label className="agregar">Empresa del Cliente:</Form.Label> <Form.Control className="agregar" type="text" name="empresa" placeholder="Nombre Generico" value={input.empresa} onChange={handleInputChange} onKeyPress={handleKeyPressEmpresa} /> </Form.Group> <Button className="boton" onClick={buscarEmpresa}> Buscar </Button> </Form> </div> <div className="btn-inf"> <Button className="boton" onClick={crearCliente}> Ingresar Cliente </Button> </div> </div> <div align="center" className="container-2"> <h1> <b> Listado de Cliente</b> </h1> <table border="1" className="content-table"> <thead> <tr> <th>RUT</th> <th>Nombre</th> <th>Correo</th> <th>Telefono</th> <th>Empresa</th> <th>Más información</th> </tr> </thead> <tbody> {ClienteEntity.map((cliente) => ( <tr key={cliente.rut}> <td> {cliente.rut} </td> <td> {cliente.nombre} </td> <td> {cliente.email} </td> <td> {cliente.telefono} </td> <td> {cliente.empresa} </td> <td style={{ textAlign: "center", verticalAlign: "middle", width: "1%" }}> <img id="editar" src={editar} alt="editar" onClick={() => ChangeViendoCliente(cliente)} /> </td> </tr> ))} </tbody> </table> </div> </div> </NavStyle> </div> ); } export default ListClienteComponents; const NavStyle = styled.nav` /* Separación de las partes */ .container { margin: 2%; border: 2px solid #d5d5d5; background-color: #f0f0f0; display: flex; flex-direction: row; gap: 20px; height: 100%; } .container-1 { background-color: #f0f0f0; width: 10%; flex-shrink: 0; /* Hace que el contenedor no se encoja */ overflow-y: auto; /* Aparecerá una barra de desplazamiento vertical si el contenido es demasiado largo */ padding: 5%; /* Espacio interno para evitar que el contenido se pegue a los bordes */ display: flex; flex-direction: column; height: 58.9vh; } .container-2 { background-color: #f0f0f0; flex-grow: 1; /* El lado derecho es flexible y ocupará todo el espacio restante */ overflow-y: auto; /* Aparecerá una barra de desplazamiento vertical si el contenido es demasiado largo */ padding: 1%; /* Espacio interno para evitar que el contenido se pegue a los bordes */ max-height: calc(0px + 74.3vh); /* Asegura que el contenedor no exceda la altura de la ventana */ } /* Parte de la tabla */ .content-table { border-collapse: collapse; margin-left: 1; font-size: 0.9em; min-width: 100px; border-radius: 5px 5px 0 0; overflow: hidden; box-shadow: 0 0 20px rgba(0, 0, 0, 0.15); } .content-table thead tr { background-color: #d2712b; color: #ffffff; text-align: left; font-weight: bold; } .content-table th, .content-table td { padding: 12px 15px; } .content-table td { font-size: 18px; } .content-table tbody tr { border-bottom: 1px solid #dddddd; } .content-table tbody tr:nth-of-type(even) { background-color: #f3f3f3; } .content-table tbody tr:last-of-type { border-bottom: 2px solid #009879; } .content-table tbody tr.active-row { font-weight: bold; color: #009879; } img { width: 50%; object-fit: cover; } img:hover { cursor: pointer; } th:hover, td:hover { cursor: default; } /* Formulario de filtro */ .inline-forms-container { flex-grow: 1; display: flex; flex-direction: column; gap: 20px; } .inline-form { display: inline-block; } form { max-width: 500px; margin: 0 auto; } label { display: block; margin-bottom: 10px; margin-left: 15px; margin-top: 10px; } input[type="text"] { background-color: rgb(201, 201, 201); width: 100%; padding: 10px; font-size: 16px; border-radius: 30px; border: 1px solid #ccc; } button { color: #fff; margin-left: 5px; margin-top: 10px; padding: 10px 20px; font-size: 16px; border-radius: 30px; border: none; cursor: pointer; } .boton { background-color: #d2712b; } /* Botón de crear */ .btn-inf .boton { font-size: 20px; } .boton:hover { border: 1px solid black; } /* Fuente de la letra */ td, th, h1, Label, Control, Button { font-family: "Pacifico", serif; } `;