投稿時間:2021-11-11 22:23:32 RSSフィード2021-11-11 22:00 分まとめ(36件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] YouTubeの経済効果は2390億円――英コンサル会社が日本向けのレポート公開 https://www.itmedia.co.jp/business/articles/2111/11/news162.html itmedia 2021-11-11 21:35:00
AWS lambdaタグが付けられた新着投稿 - Qiita Serverless Frameworkで画像をダウンロードするAPIを作成 https://qiita.com/t-mine/items/ce86461694cc92986f25 ・integrationlambdaを設定することでcontentHandlingCONVERTTOBINARYが有効になります。 2021-11-11 21:57:03
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) VagrantとVirtualBoxを使った開発環境の構築ができません。 https://teratail.com/questions/368905?rss=all VagrantとVirtualBoxを使った開発環境の構築ができません。 2021-11-11 21:56:13
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Rails5と Bootstrap4でAjax-モーダルフォームを表示したい。 https://teratail.com/questions/368904?rss=all RailsとBootstrapでAjaxモーダルフォームを表示したい。 2021-11-11 21:34:10
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) postfix:バウンスメール送信時に特的のメールアドレスにも送付することは可能でしょうか。 https://teratail.com/questions/368903?rss=all nbsppostfix 2021-11-11 21:30:01
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Threadを使って時間制限の実装をしたいです。 https://teratail.com/questions/368902?rss=all Threadを使って時間制限の実装をしたいです。 2021-11-11 21:28:02
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) z-indexの重なり順 https://teratail.com/questions/368901?rss=all zindexの重なり順クラスAのボックスを、クラスBよりも上に配置したいですが、zindexの値を変えても上手くいきません。 2021-11-11 21:25:06
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) daggerのDI注入時でパラメータ設定したい https://teratail.com/questions/368900?rss=all dagger 2021-11-11 21:08:15
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) arduino unoで1kHz以上のサンプリング周波数でAD変換したデータをSDカードに保存しようと思っていますがうまくいきません. https://teratail.com/questions/368899?rss=all 2021-11-11 21:04:56
Ruby Rubyタグが付けられた新着投稿 - Qiita 【RSpec】Railsチュートリアル第6版 第13章 https://qiita.com/supyolo888/items/c88b6acd4ff55750defc 【RSpec】Railsチュートリアル第版第章はじめにRailsチュートリアル第版のテストをRSpecで書き直していく。 2021-11-11 21:53:33
Ruby Rubyタグが付けられた新着投稿 - Qiita 【Ruby on Rails】楽天APIで商品検索アプリを作る https://qiita.com/daisuke-webapp/items/eff7af9e45f23400f9d4 【RubyonRails】楽天APIで商品検索アプリを作るプロジェクトを開始railsnewraktuensearchデータベースと接続cdrakutensearchrailsdbcreateサーバーを起動して動作確認railss“YayYoureonRailsの表示を確認できたらOK共通レイアウト共通のViewappviewslayoutsapplicationhtmlerbltDOCTYPEhtmlgtlthtmllangjagtltheadgtlttitlegtWishlistTestlttitlegtltmetanameviewportcontentwidthdevicewidthinitialscalegtltcsrfmetatagsgtltcspmetataggtltlinkrelstylesheethrefbetadistcssbootstrapmincssgtltstylesheetlinktagapplicationmediaalldataturbolinkstrackreloadgtltjavascriptpacktagapplicationdataturbolinkstrackreloadgtltscriptsrcbetadistjsbootstrapbundleminjsgtltscriptgtltheadgtltbodydataturbolinksfalsegtltrenderlayoutsnavbargtltdivclasscontainergtltrenderlayoutsflashmessagesgtltyieldgtltdivgtltbodygtlthtmlgtフラッシュメッセージappviewslayoutsflashmessageshtmlerbltflasheachdomessagetypemessagegtltdivclassalertalertltmessagetypegtgtltmessagegtltdivgtltendgtエラーメッセージappviewslayoutserrormessageshtmlerbltifmodelerrorsanygtltdividerrorexplanationclassalertalertwarninggtltulclassmbgtltmodelerrorsfullmessageseachdomessagegtltligtltmessagegtltligtltendgtltulgtltdivgtltendgtナビバーappviewslayoutsnavbarhtmlerbltheaderclassmbgtltnavclassnavbarnavbarexpandsmnavbardarkbgdarkgtltdivclasscontainerfluidpspegtltaclassnavbarbrandhrefgtMicropostsltagtltbuttonclassnavbartogglertypebuttondatabstogglecollapsedatabstargetnavbarSupportedContentgtltspanclassnavbartogglericongtltspangtltbuttongtltdivclasscollapsenavbarcollapsejustifycontentendidnavbarSupportedContentgtltulclassnavbarnavgtltliclassnavitemgtltahrefclassnavlinkgtSignupltagtltligtltliclassnavitemgtltahrefclassnavlinkgtLoginltagtltligtltulgtltdivgtltdivgtltnavgtltheadergt【楽天API】gemをインストールgemrakutenwebservicegemdotenvrails行目は楽天APIを利用するため、行目はdotenvを利用するために記述bundleinstallGemfileに追記したのでbundleinstall【楽天API】アプリケーションIDを設定取得したアプリケーションIDを設定取得したアプリケーションIDを設定するためconfiginitializersフォルダの中にrautenrbファイルを作成し、以下を記述するrakutenrbRakutenWebServiceconfiguredoc必須アプリケーションIDcapplicationidENVRWSAPPLICATIONID任意楽天アフィリエイトIDcaffiliateidENVRWSAFFILIATIONIDendアフィリエイトIDの記述は任意なので不必要な人は記述しなくてもよいtouchenv環境変数を定義するためenvファイルを作成し以下を記述envRWSAPPLICATIONID取得したアプリケーションIDControllerとViewファイルを作成railsgcontrolleritemssearchControllerの確認appcontrollersitemscontrollerrbclassItemsControllerltApplicationControllerdefsearchendendsearchアクションが記述されていることを確認。 2021-11-11 21:46:36
Ruby Railsタグが付けられた新着投稿 - Qiita 【RSpec】Railsチュートリアル第6版 第13章 https://qiita.com/supyolo888/items/c88b6acd4ff55750defc 【RSpec】Railsチュートリアル第版第章はじめにRailsチュートリアル第版のテストをRSpecで書き直していく。 2021-11-11 21:53:33
Ruby Railsタグが付けられた新着投稿 - Qiita 【Ruby on Rails】楽天APIで商品検索アプリを作る https://qiita.com/daisuke-webapp/items/eff7af9e45f23400f9d4 【RubyonRails】楽天APIで商品検索アプリを作るプロジェクトを開始railsnewraktuensearchデータベースと接続cdrakutensearchrailsdbcreateサーバーを起動して動作確認railss“YayYoureonRailsの表示を確認できたらOK共通レイアウト共通のViewappviewslayoutsapplicationhtmlerbltDOCTYPEhtmlgtlthtmllangjagtltheadgtlttitlegtWishlistTestlttitlegtltmetanameviewportcontentwidthdevicewidthinitialscalegtltcsrfmetatagsgtltcspmetataggtltlinkrelstylesheethrefbetadistcssbootstrapmincssgtltstylesheetlinktagapplicationmediaalldataturbolinkstrackreloadgtltjavascriptpacktagapplicationdataturbolinkstrackreloadgtltscriptsrcbetadistjsbootstrapbundleminjsgtltscriptgtltheadgtltbodydataturbolinksfalsegtltrenderlayoutsnavbargtltdivclasscontainergtltrenderlayoutsflashmessagesgtltyieldgtltdivgtltbodygtlthtmlgtフラッシュメッセージappviewslayoutsflashmessageshtmlerbltflasheachdomessagetypemessagegtltdivclassalertalertltmessagetypegtgtltmessagegtltdivgtltendgtエラーメッセージappviewslayoutserrormessageshtmlerbltifmodelerrorsanygtltdividerrorexplanationclassalertalertwarninggtltulclassmbgtltmodelerrorsfullmessageseachdomessagegtltligtltmessagegtltligtltendgtltulgtltdivgtltendgtナビバーappviewslayoutsnavbarhtmlerbltheaderclassmbgtltnavclassnavbarnavbarexpandsmnavbardarkbgdarkgtltdivclasscontainerfluidpspegtltaclassnavbarbrandhrefgtMicropostsltagtltbuttonclassnavbartogglertypebuttondatabstogglecollapsedatabstargetnavbarSupportedContentgtltspanclassnavbartogglericongtltspangtltbuttongtltdivclasscollapsenavbarcollapsejustifycontentendidnavbarSupportedContentgtltulclassnavbarnavgtltliclassnavitemgtltahrefclassnavlinkgtSignupltagtltligtltliclassnavitemgtltahrefclassnavlinkgtLoginltagtltligtltulgtltdivgtltdivgtltnavgtltheadergt【楽天API】gemをインストールgemrakutenwebservicegemdotenvrails行目は楽天APIを利用するため、行目はdotenvを利用するために記述bundleinstallGemfileに追記したのでbundleinstall【楽天API】アプリケーションIDを設定取得したアプリケーションIDを設定取得したアプリケーションIDを設定するためconfiginitializersフォルダの中にrautenrbファイルを作成し、以下を記述するrakutenrbRakutenWebServiceconfiguredoc必須アプリケーションIDcapplicationidENVRWSAPPLICATIONID任意楽天アフィリエイトIDcaffiliateidENVRWSAFFILIATIONIDendアフィリエイトIDの記述は任意なので不必要な人は記述しなくてもよいtouchenv環境変数を定義するためenvファイルを作成し以下を記述envRWSAPPLICATIONID取得したアプリケーションIDControllerとViewファイルを作成railsgcontrolleritemssearchControllerの確認appcontrollersitemscontrollerrbclassItemsControllerltApplicationControllerdefsearchendendsearchアクションが記述されていることを確認。 2021-11-11 21:46:36
海外TECH Ars Technica Rad Power’s RadWagon 4: A great e-bike at a surprisingly low price https://arstechnica.com/?p=1809093 pricethis 2021-11-11 12:00:30
海外TECH MakeUseOf Google Launches "Project Relate" and Wants You to Help Test It https://www.makeuseof.com/google-launches-project-relate-and-wants-you-to-help-test-it/ Google Launches amp quot Project Relate amp quot and Wants You to Help Test ItGoogle needs help to improve its speech recognition software and make it more inclusive Here s how you can join in 2021-11-11 12:45:34
海外TECH MakeUseOf The Best Black Friday Deals 2021 https://www.makeuseof.com/tag/best-black-friday-deals/ deals 2021-11-11 12:30:21
海外TECH MakeUseOf SEGA and Microsoft Are Joining Forces: What This Could Mean for Gamers https://www.makeuseof.com/sega-microsoft-joining-forces/ great 2021-11-11 12:26:21
海外TECH MakeUseOf Microsoft Announces Windows 11 SE to Wage War on Chrome OS https://www.makeuseof.com/microsoft-announces-windows-11-se/ google 2021-11-11 12:03:32
海外TECH DEV Community How to Build a Wallet System with Flutterwave Payment Integration Into NodeJs Application https://dev.to/olanetsoft/how-to-build-a-wallet-system-with-flutterwave-payment-integration-into-nodejs-application-175b How to Build a Wallet System with Flutterwave Payment Integration Into NodeJs ApplicationToday many website owners want online payment gateways especially as the industry has developed by leaps and bounds Creating a wallet system is a bit of a nightmare when designing an app for the health sector finance or other sectors We will learn how to create a wallet system and how to integrate the Flutterwave payment system in this tutorial PrerequisitesTo follow along with this tutorial we will need A working knowledge of JavaScript A good understanding of Node js A basic understanding of MongoDB or any database of our choice Postman and some knowledge on how to use Postman We also need a Flutterwave account to receive or accept payments from our application What is a Wallet System A digital wallet often known as an e wallet is an electronic device internet service or software application that allows one party to exchange digital currency units for products and services with another party This can include utilizing a computer to purchase products online or using a smartphone to buy in a store Before any transactions money can be deposited in the digital wallet or an individual s bank account can be linked to the digital wallet in other situations What Are the Benefits of a Digital Wallet Instead of having to fish your card out of your likely bulging wallet every time you want to make an online transaction you can simply hold your smartphone log into your account and you re ready to go Most applications allow you to organize all of your information in a readily accessible manner saving you time from rummaging through your wallet for the things you need Many digital wallet apps offer a variety of bonuses and prizes to their users which might help you get more bang for your buck on specific transactions What is Flutterwave From online collections to payouts and everything in between Flutterwave can help you develop any form of payment flow for your specific use case They also provide several services that allow you to transfer and receive money over the world in a matter of minutes Create a directory Install dependencies and set up authenticationTo get started we ll need to set up our project Open Visual Studio Code by navigating to a directory of our choice on our machine and opening it on the terminal Then execute code Note code won t work if we don t have Visual Studio Code installed on our system Create a directory and initialize npm Create a directory and initialize npm by typing the following command Windows power shell mkdir wallet demo with flutterwave cd wallet demo with flutterwave npm init yLinux mkdir wallet demo with flutterwave cd wallet demo with flutterwave npm init y Create files and directoriesIn the earlier step we initialized npm with the command npm init y which automatically created a package json We need to create the model config directory and files for example wallet js wallet transaction js transaction js database js using the commands below mkdir model config touch config database js model wallet js model wallet transaction js model transaction js model user jsWe can now create the index js and app js files in the root directory of our project with the command touch app js index jsAs shown in the image below Install dependenciesWe ll install several dependencies like mongoose jsonwebtoken express dotenv axios bcryptjs and development dependency like nodemon to restart the server as we make changes automatically We will install mongoose because I will be using MongoDB in this tutorial User credentials will be checked against what we have in our database As a result the entire authentication process isn t limited to the database we ll use in this tutorial npm install jsonwebtoken dotenv mongoose express bcryptjs axios npm install nodemon D Create a Node js server and connect your databaseBy adding the following snippets to our app js index js database js env in that order we can now create our Node js server and connect it to our database In our database js config database js const mongoose require mongoose const MONGO URI process env exports connect gt Connecting to the database mongoose connect MONGO URI useNewUrlParser true useUnifiedTopology true then gt console log Successfully connected to database catch error gt console log database connection failed exiting now console error error process exit In our app js wallet demo with flutterwave app jsrequire dotenv config require config database connect const express require express const bcrypt require bcryptjs const jwt require jsonwebtoken const app express app use express json Logic heremodule exports app In our index js wallet demo with flutterwave index jsconst http require http const app require app const server http createServer app const API PORT process env const port process env PORT API PORT server listening server listen port gt console log Server running on port port If you notice our file needs some environment variables We will create a new env file and add our variables before starting our application In our env API PORT MONGO URI Your database URI hereTo start our server edit the scripts object in our package json to look like the below one scripts start node index js dev nodemon index js test echo Error no test specified amp amp exit The snippet above has been successfully inserted into app js index js and database js First we built our node js server in index js and imported the app js file with routes configured Then as indicated in database js we used mongoose to create a connection to our database Execute the command npm run dev Both the server and the database should be up and running without crashing Create user model and routeWe ll define our schema for the user details when signing up for the first time and validate them against the saved credentials when logging in Add the following snippet to user js inside the model folder model user jsconst mongoose require mongoose const userSchema new mongoose Schema first name type String default null last name type String default null email type String unique true password type String module exports mongoose model user userSchema Now let s create the routes for register and login respectively app js file in the root directory we will add the following snippet for user registration and login importing user contextconst User require model user Registerapp post register req res gt our register logic goes here Loginapp post login req res gt our login logic goes here Implement register and login functionalityWe ll be implementing these two routes in our application We will be using JWT to sign the credentials and bycrypt to encrypt the password before storing them in our database From the register route we will Get user input Validate user input Validate if the user already exists Encrypt the user password Create a user in our database And finally create a signed JWT token Modify the register route structure we created earlier to look as shown below app post register async req res gt Our register logic starts here try Get user input const first name last name email password req body Validate user input if email amp amp password amp amp first name amp amp last name res status send All input is required check if user already exist Validate if user exist in our database const oldUser await User findOne email if oldUser return res status send User Already Exist Please Login Encrypt user password encryptedPassword await bcrypt hash password Create user in our database const user await User create first name last name email email toLowerCase sanitize convert email to lowercase password encryptedPassword Create token const token jwt sign user id user id email process env TOKEN KEY expiresIn h save user token user token token return new user res status json user catch err console log err Our register logic ends here Note Update your env file with a TOKEN KEY which can be a random string Using Postman to test the endpoint we ll get the response shown below after successful registration login app post login async req res gt Our login logic starts here try Get user input const email password req body Validate user input if email amp amp password res status send All input is required Validate if user exist in our database const user await User findOne email if user amp amp await bcrypt compare password user password Create token const token jwt sign user id user id email process env TOKEN KEY expiresIn h save user token user token token user res status json user res status send Invalid Credentials catch err console log err Our login logic ends here Click here to learn more about How to Build an Authentication API with JWT Token in Node js Build a Wallet System with Flutterwave Payment IntegrationWe can now utilize the user details to build wallets save wallet transactions and perform other operations in the system now that we have successfully created a user collection and authentication functionality in the previous step Let s update our wallet js wallet transaction and transaction using the following code model wallet jsconst Schema model require mongoose const walletSchema Schema balance type Number default userId type Schema Types ObjectId required true ref users timestamps true module exports model wallet walletSchema model wallet transaction jsconst mongoose require mongoose const walletTransactionSchema new mongoose Schema amount type Number default Even though user can be implied from wallet let us double save it for security userId type String ref users required true isInflow type Boolean paymentMethod type String default flutterwave currency type String required true currency is required enum NGN USD EUR GBP status type String required true payment status is required enum successful pending failed timestamp true module exports mongoose model walletTransaction walletTransactionSchema model transaction jsconst mongoose require mongoose const transactionSchema new mongoose Schema userId type Schema Types ObjectId ref user transactionId type Number trim true name type String required true name is required trim true email type String required true email is required trim true phone type String amount type Number required true amount is required currency type String required true currency is required enum NGN USD EUR GBP paymentStatus type String enum successful pending failed default pending paymentGateway type String required true payment gateway is required enum flutterwave Payment gateway might differs as the application grows timestamps true module exports mongoose model Transaction transactionSchema We ve created our wallet wallet transaction and transaction schemas which means we can now receive funds from the client validate payment using flutterwave on the backend record and update payment details in the wallet wallet transaction and transaction collections respectively Let s get the front end client ready to accept payments from clients We will use the following command to create an index html file in our root directory touch index htmlUpdate index html that we just created with the snippet below lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta name viewport content width device width initial scale gt lt title gt Receive Payment lt title gt lt head gt lt body gt lt form gt lt script src gt lt script gt lt button type button onClick makePayment gt Pay Now lt button gt lt form gt lt script gt function makePayment FlutterwaveCheckout public key YOUR PUBLIC KEY HERE tx ref hooli tx bbtyt amount currency NGN country NG payment options card specified redirect URL redirect url http localhost response use customer details if user is not logged in else add user id to the request customer email demomail gmail com phone number name Idris Olubisi callback function data console log data onclose function close modal customizations title Flutterwave Demo description Flutterwave Payment Demo logo lt script gt lt body gt lt html gt You can learn more about the snippet above from the Flutterwave documentationUpdating our app js to render the index html file from the server side we will use the following snippet const path require path app post login async req res gt Add the route belowapp get pay req res gt res sendFile path join dirname index html dirname It will resolve to your project folder Before we test our app we ll see the phrase YOUR PUBLIC KEY HERE in the index html we created earlier which implies we ll need a public key from our flutterwave dashboard Let s go to our dashboard to retrieve our public key Let s test it out by going to our browser and typing http localhost pay We should see something similar to what we have below after clicking the Pay Now button We will use the test card number expiry date and CVV We will be redirected to the page below to enter OTP which is because we are using a test card We ll be redirected to localhost response after entering the OTP but nothing will happen Let s address that by implementing the logic to handle what happens next Creating the response endpoint we will update our app js with the snippet below app get response async req res gt const transaction id req query URL with transaction ID of which will be used to confirm transaction status const url transaction id verify Network call to confirm transaction status const response await axios url method get headers Content Type application json Accept application json Authorization process env FLUTTERWAVE V SECRET KEY console log response data data We get the transaction id from the query params of our callback in the code above and we verify the transaction by sending a request to the flutterwave endpoint We should see something like the screenshot below in our log Let us create a logic to manage operations such as validating a user s wallet creating wallet transactions and transactions among others In our app js let s import Wallet Wallet transaction and transaction model importing user contextconst User require model user const Wallet require model wallet const WalletTransaction require model wallet transaction const Transaction require model transaction Updating app js with the logic to manage operations app get response async req res gt Validating User walletconst validateUserWallet async userId gt try check if user have a wallet else create wallet const userWallet await Wallet findOne userId If user wallet doesn t exist create a new one if userWallet create wallet const wallet await Wallet create userId return wallet return userWallet catch error console log error Create Wallet Transactionconst createWalletTransaction async userId status currency amount gt try create wallet transaction const walletTransaction await WalletTransaction create amount userId isInflow true currency status return walletTransaction catch error console log error Create Transactionconst createTransaction async userId id status currency amount customer gt try create transaction const transaction await Transaction create userId transactionId id name customer name email customer email phone customer phone number amount currency paymentStatus status paymentGateway flutterwave return transaction catch error console log error Update wallet const updateWallet async userId amount gt try update wallet const wallet await Wallet findOneAndUpdate userId inc balance amount new true return wallet catch error console log error We can now update the response endpoint with all the functions we created to manage different operations app get response async req res gt const transaction id req query URL with transaction ID of which will be used to confirm transaction status const url transaction id verify Network call to confirm transaction status const response await axios url method get headers Content Type application json Accept application json Authorization process env FLUTTERWAVE V SECRET KEY const status currency id amount customer response data data check if customer exist in our database const user await User findOne email customer email check if user have a wallet else create wallet const wallet await validateUserWallet user id create wallet transaction await createWalletTransaction user id status currency amount create transaction await createTransaction user id id status currency amount customer await updateWallet user id amount return res status json response wallet funded successfully data wallet Voila We re almost done so let s test our application After completing payment we should get something similar to what we have below Because of several trials while trying to fund our wallet we have a balance of in the screenshot above however the number may differ if the procedures are done attentively Let s create an endpoint to retrieve a user balance with the code snippet below app get wallet userId balance async req res gt try const userId req params const wallet await Wallet findOne userId user res status json wallet balance catch err console log err Testing our endpoint that returns the user balance Note We may have noticed that if we reload the page after being redirected to the response endpoint the same transaction with the same amount is updated in our wallet To prevent this we must verify that such a transaction id does not exist in our system otherwise we will receive a duplicate transaction error We can modify our logic as shown below app get response async req res gt const transaction id req query const status currency id amount customer response data data check if transaction id already exist const transactionExist await Transaction findOne transactionId id if transactionExist return res status send Transaction Already Exist return res status json response wallet funded successfully data wallet Next we should see something similar to the screenshot below when we refresh the page Complete code is available on GitHub ConclusionIn this article we learned how to build a simple authentication wallet system and flutterwave payment integration into our nodeJs application ReferencesFlutterwaveFlutterwave DocsI d love to connect with you at Twitter LinkedIn GitHub PortfolioSee you in my next blog article Take care 2021-11-11 12:43:55
海外TECH DEV Community Code Smell 101 - Comparison Against Booleans https://dev.to/mcsee/code-smell-101-comparison-against-booleans-3aic Code Smell Comparison Against BooleansWhen comparing to booleans we perform magic castings and get unexpected results TL DR Don t compare against true Either you are true or false or you shouldn t compare ProblemsHidden castingsThe least surprise principle violation Fail Fast principle violation SolutionsUse booleansDon t mix booleans with boolean castable objects ContextMany languages cast values to boolean crossing domains Sample Code Wrong bin bashif false then echo True else echo False fi this evaluates to true since false is a non empty stringif false true then echo True else echo False fi this also evaluates to true Right bin bashif false then echo True else echo False fi this evaluates to false Detection X Automatic Linters can check for explicit comparisons and warnings TagsCastings ConclusionIt is a common industry practice to use many non booleans as booleans We should be very strict when using booleans Relations Code Smell Big Bang JavaScript Ridiculous Castings Maxi Contieri・May ・ min read codenewbie oop programming webdev More Info Fail Fast Maxi Contieri・Dec ・ min read codenewbie programming webdev oop CreditsPhoto by Michael Held on UnsplashIf it doesn t work it doesn t matter how fast it doesn t work Mich Ravera Software Engineering Great Quotes Maxi Contieri・Dec ・ min read codenewbie programming quotes software This article is part of the CodeSmell Series How to Find the Stinky parts of your Code Maxi Contieri・May ・ min read codenewbie tutorial codequality beginners 2021-11-11 12:33:16
海外TECH DEV Community Conditional Statements and Loops in Python https://dev.to/sahilfruitwala/conditional-statements-and-loops-in-python-298p Conditional Statements and Loops in PythonWhat if you want to do some specific tasks when the string is Python and some other tasks when the string is Java To achieve this conditioning we can use conditional statements in python or any other language When we want to do some task for n number of times or we want to loop through some specific list in this kind of situation we can use different types of loops Conditional Statements in PythonIn python we have two types of conditional statements If elseif elif else if else if else Both conditional statements seem almost similar and actually they are There is just a minor difference between these two statements We will understand this difference using code examples If you know any other language s you might be wondering if python has a switch case or not NO python does not have a switch case if elseSyntax if conditional expresson statementelse statementIf I have explained the if else statement in plain English then it would be the either this or that statement Let s assume if the string is java I want to do the sum of two numbers else I want to multiply two numbers num num lang java if lang java check if value of lang variable is java c num num print c else c num num print c OUTPUT num num lang java if lang java check if value of lang variable is NOT java c num num print c else c num num print c OUTPUT It is not compulsory to use else part You can use only if part as well For example add string Programming to the existing string if it is Python or does nothing lang Python if lang Python lang lang Programming print lang Output Python Programminglang Java if lang Python lang lang Programming print lang Output JavaSometimes you can go into if statement using only variable as well For example lang Python if lang lang Programming print lang OUTPUT Pythonlang Python if lang lang Programming print lang OUTPUT Python Programminglang Python if True lang lang Programming print lang OUTPUT Python Programminglang Python if False lang lang Programming print lang OUTPUT Pythonlang Python if lang lang Programming print lang OUTPUT Pythonlang Python if random string lang lang Programming print lang OUTPUT Python Programminglang Python if None lang lang Programming print lang OUTPUT Pythonlang Python if lang lang Programming print lang OUTPUT Python Programminglang Python if lang lang Programming print lang OUTPUT Pythonlang Python if a lang lang Programming print lang OUTPUT Python Programminglang Python if lang lang Programming print lang OUTPUT PythonIf we want to combine multiple conditions we can use and and or within the if statement lang PYTHON if lang isupper and len lang gt print Worked OUTPUT Worked if lang islower or len lang print Worked again OUPUT Worked again if elif elseSyntax if conditional expresson statementelif conditional expresson statementelse statementWe use this conditional statement when we want to test more than one scenario Let s understand this by an example marks if marks gt and marks lt print Grade C elif marks gt and marks lt print Grade B elif marks gt and marks lt print Grade A elif marks gt and marks lt print FAIL else print Something is wrong OUTPUT Grade A Be aware when you use multiple if and if elif A single error in your logic and all your code base can throw an error To understand this see the below example marks if marks gt and marks lt print Grade A elif marks gt print Grade B elif marks gt print Grade C else print Something is wrong print marks if marks gt and marks lt print Grade A if marks gt print Grade B if marks gt print Grade C OUTPUT Grade B Grade B Grade C Loops in PythonIn python we have two kinds of loops forwhileLoop Control Statements for Loop in PythonSyntax for iterator in sequence statement s For loop is used when we want to traverse through the sequential datatype For example traversing through lists tuples strings etc fruits apple banana mango grapes peach for fruit in fruits print fruit OUTPUT applebananamangograpespeach for i in range len fruits print fruits i OUTPUT applebananamangograpespeach In the first example above in the fruit variable we are directly getting each element of the fruits list Whereas in the second example we are accessing each element by index reference The range n function returns a sequence of numbers Syntax range start stop step for i in range print i OUTPUT We can use for loop with dictionaries as well dict lang python year month november for item in dict print item dict item OUTPUT lang pythonyear month november while Loop in PythonSyntax while expression statement s When you need to do some work repeatedly until some condition satisfies in that situation you can use a while loop Let s assume we need to print Hello World until the count variable became count while count lt print Hello World count count Loop Control StatementsThere are times when you need to break the loop or skip some iterations in the loop or do nothing This kind of thing can be done using Loop Control Statements In python we have three loop control statements Break statementContinue statementPass statementWe use a break statement when we want to break the loop when certain conditions match For example fruits apple banana mango grapes peach for fruit in fruits if fruit mango break print fruit OUTPUT applebanana While the break statement breaks the loop the continue statement makes the loop skip the current iteration and forces it to go to the next iteration fruits apple banana mango grapes peach for fruit in fruits if fruit mango continue print fruit OUTPUT applebananagrapespeach Pass statement is a meaningless piece of code that suggests the interpreter to do nothing It is similar to the comment but comments are ignored by interpreters while pass statement executed by the interpreter and as per the name does nothing Pass statement used with function and class as well which I will explain in the next section fruits apple banana mango grapes peach for fruit in fruits if fruit mango pass print fruit OUTPUT applebananamangograpespeach for else amp while elseDuring the development journey there are times when you might need to use for else and while else These are just normal for and while loop with special else cases Let s see an example to understand it fruits apple banana mango grapes peach for fruit in fruits if fruit mango break print fruit else print Loop Did Not Break OUTPUT applebanana fruits apple banana mango grapes peach for fruit in fruits if fruit abc break print fruit else print Loop Did Not Break OUTPUT applebananamangograpespeachLoop Did Not Break So you might have guessed When loop does not break OR loop completes its all the iteration without interruption else block is executed The same happens with the while loop as well i while i lt if i break print i i else print All iteration of While are executed successfully OUTPUT ConclusionFinally We are at the end of this section I know it is a lot to take in at a time But you don t need to remember everything that I have mentioned here I just showed you so that you can recall what is possible and what is not There are some other methods as well that I have not mentioned here If you want to find out more about control statements and loops in python check out on Programiz That was it Thank you for reading I know it is a lot but I hope you were able to absorb some knowledge If you have any questions or doubt mention them in the comment section or reach out to me on Twitter LinkedIn or Instagram If you want me to explain any specific topic mention that in the comment section below 2021-11-11 12:05:19
海外TECH DEV Community Create your REST API using OpenAPI kotlin-spring generator https://dev.to/bjornvdlaan/create-your-rest-api-using-openapi-kotlin-spring-generator-5154 Create your REST API using OpenAPI kotlin spring generatorWhen building an API I like to start by first creating a formal definition before starting the actual development One of the most established standards for such API definitions is OpenAPI formerly Swagger One pleasant aspect of starting with a definition is that once the definition is created and agreed upon we can generate part of our codebase using the OpenAPI Generator As the name suggests the OpenAPI Generator generates code from an OpenAPI specification More specifically the generator is able to create code for client libraries server stubs documentation and configuration in many different languages and frameworks I know this generator from my Java projects and decided to use it with Kotlin as well Lucky for me there is actually a generator for Spring Boot based Kotlin projects I however could not find a tutorial dedicated to it and therefore I share my steps here in this tutorial TL DRYou can find the full project including target at What we want to achieveWe wish to generate the server stub using the OpenAPI Generator via its Maven plugin An advantage of using the Maven or Gradle plugin is that the generation becomes part of our API s build lifecycle and the generated code is always in sync with your OpenAPI definition when you clean compile your code For our example in this tutorial we will use the PetStore OpenAPI specification from this tutorial on Baeldung After running the Maven plugin the generated code is found in the target generated sources openapi directory see below After generation we only still need to implement the generated Delegate interfaces within our own src directory and voila the API is implemented We will implement one of the routes in the PetStore specification and test it using curl Create your Spring Boot projectWe start by creating a fresh Spring Boot project using the Spring Initializr We tell it to be a Maven project using Kotlin and packaged as a jar We also add the Spring Web dependency because the generated code depends on this dependency After downloading the project we open it in our favorite IDE and we add the petstore yml OpenAPI definition to src main resources to end up with the following project structure Before we can start we need to add one more dependency to our pom xml that the generated code depends on lt dependency gt lt groupId gt org springframework boot lt groupId gt lt artifactId gt spring boot starter validation lt artifactId gt lt dependency gt Add the Maven pluginNow it s time to add the OpenAPI Generator s Maven plugin to pom xml lt plugin gt lt groupId gt org openapitools lt groupId gt lt artifactId gt openapi generator maven plugin lt artifactId gt lt version gt lt version gt lt executions gt lt execution gt lt goals gt lt goal gt generate lt goal gt lt goals gt lt configuration gt lt inputSpec gt project basedir src main resources petstore yml lt inputSpec gt lt generatorName gt kotlin spring lt generatorName gt lt configOptions gt lt basePackage gt nl bjornvanderlaan petstoreapi lt basePackage gt lt apiPackage gt nl bjornvanderlaan petstoreapi api lt apiPackage gt lt modelPackage gt nl bjornvanderlaan petstoreapi model lt modelPackage gt lt configPackage gt nl bjornvanderlaan petstoreapi config lt configPackage gt lt delegatePattern gt true lt delegatePattern gt lt interfaceOnly gt false lt interfaceOnly gt lt modelNameSuffix gt Dto lt modelNameSuffix gt lt configOptions gt lt configuration gt lt execution gt lt executions gt lt plugin gt An overview of all configuration options is found here I would like to highlight three options where I made a design decision delegatePattern true I asked the generator to use the Delegate pattern so the routes and their logic are separated The Delegate implementations that we write ourselves can be injected in the generated code without any need to manually touch the generated sources interfaceOnly false This option determines whether the controller implementation will also be generated This controller implementation essentially just autowires the relevant Delegate to be used in the routes I feel its good to let it be generated because then no engineer can be tempted to add other functionality to the controller maintaining better separation of concerns If you really want to do a lot more in your controller then it is worth considering to set this option to true modelNameSuffix Dto I prefer to use the Dto Data Transfer Object pattern to separate these objects from the entities that I will use in the service layer As such I add a suffix to make the pattern usage explicit Generate the codeWe can generate the code by running mvn clean generate sources and we then obtain the following project structure For IntelliJ users the target generated sources openapi src main kotlin folder can be marked as an generated sources root Right click this folder then go to Mark Directory as and select Generated Sources Root The target generated sources openapi src main kotlin now contains two packages with a couple of classes each Let s quickly go through them one by one api PetsApi ktThis interface class defines one method for each API route from our specification using Spring Web annotations like RequestMapping GetMapping and PostMapping The methods are all one liners as they simply delegate the work to the Delegate exactly as we configured The interface also has an unimplemented getDelegate which will be implemented by PetsApiController api PetsApiDelegateThis interface defines the methods used by the PetsApi with a standard implementation that just returns status Not Implemented We will implement the interface in our src folder api PetsApiController ktThe Controller implements the PetsApi interface by autowiring the PetsApiDelegate implementation As mentioned I configured OpenAPI Generator to generate this class for me because I feel this is all the Controller should do api ExceptionsThis ControllerAdvice class defines default exception handling for three exceptions that are commonly encountered api ApiUtilsThis object singleton defines a utility method used by a utility method for GET mappings model ErrorDtoThis Dto can be used to send back erroneous response to the requestor model PetDtoThe Dto that resembles our pets and is used to respond to for instance GET requests that want to retrieve data Our generated code contains two examples of such routes listPets and showPetById Implement the DelegateNow it s finally time to start coding We create a new class in nl bjornvanderlaan petstoreapi api package in src not target and we override the listPets method to let it return an hardcoded response with my three favorite cat names and status Ok package nl bjornvanderlaan petstoreapi apiimport org springframework http HttpStatusimport org springframework http ResponseEntityimport org springframework stereotype Componentimport nl bjornvanderlaan petstoreapi model PetDto Componentclass PetsApiDelegateImpl PetsApiDelegate override fun listPets limit Int ResponseEntity lt List lt PetDto gt gt return ResponseEntity listOf PetDto L Charlie PetDto L Obi PetDto L Loki HttpStatus OK Verify the APIGreat so we have some generated classes in our target directory based on our OpenAPI specification and we also added some code of our own in src Let s run this with IntelliJ and see what happens We learn that the Spring Boot application is now running on port But does it actually work curl I http localhost petsHTTP Content Type application jsonTransfer Encoding chunkedDate lt redacted my author gt curl http localhost pets id name Charlie tag null id name Obi tag null id name Loki tag null Compile your codeWe might suspect that this tutorial is finished as we have verified the API s response However when we try to compile our code using mvn clean compile we are met with some red text compilation fails because the generated classes cannot be resolved Why does this happen The problem is that the kotlin maven plugin does not see target generated sources openapi as a source directory and so these files are not compiled after cleaning We resolve this by explicitly adding the path to the plugin s configuration lt plugin gt lt groupId gt org jetbrains kotlin lt groupId gt lt artifactId gt kotlin maven plugin lt artifactId gt lt configuration gt lt omitted by author gt lt executions gt lt execution gt lt id gt compile lt id gt lt goals gt lt goal gt compile lt goal gt lt goals gt lt configuration gt lt sourceDirs gt lt sourceDir gt project build directory generated sources kotlin src main kotlin lt sourceDir gt lt sourceDirs gt lt configuration gt lt execution gt lt executions gt lt dependencies gt lt omitted by author gt lt dependencies gt lt plugin gt Adding the above execution resolves our issue and Maven now tells us the build is successful Great Now we are done right Not exactly When we go a step further and run our Spring Boot application via mvn spring boot run then we are met with another error So now what The issues is caused by our design choice to generate not only the interfaces but also the Controller classes as the generator then also gives us an Application kt class As we already also have a main class in our src project Spring now cannot determine which to pick There are essentially two ways to fix this The first option is to delete our own PetStoreApplication kt and use the generated class This could be a reasonable choice if you are use that you do not want to do anything custom in the main class Alternatively we can configure spring boot maven plugin to point out the correct main class lt plugins gt lt plugin gt lt groupId gt org springframework boot lt groupId gt lt artifactId gt spring boot maven plugin lt artifactId gt lt configuration gt lt mainClass gt nl bjornvanderlaan petstoreapi PetstoreApiApplicationKt lt mainClass gt lt configuration gt lt plugin gt lt plugins gt Regardless of which option you choose we can run mvn spring boot run again and are then at last greeted with our beloved Spring banner and the message that our application can now be found at port ConclusionOpenApi allows us to create a specification for our API that we can share among teams and stakeholders to communicate our contracts The OpenAPI Generator and its Maven plugin help us to generate code from our specification We ourselves can then focus on the business logic In this tutorial we saw how we can generate a server stud from our specification for Spring Boot based Kotlin projects 2021-11-11 12:04:09
海外TECH Engadget The Morning After: PS5 and Xbox Series X and S, one year on https://www.engadget.com/the-morning-after-ps-5-and-xbox-series-x-and-s-one-year-on-121946305.html?src=rss The Morning After PS and Xbox Series X and S one year onThe PlayStation and Xbox Series X S debuted one year ago this month To celebrate we ve made a minute video conversation about the pros cons and future of both consoles hosted by PS enthusiast and Engadget Senior Editor Jessica Conditt and Xbox Series X fan and Senior Editor Devindra Hardawar There may not be a clear cut winner of this generation yet ーin fact the conversation tries to steer clear of most of the drama ーso we re focusing on what both PlayStation and Xbox have done right and wrong DualSense Game Pass Ultimate Halo The Horizon sequel Debate ーMat SmithUK Supreme Court rules in favor of Google in iPhone tracking caseJudges were unimpressed by the attempt to create a class action suit Google has escaped the risk of a lawsuit after violating the privacy of around million iPhone users in the UK The UK s Supreme Court has ruled it cannot allow a US style class action suit to be filed against the search giant after it deliberately created a workaround to track Safari users The judgment focused on procedural matters like the intersection between Google based in the US and the UK s data protection laws The battle began in with consumer rights champion Richard Lloyd and many others forming a group called Google You Owe Us which attempted to sue the company It alleged that Google had illegally collected data on iPhone users between June and February While the group lost at the High Court the UK s Court of Appeal overturned this initial decision saying it was fair for Google to face a courtroom after the intentional misuse of personal data without consent Continue reading Sponsored by CISCO Security Outcomes Study for Small BusinessesiOS beta introduces nearby AirTag searchesIt may find unwanted trackers on your person AppleApple is introducing another way to ensure its AirTags won t be used for stalking when iOS comes out According to MacRumors the just out beta version of the mobile platform has a new feature to let users scan for AirTags that may be tracking their location Beta users can find the feature under the Items tab in the Find My‌app Any trackable item nearby that belongs to someone else will be detected and show up as an unknown item Apple will then point users to a set of instructions on how to disable the device being used to track them Another interesting feature that showed up in the beta is Digital Legacy It will let users designate people as Legacy Contacts who ll be able to access their account and digital information when they pass away Continue reading The smart home gadgets and kitchen tech worth giftingLet s go beyond an Instant Pot and a Google Nest Hub EngadgetWe review smart speakers robotic vacuums and Instant Pots all year long and for the holiday season we ve compiled a list of our recent favorites in the home tech space Whoever s getting the gift doesn t have to be tech savvy to use all of them either ーplenty of our recommendations amount to baby steps into the smarthome world Start with a smart plug and work your way up Continue reading YouTube will hide dislike counts for all videosThe move could reduce harassment and targeted attacks YouTube s experiment with hiding dislikes was apparently successful The service is rolling out a change to make dislike counts private for videos across YouTube The button will still exist and affect your recommendations and producers can still see the count ーyou just won t see the numbers as a viewer The Google owned brand is aware that some people used the counts to make viewing decisions but it feels secret counts would help the community at large New and smaller creators are more often targeted by dislike campaigns YouTube said and the test reduced that harassment Continue reading Forza Horizon had the largest launch for any Xbox Game Studios titleThe new Forza had three times as many active players as its predecessor Microsoft s gaming head Phil Spencer has revealed that Forza Horizon had the best launch day of any Xbox Game Studios title There have been over million people playing the arcade racer across all platforms Xbox Windows and cloud to date and its peak concurrent players were three times those of its predecessor Continue reading Congress mandates anti drunk driving technology for carsIt could reach new vehicles by Congress is making its biggest push ever to stop drunk driving with President Biden s huge infrastructure bill As previously reported it includes a mandate for anti drunk driving technology in new cars Now the Infrastructure Investment and Jobs Act has passed Congress with the measure intact and it s expected to be signed by the president soon As part of the legislation carmakers will have to include technology to detect and stop drunk drivers by as early as Continue reading The biggest news stories you might have missedThe best gifts for the creatives in your lifeThe best gadgets for your petsNASA pushes back crewed moon landing to The Hubble telescope is recovering from another system failureCourt rules Apple can t push back ordered App Store payment changesValve s Steam Deck won t ship until 2021-11-11 12:19:46
海外TECH CodeProject Latest Articles Why Does x = ++x + x++ Give Me the Wrong Answer? https://www.codeproject.com/Articles/1208666/Why-Does-x-equals-plusplusx-plus-xplusplus-Give-Me Why Does x x x Give Me the Wrong Answer When they first meet them developers are often tempted to play with pre and post increment operators Then they get confused because they don t do what is expected Or do they 2021-11-11 12:16:00
ニュース BBC News - Home Armistice Day: UK gathers for remembrance of deaths in military conflicts https://www.bbc.co.uk/news/uk-59246093?at_medium=RSS&at_campaign=KARANGA lockdown 2021-11-11 12:50:53
ニュース BBC News - Home FW de Klerk: South Africa's former president dies at 85 https://www.bbc.co.uk/news/world-africa-59247115?at_medium=RSS&at_campaign=KARANGA person 2021-11-11 12:21:39
ニュース BBC News - Home Lives at risk from long 999 waits, say paramedics https://www.bbc.co.uk/news/health-59237935?at_medium=RSS&at_campaign=KARANGA stroke 2021-11-11 12:13:34
ニュース BBC News - Home MPs criticised for 'drunkenness' on Gibraltar military visit https://www.bbc.co.uk/news/uk-politics-59243206?at_medium=RSS&at_campaign=KARANGA accuses 2021-11-11 12:35:40
ニュース BBC News - Home Smith starts at 10 for England v Australia with Tuilagi on wing https://www.bbc.co.uk/sport/rugby-union/59249025?at_medium=RSS&at_campaign=KARANGA australia 2021-11-11 12:32:21
北海道 北海道新聞 鶴居産赤ワイン最多1116本 12日発売 昨年ブドウ収量増で https://www.hokkaido-np.co.jp/article/610677/ 赤ワイン 2021-11-11 21:14:00
北海道 北海道新聞 ウニやイクラ 高すぎ 赤潮被害 函館の鮮魚、飲食店が悲鳴 https://www.hokkaido-np.co.jp/article/610672/ 鮮魚 2021-11-11 21:10:00
北海道 北海道新聞 国内で216人感染、4人死亡 新型コロナ https://www.hokkaido-np.co.jp/article/610673/ 新型コロナウイルス 2021-11-11 21:10:00
北海道 北海道新聞 地域と医療つなぎ10年 芽室病院「支える会」 花壇整備 住民講座充実に力 https://www.hokkaido-np.co.jp/article/610669/ 公立芽室病院 2021-11-11 21:07:00
北海道 北海道新聞 「サンタカード」に名称変更 ひろおサンタメール 郵送を明確化 申し込み12月10日まで https://www.hokkaido-np.co.jp/article/610668/ 申し込み 2021-11-11 21:05:00
北海道 北海道新聞 EV、ロボット 先端技術紹介 ビジネスEXPO開幕 札幌 https://www.hokkaido-np.co.jp/article/610666/ 先端技術 2021-11-11 21:02:00
北海道 北海道新聞 「モンスターウルフ」でクマ食害防げ 北見で検証 周辺で効果確認 https://www.hokkaido-np.co.jp/article/610667/ 鳥獣 2021-11-11 21:03:00

コメント

このブログの人気の投稿

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

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

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