IT |
気になる、記になる… |
Amazon、インドで「Amazon プライム」の会費を一部値上げ |
https://taisy0.com/2023/04/26/171202.html
|
amazon |
2023-04-26 12:23:54 |
AWS |
AWS Database Blog |
Reduce data archiving costs for compliance by automating Amazon RDS snapshot exports to Amazon S3 |
https://aws.amazon.com/blogs/database/reduce-data-archiving-costs-for-compliance-by-automating-amazon-rds-snapshot-exports-to-amazon-s3/
|
Reduce data archiving costs for compliance by automating Amazon RDS snapshot exports to Amazon SMany customers use AWS Backup to automatically create Amazon Relational Database Service Amazon RDS and Aurora database snapshots RDS database snapshots are a convenient way to protect your data and make it easy to recover in the event of an accident or disaster If you re using RDS Snapshots for long term archival to meet compliance requirements … |
2023-04-26 12:57:19 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
【Python】日本語のモーラ列を仮名文字のシーケンスとして管理するクラス |
https://qiita.com/Hizuru/items/f9102a7f371f043b2555
|
morastr |
2023-04-26 21:35:41 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
復習 自分用 |
https://qiita.com/YukiyaOgura/items/7e4fbad6c3e65f3a1391
|
複雑 |
2023-04-26 21:01:45 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
【AWS】AuroraとRDSの違いチートシート |
https://qiita.com/suzuki0430/items/9ec4a4595f6000381d5b
|
aurora |
2023-04-26 21:14:08 |
Linux |
CentOSタグが付けられた新着投稿 - Qiita |
【Linux】パッケージ管理②(yum) |
https://qiita.com/hitorigotsu/items/70f7a2307aafa8f9bc72
|
linux |
2023-04-26 21:49:53 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
復習 自分用 |
https://qiita.com/YukiyaOgura/items/7e4fbad6c3e65f3a1391
|
複雑 |
2023-04-26 21:01:45 |
技術ブログ |
Mercari Engineering Blog |
会計システムにおけるインテグレーションテストの改善 |
https://engineering.mercari.com/blog/entry/20230426-accounting-system-integration-test-improvement/
|
hellip |
2023-04-26 12:37:26 |
海外TECH |
MakeUseOf |
Why Streaming Services Will Be Trying New Things In 2023 |
https://www.makeuseof.com/streaming-services-trying-new-things-2023/
|
things |
2023-04-26 12:15:16 |
海外TECH |
DEV Community |
Tutorial: Create an AI agent that reads Wikipedia for you |
https://dev.to/lgrammel/tutorial-create-an-ai-agent-that-reads-wikipedia-for-you-31cm
|
Tutorial Create an AI agent that reads Wikipedia for youIn this tutorial you ll learn how to create an agent that answers questions by searching and reading Wikipedia articles using JS Agent You can find the complete code in the Wikipedia agent example This is the high level flow of the agent The agent will use the following components OpenAI gpt turbo chat completion modelA loop in which the agent determines and executes steps GenerateNextStepLoop A custom promptWikipedia search tool implemented using a Programmable Search Engine Wikipedia article reading toolCommand line interface and console logger that shows the agent s progress Setup Pre requisitesThis tutorial assumes that you have Node js v or newer installed You also need access to the OpenAI API Create a new Node js projectmkdir wikipedia agentcd wikipedia agentnpm init ymkdir src Setup TypeScriptnpm install save dev typescript ts node types nodenpx tsc init rootDir src outDir build Install JS Agentnpm install js agentYou should have a basic Node js project that has TypeScript and JS Agent installed Create agent tssrc agent ts will contain the Wikipedia agent To get started add the following content const task process argv slice join runWikipediaAgent then gt catch error gt console error error async function runWikipediaAgent console log task You can now run it with e g ❯npx ts node src agent ts how many people live in BC Canada At this point it only outputs the task to the console Setup the LLM modelNext we ll set up the LLM model and create the agent loop with a basic prompt Load OpenAI API keyUpdate the code to load the OpenAI API key from the environment and inject it into the agent const task process argv slice join const openAiApiKey process env OPENAI API KEY if openAiApiKey throw new Error OPENAI API KEY is not set runWikipediaAgent then gt catch error gt console error error async function runWikipediaAgent console log openAiApiKey console log task Create the LLM modelFirst import JS Agent import as from js agent You can then create the chat model in runWikipediaAgent const chatGpt provider openai chatModel apiKey openAiApiKey model gpt turbo Call the model with a basic promptOnce you have a model you can call it directly with a basic prompt const fullResponse await chatGpt generate role user as const content task And extract the main output from its response const output await chatGpt extractOutput fullResponse console log output Putting this together this is the current code import as from js agent const task process argv slice join const openAiApiKey process env OPENAI API KEY if openAiApiKey throw new Error OPENAI API KEY is not set runWikipediaAgent then gt catch error gt console error error async function runWikipediaAgent const chatGpt provider openai chatModel apiKey openAiApiKey model gpt turbo const fullResponse await chatGpt generate role user as const content task const output await chatGpt extractOutput fullResponse console log task console log output When you run it it ll use the knowledge that s trained into the LLM to answer the question ❯npx ts node src agent ts how many people live in BC Canada how many people live in BC Canada As an AI language model I do not have access to real time data However according to the latest census conducted in the population of British Columbia Canada was approximately million Create the basic agentNow we re ready to create a basic agent Let s update the runWikipediaAgent function with the following code const chatGpt provider openai chatModel apiKey openAiApiKey model gpt turbo return runAgent lt task string gt properties task agent step generateNextStepLoop actions actionFormat action format flexibleJson prompt async runState task gt role user as const content task model chatGpt controller agent controller maxSteps observer agent observer showRunInConsole name Wikipedia Agent When you run it it ll output the basic LLM answer to the console until the maximum number of steps is reached ❯npx ts node src agent ts how many people live in BC Canada Wikipedia Agent task how many people live in BC Canada Thinking…As an AI language model I do not have access to real time data However according to the latest census conducted in the population of British Columbia Canada was approximately million Thinking…As an AI language model I do not have access to real time data However according to the latest census conducted in the population of British Columbia Canada was approximately million Thinking…As an AI language model I do not have access to real time data However according to the latest census conducted in the population of British Columbia Canada was approximately million Cancelled Maximum number of steps exceeded Let s dig into the code runAgent runs an agent It is typed to the properties of the agent which are also its input We pass in the task as a property return runAgent lt task string gt properties task The agent property contains the root step of the agent We use a step generateNextStepLoop step which generates steps using the LLM until the agent is done return runAgent lt gt agent step generateNextStepLoop actions actionFormat action format flexibleJson prompt async runState task gt role user as const content task model chatGpt The loop is configured with our earlier prompt function and the chatGpt model This prompt is used when calling the chatGpt model generate function We ll configure and talk about the actions later Because the agent has no actions yet and does not know when to stop we limit the maximum number of steps to return runAgent lt gt controller agent controller maxSteps And finally we use an observer that outputs the agent s run to the console return runAgent lt gt observer agent observer showRunInConsole name Wikipedia Agent With the basic agent in place let s add some tools next Create the Wikipedia search tool Create a programmable search engineFirst you need to create a programmable search engine for Wikipedia When you set up the search engine configure the site to be en wikipedia org The search engine id the cx parameter is on the overview page You can get the search engine key in the documentation Get a Key requires a Google project Create the search actionJS Agent has a built in tool for using programmable search engines You can use it to create a search action Tools are actions that run potentially external code in some fashion They don t affect the control flow directly There are other kinds of actions e g the done action that an agent can select const searchWikipediaAction tool programmableGoogleSearchEngineAction id search wikipedia description Search wikipedia using a search term Returns a list of pages execute tool executeProgrammableGoogleSearchEngineAction key your search engine key cx your search engine id The id and description parameters are included in the LLM prompt It is important to choose names and descriptions that are easy to understand for the LLM because they will determine if and when the agent decides to use this action The execution parameter contains the function that is running the tool code It provides additional flexibility e g using executors that run in a Docker container Create an article readerThe read article action is implemented using the JS Agent extractInformationFromWebpage tool const readWikipediaArticleAction tool extractInformationFromWebpage id read wikipedia article description Read a wikipedia article and summarize it considering the query inputExample url topic query that you are answering execute tool executeExtractInformationFromWebpage extract text extractRecursively split text splitRecursivelyAtCharacter maxCharactersPerChunk extract text generateText id summarize wikipedia article chunk prompt prompt extractChatPrompt model chatGpt In addition to the id and the description the action has an inputExample that will be shown to the LLM Input examples help with guiding the LLM to take the right action Every tool has a default input example that can be overridden The page is then summarized using text extraction It is split recursively until the chunks are small enough for gpt turbo to handle gpt turbo is used to generate a summary for each chunk and the concatenated summaries prompt extractChatPrompt which is part of JS Agent contains the following prompt async text topic text string topic string gt role user as const content TOPIC n topic role system as const content ROLEYou are an expert at extracting information You need to extract and keep all the information on the topic above topic from the text below Only include information that is directly relevant for the topic role user as const content TEXT n text Now that we have created a summarization tool we can put everything together and craft a better agent prompt Adding the actions to the agentNow that we have a search Wikipedia and a read article action we can set up the actions in the Wikipedia agent Let s add them to the actions section of step generateNextStepLoop return runAgent lt gt agent step generateNextStepLoop actions searchWikipediaAction readWikipediaArticleAction actionFormat action format flexibleJson The actionFormat parses the first flat JSON object in the LLM output It is specifically designed for ChatGPT which tends to output the JSON object in various places in the response Create a better promptThe agent has yet to be made aware of the actions and it does not know that it should read Wikipedia articles Let s improve the agent prompt return runAgent lt gt prompt prompt concatChatPrompts async runState task gt role system content ROLEYou are an knowledge worker that answers questions using Wikipedia content CONSTRAINTSAll facts for your answer must be from Wikipedia articles that you have read TASK task prompt availableActionsChatPrompt prompt recentStepsChatPrompt maxSteps Let s dissect the prompt We first tell the model about its general role and then we instruct it always to read Wikipedia articles to find the answer and give it the task ROLEYou are an knowledge worker that answers questions using Wikipedia content CONSTRAINTSAll facts for your answer must be from Wikipedia articles that you have read TASK task The next part informs the model about the available actions After that we ensure to include the last steps the model took in the prompt for the next iteration This provides some basic memory required for moving the agent forward in its task return runAgent lt gt prompt prompt concatChatPrompts prompt availableActionsChatPrompt prompt recentStepsChatPrompt maxSteps The different prompts are concatenated using prompt concatChatPrompts Update the maximum stepsThe agent is now ready to be run We increase the maximum number of steps to to provide the agent with more time to find the answer return runAgent lt gt controller agent controller maxSteps The complete Wikipedia AgentThe agent now looks like this import as from js agent const task process argv slice join const openAiApiKey process env OPENAI API KEY if openAiApiKey throw new Error OPENAI API KEY is not set runWikipediaAgent task openAiApiKey then gt catch error gt console error error async function runWikipediaAgent task openAiApiKey task string openAiApiKey string const chatGpt provider openai chatModel apiKey openAiApiKey model gpt turbo const searchWikipediaAction tool programmableGoogleSearchEngineAction id search wikipedia description Search wikipedia using a search term Returns a list of pages execute tool executeProgrammableGoogleSearchEngineAction key your search engine key cx your search engine id const readWikipediaArticleAction tool extractInformationFromWebpage id read wikipedia article description Read a wikipedia article and summarize it considering the query inputExample url topic query that you are answering execute tool executeExtractInformationFromWebpage extract text extractRecursively split text splitRecursivelyAtCharacter maxCharactersPerChunk extract text generateText id summarize wikipedia article chunk prompt prompt extractChatPrompt model chatGpt return runAgent lt task string gt properties task agent step generateNextStepLoop actions searchWikipediaAction readWikipediaArticleAction actionFormat action format flexibleJson prompt prompt concatChatPrompts async runState task gt role system content ROLEYou are an knowledge worker that answers questions using Wikipedia content CONSTRAINTSAll facts for your answer must be from Wikipedia articles that you have read TASK task prompt availableActionsChatPrompt prompt recentStepsChatPrompt maxSteps model chatGpt controller agent controller maxSteps observer agent observer showRunInConsole name Wikipedia Agent Example RunHere are the results of a test run ❯npx ts node src agent ts how many people live in BC Canada Wikipedia Agent task how many people live in BC Canada Thinking…I will start by searching for the population of British Columbia Canada on Wikipedia action search wikipedia query population of british columbia canada Executing search wikipedia… Found search results British Columbia WikipediaWith an estimated population of million as of it is Canada s third most populous province The capital of British Columbia is Victoria and its Vancouver WikipediaVancouver is a major city in western Canada located in the Lower Mainland region of British Columbia Vancouver has the highest population density in Canada with over Demographics of British Columbia WikipediaPopulation of British Columbia million Percentage of National Population unchanged Population Growth Rate Victoria British Columbia Wikipedia British ColumbiaVictoria is the capital city of the Canadian province of British Columbia on the southern In the Census of Population conducted by Statistics Canada Surrey British Columbia Wikipedia British ColumbiaIn the Canadian census conducted by Statistics Canada Surrey had a population of living in of its total private dwellings a Thinking…The third search result Demographics of British Columbia Wikipedia seems to be the most relevant I will read the article and summarize it to answer the question action read wikipedia article url topic population of British Columbia Canada Executing read wikipedia article… Extracted information on topic population of British Columbia Canada from The population of British Columbia Canada is million as of which represents of the national population The population growth rate is In terms of visible minorities and indigenous peoples of the population in were visible minorities and were indigenous The largest visible minority groups were South Asian Chinese and Black In terms of immigration in immigrants comprised of the total population of British Columbia with the largest immigrant groups being from China India and the Philippines Finally the Canadian census counted a total of people who immigrated to British Columbia between and Thinking…According to the information I found on Wikipedia the population of British Columbia Canada is million as of action done Done |
2023-04-26 12:49:09 |
海外TECH |
DEV Community |
How to Build a Personal Website Using GitHub Pages and Hugo? |
https://dev.to/juliecodestack/how-to-build-a-personal-website-using-github-pages-and-hugo-3n93
|
How to Build a Personal Website Using GitHub Pages and Hugo A personal website is a good place to display your work either your projects or your technical notes Then how to build one In this article I ll introduce the simplest way to build a site Maybe you d like to have a look at my site first Site Building PipelineThere are two kinds of sites static sites and dynamic ones Static sites generate web pages locally and put them on the server so every user will get the same view when they click the link Dynamic sites display different pages to different users on their requests so it need things like databases As beginners we choose the simpler one ーstatic sites and it s easy to follow after you learn the pipeline Figure The pipeline of building a static websiteAs shown in the figure above there are two main steps in building a static website Generate pages locally The popular static site generators or frameworks are JekyII Hugo Hexo etc Here we ll use Hugo as an example Many people including me like Hugo because it s super fast to build a site Deploy the site to the server Here we ll use GitHub as the server to store the pages Not that hard right Now let s dive into the details Step PreparationInstall Git We will use Git Command to generate website connect to GitHub and push web pages to it Step Generate pages locally Install HugoGo to Hugo Installation Page and find the corresponding installation for the operating system you re using I m using Windows and I haven t installed Chocolatey or Scoop so I installed Hugo using binary files following this installation tutorial If you re in the same case as mine you may follow the steps below to install Hugo In the following steps YourUserName refers to the user name of your Windows system computer More specifically it s the name displayed on the screen when you login in Windows Go to folder C Users YourUserName and create a bin folder in it if it doesn t exist The bin folder is the place to store the Hugo binary file Add the bin folder to PATH In Windows Taskbar Search Box enter cmd and select the Command Prompt result right click and choose the “Run as administrator option In Command Prompt enter setx PATH C Users YourUserName bin PATH Then close and reopen the Command Prompt again enter echo PATH to check if bin has been successfully added to PATH Download zip file from Hugo release page on GitHub Be Sure to choose the extended version which will be found near the bottom of the list of archives From the zip extract the binary file hugo exe and move it to the bin folder After that open Command Prompt and enter hugo versionIf Hugo is successfully installed you will see a series of characters about information including Hugo version operating system build date Create a Hugo siteSupposing you use FolderA to store your site files Right click FolderA and select “Git Bash Here in the menu to open the Git Bash Command Now enter hugo new site MySiteThen a new folder named MySite will be created in FolderA that is your Hugo site Pick a theme and configure the siteSince a new site has been created maybe you d like to see what your Hugo site looks like but wait a minute you have to choose a theme first What is a theme You can regard it as the design of your website Hugo Themes site has many different themes When you pick a theme you can download it from its GitHub repository How to pick a theme Here I d like to give you some advice to save your time on choosing themes for I ve spent a lot of time on Hugo themes picking one configuring it and then changing to another one A theme that has an exampleSite folder is easier to use Different themes have different settings for example on choosing which folder to store the posts The most important file in exampleSite is the config toml or config yml or config json file which provides an example for your configuration so you know which parameters to tweak to get the desired result Without exampleSite you ll need much more time to configure it When previewing the theme you need pay attention to some features that you ll use For example if you write technical articles you should check whether the theme displays Math equations and highlights code blocks well After I pick a theme how to configure it Copy the theme folder you ve downloaded into MySite gt themes folder If the theme folder contains exampleSite you can copy the files in exampleSite to MySite folder After that copy other folders except exampleSite especially archetypes layouts static folders to MySite folder Some themes don t have exampleSite If you re a beginner I don t recommend you to use it now because you ll spend much more time to figure out how to set the parameters When I wrote this article I was using Hyde as the theme of my site I like its simple design It doesn t have exampleSite However I have used several themes before so I used config file of the previous themes and changed some parameters to set as the Hyde Theme Then Open Git Bash Prompt on MySite folder and enter hugo serverWhen it s done open the URL displayed in your terminal and you ll see the example site locally If you change the parameters in config toml the page will make corresponding changes at the same time In this way you can configure your site In the future when you write a new post or make some revisions you can still use hugo server to view your site locally before pushing to GitHub Write postsTo create a new post open Git Bash Command on MySite folder and enter hugo new new post mdIt will create a new markdown file named “new post in MySite gt content folder But if you use hugo server you may not see the new post Why Depending on the theme you choose you may need to put the new post md into post or posts folder in the content folder to generate the web page In this case you can also enter the following command to create a new post hugo new post new post md Open the new post in your editor Typora VS Code etc In the header of the post there are settings about the post it s also called front matter Find draft true which means this post is a draft and you don t want to publish it now Change it to draft false so that the post will be published on the site Besides the title in the header refers to the title of the post and it is set to be the file name when created for example “new post here You can change it to whatever you want in your editor How to display images Although many tutorials didn t mention how to insert and display images I think for beginners it s an important part in the building process for you may add pictures to make your article easier to understand or look better For local imagesIn Hugo the local images are stored in MySite gt static folder in order to be displayed Supposing you have an image named image jpg after putting it into the static folder you can insert it in your post this way image title image jpg Or you may put all images in one folder MySite gt static gt imgs then insert the image in your post by image title imgs image jpg But the above method doesn t display the title of the image If you want to show the title along with the image you can use lt figure src image jpg title image title gt Here please notice the space between the angle brackets lt and gt and the content The pipeline figure you ve seen in “Site Building Pipeline Section was inserted in this way For web imagesIf your image is stored on the web you can insert the image using its web link by one of the three ways below Way show the image without the title image title image weblink Way show the image with the title lt figure src image weblink title image title gt Way show the image without the title lt img src image weblink alt image title align center gt In way and way there are no double quotes around image weblink or image title i e write image weblink not “image weblink You may look at the post on my site to look at the example of web image display Step Deploy the site to GitHub Create a GitHub repositoryLog in GitHub and create a public repository named YourGitHubName github io this is where you re going to store your web pages on GitHub so that others can view your site Here please make sure YourGitHubName is the same as your GitHub username Build your site and push it to the repository on GitHubI followed the steps introduced in this tutorial Things you need to do before deploying for the first time For the first time you need to connect MySite gt public folder to your GitHub repository The public folder is the place to store your site files after they are generated by Hugo Connect it to your GitHub repository so that the site files will be synchronized on GitHub Open Git Bash Command on MySite folder enter cd publicgit initgit remote add upstream After that set the parameter baseurl in config toml to be your GitHub repository above baseurl The following are the things you do every time you push your site to GitHub First generate the site files Open Git Bash Command on MySite folder enter hugoWhen it s done Hugo will generate the site files and store it in the public folder Then we ll push these files to GitHub continue to enter cd publicgit add git commit m your commit message git push upstream masterThe above commands use git remote add upstream and git push upstream master I also used these two commands I saw a tutorial use origin instead of upstream i e git remote add origin and git push origin master which also works You may have a try Future WorkSome tutorials introduced GitHub Actions for automating the deployment and next I m going to learn it ReferencesHui Gong How to build personal blog using GitHub Pages and HugoFlavio Copes How to start a blog using HugoHugo installation Set the Hugo theme quickly I wish I had read the step in it about the configuration of website earlier it s efficient Deploy Hugo site to GitHub |
2023-04-26 12:16:52 |
海外TECH |
DEV Community |
Impact of Artificial Intelligence in Retail Market ? |
https://dev.to/sofster_/impact-of-artificial-intelligence-in-retail-market--4jp3
|
Impact of Artificial Intelligence in Retail Market Artificial Intelligence AI is revolutionizing the retail industry transforming the way retailers operate and serve their customers AI has become an essential tool for retailers to stay competitive and achieve growth in today s digital age In this guide we will discuss the impact of AI in retail and provide some examples of how AI is being used in the industry Personalized Marketing AI powered marketing algorithms enable retailers to analyze customer data and create personalized marketing campaigns These campaigns are tailored to specific customer needs and preferences increasing the chances of customer engagement and conversion For instance Amazon uses AI powered recommendations to suggest products to customers based on their previous searches and purchase history Inventory Management AI powered inventory management systems enable retailers to optimize their inventory levels and ensure that they always have the right products in stock This leads to increased efficiency and cost savings as well as improved customer satisfaction Walmart uses AI powered inventory management to ensure that their stores are always stocked with the products that customers want Chatbots and Customer Service AI powered chatbots are being increasingly used by retailers to improve customer service Chatbots are able to quickly and efficiently respond to customer inquiries providing them with the information they need in real time This improves customer satisfaction and reduces the workload of customer service teams Sephora uses chatbots to help customers find the right products and answer common beauty questions Predictive Analytics AI powered predictive analytics enable retailers to forecast customer behavior and make informed decisions Retailers can use predictive analytics to identify trends anticipate customer needs and make pricing and promotional decisions For example H amp M uses predictive analytics to determine which products will be popular in each store location and adjust their inventory accordingly Supply Chain Optimization AI powered supply chain optimization systems help retailers improve their supply chain efficiency and reduce costs These systems use machine learning algorithms to analyze data and make predictions about inventory levels shipping times and other factors that affect the supply chain For example Alibaba uses AI powered supply chain optimization to reduce delivery times and improve overall efficiency Wrapping up AI is transforming the retail industry by improving customer experiences optimizing operations and increasing efficiency Retailers that adopt AI technologies are more likely to stay competitive and achieve growth in today s digital age Are you ready to be a part of this revolutionary future Contact AI application Development Services today |
2023-04-26 12:05:39 |
海外TECH |
DEV Community |
Node.js Pitfalls to Avoid |
https://dev.to/appsignal/nodejs-pitfalls-to-avoid-3o74
|
Node js Pitfalls to AvoidDespite its many advantages Node js comes with a set of potential pitfalls if you don t maintain your application properly such as outdated dependenciesmemory leaksimproper error handlingovercomplicated codeneglecting security practicesblocking codecallback hellthe overuse of global variablesIn this post we ll explore these pitfalls and how to avoid them Let s dive straight in Outdated DependenciesKeep your dependencies up to date to avoid potential security issues and ensure your applications run on the most up to date version of Node js Outdated dependencies can cause compatibility issues resulting in unexpected behavior and errors Deprecated packages can be more prone to bugs and security vulnerabilities and may not have the latest features available They can be more difficult to debug and support assistance might be lacking So keep your dependencies up to date for a performant reliable and secure application Major Vs Minor Version ChangesWhen making changes to an application you need to understand the difference between major and minor changes Major version updates usually contain backward incompatible changes to a library e g function class name changes function class deletions changes in function parameters or return types etc When you update to a major version of a library in your project it s likely the code using that library won t work well with the new library Minor changes on the other hand are backward compatible and won t break your code As for upgrading packages most package publishers use Semantic Versioning SemVer for short to identify whether an update introduces breaking changes The version is formatted as MAJOR MINOR PATCH MAJOR version changes introduce incompatible API changesMINOR version changes add functionalities that are backward compatiblePATCH version changes make backward compatible bug fixesIt is a good practice to write code tests that might notify you of any issues after a package update Making Sure Your Dependencies Stay Up To DateTo ensure that your dependencies stay up to date there are several steps you can take Create a process to regularly check for updates and ensure that it is followed Use version control to keep track of the versions of packages and dependencies being used Version control allows you to easily test different versions of dependencies in your project and it also enables you to take your app back to a stable state in cases where a problematic dependency or update was introduced A package manager such as npm or yarn can automate the process of updating packages and dependencies Consider using a vulnerability scanner such as Snyk to identify potential security risks Now let s turn our attention to another potential pitfall in Node memory leaks Memory Leaks in Node jsMemory leaks can be caused by objects that are no longer being used but still exist in memory Memory leaks occur when an application continues to allocate more and more memory over time but fails to release it when it is finished with it This can cause an application to become sluggish and eventually crash Common causes of memory leaks include Not properly disposing of objects Forgetting to release references to objects Improperly managing callbacks How to Manage Memory AllocationTo grasp memory leaks you should familiarize yourself with memory management in Node js This entails understanding how the V Engine the JavaScript engine used by Node js manages memory Memory allocation is a broad topic Our article Avoiding Memory Leaks in Node js Best Practices for Performance will give you some initial pointers about how to handle memory leaks Monitoring Memory Leaks with AppSignalAppSignal can be used to monitor memory leaks in Node js applications It s designed to help developers identify and fix memory leaks quickly and easily AppSignal provides detailed information about memory usage including total memory used the amount of memory allocated and the most frequent allocations It also pinpoints the code and call stack causing the memory leak Here is how a heap size graph looks in AppSignal You can set alerts when specific values trigger set thresholds The next possible pitfall we ll look at is improper error handling Poor Error Handling in Node jsError handling is an important part of any program and Node js is no exception Poor error handling can cause your application to crash You must properly handle errors to prevent them from propagating up the stack Handle errors as close to their source as possible Failing to do so can cause memory leaks stability issues and bugs within your application Log errors to help identify and debug issues quickly and easily Best Practices for Error HandlingIt is a good practice to handle errors using the error first callback pattern This pattern involves passing an error object as the first argument to a callback function and checking for the existence of an error before proceeding with any further logic const errorFirstCallback err data gt if err return console log err console log It works wafel addTopping topping errorFirstCallback Don t swallow errors ーthat means don t use try catch blocks Instead let an error bubble up and be handled by the caller Having a robust and comprehensive error handling strategy in place will ensure that your application stays safe and can handle any unexpected errors See Node js Error Handling Tips and Tricks for a summary of what to consider Here are some things to keep in mind Log errors and their stack traces to help track down the cause of an issue Define custom error classes to differentiate between different types of errors Wrap callback functions with a try catch block to handle errors properly Return early from functions to avoid deep nesting Avoid throwing errors from within callbacks Use Promise catch to catch errors with Promises Handle errors that are thrown from asynchronous code Handle errors gracefully and provide useful feedback to the user Tracking Errors with AppSignalTools such as AppSignal can help centralize error handling in your application It can capture and log unhandled errors as well as provide helpful debugging information AppSignal provides detailed error reports that include stack trace metadata and diagnostic information like the environment in which an error occurs and the request that caused it Here s an example showing the details of an error in AppSignal Now let s move on to another potential problem you might fall prey to writing overly complex or unreadable code Overcomplicated and Unreadable CodeBadly written and unreadable code can cause a variety of issues ranging from performance issues to security vulnerabilities It can be difficult to debug and maintain and leads to errors and unexpected behavior When writing code it is important you keep it clean and organized This means breaking code into modules using descriptive variable and function names and avoiding deep nesting This will make the code easier to debug Additionally using comments is a great way to make code more understandable Following Don t Repeat Yourself DRY Duplication is Evil DIE Keep it Simple Stupid KISS and SOLID principles can ensure better code quality Development tools such as linters identify badly written code and inconsistencies and suggest improvements to improve code readability Regular code reviews also ensure that code is written properly and is easy to read Here s an example of code that s badly written and well written Bad codefunction doSomething a b c let x a b let y x c let z y return z Good codefunction calculateResult num num num let sum num num let product sum num let halfProduct product return halfProduct The first code block is difficult to read due to the lack of descriptive variable names The next thing to consider is your security practices Security Practices and Measures for Your Node js ApplicationNeglecting to address security issues can lead to data breaches data loss and other serious consequences for your Node js application By taking the necessary precautions your application stays secure Here are a few practices to follow Avoid Injection AttacksInjection attacks are when an attacker injects malicious code into an application through user input Prevent this by using prepared statements or parameterized queries and properly sanitizing user input Prevent Insecure SecretsSecrets like API keys or database credentials stored in plain text or in the codebase are considered insecure secrets You can avoid this by using environment variables or a secrets management solution Use HTTPS and SSL TLSUsing HTTPS and SSL TLS is essential for encrypting data sent between a server and a client This protects sensitive data such as passwords and credit card numbers Utilize Security HeadersSecurity headers are HTTP headers that help secure an application These headers can provide additional security measures such as prohibiting content from being embedded on other sites preventing the browser from executing malicious code and preventing clickjacking attacks Set Up Access ControlAccess control ensures that only authorized users can access certain resources Setting up proper access control will ensure that unauthorized users cannot access sensitive data Make Use of EncryptionEncrypting data is an important security measure Encryption ensures that data is not readable by anyone other than the intended recipient Perform Security AuditsPerform regular security audits both manually and with automated tools to identify any potential security issues We ll now focus on another problem you might run into blocking code Blocking CodeBlocking code blocks the main thread from executing other tasks while it is running This can cause performance issues as an application cannot respond to requests or perform other tasks until the blocking code has finished running The main causes of blocking code include long running loops and synchronous functions Nested loops can take a long time to run so an application becomes unresponsive as the main thread is occupied in executing the loop Synchronous functions cause a block as an application will wait for a function to finish executing before moving on to the next task To avoid blocking code use asynchronous functions whenever possible Avoid using highly nested loops by breaking them up into separate loops using recursion or another better performing algorithm Additionally consider using a task queue to separate long running tasks from the main thread Blocking synchronous codeconst fs require fs const data fs readFileSync wafel txt Blocks here until the file is read Non blocking asynchronous codeconst fs require fs fs readFile wafel txt err data gt if err throw err To better understand asynchronous code refer to How to Handle Async Code in JavaScript Next up is an issue you re likely familiar with callback hell Callback HellCallback hell describes a program with an excessive number of nested callbacks resulting in code that is difficult to read and maintain This can be caused by poorly structured code or too many asynchronous functions Callbacks are used to handle asynchronous operations and they can be nested to allow for complex operations However excessive nesting of callbacks can lead to confusing and unreadable code It can also lead to errors and unexpected behavior making debugging and maintaining such code difficult To avoid callback hell structure code properly and use other techniques such as Promises async await and generators Callback hellfs readFile wafel txt err data gt if err console error err return fs readFile wafel txt err data gt if err console error err return fs readFile wafel txt err data gt if err console error err return fs readFile wafel txt err data gt if err console error err return Do something with data data data and data async waterfall callback gt fs readFile wafel txt callback data callback gt fs readFile wafel txt callback data callback gt fs readFile wafel txt callback data callback gt fs readFile wafel txt callback err data gt if err console error err return Do something with the data Promises and callback hell are also covered in How to Handle Async Code in JavaScript For a more detailed approach to callback hell refer to callbackhell com Finally we ll look at another common problem overusing global variables Overuse of Global VariablesGlobal variables are available to an entire program They are useful for storing data that may be needed in multiple places throughout the program However overusing global variables can lead to issues such as increased complexity and security risks Using global variables can make code difficult to debug and maintain as they can be accessed from anywhere in a program Changes to a global variable in one part of the program can have unexpected consequences elsewhere Overusing global variables can introduce vulnerabilities in a program This is because global variables usually disconnect a source of data from its usage and make it difficult to track all the places in your code where the variable can be modified So a value that comes from an unsafe source e g user input could be used in the same way as a value from a safer source e g a database or calculation without the added safety checks that should be used on such values This leaves your program vulnerable to malicious actors Limit your use of global variables to only when they are absolutely necessary When possible variables should be passed as arguments to functions instead of being stored as global variables Wrapping UpIn this article we discussed several Node js pitfalls that you should avoid including having outdated dependenciesmemory leaksimproper error handlingovercomplicated codeneglecting security practicesblocking codecallback hellthe overuse of global variablesTo maintain a secure and reliable application ensure your code is readable and maintainable follow good coding practices and use asynchronous functions and security measures Happy coding P S If you liked this post subscribe to our JavaScript Sorcery list for a monthly deep dive into more magical JavaScript tips and tricks P P S If you need an APM for your Node js app go and check out the AppSignal APM for Node js |
2023-04-26 12:04:14 |
海外TECH |
DEV Community |
5 Unknown Free Resources to Learn Prompt Engineering | Here is Why it is Most Valuable Skill 2023 |
https://dev.to/sandy088/5-unknown-free-resources-to-learn-prompt-engineering-here-is-why-it-is-most-valuable-skill-2023-30ph
|
Unknown Free Resources to Learn Prompt Engineering Here is Why it is Most Valuable Skill Prompt engineering is a skill set that is in high demand in today s technological world With the ever growing popularity of digital assistants and chatbots the ability to create effective prompts is becoming increasingly important In this article we will explore the importance of prompt engineering why it is crucial for businesses and how to learn it best free resources to learn professional prompt engineering What is Prompt Engineering Prompt engineering is the process of creating prompts for conversational agents such as chatbots virtual assistants or voice assistants A prompt is a message that initiates a conversation with the user and prompts them to take an action or provide information The quality of a prompt can make or break the user experience as it sets the tone for the entire conversation Why is Prompt Engineering Important Prompt engineering is crucial for businesses that want to provide a seamless and efficient user experience A poorly crafted prompt can lead to confusion frustration and even abandonment of the conversation On the other hand a well designed prompt can guide the user towards their desired outcome and increase their satisfaction With the increasing popularity of conversational interfaces the importance of prompt engineering is only going to grow By it is estimated that over of all searches will be voice searches This means that businesses that do not prioritize prompt engineering risk falling behind their competitors and losing out on potential customers Here are Best Free resources to Learn professional Prompt engineering Unknown Resources to Learn Prompt Engineering |
2023-04-26 12:03:48 |
Apple |
AppleInsider - Frontpage News |
Apple's Shenzhen, China retails store opens on April 28 |
https://appleinsider.com/articles/23/04/26/apples-shenzhen-china-retails-store-opens-on-april-28?utm_medium=rss
|
Apple x s Shenzhen China retails store opens on April Apple s MixC Shenzhen store is its second store in the region and the company built it with sustainable materials Apple MixC ShenzhenThe new store opens on April in The MixC shopping mall in Shenzhen s Luohu area It follows the launch of fresh Apple Stores in Wuhan the administrative center of central Hubei province in and Changsha the capital of south central Hunan province in Read more |
2023-04-26 12:35:18 |
Apple |
AppleInsider - Frontpage News |
Apple headset factories rumored to be in 'final sprint' with WWDC announcement expected |
https://appleinsider.com/articles/23/04/26/apple-headset-factories-rumored-to-be-in-final-sprint-with-wwdc-announcement-expected?utm_medium=rss
|
Apple headset factories rumored to be in x final sprint x with WWDC announcement expectedApple s supply chain is rumored to be in the final mass production preparatory stages of the long rumored Apple AR headset with a final push underway to finalize techniques and assembly procedures A render of the possible headset from AppleInsiderA supply chain report claims that Foxconn subsidiary GIS has a production line fired up for the lens assembly for the headset The lenses are then in turn provided to a company called Lixun for assembly Read more |
2023-04-26 12:19:47 |
海外TECH |
Engadget |
The best fitness trackers for 2023 |
https://www.engadget.com/best-fitness-trackers-133053484.html?src=rss
|
The best fitness trackers for The fitness tracker isn t dead and if you re reading this you re probably one of the people keeping these little devices alive Smartwatches like the Apple Watch and the Samsung Galaxy Watch have all but taken over the mainstream wearable space but the humble fitness tracker remains an option for those who want a gadget to do one thing right all the time track fitness metrics accurately without the barrage of notifications you d get from other wearables Despite the headwinds there are still a bunch of fitness bands out there to choose from Engadget has tested many of them and picked out the best fitness trackers for most people What do fitness trackers do best The answer seems simple Fitness trackers are best at monitoring exercise be it a minute walk around the block or that half marathon you ve been diligently training for Obviously smartwatches can help you reach your fitness goals too but there are some areas where fitness bands have the upper hand focus design battery life and price When I say “focus I m alluding to the fact that fitness trackers are made to track activity well anything else is extra They often don t have the bells and whistles that smartwatches do which could distract from their health tracking abilities They also tend to have fewer sensors and internal components which keeps them smaller and lighter Fitness trackers are also a better option for those who just want a less conspicuous device on their wrists all day Battery life tends to be better on fitness trackers too While most smartwatches last one to two days on a single charge fitness bands offer between five and seven days of battery life ーand that s with all day and all night use even with sleep tracking features enabledWhen it comes to price there s no competition Most worthwhile smartwatches start at to but you can get a solid fitness tracker starting at Yes more expensive bands exist and we recommend a few here but you ll find more options under in the fitness tracker space than in the smartwatch space When to get a smartwatch insteadIf you need a bit more from your wearable you ll likely want a smartwatch instead There are things like on watch apps alerts and even more robust fitness features that smartwatches have and the best fitness trackers don t You can use one to control smart home appliances set timers and reminders check weather reports and more Some smartwatches let you choose which apps you want to receive alerts from and the options go beyond just call and text notifications But the extra fitness features are arguably the most important thing to think about when deciding between a fitness tracker and a smartwatch The latter devices tend to be larger giving them more space for things like GPS barometers onboard music storage and more While you can find built in GPS on select fitness trackers it s not common Best overall Fitbit Charge Fitbit s Charge has everything most people would want in a fitness tracker First and foremost it s not a smartwatch That means it has a slightly lower profile on the wrist and lasts days on a single charge while tracking activity and monitoring your heart rate and sleep It also has a full color AMOLED display ーa big improvement from the smaller grayscale screen on the previous Charge That display along with a thinner design make Charge feel more premium than its predecessor The Charge has EDA sensors for stress tracking and it will eventually support ECG measurements and Daily Readiness Scores the latter is only for Premium subscribers Those are on top of existing features that were carried over from the Charge ーmost notably Fitbit Pay support and built in GPS tracking The former lets you pay for coffee or groceries with a swipe of your wrist while the latter helps map outdoor runs bike rides and other activities Built in GPS remains the star of the show here ーit s fast and accurate making the Charge the best option if you want a focused do it all wearable fitness watch Runner up Garmin Vivosmart A more subtle looking fitness band alternative is the Garmin Vivosmart It s thinner than the Fitbit Charge and fits in a bit better with bracelets and other jewelry you might wear regularly But its attractive design is only part of its appeal ーGarmin knows how to track fitness and the Vivosmart is proof that you don t need to drop hundreds on one of the company s fitness watches to get a capable device It has a lot of the same features as the Charge except for a built in GPS It does support connected GPS though so you can map outdoor runs and bike rides as long as you bring your phone with you The Vivosmart tracks all day heart rhythm and activity plus sleep data and workouts and we ve always appreciated how many workout profiles Garmin has to choose from You can customize which show up on your device and change them whenever you want You ll also get additional health information like Garmin s Body Battery score which tells you how long after a hard workout you ll need to wait until you can train at peak performance again blood oxygen levels sleep stage data women s menstrual cycle monitoring and more The biggest disadvantages to fitness tracking with the Vivosmart are the aforementioned lack of built in GPS plus its slightly harder to use mobile app But on the flip side Garmin devices can sync with Apple Health whereas Fitbit devices still don t have that feature Best budget Fitbit Inspire If you only have to spare the Fitbit Inspire is the best fitness tracker option It strips out all the luxury features from the Charge and keeps only the essential tracking features You won t get built in GPS tracking or Fitbit Pay or Spotify control but you do get excellent activity tracking automatic workout detection smartphone alerts and plenty more The updated version has a sleeker design and includes a color touchscreen and connected GPS the latter of which lets you track pace and distance while you run or bike outside while you have your phone with you The Inspire is definitely the more fashionable out of the two Fitbit devices on this list Its interchangeable bands let you switch up the look and feel of your tracker whenever you want and it s slim enough to blend in with other jewelry you might be wearing We were also impressed by its battery life Fitbit promises up to days on a single charge and that checked out for us After four days of round the clock use the Inspire still had percent battery left to go Most fashionable Withings MoveAll of the previously mentioned fitness trackers are attractive in their own way bonus points to those that have interchangeable bands but they share a similar look There aren t many alternative designs for these devices anymore The Withings Move watch is an exception and one of the most traditionally fashionable fitness trackers you can get It s an analog watch with a couple of health monitoring features including step calorie distance and sleep tracking connected GPS auto recognition for more than workouts and a water resistant design But we really love it for its battery life it ll last up to months before the coin cell needs a replacement This article originally appeared on Engadget at |
2023-04-26 12:35:17 |
ニュース |
BBC News - Home |
'UK was slower but still they saved us from Sudan' |
https://www.bbc.co.uk/news/uk-65398112?at_medium=RSS&at_campaign=KARANGA
|
board |
2023-04-26 12:43:16 |
ニュース |
BBC News - Home |
Olivia Pratt-Korbel: Man who helped schoolgirl's killer jailed |
https://www.bbc.co.uk/news/uk-england-merseyside-65397256?at_medium=RSS&at_campaign=KARANGA
|
cashman |
2023-04-26 12:26:12 |
ニュース |
BBC News - Home |
Patsy Kelly: Murdered councillor's family 'failed by police' |
https://www.bbc.co.uk/news/uk-northern-ireland-65389703?at_medium=RSS&at_campaign=KARANGA
|
murder |
2023-04-26 12:19:08 |
ニュース |
BBC News - Home |
Microsoft's deal to buy Call of Duty maker Activision Blizzard blocked in UK |
https://www.bbc.co.uk/news/entertainment-arts-65378617?at_medium=RSS&at_campaign=KARANGA
|
candy |
2023-04-26 12:45:24 |
ニュース |
BBC News - Home |
Zelensky holds first war phone call with China's Xi |
https://www.bbc.co.uk/news/world-europe-65396613?at_medium=RSS&at_campaign=KARANGA
|
invasion |
2023-04-26 12:28:52 |
ニュース |
BBC News - Home |
Bank of England: 'Accept' you are poorer remark sparks backlash |
https://www.bbc.co.uk/news/business-65397276?at_medium=RSS&at_campaign=KARANGA
|
people |
2023-04-26 12:53:17 |
ニュース |
BBC News - Home |
Amazon customers caught up in scarf scam |
https://www.bbc.co.uk/news/business-65398948?at_medium=RSS&at_campaign=KARANGA
|
customers |
2023-04-26 12:08:16 |
ニュース |
BBC News - Home |
Migration plans are compassionate, says Suella Braverman |
https://www.bbc.co.uk/news/65397710?at_medium=RSS&at_campaign=KARANGA
|
serious |
2023-04-26 12:44:37 |
ニュース |
BBC News - Home |
CBI: New business group boss says sorry for failing victims |
https://www.bbc.co.uk/news/business-65390216?at_medium=RSS&at_campaign=KARANGA
|
claims |
2023-04-26 12:55:27 |
ニュース |
BBC News - Home |
Government hits 20,000 new police officers pledge |
https://www.bbc.co.uk/news/65377091?at_medium=RSS&at_campaign=KARANGA
|
officers |
2023-04-26 12:08:53 |
ニュース |
BBC News - Home |
Steve Shanks: London Marathon runner dies on way home from race |
https://www.bbc.co.uk/news/uk-england-nottinghamshire-65399371?at_medium=RSS&at_campaign=KARANGA
|
distance |
2023-04-26 12:27:43 |
ニュース |
BBC News - Home |
Sudan: Third evacuation flight of Britons lands in Cyprus |
https://www.bbc.co.uk/news/uk-65395361?at_medium=RSS&at_campaign=KARANGA
|
sudan |
2023-04-26 12:03:54 |
ニュース |
BBC News - Home |
War crimes suspect free amid chaos |
https://www.bbc.co.uk/news/world-africa-65394913?at_medium=RSS&at_campaign=KARANGA
|
darfur |
2023-04-26 12:23:40 |
ニュース |
BBC News - Home |
Sudan evacuation: 'We had to leave my elderly mum behind' |
https://www.bbc.co.uk/news/world-africa-65387583?at_medium=RSS&at_campaign=KARANGA
|
khartoum |
2023-04-26 12:11:04 |
ニュース |
Newsweek |
日本が韓国をパクった!? 日清のUFO新商品が韓国の激辛麺「ブルダック」に激似と韓国ネット民大騒ぎ |
https://www.newsweekjapan.jp/stories/business/2023/04/ufo-7.php
|
ロボットテコンV社が、玩具輸入会社を著作権侵害で提訴すると、輸入会社側は、テコンVではなく日本のマジンガーZをイメージしたと反論。 |
2023-04-26 21:20:45 |
コメント
コメントを投稿