IT |
ITmedia 総合記事一覧 |
[ITmedia News] Excelのシート名に設定できない言葉は〇〇 そのワケとは? |
https://www.itmedia.co.jp/news/articles/2308/28/news113.html
|
excel |
2023-08-28 15:40:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia ビジネスオンライン] 八ツ場ダム建設で廃止の線路を行く 吾妻峡レールバイク「アガッタン」 |
https://www.itmedia.co.jp/business/articles/2308/28/news106.html
|
観光資源 |
2023-08-28 15:30:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia PC USER] R0DE、4Kパススルー出力も備えた配信向けオールインワンデバイス |
https://www.itmedia.co.jp/pcuser/articles/2308/28/news112.html
|
itmediapcuserrde |
2023-08-28 15:28:00 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Pythonの仮想環境構築について |
https://qiita.com/taidong5588/items/740f1015b5d67297400a
|
macos |
2023-08-28 15:30:19 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
plunkerでvue その57 |
https://qiita.com/ohisama@github/items/3229ab46bb69226ad70b
|
ategtltdivgtlthgtfizzbuzz |
2023-08-28 15:38:08 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
【AWS】 EC2インスタンスへElastic IP再紐付けの自動化 |
https://qiita.com/minimabot/items/46e159ad73fda15fc9f6
|
amazon |
2023-08-28 15:44:15 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
S3からBigQuery Data Transfer Serviceでインポート時にAccess Denied |
https://qiita.com/kawashinji/items/512c2f44052d572d6e23
|
errorc |
2023-08-28 15:41:44 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
Github ActionsでVPSに自動デプロイする(AWS lightsail) |
https://qiita.com/noshiro3/items/aa677dd598cb8aa0535e
|
awslightsail |
2023-08-28 15:28:15 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
Dockerでマルチラインの環境変数を扱いたかった |
https://qiita.com/kyubey1228/items/2a12b26ea0894d31e7cf
|
docker |
2023-08-28 15:20:55 |
技術ブログ |
Developers.IO |
大阪オフィスで開催された勉強会で「OpentelemetryでアプリケーションのObservabilityを強化しよう」というテーマで発表しました |
https://dev.classmethod.jp/articles/osaka-cx-meetup-opentelemetry/
|
observability |
2023-08-28 06:04:58 |
海外TECH |
DEV Community |
Angular Signals: A Reactive Way to Manage State |
https://dev.to/chintanonweb/angular-signals-a-reactive-way-to-manage-state-lih
|
Angular Signals A Reactive Way to Manage StateIntroductionAngular introduced a new feature called Signals which provide a reactive way to manage state in Angular applications Signals are based on the Observer design pattern which means that they can be used to subscribe to changes in a value and be notified when those changes occur This makes them ideal for managing state in Angular applications where it is important to be able to react to changes in data as quickly as possible What are Signals A Signal is a function that returns a value and can be updated by calling it with a new value Signals can also depend on other signals creating a reactive value graph that automatically updates when any dependencies change Signals are available in the angular core module and can be used in any Angular application How to Use SignalsTo use a Signal you first need to create one You can do this by importing the Signal class from the angular core module and then calling the new keyword import Signal from angular core const mySignal new Signal Once you have created a Signal you can set its value by calling the set method mySignal set You can also subscribe to changes in the Signal s value by calling the subscribe method The subscribe method takes a callback function as its argument This callback function will be called whenever the Signal s value changes mySignal subscribe value gt console log The value of the signal has changed to value Benefits of Using SignalsThere are several benefits to using Signals to manage state in Angular applications First Signals are reactive which means that they notify subscribers of changes as soon as they occur This can help to improve the performance of your application by reducing the number of unnecessary change detection cycles Second Signals are easy to use They can be used in a similar way to observables but they are simpler to understand and implement Third Signals can be used to create unidirectional data flow This can help to improve the readability and maintainability of your code When to Use SignalsSignals are a good choice for managing state in Angular applications where it is important to be able to react to changes in data as quickly as possible They are also a good choice for applications where you need to create unidirectional data flow ExampleHere is an example of how to use Signals to manage state in an Angular application import Component OnInit from angular core import Signal from angular core Component selector my app templateUrl app component html export class AppComponent implements OnInit Create a Signal to track the current count count new Signal ngOnInit Subscribe to changes in the count Signal this count subscribe value gt console log The count is now value Increase the count by incrementCount this count set this count value In this example we create a Signal to track the current count We then subscribe to changes in the count Signal and log the new value to the console whenever the value changes Finally we provide a method to increment the count by ConclusionSignals are a powerful new feature in Angular that can be used to manage state in a reactive way They are easy to use and can help to improve the performance and readability of your code If you are looking for a way to manage state in your Angular applications I encourage you to give Signals a try FAQWhat are the limitations of Signals Signals have a few limitations First they are not as flexible as observables Second they cannot be used to create nested subscriptions What are some alternatives to Signals Some alternatives to Signals include observables BehaviorSubjects and ReplaySubjects |
2023-08-28 06:24:44 |
海外TECH |
DEV Community |
Automating CI/CD (Continuous Integration/Continuous Deployment) pipelines for AI and ML |
https://dev.to/blackrossay/automating-cicd-continuous-integrationcontinuous-deployment-pipelines-for-ai-and-ml-1dik
|
Automating CI CD Continuous Integration Continuous Deployment pipelines for AI and MLAutomating CI CD Continuous Integration Continuous Deployment pipelines for AI and ML projects is crucial for ensuring efficient development testing and deployment processes In this case I would highly recomemnd G CloudArts service CodeArts is a one stop cloud based DevSecOps platform that provides a bundle of out of the box cloud services covering requirement delivery code commit code check code build verification deployment and release It streamlines software delivery and provides EE software R amp D support Here s a high level overview of how you can automate CI CD pipelines specifically for AI and ML projects Version Control System VCS Start by using a version control system like Git to manage your AI ML project s code data and model files Host your repository on platforms like GitHub GitLab or Bitbucket Infrastructure as Code IaC Define your infrastructure virtual machines containers etc as code using tools like Terraform or CloudFormation This ensures consistent and reproducible environments for development testing and deployment Choose a CI CD Tool Select a CI CD tool that supports the automation of AI ML pipelines Popular options include G Cloud CodeArts Jenkins GitLab CI CD Travis CI CircleCI and Azure DevOps Some platforms like GitLab also offer specialized features for ML pipelines Pipeline Configuration Define your CI CD pipeline stages and tasks in the chosen tool s configuration file e g gitlab ci yml for GitLab CI CD These stages typically include Build Set up the environment install dependencies and build your AI ML code Test Run unit tests integration tests and any custom validation scripts Train and Evaluate Models Train your ML models using available data and evaluate their performance Package Create deployment ready artifacts such as Docker containers or model files Deploy Deploy models to production or staging environments Environment Management Use tools like Docker Kubernetes or G Cloud Container Engine CCE to containerize your AI ML applications This ensures consistent environments across development testing and production Automated Testing Implement automated testing for your AI ML models This could involve unit tests for code data validation tests and model performance tests Tools like pytest and TensorFlow s testing framework can be helpful Artifact Storage Store your trained models datasets and other artifacts in a versioned and accessible storage system such as G Cloud Object Storage Service OBS AWS S Google Cloud Storage or an artifact repository like JFrog Artifactory Continuous Deployment Set up automated deployment to your target environment using the defined pipeline This might involve deploying models as REST APIs deploying containers to Kubernetes or G Cloud CCE clusters or deploying to cloud platforms like G Cloud FunctionGraph AWS Lambda or Azure Functions Monitoring and Logging Implement monitoring and logging solutions to keep track of the pipeline s health and performance This helps catch issues early and ensures reliable deployments Feedback Loop and Iteration Continuously improve your CI CD pipeline based on feedback As your AI ML project evolves you might need to adjust your pipeline to accommodate new features data and requirements Security and Privacy Pay special attention to security and privacy aspects especially when dealing with sensitive data Implement proper access controls encryption and data anonymization as necessary Documentation Document your CI CD pipeline and the steps required to set it up This makes it easier for team members to understand and contribute to the pipeline Remember that AI ML projects can be complex and your CI CD pipeline should be tailored to your specific needs Regularly review and update your pipeline to adapt to changes in technology and project requirements Find me on my socialsLinkedIn ashley chamboko b twitter X blackrossayemail blackrossay gmail com |
2023-08-28 06:24:14 |
海外TECH |
DEV Community |
Optimizing iOS Apps for Different Screen Sizes and Resolutions: A Comprehensive Guide |
https://dev.to/dhruvjoshi9/optimizing-ios-apps-for-different-screen-sizes-and-resolutions-a-comprehensive-guide-2m9e
|
Optimizing iOS Apps for Different Screen Sizes and Resolutions A Comprehensive GuideAre you an iOS app developer With the increasing diversity of iOS devices optimizing your apps for various screen sizes and resolutions is crucial to provide a seamless user experience Learn the best practices from this blog Discover how to Create a responsive UI with Auto LayoutDesign for different screen densities using high resolution assets and vector graphicsUtilize size classes to adapt your UI across devicesApply constraints to control element positioningEnhance your app using the safe area to avoid cut off elementsLeverage a design system for a consistent UIAdopt a responsive design approach for flexibilityRead Full Blog here How to Optimize iOS Apps for Different Screen Sizes and Resolutions Quokka Labs Optimize your iOS app for different screen sizes and resolutions with Auto Layout Dynamic Type and testing quokkalabs com By optimizing your iOS apps you ensure they look exceptional and work flawlessly on any device regardless of its dimensions Don t miss out on the chance to improve user experiences attract more downloads and boost app ratings Read the full blog for in depth insights and step up your iOS app development game |
2023-08-28 06:22:38 |
海外TECH |
DEV Community |
LED interactive floor tile screen application guide |
https://dev.to/sostrondylan/led-interactive-floor-tile-screen-application-guide-29g5
|
LED interactive floor tile screen application guideThe LED floor tile screen is a personalized LED display specially designed for the ground Compared with the traditional LED display screen the LED floor tile screen has been specially designed and processed in terms of load bearing protective performance and heat dissipation performance so that it can adapt to high intensity trampling and run normally for a long time Take you minutes to understand the working principle of the LED interactive floor tile screen The LED interactive floor tile screen is based on the LED floor tile screen adding a sensory interaction function With the help of infrared sensing it can track the trajectory of people s movement and can follow the activities of the human body to present instant picture effects so that effects such as actors and audience walking by water ripples appearing under the feet and flowers blooming can be realized LED floor screens have a wide range of applications and their attention grabbing and creative interactivity make them useful in multiple industries Entertainment venues Entertainment venues such as amusement parks theme parks entertainment centers and nightclubs use LED floor screens to increase fun and interactivity These screens can be used to create immersive experiences such as interactive games musical performances or visual effects on the floor The stage adopts the p LED display model which can dynamically play video content can be stepped on and has a built in sensor chip to track footsteps presenting a timely interactive picture effect and realizing interaction with people which is very interesting Exhibitions and Museums Museums exhibitions and art galleries utilize LED floor screens to enhance the educational and entertainment experience of the audience They can be used to present historical information simulate environments or give viewers insight into artworks and exhibits Hotels and restaurants High end hotels and restaurants can enhance customer experience by installing LED screens in the lobby or on the restaurant floor These screens can display welcome messages menus special offers or decorative visuals The restaurant with LED interactive floor tile screen created by using sound electricity and light is favored by customers which enhances the attractiveness of the restaurant increases the passenger flow and improves the dining experience of users Stadiums Stadiums use LED floor screens to increase the entertainment of games These screens can display stadium advertisements game statistics and celebrations engaging spectators and increasing interactivity Displays and exhibitions In various displays and exhibitions LED floor screens are used to attract audiences and convey information They can be used to showcase new products company information or provide an interactive display Education In the field of education LED floor screens can be used for interactive teaching providing opportunities for student participation Teachers and students can explore course content through touch and interaction The kindergarten adopts LED interactive floor tile screen wall screen which can not only carry out publicity but also mobilize the enthusiasm of children When stepping on the LED interactive floor tile screen the screen will project fireworks lake water fish birds and other patterns to attract children s attention and the patterns on the floor tile screen will also change with the children s footsteps LED floor screens are used in a wide variety of industries and their interactivity visual appeal and messaging capabilities make them innovative and eye catching tools These screens are still evolving and new areas of application may emerge in the future LED floor screens offer many opportunities for innovation in advertising and branding They generate interest provide interactivity deliver a brand message and have potential for branding Thank you for watching I hope we can solve your problems Sostron is a professional LED display manufacturer We provide all kinds of displays display leasing and display solutions around the world |
2023-08-28 06:17:31 |
海外TECH |
DEV Community |
Add License Headers to Your Code Files: NWA - A More Powerful License Statement Management Tool |
https://dev.to/justlorain/add-license-headers-to-your-code-files-nwa-a-more-powerful-license-statement-management-tool-86o
|
Add License Headers to Your Code Files NWA A More Powerful License Statement Management Tool IntroductionAs developers we often need to ensure that our code complies with the appropriate licenses to protect our intellectual property This article introduces a more powerful license statement management tool called NWA It helps you effortlessly add license headers to your code files and also check update and remove existing license statements ensuring the legality and compliance of your code What Is a License Statement A license statement license header is a comment section at the top of a source code file that declares the licensing information for the code It typically includes copyright information license type and other relevant legal statements License statements help protect the rights of the code s author and also help other developers understand how they can use the code If you ve ever looked at code files from open source projects you ve probably noticed that they clearly mark their license statements within the code files For example kubernetesspring bootAdditionally some open source projects use tools like GitHub Actions to check if your code has the correct license header when you submit a pull request hertz License Header Adding ToolsUsually we need to display license statements in the form of comments at the beginning of each code file similar to what kubernetes and spring boot did in the previous section However when you are working on a large project the number of code files can become extensive making manually adding license headers a tedious and painful task This is where license header adding tools come in handy One commonly used tool is the addlicense project under the google organization addlicense allows you to add license statements to specified files via command line interaction However addlicense has limited functionality it only adds license headers to files Some issues raised for addlicense include Request for support for line comments instead of only block comments Request to add a feature for updating license statements Request for customizable license statement checking logic Unfortunately issue is not supported due to concerns about adding complexity to addlicense issue is marked as unsupported and issue is currently awaiting review NWA s development took these issues into consideration and provided solutions It also supports more operations related to license statements such as removal You can see how NWA addresses these issues and get started quickly in the Usage section Installation Installation via Go if you have Go installed go install github com BNARY GRUP nwa latestExecute the following command to verify a successful installation nwa version Installation via Docker if you don t have Go installed InstallationGet NWA s Docker image directly docker pull ghcr io bnary grup nwa mainAlternatively you can build the image from source for example docker build t ghcr io bnary grup nwa main Verify Installationdocker run it ghcr io bnary grup nwa main versionMount the directory you want NWA to operate on to src Here s an example but you can learn more about NWA s usage in the Usage section docker run it v PWD src ghcr io bnary grup nwa main add c RHINE LAB LLC y UsageTo help you get started with NWA s functionality developers have provided nwa examples to help you learn how to use NWA in a practical way You can clone this project and follow the tutorial or simply refer to this guide and use nwa examples for more usage examples NWA is a command line tool built on cobra Here s an overview of NWA s commands Usage nwa command Common Mode Commands add add license headers to files check check license headers of files remove remove license headers of files update update license headers of filesConfig Mode Commands config edit the files according to the configuration fileAdditional Commands help Help about any commandFlags h help help for nwa v version version for nwaUse nwa command help for more information about a command Command List Add Add license headers to files Remove Remove license headers from files Update Update license headers in files Check Check license headers in files Config Edit license headers in files using a configuration file Add Add License Headers to Files Usagenwa add flags path Use the add command after nwa to add license headers flags allows you to specify optional flags and path lets you specify one or more file paths to add license headers to Examplenwa add l apache c RHINE LAB LLC y server utils bufferpoolIn the above example the command adds the following to all files in the relative paths server and utils bufferpool License type Apache Copyright holder RHINE LAB LLC Copyright year NWA generates the corresponding license statement for each file based on its type e g py files use comments and go files use comments If your file type is not supported by NWA you can Specify a template file using the t tmpl flag Contribute to NWA by creating an issue or pull request NWA will also provide logoutputs indicating files that already have license headers or are not allowed for editing such as some generated code files FlagsThe add command supports the following flags Short FlagLong FlagDefaultDescription c copyright lt COPYRIGHT HOLDER gt Copyright holder l licenseapacheLicense type m mutefalse unspecified Mute mode s skip Skipped file paths t tmpl Template file path y yeartime Now Year current year Copyright year h helpNoneHelpMost flags are self explanatory Notable flags are s skip and t tmpl s s default value is an empty array so you can use zero or more s flags to specify file paths to skip This path supports doublestar syntax making it very flexible For example nwa add s py s example txt c Lorain t allows you to specify a template file path NWA reads the content of this template file and adds its content to the files that require license headers Note If you specify a template NWA won t generate license headers based on file types and it will ignore c l and y configurations Here s an example of a template file example tmpl txt Copyright RHINE LAB LLC Licensed under the Apache License Version the License you may not use this file except in compliance with the License You may obtain a copy of the License at 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 For more usage examples refer to nwa examples Remove Remove License Headers from Files Usagenwa remove flags path Use the remove command after nwa to remove license headers flags allows you to specify optional flags and path lets you specify one or more file paths to remove license headers from Examplenwa remove l mit c RHINE LAB LLC s py pkgIn the above example the command removes the following from all non Python files in the relative path pkg License type MITCopyright holder RHINE LAB LLC Copyright year NWA provides log outputs indicating files without license headers or files that are not editable FlagsThe remove command supports the following flags Short FlagLong FlagDefaultDescription c copyright lt COPYRIGHT HOLDER gt Copyright holder l licenseapacheLicense type m mutefalse unspecified Mute mode s skip Skipped file paths t tmpl Template file path y yeartime Now Year current year Copyright year h helpNoneHelpNote If you specify a template NWA won t generate license headers based on file types and it will ignore c l and y configurations For more usage examples refer to nwa examples Update Update License Headers in Files Usagenwa update flags path Use the update command after nwa to update license headers flags allows you to specify optional flags and path lets you specify one or more file paths to update license headers in Examplenwa update l apache c BINARY Members In the above example the command updates the license headers in all files in the current path with the following License type Apache Copyright holder BINARY MembersCopyright year The previous copyright statement is replaced regardless of its content Note Update is essentially a combination of Remove and Add operations The update command recognizes the content before the first empty line in a file as the license header with the exception of shebang lines NWA generates a new license statement based on the specified flags and replaces the existing one If the content before the first empty line in your file includes something other than the license statement it s recommended to use the remove and add operations separately to achieve the same effect This approach along with the template file flag can lead to better removal results in the remove operation FlagsThe update command supports the following flags Short FlagLong FlagDefaultDescription c copyright lt COPYRIGHT HOLDER gt Copyright holder l licenseapacheLicense type m mutefalse unspecified Mute mode s skip Skipped file paths t tmpl Template file path y yeartime Now Year current year Copyright year h helpNoneHelpNote If you specify a template NWA won t generate license headers based on file types and it will ignore c l and y configurations For more usage examples refer to nwa examples Check Check License Headers in Files Usagenwa check flags path Use the check command after nwa to check license headers flags allows you to specify optional flags and path lets you specify one or more file paths to check license headers in Examplenwa check tmpl tmpl txt clientIn the above example the command checks if license headers in all files within the client folder match the content specified in the tmpl txt template file After checking NWA provides log outputs indicating the result of the check Here s a sample output time T level info msg skip file path README mdtime T level info msg file has a matched header path dirA fileA go time T level info msg file does not have a matched header path dirB dirC fileC go time T level info msg file has a matched header path dirB fileB go time T level info msg file does not have a matched header path main go FlagsThe check command supports the following flags Short FlagLong FlagDefaultDescription c copyright lt COPYRIGHT HOLDER gt Copyright holder l licenseapacheLicense type m mutefalse unspecified Mute mode s skip Skipped file paths t tmpl Template file path y yeartime Now Year current year Copyright year h helpNoneHelpNote Avoid using the m flag with the check command as it will prevent NWA from outputting the check results For more usage examples refer to nwa examples Config Edit License Headers via Configuration File Usagenwa config flags pathUse the config command after nwa to edit license headers based on a configuration file flags allows you to specify optional flags and path is required to specify the path to the configuration file Examplenwa config config yamlIn the above example the command reads the config yaml configuration file and edits license headers in specified files according to its content The structure of the configuration file is provided below FlagsSince all configuration is in the configuration file there s only one help flag Short FlagLong FlagDefaultDescription h helpNoneHelp Configuration FileHere s an example of a complete configuration file config yaml nwa cmd add Default add Options add check remove update holder RHINE LAB LLC Default lt COPYRIGHT HOLDER gt year Default Current Year license apache Default apache mute false Default false unspecified path server client pkg Default skip py Default tmpl nwa txt Default If you don t specify certain fields in the configuration file NWA will use default values For example if you don t specify the license type Apache will be used by default Note If you set the tmpl field NWA will ignore the holder year and license fields For more usage examples refer to nwa examples ConclusionThe above content introduces NWA ーA Powerful License Header Management Tool If you find this tool helpful please consider giving our project a star If you notice any errors or have questions feel free to leave a comment or send a message References |
2023-08-28 06:10:11 |
海外TECH |
DEV Community |
Explicit Design, Part 7. App Composition without Hooks |
https://dev.to/bespoyasov/explicit-design-part-7-app-composition-without-hooks-36cl
|
Explicit Design Part App Composition without HooksLet s continue experimenting with explicit software design In the previous posts we ve built the converter app from its parts composed everything with hooks discussed ways to simplify composition and talked about various types of testing In this post we ll take a small side road and discuss how to compose an app without hooks how to inject dependencies “before runtime and whether there s any benefit to doing so But first disclaimer This is not a recommendation on how to write or not write code I am not aiming to “show the correct way of coding because everything depends on the specific project and its goals My goal in this series is to try to apply the principles from various books in a fairly over engineered frontend application to understand where the scope of their applicability ends how useful they are and whether they pay off You can read more about my motivation in the introduction Take the code examples in this series sceptically not as a direct development guide but as a source of ideas that may be useful to you By the way all the source code for this series is available on GitHub Give these repo a star if you like the series Problems with HooksThis post is probably going to be the most subjective in the entire series My criticism of hooks is just my opinion I could be wrong and I am probably wrong So before we start writing code I want to explain the reasons why hooks have recently become less attractive to me as a tool High Infectiousness and Multiple LimitationsHooks infect everything around them If we decide to use a hook somewhere to solve a particular problem we have to use them in all other parts of the code that are somehow related to that problem even if they re not needed there Developing with hooks requires making too many decisions too early We have to deal with low level implementation details before it becomes really necessary In addition hooks introduce not always justified restrictions which can suddenly change for weakly substantiated reasons The volatile restrictions of a tool decrease trust in it because it becomes expensive to maintain in the long term Changing such tools add extra work and inflate technical debt consuming resources that could have been saved Vendor Lock InHooks tightly bind the project to specific technologies and tools making it excessively costly to switch them This may not be critical for every project especially if the project is short lived But if we are going to write code that will live for years we should allocate resources in advance to update the codebase and consider the likelihood of switching to another framework or library Implicit Dependencies and Leaking AbstractionsHooks encourage combining data and behavior Composing hooks leads to a composition of side effects which is called one of the main problems of OOP for example Hidden dependencies and the influence of effects on each other are difficult to grasp making it harder to control program behavior By “encouragement I mean not so much the examples from the documentation as the difference in how easy it is to write code by combining data with behavior versus not doing so With hooks the latter is even more difficult on a syntactical level Implementation details of hooks are often overly or insufficiently abstracted A single hook may contain functionality from different abstraction levels which requires mentally jumping between different levels while reading This increases cognitive load and clouds the interaction between parts of the application For the same reasons testing hooks can be difficult Composing effects requires not only preparing input data for the hook but also “recreating its state and implicit dependencies require complex testing infrastructure For example to test such a hook const useUser gt const data isLoading useSWR users id fetchUser const role useRoles data const session useStore s gt s session return data session role For example to test such a hook we need to mock fetch or useSWR set up a store provider check what useRoles consists of so that we can mock it or its dependencies if necessary Finally since the composition of effects and excessive abstraction do not fit in our heads we may forget to test edge cases a specific user role an incorrect server response data revalidation overwriting session data from old to new etc As a result we have to keep in mind not only the code of the hook itself but also many other aspects Complicated Mental ModelIt is difficult to give a comprehensive definition of hooks and in my observations their mental model raises many questions for new developers They seem to be similar to functions but behave differently Conditions for re rendering complicate the understanding of how component re rendering works The concept of hooks seems to be established but details and rules can change drastically from version to version This again reduces confidence in the stability of the API and complicates learning DisclaimerAll of this doesn t mean that it s impossible to write good and well structured code with hooks It s possible of course I just feel that if a technology imposes restrictions they should guide developers and make it impossible or at least difficult to write code “incorrectly With hooks however I get the feeling that they don t provide a clear mental framework for understanding how to write code using them For me hooks are a way of composing different functionality I think of them as “injectors of services functions and data that trigger component re renders If the functionality is not directly related to the UI state or component re rendering then I will first consider whether it can be written without using hooks By the way in the new React documentation I found something similar to this idea Composition without HooksNow that we have aligned our understanding of hooks let s try to rebuild the converter without using them Since the application itself is already designed we can immediately move on to choosing the appropriate tools for the task By the way this section can be an example of why it s better to choose tools later when you know as much as possible about the project It s clear that our requirement “to be able to work without hooks is artificial but it can be replaced with a more significant requirement that is directly related to the business needs The service that requests data from the API doesn t use hooks so we will leave it unchanged but we will slightly modify the store Instead of using context we will use the Zustand library It is a state manager that is somewhat similar to Redux but simpler and doesn t require providers Store ServiceAfter installing Zustand in the project we can describe a basic implementation of the store using it infrastructure store tsexport const converter createStore lt Converter gt gt Default model values Next let s describe the composition that is how this service will implement the application ports declared earlier infrastructure store composition ts Output ports connect the service with the use cases export const readConverter ReadConverter converter getState export const saveConverter SaveConverter converter setState Input ports will be implemented directly since there s no “domain logic in the selectors export const useBaseValue SelectBaseValue gt useStore converter vm gt vm baseValue export const useQuoteCode SelectQuoteCode gt useStore converter vm gt vm quoteCode export const useQuoteValue SelectQuoteValue gt useStore converter vm gt vm quoteValue We will leave the data selectors unchanged These are precisely the “reactive data that should update the UI so providing them through hooks makes sense On the other hand the implementation of output ports will be used by use cases which we will implement as functions Therefore readConverter and saveConverter will be references to read and write functions not hooks Composition of Use CasesLet s update the composition of use cases to use readConverter and saveConverter functions directly core updateBaseValue composition import readConverter saveConverter from infrastructure store export const useUpdateBaseValue Provider lt UpdateBaseValue gt gt return useCallback value gt updateBaseValue value readConverter saveConverter readConverter saveConverter Since the imported functions won t change their references we can remove the useCallback core updateBaseValue compositionimport readConverter saveConverter from infrastructure store export const useUpdateBaseValue Provider lt UpdateBaseValue gt gt return value gt updateBaseValue value readConverter saveConverter After that it will become clear that creating an extra lambda in the hook and passing dependencies to the updateBaseValue function at runtime no longer makes sense Instead we will use “bake in dependencies and prepare the entire use case in advance Currently the code for the updateBaseValue function looks like this core updateBaseValueconst stub as Dependencies export const updateBaseValue UpdateBaseValue rawValue readConverter saveConverter Dependencies stub gt We will change the function signature so that it can be partially applied by specifying dependencies We will extract the dependency argument put it first and make the function “curried core updateBaseValueexport const createUpdateBaseValue readConverter saveConverter Dependencies UpdateBaseValue gt rawValue gt I have covered dependency “baking in more detail in a previous post about infrastructure If you re not quite clear on what s happening here I recommend reading that post first Also technically it s not quite accurate to call this “currying in JS but we won t delve into terminology here Also the current way to make the function partially applicable is somewhat cumbersome However when native partial application is introduced to JS working with this concept will be slightly easier Next we can partially apply the factory function by passing in the dependency argument and obtain a prepared use case core updateBaseValue compositionexport const updateBaseValue UpdateBaseValue createUpdateBaseValue readConverter saveConverter As we mentioned earlier partial application is more type safe than an optional argument with dependencies so we have less chance of passing the wrong service or forgetting to pass it And since the real values are substituted only once such composition should not affect performance Composition of ComponentsSince the use case is now just a function components can use it directly ui BaseValueInputtype BaseValueInputDeps Using the function directly updateBaseValue UpdateBaseValue useBaseValue SelectBaseValue In the component itself we ll remove the useUpdateBaseValue call and will use the given updateBaseValue function directly The composition of the component itself will not change significantly ui BaseValueInput composition Import the function import updateBaseValue from core updateBaseValue export const BaseValueInput gt Pass it when “registering the component Component updateBaseValue useBaseValue Let s do the same with other components that depend on this use case Again if we don t use explicit composition it would be enough to import and use the function directly in the component More details about explicit and implicit composition can be found in one of the previous posts Composition of TestsSince we are not touching the logic in tests we only need to update the preparation of stubs and mocks core updateBaseValue testconst readConverter gt converter const saveConverter vi fn const updateBaseValue createUpdateBaseValue readConverter saveConverter ui BaseValueInput testconst updateBaseValue vi fn const useBaseValue gt const dependencies updateBaseValue useBaseValue The test code and its logic will remain unchanged Exchange Rates RefreshWe can do the same with the update quotes use case First we change the function s signature to be prepared for the partial application core refreshRatesexport const createRefreshRates fetchRates readConverter saveConverter Dependencies RefreshRates gt async gt Next we can partially apply it passing freshly created functions for working with the store as dependencies core refreshRates compositionimport readConverter saveConverter from infrastructure store import fetchRates from infrastructure api export const refreshRates RefreshRates createRefreshRates fetchRates readConverter saveConverter After this we need to decide how we want to work with the asCommand adapter and update its code For example we want the use case to be independent and work without hooks but we want to see the reactive status of the operation in the UI Then we can rewrite asCommand so that it turns the use case function into a hook that returns the result execute interface shared infrastructure cqsexport const asCommand lt F extends AsyncFn gt command F Provider lt Command lt F gt gt gt gt const execute async gt return result execute The component in this case will continue depending on a hook ui RefreshRatestype RefreshRatesProps useRefreshRates Provider lt Command lt RefreshRates gt gt But at composition time we can provide a regular function to a component the adapter will transform it into a hook ui RefreshRates compositionimport refreshRates from core refreshRates import asCommand from shared infrastructure cqs export const RefreshRates gt Component useRefreshRates asCommand refreshRates Other ToolsIn this example we chose Zustand as our state manager because it is suitable for working with objects where multiple fields can be inter related In other applications we might need other tools such as Jotai or MobX In the repository I left a couple of examples of how to implement the store using these two libraries as well Sources and ReferencesLinks to books articles and other materials I mentioned in this post Source code for the current step on GitHub React Hooks and ComponentsBuilt in React HooksComponentHow to handle the Effect firing twice in development Rules of Hooks State and Effect ManagementEnsuring reusable stateLifecycle of Reactive EffectsSeparating Events from Effects Abstractions and DecompositionAbstraction as a design toolFunctional architecture The pits of successReferential transparency fits in your head Infrastructure ToolsJotaiMobXZustand Other TopicsCurried functionsPartial Application Syntax for ECMAScriptUnit Testing Principles Practices and Patterns by Vladimir KhorikovP S This post was originally published at bespoyasov me Subscribe to my blog to read posts like this earlier |
2023-08-28 06:00:36 |
医療系 |
医療介護 CBnews |
流行初期医療確保措置の収入を事業税非課税に-来年度の税制改正に向けて要望へ、厚労省 |
https://www.cbnews.jp/news/entry/20230828150915
|
医療機関 |
2023-08-28 15:20:00 |
金融 |
JPX マーケットニュース |
[OSE]最終清算数値(2023年8月限):金、白金 |
https://www.jpx.co.jp/markets/derivatives/special-quotation/
|
清算 |
2023-08-28 15:15:00 |
金融 |
ニッセイ基礎研究所 |
日本のセキュリティ・クリアランス-求められる企業の経済安全保障対応 |
https://www.nli-research.co.jp/topics_detail1/id=75927?site=nli
|
目次ーはじめにーセキュリティ・クリアランスSC制度ー企業から見たSC制度制度導入のメリットビジネス機会の拡大産業競争力の向上セキュリティの強化制度導入のデメリットコストの増加制約要因の追加ー企業における取組みーおわりに来年中の法案成立を目指して、政府は機密扱いとした情報にアクセス可能な人や施設を審査し、認証する「セキュリティ・クリアランス以下、SC制度」の導入に向けた議論を進めている。 |
2023-08-28 15:47:00 |
ニュース |
BBC News - Home |
Liverpool flood deaths: Two dead after driving car into floodwater |
https://www.bbc.co.uk/news/uk-england-merseyside-66635952?at_medium=RSS&at_campaign=KARANGA
|
liverpool |
2023-08-28 06:17:07 |
ニュース |
BBC News - Home |
Simone Biles wins record eighth US all-around title as comeback continues |
https://www.bbc.co.uk/sport/gymnastics/66636944?at_medium=RSS&at_campaign=KARANGA
|
Simone Biles wins record eighth US all around title as comeback continuesSimone Biles breaks a year record by winning her eighth all around title at the US Gymnastics Championships less than a month after returning to competition |
2023-08-28 06:27:33 |
マーケティング |
MarkeZine |
【視聴無料】売上に貢献できるBtoBマーケターになるための基本を学ぶ |
http://markezine.jp/article/detail/43258
|
貢献 |
2023-08-28 15:30:00 |
マーケティング |
MarkeZine |
【残席わずか】丸亀製麵のデータドリブンな意思決定のベースにある「MMM実践状況」を公開 |
http://markezine.jp/article/detail/43257
|
意思決定 |
2023-08-28 15:15:00 |
IT |
週刊アスキー |
X(旧Twitter)、企業が求人募集可能に「X Hiring」テスト開始 |
https://weekly.ascii.jp/elem/000/004/152/4152447/
|
twitter |
2023-08-28 15:25:00 |
IT |
週刊アスキー |
焼肉「メガ盛りセット」+レッドブルの最強エナジーキャンペーン、焼肉ライクが9月1日~9月3日開催 |
https://weekly.ascii.jp/elem/000/004/152/4152421/
|
開催 |
2023-08-28 15:15:00 |
IT |
週刊アスキー |
20万本の花々で彩られた大花壇は圧巻! 「ガーデンネックレス横浜 2023『里山ガーデンフェスタ』」9月16日から |
https://weekly.ascii.jp/elem/000/004/152/4152443/
|
平方メートル |
2023-08-28 15:15:00 |
IT |
週刊アスキー |
ピカチュウの寝顔がかわいい! Pokémon Sleep × めぐりズムがコラボ! |
https://weekly.ascii.jp/elem/000/004/152/4152437/
|
sleep |
2023-08-28 15:30:00 |
IT |
週刊アスキー |
スタバの秋フラぺは「おさつバター」♡ “おさつカスタマイズ”も予定 |
https://weekly.ascii.jp/elem/000/004/152/4152389/
|
秋の味覚 |
2023-08-28 15:20:00 |
IT |
週刊アスキー |
日高屋「肉そば」4年ぶりに復活! 飲んだ〆にもぴったり |
https://weekly.ascii.jp/elem/000/004/152/4152410/
|
期間限定 |
2023-08-28 15:40:00 |
コメント
コメントを投稿