投稿時間:2022-11-14 00:19:43 RSSフィード2022-11-14 00:00 分まとめ(22件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
python Pythonタグが付けられた新着投稿 - Qiita Jupyter lab上でジョイスティックF710を使おう。 https://qiita.com/TakeoChan/items/e9bd0f0af95fa7376263 displayimportclearoutput 2022-11-13 23:03:32
js JavaScriptタグが付けられた新着投稿 - Qiita [JavaScript]名前付きexportとデフォルトexportの違い https://qiita.com/tarian/items/0004eb9ef04123000292 export 2022-11-13 23:53:04
js JavaScriptタグが付けられた新着投稿 - Qiita OpenLayers入門 https://qiita.com/asahina820/items/61520dcf1a36c889391b https 2022-11-13 23:52:09
js JavaScriptタグが付けられた新着投稿 - Qiita Vercelにデプロイ時のビルドエラー[ModuleNotFoundError: Module not found: Error: Can't resolve 'xxx' in '/vercel/path0/components'] https://qiita.com/tarian/items/f666bf5e8daf5e31a0de Vercelにデプロイ時のビルドエラーModuleNotFoundErrorModulenotfoundErrorCanxtresolvexxxxxinxvercelpathcomponentsx内容NextjsプロジェクトをVercelにデプロイ時のビルドで、ModuleNotFoundエラーが発生したため、解決した手段を記述。 2022-11-13 23:18:28
Linux Ubuntuタグが付けられた新着投稿 - Qiita Ubuntuのバージョンによってtopコマンドのデフォルト単位サイズが違う https://qiita.com/akitin7/items/34f041f6aac1800689f6 ubuntu 2022-11-13 23:51:02
Linux Ubuntuタグが付けられた新着投稿 - Qiita 【初級】pythonを使ってみる https://qiita.com/middle_aged_rookie_programmer/items/2f2f518903e54dbaf067 osubuntuvscode 2022-11-13 23:36:09
AWS AWSタグが付けられた新着投稿 - Qiita AWSハンズオン_3_ユーザにアクセス権限の境界設定 https://qiita.com/ShuSaToShi/items/441682f7b8483881467a 設定 2022-11-13 23:55:38
AWS AWSタグが付けられた新着投稿 - Qiita 【AWS】CloudFront経由でS3のファイル更新が反映されない場合の対処法(一時的なキャッシュ無効化) https://qiita.com/shinkai_/items/152cf891be4addc19c94 cloudfront 2022-11-13 23:50:23
AWS AWSタグが付けられた新着投稿 - Qiita bitnami wordpress でサブディレクトリタイプのマルチサイトを構築するとき https://qiita.com/Josezawa/items/6ddc8388839bb5c3da7d bitnami 2022-11-13 23:30:28
AWS AWSタグが付けられた新着投稿 - Qiita ECS で Container Insights を使ってみた https://qiita.com/sugimount-a/items/7c62582972a80deccd7d amazonecs 2022-11-13 23:20:46
技術ブログ Developers.IO 自作VS Code拡張機能のコマンドをMacBookのタッチバーから実行できるようにする https://dev.classmethod.jp/articles/make-it-possible-to-execute-commands-for-self-made-vs-code-extensions-from-the-macbook-touch-bar/ macbook 2022-11-13 14:53:31
海外TECH MakeUseOf Level Up Your Mobile Tech With ESR Gear https://www.makeuseof.com/10-off-esr-gear-mobile-accessories/ chargers 2022-11-13 14:01:14
海外TECH DEV Community App to grab your Revue newsletters https://dev.to/nickytonline/app-to-grab-your-revue-newsletters-1gci App to grab your Revue newslettersSo I wrote about how Twitter is scrapping Revue Revue being phased out by Twitter Nick Taylor・Nov ・ min read news discuss I was able to pull down all my subscribers as you can export them That is important but I also wanted all my past newsletter issues Revue has an API so I wrote a Deno script to save them This works great but I was like let s make this easier for folks who want to grab their newsletters and not have to worry about coding all this So I wrote a small app to do it It uses Netlify functions written in TypeScript to grab the newsletter issues and good old HTML with some inlined style and inlined JavaScript Nick Taylor he him nickytonline I actually made it a site now if you want to be lazy revue iamdeveloper com twitter com nickytonline s… AM Nov Nick Taylor he him nickytonline If you need to grab all your Revue newsletters here s a small script to run with Deno Instructions in the Gist comments Here s the source code if you re interested It s all open source MIT licensed nickytonline get revue newsletters Gets your getrevue co Newsletters Get Revue NewslettersRevue integration is apparently being phased out at Twitter so grab your past newsletter issues while you can and download them That s it View on GitHubIf you have a Revue newsletter try it out at revue iamdeveloper com All you need to do is get a Revue API key To get one go to and request one It should be at the bottom of the page It takes around hours to get your API key 2022-11-13 14:44:58
海外TECH DEV Community Creating and Generating UUIDs with Javascript https://dev.to/smpnjn/creating-and-generating-uuids-with-javascript-4p46 Creating and Generating UUIDs with JavascriptUniversally Unique Identifiers UUIDs are used all over the place in software development for everything from identifying object elements to DOM elements on a web page They are unique bit identifiers consisting of characters in the format for example feaf fcf cdd ba aaa UUIDs typically do not rely on a registry or database to ensure uniqueness The chances of a UUID being a duplicate is not zero but it is so close that most ignore the risk In Javascript there are many ways to create UUIDs With that in mind let s look at how you can create UUIDs with Javascript  Option use the crypto randomUUID methodcrypto randomUUID is a relatively new and reliable way of making UUIDs with native Javascript It s supported in all modern evergreen browsers and can generate a UUID with one line of code The crypto method is available on the global this object on browsers also known as window It is also available on Node JS You can therefore now generate UUIDs like so in the browser console log this crypto randomUUID feaf fcf cdd ba aaaOr in Node JS from version like this import crypto from crypto console log crypto randomUUID feaf fcf cdd ba aaa  Option use the UUID packageThere is a very popular package on NPM called uuid which does all the grunt work for you and generates reliable UUIDs It can be used in a Node JS project by first installing it and then running it in your code First use npm to install npm i uuidThen you just have to import and use it in your code like this import v as uuid from uuid let myUUID uuid Returns a random UUID xxxxxxx xxxx xxxx xxxx xxxxxxxxxxxxThe uuid package is a reliable method of creating UUIDs in Node JS  Option use the crypto getRandomValues methodIt is possible to generate your own uuid function using crypto getRandomValues This is useful in situations where you re dealing with Node JS versions before or have to support old browsers crypto getRandomValues is supported as far back as Chrome function uuid return replace g c gt c crypto getRandomValues new UintArray amp gt gt c toString This function is based off the work here and generates reliable UUIDs if you need your own function to do so Option Math random not recommended The last resort and the dirtiest solution is to use Math random however this is not generally a good idea since Math random does not do a sufficiently good job of generating UUIDs to enure uniqueness You should also not need this since we now have the crypto randomUUID method widely available If you want a real UUID it s best to avoid this solution but it can provide a quick fix on a project where you need a UUID fast for testing This could be acceptable as a fall back when you don t have randomUUID support or the uuid package available function uuid return xxxxxxxx xxxx xxx yxxx xxxxxxxxxxxx replace xy g function c var r Math random v c x r r amp x x return v toString  ConclusionThat about covers all the different ways to make UUIDs in Javascript Hope you ve enjoyed this guide check out more about Javascript here 2022-11-13 14:39:50
海外TECH DEV Community Five simple steps to use any Arduino C++ library in a Rust project 🦀 https://dev.to/kgrech/five-simple-steps-to-use-any-arduino-c-library-in-a-rust-project-1k78 Five simple steps to use any Arduino C library in a Rust project Arduino helps circuit developers to build electronic projects and is perhaps the most used open source hardware and software platform It is popular across millions of hobbyists across the world Historically Arduino boards are programmed with C programming language using the Arduino IDE The availability of powerful ARM based Arduino compatible boards made it possible to use python JavaScript or even a browser to program your circuit While they are easier to study for a new joiner without an existing programming background C stays a default language choice especially when dealing with cheap and low memory AVR controller boards and having a need to run more or less complex projects However the compact binary size and efficiency of compiled code is probably not the main advantage of the traditional Arduino ecosystem If the project is more complex than blinking the led it would likely require integration with the range of sensors servo motors and other third party peripheries Most manufacturers develop precisely C Arduino compatible driver libraries to be used out of the box Rust language shares all advantages of efficient C code With the rust community growing year after year more and more people try using rust to program their Arduino boards Consequently the Arduino Rust ecosystem have significantly developed in the last couple of years The Hardware Abstraction Layer for AVR microcontrollers avr hal Rudino library and ravedude CLI utility to make Rust development for AVR microcontrollers easier are just a few examples of the solid foundation developed so far Third party library availability is however still lagging behind Luckily enough Rust supports nearly seamless interaction with the C code While it is very well possible to link almost any Arduino library to the rust project I was not able to find any meaningful description of the steps required to do so My best hit was the rust arduino helpers project Despite that the code quality is unfortunately not great it contains large fragments of commented code and was not updated for a while it was a great help for me to find the right direction The absence of the well documented steps was my motivation to write this tutorial Project and GoalsHere is the set of steps we will cover today Prepare environment to program Arduino board with Rust Create the avr hal based rust project and blink the led Compile Arduino SDK and the third party library and link it to the rust project Generate rust bindings for the Arduino library Write the code and run it on your board The list of the hardware I ve had in my possession for this project is the following Arduino Uno board LCD Display Module with IC InterfaceLEDLinux or Windows PCWhat we are going to do is simply try writing a text message to the LCD Display using Rust In order to do so we will have to figure out how to link and use the LiquidCrystal IC Arduino library in our rust crate In other words we would like to do something like this but in Rust Here is the little demonstration of the final project As a bonus we will write a nice configuration file to configure Arduino dependencies to make the setup extensible and reusable The source code is available on GitHub I was able to run it on both Linux and Windows PC I would be focusing on the Linux Fedora installation steps in this tutorial windows users could refer to the corresponding section in the readme md file This article assumes the reader has the basic knowledge about Rust project setup I also assume the reader has a rust standard development environment rustup and cargo configured Step Environment setup Compiler and Arduino IDEArduino IDE and Arduino libraries are intended to be used by non professional programmers and so they are designed to just work out of the box We will have to gain some understanding of what happens under the hood of them to be able to compile the Arduino code outside of the Arduino IDE First all we would need to download and install the Arduino IDE I am using version Linux users could install it running the following command curl fsSL shAt this point you can run some Arduino C Hello World project to ensure that your board is recognized by your PC and working fine It is also important because it would force Arduino IDE to download require tools and libraries While you are there install LiquidCrystal IC library to Arduino Libraries folder using Arduino IDE like how you would normally do Next we need to familiarize ourselves with a set of tools used for AVR development avrdude is a command line program for programming AVR chips It allows uploading compiled sketch to your board avr gcc is a compiler that takes C language high level code and creates a binary source which can be uploaded into an AVR micro controller avr libc is C standard library for use with avr gcc on Atmel AVR microcontrollers These tools come bundled with the Arduino IDE On my laptop they are installed in the arduino packages arduino tools folder Despite this I prefer to also install the system wide copy of them from Fedora repositories to avoid adding the above folder to the PATH manually sudo dnf install avrdude avr gcc avr libcThe above step is technically optional I skipped it on Windows as there is no easy way to the same there RavedudeWe could have been just using avrdude to program our board However since we are planning to develop in rust ravedude would be a better alternative as we could just configure it as a runner for cargo build tool I had to install some dependencies to compile ravedude first sudo dnf install systemd devel pkgconf pkg configInstalling ravedude is then as easy as runningcargo install ravedudeI also assume the reader has a rust standard development environment rustup and cargo configured BindgenWe are planning to use rust bindgen project to automatically generate rust bindings based on the C library header We will use bindgen as rust library during the build time however it require libclang to operate so we have to install it sudo dnf install clang devel Cargo generateWe would like to simply the next step and use cargo generate tool to create our Arduino project from a template Somehow please do not ask me why it requires Perl to compile so we have to do sudo dnf install perlcargo install cargo generate Step Project setupAs I ve just mentioned we would create out project using cargo generate command cargo generate git You will have to specify the project name and select the board type There is an excellent creativcoder s article outlining the process step by step in case you would like to do project the setup manually Have a look to cargo config toml to understand why we ve installed ravedude earlier The following section target cfg target arch avr runner ravedude uno cb passing compiled file to ravedude when you execute cargo run command so it would be programmed to your board ravedude would also listen the serial port to print the debug output of your sketch Let s update main rs with a simple program to use the serial port and blink the LED on a pin use arduino hal prelude use panic halt as arduino hal entry unsafe fn main gt let dp arduino hal Peripherals take unwrap let pins arduino hal pins dp let mut serial arduino hal default serial dp pins let mut led pins d into output ufmt uwriteln amp mut serial Hello world r void unwrap loop led toggle arduino hal delay ms Simply executecargo runand the above code should be running on your board If you are having trouble understanding the above code consider referring to avr hal documentation and creativcoder s article for more information Step Compile and Link Arduino SDK and library Arduino SDK dependencyOk we have a working rust project Let s connect our IC display to the Arduino board as explained in the article and try figure out how we can port the C example outlined there to rust include lt LiquidCrystal IC h gt LiquidCrystal IC lcd xF set the LCD address to xF for a chars and line displayvoid setup lcd init lcd clear lcd backlight Make sure backlight is on Print a message on both lines of the LCD lcd setCursor Set cursor to character on line lcd print Hello world lcd setCursor Move cursor to character on line lcd print LCD Tutorial void loop Clearly we would like to compile LiquidCrystal IC link it to our crate as a dependency and call the same functions from rust Ok should be easy right Well if you just have a standalone C library compiling and calling it from rust is straightforward Let s have a closer look at the source code of LiquidCrystal IC cpp include lt inttypes h gt include lt Arduino h gt include lt Wire h gt What are they Arduino h is the main include file for the Arduino SDKWire h is TWI IC library for Arduino amp Wiring provided as part of Arduino SDKinttypes h is standard library header file providing the support for width based integral types What does it mean Well it means we can t just use LiquidCrystal IC alone without compiling Arduino SDK Compiling Arduino SDK and the library Configuring Arduino SDK locationLet s create an empty file named build rs in the root of our project This is where we would write steps to compile a link to Arduino dependencies First we should find the location of Arduino SDK and rd party LiquidCrystal IC library installed earlier In my case Arduino is installed at arduino and rd party library folder is Arduino libraries We could have just hardcoded the above as a constant in our build rs but let s try to apply some better engineering principles and make our configuration more reusable I propose to create a file called arduino yaml next to the build rs We could then use serde yaml to read it in the build rs file to avoid making code changes if the location changes in the future arduino home HOME arduinoexternal libraries home HOME Arduino librariesNow let s locate the Arduino SDK inside the home folder of Arduino In my case it is arduino packages arduino hardware avr The path is pretty standard but the version might change in future so we can move the version to our yaml file as well The Arduino SDK folder contains a set of the subfolders but we are interested in two of them libraries and variants The libraries folder contains the code which can run on any Arduino board This is where we can find Wire library we need Nice The variants folder definition of the pins specific to the given board The folder for Arduino UNO is called eightanaloginputs again do not ask my why please Finally we would also need C standard library headers e g inttypes h provided by the compiler It is also installed with Arduino In my case the path is arduino packages arduino tools avr gcc atmel arduino avr include We can now add more information to our arduino yaml specifying the core version the compiler version list of Arduino and external libraries to build arduino home HOME arduinoexternal libraries home HOME Arduino librariescore version variant eightanaloginputsavr gcc version atmel arduinoarduino libraries Wireexternal libraries LiquidCrystal IC Reading the configurationWe can now read the above file in build rs In order to do some add serde yaml compile time dependency We would also use envmnt crate to resolve the environment variables mentioned in the file build dependencies envmnt serde version features derive serde yaml Then we can define the Config struct and helper methods to construct the above path in the codeconst CONFIG FILE amp str arduino yaml derive Debug Deserialize struct Config pub arduino home String pub external libraries home String pub core version String pub variant String pub avr gcc version String pub arduino libraries Vec lt String gt impl Config fn arduino package path amp self gt PathBuf let expanded envmnt expand amp self arduino home None let arduino home path PathBuf from expanded arduino home path join packages join arduino fn core path amp self gt PathBuf self arduino package path join hardware join avr join amp self core version fn avr gcc homeavr gcc home amp self gt PathBuf self arduino package path join tools join avr gcc join amp self avr gcc version fn avg gcc amp self gt PathBuf self avr gcc home join bin join avr gcc fn arduino core path amp self gt PathBuf self core path join cores join arduino Since we were dealing with path we also defined the helper avg gcc method to provide the path to the compiler binaryWe can now read this file and print it to consolefn main println cargo rerun if changed CONFIG FILE let config string std fs read to string CONFIG FILE unwrap or else e panic Unable to read file CONFIG FILE e let config Config serde yaml from str amp config string unwrap or else e panic Unable to parse file CONFIG FILE e println Arduino configuration config The following line ensure the project is rebuild each time the yaml file is updated println cargo rerun if changed CONFIG FILE At this point we can run cargo build vv very verbose and be able to see the parse config printed Headers and sourcesOk we know where our dependencies are We will need to pass them to avr gcc compiler soon There are types of files we need to take care of Header files hC source code cC source code cppHeaders are the easiest to deal with We would just pass it to the compiler using I flag We need header folders to be included Arduino variant specific header s C standard libraryArduino librariesExternal librariesLet s implement the helper methods to get the paths of them impl Config fn arduino include dirs amp self gt Vec lt PathBuf gt let variant path self core path join variants join amp self variant let avr gcc include path self avr gcc home join avr join include vec self arduino core path variant path avr gcc include path fn arduino libraries path amp self gt Vec lt PathBuf gt let library root self core path join libraries let mut result vec for library in amp self arduino libraries result push library root join library join src result fn external libraries path amp self gt Vec lt PathBuf gt let expanded envmnt expand amp self external libraries home None let external library root PathBuf from expanded let mut result vec for library in amp self external libraries result push external library root join library result fn include dirs amp self gt Vec lt PathBuf gt let mut result self arduino include dirs result extend self arduino libraries path result extend self external libraries path result C and C files would be passed to the compiler as an input one by one The will need to be compiled with a slightly different set of the compiler flags so let s define separate helpers to get the list of them impl Config fn project files amp self patten amp str gt Vec lt PathBuf gt let mut result files in folder self arduino core path to string lossy as ref patten let mut libraries self arduino libraries path libraries extend self external libraries path let pattern format patten for library in libraries let lib sources files in folder library to string lossy as ref amp pattern result extend lib sources result fn cpp files amp self gt Vec lt PathBuf gt self project files cpp fn c files amp self gt Vec lt PathBuf gt self project files c fn files in folder folder amp str pattern amp str gt Vec lt PathBuf gt let cpp pattern format folder pattern let mut results vec for cpp file in glob amp cpp pattern unwrap let file cpp file unwrap if file ends with main cpp results push file results Here we use the glob create to look for the files recursively so we need to also add it to Cargo toml as a build dependency glob Compiler flags and definitionsIn order to compile for Arduino UNO we would need to pass some board specific flags to the compiler in paricular DARDUINO DF CPU L DARDUINO AVR UNO DARDUINO ARCH AVR mmcu atmegapAs they are board specific let s move the definition of them to arduino yaml as well definitions ARDUINO F CPU L ARDUINO AVR UNO ARDUINO ARCH AVR flags mmcu atmegap We will also have to add corresponding fields to a Config struct derive Debug Deserialize struct Config Existing fields here pub definitions HashMap lt String String gt pub flags Vec lt String gt Compilation and linkingWhile it is technically possible to construct the command line to invoke compiler manually using the CC crate is a much better option Let s add the CC dependency to Cargo toml build dependencies cc As mentioned above C and C code needs be compiled with a slightly different set of flags Let s define a helper function to define the common part of the configurationfn configure arduino config amp Config gt Build let mut builder Build new for k v in amp config definitions builder define k v as str for flag in amp config flags builder flag flag builder compiler config avg gcc flag Os cpp set stdlib None flag fno exceptions flag ffunction sections flag fdata sections for include dir in config include dirs builder include include dir builder Here we create CC provided builder and pass compile flags definition and include folders We can then use configured build to compile C C parts of Arduino standard library pub fn add source file builder amp mut Build files Vec lt PathBuf gt for file in files println cargo rerun if changed file to string lossy builder file file fn compile arduino config amp Config let mut builder configure arduino amp config builder cpp true flag std gnu flag fpermissive flag fno threadsafe statics add source file amp mut builder config cpp files builder compile libarduino c a let mut builder configure arduino amp config builder flag std gnu add source file amp mut builder config c files builder compile libarduino c a println cargo rustc link lib static arduino c println cargo rustc link lib static arduino c We simply compile each C and CPP file we can find together with the only exception of the main cpp as the main method is defined in rust CC crate will call avr gcc and produce to object files libarduino c a and libarduino c a We then instruct cargo to statically link rust code with them by printingcargo rustc link lib static arduino c cargo rustc link lib static arduino clines to the standard output Generate rust bindingsSo far we ve compiled the required dependencies with our rust project But running cargo run still does nothing but blinks the LED In order to interact with the display we need to write code to do so But how could we call a C function defined in liquidcrystal ic h from rust This is where bingen is coming to help Bingen takes C C header files as an input and generates rust definitions of the functions and types provided by them Let s add it to our Cargo toml as well build dependencies bindgen First step is to define the headers files to pass to bindgen We can just implement a small helper method to find them in the external libraries folder impl Config fn bindgen headers amp self gt Vec lt PathBuf gt let mut result vec for library in self external libraries path let lib headers files in folder library to string lossy as ref h result extend lib headers result Next we need to define the bingen configuration fn configure bindgen for arduino config amp Config gt Builder let mut builder Builder default for k v in amp config definitions builder builder clang arg amp format D k v for flag in amp config flags builder builder clang arg flag builder builder clang args amp x c std gnu use core layout tests false parse callbacks Box new bindgen CargoCallbacks for include dir in config include dirs builder builder clang arg amp format I include dir to string lossy for header in config bindgen headers builder builder header header to string lossy builder Note that we need to pass the same set of compiler flags and definitions to bingen as we passed to avr gcc earlier Then we can call generate method to generate the bindings and write them to src arduino rs file fn generate bindings config amp Config let bindings Bindings configure bindgen for arduino amp config generate expect Unable to generate bindings let project root PathBuf from env CARGO MANIFEST DIR join src join arduino rs bindings write to file project root expect Couldn t write bindings We can now open src arduino rs and see generated code A lot of generated code This is because by default bingen goes over each header file recursively and generates bindings for every type and method As we do not need most of them we can configure allow and block list to exclude useless parts To do so we can add a new section to arduino yaml bindgen lists allowlist function LiquidCrystal IC allowlist type LiquidCrystal IC blocklist function Print String blocklist type Print String We can then modify the config object derive Debug Deserialize struct BindgenLists pub allowlist function Vec lt String gt pub allowlist type Vec lt String gt pub blocklist function Vec lt String gt pub blocklist type Vec lt String gt derive Debug Deserialize struct Config Existing fields pub bindgen lists BindgenLists and configure bindgen for arduino function to make use of themfn configure bindgen for arduino config amp Config gt Builder Existing code for item in amp config bindgen lists allowlist function builder builder allowlist function item for item in amp config bindgen lists allowlist type builder builder allowlist type item for item in amp config bindgen lists blocklist function builder builder blocklist function item for item in amp config bindgen lists blocklist type builder builder blocklist type item builder arduino rs looks so much nicer now Step Writing and running the codeHave you ever wondered why there is no main method in the Arduino sketches Indeed the standard template of the Arduino file is the following void setup put your setup code here to run once void loop put your main code here to run repeatedly Remember the main cpp file we ve excluded in the step Let s look inside simplified code include lt Arduino h gt int main void init setup for loop if serialEventRun serialEventRun return Looks like no magic at all It just calls setup and then loop method in the loop We do not care about setup and loop in rust but what is the init call It turns out that it is Arduino SDK provided function to initialize the board We would need to call it in rust as well before we start using any Arduino library We could have just generated it using bindgen but since its signature is so simple no arguments we can just define it in place extern C fn init Now we are ready to modify our main rs with some code to initialize our display and print some text arduino hal entry unsafe fn main gt init let dp arduino hal Peripherals take unwrap let pins arduino hal pins dp let mut serial arduino hal default serial dp pins let mut led pins d into output ufmt uwriteln amp mut serial starting on r x void unwrap let mut lcd LiquidCrystal IC new x let ferris amp bu bu bu bu bu bu bu bu lcd begin lcd init lcd backlight lcd clear lcd printstr Good morning as ptr cast lcd setCursor lcd printstr from Rust as ptr cast lcd createChar ferris as ptr as mut lcd setCursor LiquidCrystal IC write amp mut lcd as mut LiquidCrystal IC cast loop led toggle arduino hal delay ms Here we combine the arduino hal method and the methods provided by LiquidCrystal IC library It is now time to run cargo run and see the message on the display Well done SummaryI really hope you ve learned something by reading this article We covered the following topics today Rust Arduino Environment setupStructure of Arduino SDKCompilation Arduino library linking it to rust crate and generation of the rust definitions for C methods If the article was useful for you please put a reaction and start the GitHub repository I am also happy to hear a feedback about the arduino yaml DSL developed as part of this article Would it be useful to move it into separate library to be used in the build time Is there a better way to do the same Please share your opinion in the comments 2022-11-13 14:27:16
海外TECH DEV Community High Performance Web Framework Tasting-Database Operations https://dev.to/justlorain/high-performance-web-framework-tasting-database-operations-3m7 High Performance Web Framework Tasting Database Operations IntroductionIn the previous post we gave a brief introduction to the high performance Go HTTP framework Hertz and completed a simple demo using Hertz to get you started In this post you ll learn more about using the Hertz framework with an official demo And we ll highlight the following features Use thrift IDL to define HTTP interfaceUse hz to generate codeUse Hertz binding and validateUse GORM and MySQL InstallationRun the following command to get the official demo git clone cd bizdemo hertz gorm Project Structurehertz gorm├ーbiz ├ーdal Logic code that interacts with the database│├ーhandler Main logical code that handles HTTP requests │├ーhertz gen Scaffolding generated by hertz from idl files ├ーmodel Go struct corresponding to the database table ├ーpack Transformation between database model and response model ├ーrouter Middleware and mapping of routes to handlers├ーgo mod go mod ├ーidl thift idl ├ーmain go Initialize and start the server ├ーrouter go Sample route registration├ーrouter gen go Route registration ├ーdocker compose yml docker compose yml├ーMakefile MakefileThis is the basic architecture for the project It s pretty clean and simple and hz generated a lot of scaffolding code for us as well Define IDLhz is a tool provided by the Hertz framework for generating code Currently hz can generate scaffolding for Hertz projects based on thrift and protobuf IDL The definition of an excellent IDL file plays an important role in developing with Hertz We will use the thrift IDL for this project as an example We can use api annotations to let hz help us with parameter binding and validation route registration code generation etc hz will generate the go tag based on the following api annotations so that Hertz can retrieve these values using reflection and parse them Field AnnotationThe go tagexpr open source library is used for parameter binding and validation of the Field annotation as shown in the following example for CreateUserRequest api thriftstruct CreateUserRequest string name api body name api form name api vd len gt amp amp len lt Gender gender api body gender api form gender api vd i age api body age api form age api vd gt string introduce api body introduce api form introduce api vd len gt amp amp len lt The form annotation allows hz to automatically bind the parameters in the form of an HTTP request body for us saving us the trouble of manually binding them using methods such as PostForm The vd annotation allows for parameter validation For example CreateUserRequest uses the vd annotation to ensure that the gender field is only or You may refer to here for more information about parameter validation syntax Method AnnotationThe Method annotation can be used to generate route registration code Consider the following UserService api thriftservice UserService UpdateUserResponse UpdateUser UpdateUserRequest req api post v user update user id DeleteUserResponse DeleteUser DeleteUserRequest req api post v user delete user id QueryUserResponse QueryUser QueryUserRequest req api post v user query CreateUserResponse CreateUser CreateUserRequest req api post v user create We defined POST methods and routes using post annotations and hz will generate handler methods for each route as well as route grouping middleware embedding scaffolding etc As shown in biz router user gorm api go and biz handler user gorm user service go And we can also define the business error code in the idl file api thriftenum Code Success ParamInvalid DBErr hz will generate constants and related methods for us based on these biz hertz gen user gorm api gotype Code intconst Code Success Code Code ParamInvalid Code Code DBErr Code Generate Code with hzAfter we finish writing IDL we can generate the scaffolding code for us by using hz Execute the following command to generate code hz new model dir biz hertz gen mod github com cloudwego hertz examples bizdemo hertz gorm idl idl api thriftExecute the following command to update the code if you edit the IDL after the first generated hz update model dir biz hertz gen idl idl api thriftOf course the project has already generated the code for you so you don t need to execute it When you actually use Hertz for web development yourself I m sure you ll find it a very efficient and fun tool Use MiddlewareIn this project we configured the root route group to use the gzip middleware for all routes to improve performance biz router user gorm middleware gofunc rootMw app HandlerFunc your code use gzip middleware return app HandlerFunc gzip Gzip gzip DefaultCompression Just add one line of code to the generated scaffolding code very easy You can also refer to the hertz contrib gzip for more custom configuration Manipulating database with GORM Configure GORMTo use GORM with a database you first need to connect to the database using a driver and configure GORM as shown in biz dal mysql init go biz dal mysql user gopackage mysqlimport gorm io driver mysql gorm io gorm gorm io gorm logger var dsn gorm gorm tcp localhost gorm charset utf amp parseTime True amp loc Local var DB gorm DBfunc Init var err error DB err gorm Open mysql Open dsn amp gorm Config SkipDefaultTransaction true PrepareStmt true Logger logger Default LogMode logger Info if err nil panic err Here we connect with MySQL database by means of DSN and maintain a global database operation object DB In terms of GORM configuration since this project does not involve the operation of multiple tables at the same time we can configure SkipDefaultTransaction to true to skip the default transaction and enable caching through PrepareStmt to improve efficiency We also use the default logger so that we can clearly see the SQL generated for us by GORM Manipulating MySQLGORM concatenates SQL statements to perform CRUD so the code is very concise and easy to read where all the database operations are in biz dal mysql user go We also declare a model corresponding to the database table the gorm Model contains some common fields which GORM can automatically fill in for us and support operations such as soft deletion biz model user gotype User struct gorm Model Name string json name column name Gender int json gender column gender Age int json age column age Introduce string json introduce column introduce Handle HTTP RequestIn this section we ll explore the handler biz handler user gorm user service go which is the main business logic code CreateUser amp DeleteUser amp UpdateUser CreateUserSince we are using api annotations in the thift IDL BindAndValidate will do the parameter binding and validation for us Very conveniently all valid parameters will be injected into CreateUserRequest If there is an error we can use the JSON method to return the data in JSON format Whether it is CreateUserResponse or the business code we can directly use the code generated by hz After that we can insert a new user into MySQL by calling the CreateUser in the dal layer passing in the encapsulated arguments If there is an error we return JSON with the error code and information just like we did in the beginning Otherwise the correct service code is returned to represent the successful creation of the user biz handler user gorm user service go CreateUser router v user create POST func CreateUser ctx context Context c app RequestContext var err error var req user gorm CreateUserRequest err c BindAndValidate amp req if err nil c JSON amp user gorm CreateUserResponse Code user gorm Code ParamInvalid Msg err Error return if err mysql CreateUser model User Name req Name Gender int req Gender Age req Age Introduce req Introduce err nil c JSON amp user gorm CreateUserResponse Code user gorm Code DBErr Msg err Error return resp new user gorm CreateUserResponse resp Code user gorm Code Success c JSON resp DeleteUserThe logic for DeleteUser and CreateUser is almost identical Bind and validate the arguments use mysql DeleteUser to delete the user and return if there is an error otherwise return success biz handler user gorm user service go DeleteUser router v user delete user id POST func DeleteUser ctx context Context c app RequestContext var err error var req user gorm DeleteUserRequest err c BindAndValidate amp req if err nil c JSON amp user gorm DeleteUserResponse Code user gorm Code ParamInvalid Msg err Error return if err mysql DeleteUser req UserID err nil c JSON amp user gorm DeleteUserResponse Code user gorm Code DBErr Msg err Error return c JSON amp user gorm DeleteUserResponse Code user gorm Code Success UpdateUserUpdateUser is much the same with the notable model transformation from an object that receives HTTP request parameters to a data access object that corresponds to a database table biz handler user gorm user service go UpdateUser router v user update user id POST func UpdateUser ctx context Context c app RequestContext var err error var req user gorm UpdateUserRequest err c BindAndValidate amp req if err nil c JSON amp user gorm UpdateUserResponse Code user gorm Code ParamInvalid Msg err Error return u amp model User u ID uint req UserID u Name req Name u Gender int req Gender u Age req Age u Introduce req Introduce if err mysql UpdateUser u err nil c JSON amp user gorm UpdateUserResponse Code user gorm Code DBErr Msg err Error return c JSON amp user gorm UpdateUserResponse Code user gorm Code Success QueryUserWhat s worth noting in QueryUser is that we re doing paging and a transformation from model User to user gorm User which is the reverse of the operation we just mentioned in UpdateUser With a simple paging formula startIndex currentPage pageSize we re paging the data as we re querying it And this time we ve wrapped our transformation model in biz pack user go biz pack user go Users Convert model User list to user gorm User listfunc Users models model User user gorm User users make user gorm User len models for m range models if u User m u nil users append users u return users User Convert model User to user gorm Userfunc User model model User user gorm User if model nil return nil return amp user gorm User UserID int model ID Name model Name Gender user gorm Gender model Gender Age model Age Introduce model Introduce biz handler user gorm user service go QueryUser router v user query POST func QueryUser ctx context Context c app RequestContext var err error var req user gorm QueryUserRequest err c BindAndValidate amp req if err nil c JSON amp user gorm QueryUserResponse Code user gorm Code ParamInvalid Msg err Error return users total err mysql QueryUser req Keyword req Page req PageSize if err nil c JSON amp user gorm QueryUserResponse Code user gorm Code DBErr Msg err Error return c JSON amp user gorm QueryUserResponse Code user gorm Code Success Users pack Users users Totoal total The rest of the business logic is the same as before and we re done with all the handler functions Run DemoRun mysql dockercd bizdemo hertz gorm amp amp docker compose upGenerate MySQL tableConnect MySQL and execute user sqlRun democd bizdemo hertz gormgo build o hertz gorm amp amp hertz gorm SummaryThat s it for this post Hopefully it will give you a quick overview of how to develop with Hertz and GORM Both of them are well documented Feel free to check out the official documentation for more information Reference List 2022-11-13 14:25:20
海外科学 NYT > Science Your Cat Might Not Be Ignoring You When You Speak https://www.nytimes.com/2022/11/12/science/cat-talking-owners-voice-dog.html study 2022-11-13 14:20:43
ニュース BBC News - Home Jeremy Hunt: Everyone will have to pay more tax https://www.bbc.co.uk/news/uk-politics-63614124?at_medium=RSS&at_campaign=KARANGA chancellor 2022-11-13 14:07:26
ニュース BBC News - Home Istanbul: Four dead, dozens wounded in explosion https://www.bbc.co.uk/news/world-europe-63615076?at_medium=RSS&at_campaign=KARANGA turkish 2022-11-13 14:56:23
ニュース BBC News - Home T20 World Cup: England beat Pakistan to win T20 World Cup https://www.bbc.co.uk/sport/av/cricket/63616028?at_medium=RSS&at_campaign=KARANGA T World Cup England beat Pakistan to win T World CupWatch highlights as Ben Stokes Sam Curran and Adil Rashid star in helping England claim their second T World Cup title with a five wicket victory over Pakistan in the final 2022-11-13 14:45:28
ニュース BBC News - Home Burnley 3-0 Blackburn Rovers: Clarets win East Lancashire derby to return to top of Championship https://www.bbc.co.uk/sport/football/63531134?at_medium=RSS&at_campaign=KARANGA Burnley Blackburn Rovers Clarets win East Lancashire derby to return to top of ChampionshipTwo goal Ashley Barnes and Anass Zaroury score as Burnley hammer Blackburn Rovers to return to the top of the Championship 2022-11-13 14:37:38
北海道 北海道新聞 日韓首脳、3年ぶり正式会談 元徴用工問題の早期解決で一致 https://www.hokkaido-np.co.jp/article/759985/ 岸田文雄 2022-11-13 23:07:56

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)