TECH |
Engadget Japanese |
2C2A 100WのUSB ACアダプタが驚きの2970円。フォーカルポイントがブラックフライデーセール |
https://japanese.engadget.com/focalpoint-black-sale-111949615.html
|
tunemaxganw |
2021-11-22 11:19:49 |
IT |
ITmedia 総合記事一覧 |
[ITmedia ビジネスオンライン] 総務省、グーグルのPixel 6を「技適不適合」へ 緊急通報で不具合 |
https://www.itmedia.co.jp/business/articles/2111/22/news146.html
|
itmedia |
2021-11-22 20:19:00 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
google colab でログ出力無しで進捗を表示する |
https://qiita.com/jun40vn/items/170d9ed42b8acda8e5cd
|
googlecolabでログ出力無しで進捗を表示するはじめにgooglecolabでライブラリのインストールなどを行うとき、場合によっては長々とログを出力することがあります。 |
2021-11-22 20:29:22 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
翻訳モデルの翻訳時の語順の並び替えを可視化してみた |
https://qiita.com/sentencebird/items/6f4ef30187d329a95543
|
transformers翻訳pyvis単語の対応のネットワーク図作成streamlit入出力をwebアプリ化翻訳時の語の並び替えとアテンション翻訳元と翻訳先の語の対応を調べるために、翻訳モデルTransformerのアテンションの重みを使用しています。 |
2021-11-22 20:11:00 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
【javascript】ループ分とブロックスコープ |
https://qiita.com/Quest_love33/items/aa5f7553843555f7a549
|
forletiiltivarjisetTimeoutfunctionconsolelogjgtgtgt⑤なぜかvarはブロックスコープをとらないsetTimeoutで秒後に出力されている間に、varjiが回処理されて、処理の最後、すなわちが回出力されることになる。 |
2021-11-22 20:31:33 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
2つのソート済みの整数列を併合する |
https://teratail.com/questions/370539?rss=all
|
つのソート済みの整数列を併合する前提・実現したいことつのソート済みの整数列を併合させる問題です。 |
2021-11-22 20:59:21 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
swiftUI Cannot find ・・・・ in scope |
https://teratail.com/questions/370538?rss=all
|
swiftUICannotfind・・・・inscopeSwiftUIの素人です。 |
2021-11-22 20:54:33 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
ネットワークエンジニアになるのは諦めたほうがいいのか? |
https://teratail.com/questions/370537?rss=all
|
ネットワークエンジニアになるのは諦めたほうがいいのかはじめまして、ご覧いただきありがとうございます。 |
2021-11-22 20:52:53 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
linuxはルーターの機能が最初から備わっているのですか? |
https://teratail.com/questions/370536?rss=all
|
linux |
2021-11-22 20:47:07 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
ajaxで商品一覧を取得したい |
https://teratail.com/questions/370535?rss=all
|
ajaxで商品一覧を取得したいお世話になっております。 |
2021-11-22 20:30:54 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
WordPressの記事ページのパンくずリストの作り方について |
https://teratail.com/questions/370534?rss=all
|
WordPressの記事ページのパンくずリストの作り方についてご閲覧いただき、ありがとうございます。 |
2021-11-22 20:24:00 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
自作したC#プログラムにて、外部アプリであるメモ帳で保存したテキストファイルのPathを取得したいです |
https://teratail.com/questions/370533?rss=all
|
自作したCプログラムにて、外部アプリであるメモ帳で保存したテキストファイルのPathを取得したいです実現したいこと・Windows標準テキストエディタである「メモ帳」にて、「名前を付けて保存」をした場合に、保存したテキストファイルのPathを、自作したCプログラムで取得したいです。 |
2021-11-22 20:23:52 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
WEBサイトに、他のWEBサイトをスクロールさせたgifを埋め込みたいです。 |
https://teratail.com/questions/370532?rss=all
|
方法 |
2021-11-22 20:20:19 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
Box2Dにおいて、物体同士がすり抜けてしまう問題について |
https://teratail.com/questions/370531?rss=all
|
BoxDにおいて、物体同士がすり抜けてしまう問題についてBoxDにおいて、作成した物体同士がすり抜けてしまいます。 |
2021-11-22 20:18:21 |
技術ブログ |
Developers.IO |
【小ネタ】GitHub Actions用のIAMロールをAWSマネジメントコンソールから作成する際の注意点 |
https://dev.classmethod.jp/articles/create-iam-id-provider-for-github-actions-with-management-console/
|
githubactions |
2021-11-22 11:52:43 |
技術ブログ |
Developers.IO |
SQSを利用したS3イベント通知の処理で、Lambda関数から断続的に発生するエラーを回避する方法を教えてください |
https://dev.classmethod.jp/articles/tsnote-sqs-and-lambda-configure-s3-event-notification/
|
lambda |
2021-11-22 11:36:55 |
海外TECH |
MakeUseOf |
5 Banned Content Topics You Can't Talk About on YouTube |
https://www.makeuseof.com/youtube-banned-content-topics/
|
overview |
2021-11-22 11:00:32 |
海外TECH |
DEV Community |
🗂 Decomposing theme elements styles in your Flutter app |
https://dev.to/koddr/decomposing-theme-elements-styles-in-your-flutter-app-1a8k
|
Decomposing theme elements styles in your Flutter app IntroductionHey hey DEV friends Lately I ve been reading and refactoring other people s code more and more often Both incredibly beautiful and…the kind of code I d like to take apart with you today Disclaimer This article does not claim to be the ultimate truth The method of code decomposition shown below is just an example you can always write how you do it in the comments below Feel free it will be interesting to read Great let s do it Table of contentsHow task decomposition helps usNote about the decomposition in FlutterExample of architectural planProblems with code without decompositionHow I do it How task decomposition helps usLet s begin by defining what decomposition from Wiki Decomposition in computer science also known as factoring is breaking a complex problem or system into parts that are easier to conceive understand program and maintain Let s turn to a simple diagram to better understand the principles of tasks decomposition Take the launch of the “Awesome App to market as an example Without decomposing this task its diagram would look something like this Where do you need to start and how do you come to launch Only the desired result without detailing the process itself Nothing is clear…But if we apply even basic knowledge of decomposition the diagram will look something like this Much better isn t it We ve broken down the process of launching an application into big blocks with clear actions research design writing code testing and launching Next we can break these blocks into smaller ones and so on until we get to atomic tasks which can no longer be broken down into smaller ones ↑Table of contents Note about the decomposition in FlutterI would like to note that the code written on the multiplatform Flutter framework like no other requires constant refactoring and decomposition almost from the beginning of the project All because the framework has been designed to write code in declarative style where every element is a separate widget And when the code becomes a lot for example starting from the th degree of nesting it is simply impossible to read it without effort That s why you should always have an architectural plan for your application which you will stick to most of the time In my opinion this is both a plus and a minus at the same time Otherwise maintaining and further developing the project inevitably turns into a natural pain ↑Table of contents Example of architectural planWhat is an “architectural plan for writing software Simple it is a set of rules that all programmers follow when writing code If you re familiar with a frontend development React Vue etc here s a sample set of rules for writing project code All components must be stored in the src components folder with easy to understand names All helper functions must have a pointer to the action in their name for example if the helper get a link to the user s avatar its name could be getUserAvatarURL The maximum number of props in a component should not exceed …and many more Do you feel like there s no more chaos in your head when you have rules like that That s the beauty of an architecture plan for software You just have to follow the accepted rules for a particular project That s it ️Warning Please don t confuse an architecture plan with a style guide or language framework best practices The architecture plan is more like a local checklist for a particular project than a globally accepted norms and standards ↑Table of contents Problems with code without decompositionI was recently doing a review of a project that was written in Flutter and found a widget like this lib screens app dart Application widget class MyApp extends StatelessWidget const MyApp Key key super key key override Widget build BuildContext context return MaterialApp title My App debugShowCheckedModeBanner false start default theme light theme theme ThemeData copyWith textTheme GoogleFonts interTextTheme Theme of context textTheme copyWith bodyText TextStyle color BrandColor secondary subtitle TextStyle color BrandColor secondary headline TextStyle color BrandColor primary scaffoldBackgroundColor BrandColor secondary primaryColor BrandColor primary textButtonTheme TextButtonThemeData style TextButton styleFrom primary BrandColor primary elevatedButtonTheme ElevatedButtonThemeData style ElevatedButton styleFrom onPrimary Colors white primary BrandColor primary shape RoundedRectangleBorder borderRadius BorderRadius circular padding const EdgeInsets symmetric vertical outlinedButtonTheme OutlinedButtonThemeData style OutlinedButton styleFrom primary BrandColor primary side BorderSide color BrandColor primary as Color bottomNavigationBarTheme BottomNavigationBarThemeData backgroundColor BrandColor secondary showSelectedLabels false showUnselectedLabels false selectedIconTheme const IconThemeData size unselectedIconTheme const IconThemeData size selectedItemColor BrandColor primary unselectedItemColor BrandColor primary start dark theme darkTheme ThemeData dark copyWith scaffoldBackgroundColor BrandColor secondary primaryColor BrandColor primary textTheme GoogleFonts interTextTheme Theme of context textTheme copyWith bodyText TextStyle color BrandColor secondary subtitle TextStyle color BrandColor secondary headline TextStyle color BrandColor primary textButtonTheme TextButtonThemeData style TextButton styleFrom primary BrandColor primary elevatedButtonTheme ElevatedButtonThemeData style ElevatedButton styleFrom onPrimary Colors white primary BrandColor primary shape RoundedRectangleBorder borderRadius BorderRadius circular padding const EdgeInsets symmetric vertical outlinedButtonTheme OutlinedButtonThemeData style OutlinedButton styleFrom primary BrandColor primary side BorderSide color BrandColor primary as Color bottomNavigationBarTheme BottomNavigationBarThemeData backgroundColor BrandColor secondary showSelectedLabels false showUnselectedLabels false selectedIconTheme const IconThemeData size unselectedIconTheme const IconThemeData size selectedItemColor BrandColor primary unselectedItemColor BrandColor primary themeMode ThemeMode system initialRoute routes lt String WidgetBuilder gt gt const SplashScreen sign in gt const SignInScreen main gt const MainScreen And that s not counting the imports which take up the first lines It s already quite difficult to read or make edits to such code But this massive code can easily be decomposed ↑Table of contents How I do it️⃣First you need to identify the most appropriate elements for it One of the most eye catching parts of the code is the code section defining the application s design themes the light and dark themes ️⃣Second let s think about how we re going to do this I think it will be enough to put the styles in separate functions for example lightThemeData and darkThemeData which will be available in the context of each widget ️⃣Third for easier access to styles out of context I will use the extension methods a built in Dart language functionality If you aren t yet familiar with it I suggest you watch this short video by Filip Hracek Note Furthermore I usually store the styles in the lib styles folder but you can name it whatever you like Sounds like a good plan Let s rewrite the code Starting with methods for the class with styles lib styles themes dart Theme data for project extension BrandThemeData on BuildContext Styles for the light theme ThemeData lightThemeData return ThemeData copyWith textTheme GoogleFonts interTextTheme Theme of this textTheme copyWith bodyText TextStyle color BrandColor secondary subtitle TextStyle color BrandColor secondary headline TextStyle color BrandColor primary scaffoldBackgroundColor BrandColor secondary primaryColor BrandColor primary textButtonTheme TextButtonThemeData style TextButton styleFrom primary BrandColor primary elevatedButtonTheme ElevatedButtonThemeData style ElevatedButton styleFrom onPrimary Colors white primary BrandColor primary shape RoundedRectangleBorder borderRadius BorderRadius circular padding const EdgeInsets symmetric vertical outlinedButtonTheme OutlinedButtonThemeData style OutlinedButton styleFrom primary BrandColor primary side BorderSide color BrandColor primary as Color bottomNavigationBarTheme BottomNavigationBarThemeData backgroundColor BrandColor secondary showSelectedLabels false showUnselectedLabels false selectedIconTheme const IconThemeData size unselectedIconTheme const IconThemeData size selectedItemColor BrandColor primary unselectedItemColor BrandColor primary Styles for the dark theme ThemeData darkThemeData return ThemeData dark copyWith scaffoldBackgroundColor BrandColor secondary primaryColor BrandColor primary textTheme GoogleFonts interTextTheme Theme of this textTheme copyWith bodyText TextStyle color BrandColor secondary subtitle TextStyle color BrandColor secondary headline TextStyle color BrandColor primary textButtonTheme TextButtonThemeData style TextButton styleFrom primary BrandColor primary elevatedButtonTheme ElevatedButtonThemeData style ElevatedButton styleFrom onPrimary Colors white primary BrandColor primary shape RoundedRectangleBorder borderRadius BorderRadius circular padding const EdgeInsets symmetric vertical outlinedButtonTheme OutlinedButtonThemeData style OutlinedButton styleFrom primary BrandColor primary side BorderSide color BrandColor primary as Color bottomNavigationBarTheme BottomNavigationBarThemeData backgroundColor BrandColor secondary showSelectedLabels false showUnselectedLabels false selectedIconTheme const IconThemeData size unselectedIconTheme const IconThemeData size selectedItemColor BrandColor primary unselectedItemColor BrandColor primary Yay Now we can rewrite widget lib screens app dart like this lib screens app dart Application widget class MyApp extends StatelessWidget const MyApp Key key super key key override Widget build BuildContext context return MaterialApp title My App debugShowCheckedModeBanner false theme context lightThemeData default theme light darkTheme context darkThemeData dark theme themeMode ThemeMode system initialRoute routes lt String WidgetBuilder gt gt const SplashScreen sign in gt const SignInScreen main gt const MainScreen The app works and looks the same but the development experience has grown several times over What a great way to decompose code ↑Table of contents Photos and videos byFilip Hracek amp the Flutter team Vic Shóstak P S If you want more articles like this on this blog then post a comment below and subscribe to me Thanks And of course you can support me by donating at LiberaPay Each donation will be used to write new articles and develop non profit open source projects for the community |
2021-11-22 11:46:00 |
海外TECH |
DEV Community |
Let's create a typing practice game with JavaScript |
https://dev.to/0shuvo0/lets-create-a-typing-practice-game-with-javascript-518l
|
Let x s create a typing practice game with JavaScript As a programming we type a lot But use some random app for typing practice Nah fam we are creating our own typing practice game from scratch using vanilla JavaScript Video tutorial available on YouTubeBefore we start here are the features our game will have Time limitWill work with any amount of textHighlight text in green if you type correctlyHighlight text in red if you type incorrectlyStart game as soon as user stars typingOkay lets start by creating our html css and js file And then in the html we will have three elements A div where we will show our textA div that will work as our progress barA textarea where we can type lt DOCTYPE html gt lt html lang en gt lt head gt lt meta charset UTF gt lt meta http equiv X UA Compatible content IE edge gt lt meta name viewport content width device width initial scale gt lt link rel stylesheet href style css gt lt title gt Document lt title gt lt head gt lt body gt lt div class text gt lt div gt lt div class progress bar gt lt div gt lt textarea class input placeholder Start Typing gt lt textarea gt lt script src main js gt lt script gt lt body gt lt html gt Now let s style them in our css margin padding box sizing border box body background color ffec font family Gill Sans text input display block width border none outline none padding em height calc vh px font size em font weight bold progress bar height px background color rgb Now if we open it up in our browser we will see this Now we want to show some text in our div We will do that in JavaScript Because we want to wrap every character in a span Why because then we can add a green or red background to the span to indicate if we ve typed correct or wrong Lets create a function to populate the text in our div Any string that you want to useconst str Type this as fast as possible Selected necessary elementsconst text document querySelector text const input document querySelector input const progressBar document querySelector progress bar function populateText str str split will convert our string to characters array Then we can loop through them str split map letter gt const span document createElement span span innerText letter text appendChild span populateText str Now you will see text is displayed and each letter is wrapped by a spanWe would need to access those spans later on So lets store them in a array for easy access const str Type this as fast as possible const text document querySelector text const input document querySelector input const progressBar document querySelector progress bar const charEls function populateText str str split map letter gt const span document createElement span span innerText letter text appendChild span Adding span in array charEls push span populateText str Great now when we type something in our textarea we want to get the valueconst str Type this as fast as possible const text document querySelector text const input document querySelector input const progressBar document querySelector progress bar const charEls function populateText str str split map letter gt const span document createElement span span innerText letter text appendChild span charEls push span populateText str input addEventListener keyup gt const val input value console log val Now we are going to loop through all the letters inside our textarea And for each of the letter we will compare it with the letter of our str at that index If they match that means we typed correct so we can add a correct class to the span at that index Otherwise we will add wronginput addEventListener keyup gt const val input value resetCharEls val split map letter i gt if letter str i charEls i classList add correct else charEls i classList add wrong Let s create those classes in our css correct background color rgb wrong background color rgb Now if you type something you will see text is being highlighted accordingly Now we need to keep track of the error count How many letters are not typed correctly And we will also check if val length str length and error count is If so that means we have typed everything correctly input addEventListener keyup gt const val input value resetCharEls let errorCount val split map letter i gt if letter str i charEls i classList add correct else charEls i classList add wrong errorCount if val length str length amp amp errorCount alert Well Done Great Now lets make the progress bar animate We will make the progress bars width go from to in seconds time is up to you if it has a class of active Which we will add in JavaScript progress bar active animation s animate linear keyframes animate width background color rgb width background color rgb width background color rgb And finally when the user starts typing we will add active class to our progress bar and also start a timer that will alert Time s up when the time is over const str Type this as fast as possible const text document querySelector text const input document querySelector input const progressBar document querySelector progress bar Timer for our gamelet timer nullconst charEls function populateText str str split map letter gt const span document createElement span span innerText letter text appendChild span charEls push span populateText str function resetCharEls charEls map charEl gt charEl classList remove correct charEl classList remove wrong input addEventListener keyup gt if timer is null that means the game is not started yet if timer progressBar classList add active timer setTimeout gt alert Time s up ms s we have s animated duration in css also const val input value resetCharEls let errorCount val split map letter i gt if letter str i charEls i classList add correct else charEls i classList add wrong errorCount if val length str length amp amp errorCount alert Well Done clear the timer when the game is finished clearTimeout timer And just like that we have successfully created a typing practice game with nothing but JavaScript You can get finished codes here Make sure you checkout my other articles and YouTube Channel ltag user id follow action button background color important color ffffff important border color important ShuvoFollow Frontend Developer and YouTuber Channel link Was it helpful Support me on Patreon |
2021-11-22 11:43:15 |
海外TECH |
DEV Community |
How to create Modern Dashboards directly in Figma |
https://dev.to/fredy/how-to-create-modern-dashboards-directly-in-figma-40ld
|
How to create Modern Dashboards directly in Figma |
2021-11-22 11:43:11 |
海外TECH |
DEV Community |
How to Transfer a Website to a Different Host (Without Downtime or Issues) |
https://dev.to/derosaj/how-to-transfer-a-website-to-a-different-host-without-downtime-or-issues-3ph6
|
How to Transfer a Website to a Different Host Without Downtime or Issues Picking the best hosting provider for your website can be time consuming as there are so many options available Unfortunately sometimes when you make your choice the service doesn t meet your expectations making you feel stuck In this case the next suitable step might be to switch to another hosting company Yet this option also has its risks such as downtime issues and complicated processes This article will provide a step by step guide to help transfer your website to a different web host safely You ll learn all of the essential points from choosing the best web host to canceling your current hosting service Choose a New Web Hosting ProviderIt s important to pick a new web hosting provider before canceling your existing hosting plan Several aspects to consider when choosing a new provider are cost resources and performance If you don t want to transfer your website manually choose a hosting provider that offers free site migration That way you only need to make the request and provide website details like the current hostname and control panel login details Backup and Transfer Your FilesBackups ensure that you save the latest version of your site To transfer it to the new web host log in to the control panel make another backup and begin the transfer One way to move your site is to use a file transfer protocol FTP program like FileZilla It provides access to the files on the current web host s servers from your computer Download the files from your old web host then upload all the files to the new one Image sourceIf you use WordPress consider installing a migration tool plugin like All in One WP Migration This plugin will help migrate your WordPress site to a new hosting provider without any technical knowledge Move Your Database and Import to the New HostMost content management systems CMS depend on a database to store content and settings To move your database export it from your old web host using phpMyAdmin You should see phpMyAdmin in the Databases if your old hosting provider uses the cPanel If not install phpMyAdmin on your PC first Follow these steps to export your database once you open the phpMyAdmin On the left section select the database you want to move Click the Export tab Image sourceIn the Export method click Quick and choose SQL for the format Image sourceClick Go After that create a new database by opening MySQL Databases in your new web host s control panel Then open phpMyAdmin and go to the Import tab to upload the database you downloaded from your old web host Image source Install and Configure Applications at the New HostThis step requires editing the wp config php by using the FTP program or file manager at the new host s control panel Before editing this file prepare information like database name username and password Then install or update your CMS platform like WordPress or Joomla and configure other applications you need Point Your Domain Name to the New Web HostThe first step is to look for the nameservers of your new web host on its control panel Then go to the dashboard of your domain name provider and replace the old nameservers with the new host s nameservers Doing so will ensure that visitors come to your website and not receive an error or a misdirect The process until your domain name points to the new web host will take up to hours A DNS checker like Whatsmydns net helps check the moving progress Image source Test Your WebsiteAt this step your site should work properly on your new hosting provider However errors can happen sometimes One typical error is broken links To solve this consider installing a plugin like Broken Link Checker It will scan all links on your website and show the status whether they re errors or not Here you have the option to edit or delete the links Also there is a risk that the database is corrupted To resolve this try to disable all plugins and enable them one by one If you can t access your WordPress dashboard it may be necessary to reupload your database Check Your Email AccountsThere are four possible scenarios when transferring your custom email to the new web host such as Email is hosted on a third party It can be Microsoft or Google Workspace It s the simplest scenario as you can keep using it Email is hosted on a domain registrar Login to the domain registrar and change the details like nameservers into the new hosting provider Email is hosted with the old host See whether it s possible to download the email accounts and upload them to the new hosting provider If not you have to recreate the accounts on the new web host s platform manually Finalize the MoveWhen the changes are complete it s essential to double check if they work correctly First check your website using a temporary URL Ask your new host s support team about the address or use a temporary URL generator Also it s better to inform your visitors about the switch beforehand in case something goes wrong and everything results in downtime Image source Close the Previous Web Hosting AccountAfter making sure everything works well it s time to close your old web hosting account You ll see an option to cancel the hosting subscription on the old web host s control panel Ensure that you cancel only the hosting plan to avoid losing your domain name if you host your domain name with them too ConclusionThe risks of switching hosting services may seem intimidating at first However it s possible to transfer your website to another web host without any hassle or downtime as long as you carefully take these steps Pick a new web host Back up your files and move them to the new web host Export and import your database Set up necessary applications on the new hosting provider s platform Point your domain to the new host Test the website Transfer your email accounts Cancel your old hosting plan This is how you can move your website to a new host Good luck |
2021-11-22 11:37:44 |
海外TECH |
DEV Community |
Writing an NFT Collectible Smart Contract |
https://dev.to/rounakbanik/writing-an-nft-collectible-smart-contract-2nh8
|
Writing an NFT Collectible Smart Contract IntroductionIn my previous tutorials we showed you how to use our generative art library to create a collection of avatars generate compliant NFT metadata and upload the metadata JSON and media files to IPFS However we haven t minted any of our avatars as NFTs yet Therefore in this tutorial we will write a smart contract that will allow anyone to mint an NFT from our collection by paying gas and a price that we ve set for each NFT piece PrerequisitesIntermediate knowledge of Javascript In case you need a refresher I d suggest this YouTube tutorial Intermediate knowledge of Solidity and OpenZeppelin Contracts I will be releasing tutorials on this very soon For the time being I strongly recommend CryptoZombies and Buildspace node and npm installed on your local computerA collection of media files and NFT metadata JSON uploaded to IPFS In case you don t have this we have created a toy collection for you to experiment with You can find the media files here and the JSON metadata files here While it may be possible for readers who do not satisfy the prerequisites to follow along and even deploy a smart contract we strongly recommend getting a developer who knows what s he is doing if you re serious about your project Smart contract development and deployment can be incredibly expensive and unforgiving w r t security flaws and bugs Setting up our local development environmentWe will be using Hardhat an industry standard ethereum development environment to develop deploy and verify our smart contracts Create an empty folder for our project and initialize an empty package json file by running the following command in your Terminal mkdir nft collectible amp amp cd nft collectible amp amp npm init yYou should now be inside the nft collectible folder and have a file named package json Next let s install Hardhat Run the following command npm install save dev hardhatWe can now create a sample Hardhat project by running the following command and choosing Create a basic sample project npx hardhatAgree to all the defaults project root adding a gitignore and installing all sample project dependencies Let s check that our sample project has been installed properly Run the following command npx hardhat run scripts sample script jsIf all goes well you should see output that looks something like this We now have our hardhat development environment successfully configured Let us now install the OpenZeppelin contracts package This will give us access to the ERC contracts the standard for NFTs as well as a few helper libraries that we will encounter later npm install openzeppelin contractsIf we want to share our project s code publicly on a website like GitHub we wouldn t want to share sensitive information like our private key our Etherscan API key or our Alchemy URL don t worry if some of these words don t make sense to you yet Therefore let us install another library called dotenv npm install dotenvCongratulations We are now in a good place to start developing our smart contract Writing the Smart ContractIn this section we are going to write a smart contract in Solidity that allows anyone to mint a certain number of NFTs by paying the required amount of ether gas In the contracts folder of your project create a new file called NFTCollectible sol We will be using Solidity v Our contract will inherit from OpenZeppelin s ERCEnumerable and Ownable contracts The former has a default implementation of the ERC NFT standard in addition to a few helper functions that are useful when dealing with NFT collections The latter allows us to add administrative privileges to certain aspects of our contract In addition to the above we will also use OpenZeppelin s SafeMath and Counters libraries to safely deal with unsigned integer arithmetic by preventing overflows and token IDs respectively This is what the skeleton of our contract looks like SPDX License Identifier MITpragma solidity import openzeppelin contracts utils Counters sol import openzeppelin contracts access Ownable sol import openzeppelin contracts utils math SafeMath sol import openzeppelin contracts token ERC extensions ERCEnumerable sol contract NFTCollectible is ERCEnumerable Ownable using SafeMath for uint using Counters for Counters Counter Counters Counter private tokenIds Storage constants and variablesOur contract needs to keep track of certain variables and constants For this tutorial we will be defining the following Supply The maximum number of NFTs that can be minted in your collection Price The amount of ether required to buy NFT Maximum number of mints per transaction The upper limit of NFTs that you can mint at once Base Token URI The IPFS URL of the folder containing the JSON metadata In this tutorial we will set as constants In other words we won t be able to modify them once the contract has been deployed We will write a setter function for baseTokenURI that will allow the contract s owner or deployer to change the base URI as and when required Right under the tokenIds declaration add the following uint public constant MAX SUPPLY uint public constant PRICE ether uint public constant MAX PER MINT string public baseTokenURI Notice that I ve used all caps for the constants Feel free to change the values for the constants based on your project ConstructorWe will set the baseTokenURI in our constructor call We will also call the parent constructor and set the name and symbol for our NFT collection Our constructor therefore looks like this constructor string memory baseURI ERC NFT Collectible NFTC setBaseURI baseURI Reserve NFTs functionAs the creator of the project you probably want to reserve a few NFTs of the collection for yourself your team and for events like giveaways Let s write a function that allows us to mint a certain number of NFTs in this case ten for free Since anyone calling this function only has to pay gas we will obviously mark it as onlyOwner so that only the owner of the contract will be able to call it function reserveNFTs public onlyOwner uint totalMinted tokenIds current require totalMinted add lt MAX SUPPLY Not enough NFTs for uint i i lt i mintSingleNFT We check the total number of NFTs minted so far by calling tokenIds current We then check if there are enough NFTs left in the collection for us to reserve If yes we proceed to mint NFTs by calling mintSingleNFT ten times It is in the mintSingleNFT function that the real magic happens We will look into this a little later Setting Base Token URIOur NFT JSON metadata is available at this IPFS URL ipfs QmZbWNKJPAjxXuNFSEaksCJVdMDaKQViJBYPKBdpDEP When we set this as the base URI OpenZeppelin s implementation automatically deduces the URI for each token It assumes that token s metadata will be available at ipfs QmZbWNKJPAjxXuNFSEaksCJVdMDaKQViJBYPKBdpDEP token s metadata will be available at ipfs QmZbWNKJPAjxXuNFSEaksCJVdMDaKQViJBYPKBdpDEP and so on Please note that there is no json extension to these files However we need to tell our contract that the baseTokenURI variable that we defined is the base URI that the contract must use To do this we override an empty function called baseURI and make it return baseTokenURI We also write an only owner function that allows us to change the baseTokenURI even after the contract has been deployed function baseURI internal view virtual override returns string memory return baseTokenURI function setBaseURI string memory baseTokenURI public onlyOwner baseTokenURI baseTokenURI Mint NFTs functionLet us now turn our attention to the main mint NFTs function Our users and customers will call this function when they want to purchase and mint NFTs from our collection Since they re sending ether to this function we have to mark it as payable We need to make three checks before we allow the mint to take place There are enough NFTs left in the collection for the caller to mint the requested amount The caller has requested to mint more than and less than the maximum number of NFTs allowed per transaction The caller has sent enough ether to mint the requested number of NFTs function mintNFTs uint count public payable uint totalMinted tokenIds current require totalMinted add count lt MAX SUPPLY Not enough NFTs require count gt amp amp count lt MAX PER MINT Cannot mint specified number of NFTs require msg value gt PRICE mul count Not enough ether to purchase NFTs for uint i i lt count i mintSingleNFT Mint Single NFT functionLet s finally take a look at the private mintSingleNFT function that s being called whenever we or a third party want to mint an NFT function mintSingleNFT private uint newTokenID tokenIds current safeMint msg sender newTokenID tokenIds increment This is what is happening We get the current ID that hasn t been minted yet We use the safeMint function already defined by OpenZeppelin to assign the NFT ID to the account that called the function We increment the token IDs counter by The token ID is before any mint has taken place When this function is called for the first time newTokenID is Calling safeMint assigns NFT with ID to the person who called the contract function The counter is then incremented to The next time this function is called newTokenID has value Calling safeMint assigns NFT with ID to the person who…I think you get the gist Note that we don t need to explicitly set the metadata for each NFT Setting the base URI ensures that each NFT gets the correct metadata stored in IPFS assigned automatically Getting all tokens owned by a particular accountIf you plan on giving any sort of utility to your NFT holders you would want to know which NFTs from your collection each user holds Let s write a simple function that returns all IDs owned by a particular holder This is made super simple by ERCEnumerable s balanceOf and tokenOfOwnerByIndex functions The former tells us how many tokens a particular owner holds and the latter can be used to get all the IDs that an owner owns function tokensOfOwner address owner external view returns uint memory uint tokenCount balanceOf owner uint memory tokensId new uint tokenCount for uint i i lt tokenCount i tokensId i tokenOfOwnerByIndex owner i return tokensId Withdraw balance functionAll the effort we ve put in so far would go to waste if we are not able to withdraw the ether that has been sent to the contract Let us write a function that allows us to withdraw the contract s entire balance This will obviously be marked as onlyOwner function withdraw public payable onlyOwner uint balance address this balance require balance gt No ether left to withdraw bool success msg sender call value balance require success Transfer failed Final ContractWe re done with the smart contract This is what it looks like By the way if you haven t already delete the Greeter sol file SPDX License Identifier MITpragma solidity import openzeppelin contracts utils Counters sol import openzeppelin contracts access Ownable sol import openzeppelin contracts utils math SafeMath sol import openzeppelin contracts token ERC extensions ERCEnumerable sol contract NFTCollectible is ERCEnumerable Ownable using SafeMath for uint using Counters for Counters Counter Counters Counter private tokenIds uint public constant MAX SUPPLY uint public constant PRICE ether uint public constant MAX PER MINT string public baseTokenURI constructor string memory baseURI ERC NFT Collectible NFTC setBaseURI baseURI function reserveNFTs public onlyOwner uint totalMinted tokenIds current require totalMinted add lt MAX SUPPLY Not enough NFTs left to reserve for uint i i lt i mintSingleNFT function baseURI internal view virtual override returns string memory return baseTokenURI function setBaseURI string memory baseTokenURI public onlyOwner baseTokenURI baseTokenURI function mintNFTs uint count public payable uint totalMinted tokenIds current require totalMinted add count lt MAX SUPPLY Not enough NFTs left require count gt amp amp count lt MAX PER MINT Cannot mint specified number of NFTs require msg value gt PRICE mul count Not enough ether to purchase NFTs for uint i i lt count i mintSingleNFT function mintSingleNFT private uint newTokenID tokenIds current safeMint msg sender newTokenID tokenIds increment function tokensOfOwner address owner external view returns uint memory uint tokenCount balanceOf owner uint memory tokensId new uint tokenCount for uint i i lt tokenCount i tokensId i tokenOfOwnerByIndex owner i return tokensId function withdraw public payable onlyOwner uint balance address this balance require balance gt No ether left to withdraw bool success msg sender call value balance require success Transfer failed Deploying the contract locallyLet us now make preparations to deploy our contract to the Rinkeby test network by simulating it in a local environment In the scripts folder create a new file called run js and add the following code const utils require ethers async function main const baseTokenURI ipfs QmZbWNKJPAjxXuNFSEaksCJVdMDaKQViJBYPKBdpDEP Get owner deployer s wallet address const owner await hre ethers getSigners Get contract that we want to deploy const contractFactory await hre ethers getContractFactory NFTCollectible Deploy contract with the correct constructor arguments const contract await contractFactory deploy baseTokenURI Wait for this transaction to be mined await contract deployed Get contract address console log Contract deployed to contract address Reserve NFTs let txn await contract reserveNFTs await txn wait console log NFTs have been reserved Mint NFTs by sending ether txn await contract mintNFTs value utils parseEther await txn wait Get all token IDs of the owner let tokens await contract tokensOfOwner owner address console log Owner has tokens tokens main then gt process exit catch error gt console error error process exit This is some Javascript code that utilizes the ethers js library to deploy our contract and then call functions of the contract once it has been deployed Here is the series of what s going on We get the address of the deployer owner us We get the contract that we want to deploy We send a request for the contract to be deployed and wait for a miner to pick this request and add it to the blockchain Once mined we get the contract address We then call public functions of our contract We reserve NFTs mint NFTs by sending ETH to the contract and check the NFTs owned by us Note that the first two calls require gas because they re writing to the blockchain whereas the third simply reads from the blockchain Let s give this a run locally npx hardhat run scripts run jsIf all goes well you should see something like this Deploying the contract to RinkebyTo deploy our contract to Rinkeby we will need to set up a few things First we will need an RPC URL that will allow us to broadcast our contract creation transaction We will use Alchemy for this Create an Alchemy account here and then proceed to create a free app Make sure that the network is set to Rinkeby Once you ve created an app go to your Alchemy dashboard and select your app This will open a new window with a View Key button on the top right Click on that and select the HTTP URL Acquire some fake Rinkeby ETH from the faucet here For our use case ETH should be more than enough Once you ve acquired this ETH open your Metamask extension and get the private key for the wallet containing the fake ETH you can do this by going into Account Details in the dots menu near the top right Do not share your URL and private key publicly We will use the dotenv library to store the aforementioned variables as environment variables and will not commit them to our repository Create a new file called env and store your URL and private key in the following format API URL lt YOUR ALCHEMY URL HERE gt PRIVATE KEY lt YOUR PRIVATE KEY HERE gt Now replace your hardhat config js file with the following contents require nomiclabs hardhat waffle require dotenv config const API URL PRIVATE KEY process env This is a sample Hardhat task To learn how to create your own go to task accounts Prints the list of accounts async taskArgs hre gt const accounts await hre ethers getSigners for const account of accounts console log account address You need to export an object to set up your config Go to to learn more type import hardhat config HardhatUserConfig module exports solidity defaultNetwork rinkeby networks rinkeby url API URL accounts PRIVATE KEY We re almost there Run the following command npx hardhat run scripts run js network rinkebyThis should give you output very similar to what you got earlier except that this has been deployed to the real blockchain Make a note of the contract address Ours was xaeCcbffcdF You can check this contract out on Etherscan Go to Etherscan and type in the contract address You should see something like this Viewing our NFTs on OpenSeaBelieve it or not our NFT collection is now already available on OpenSea without us having to upload it explicitly Go to testnets opensea io and search for your contract address This is what our collection looks like Verifying our contract on EtherscanWe have come a LONG way in this article but there is one final thing we d like to do before we go Let s verify our contract on etherscan This will allow your users to see your contract s code and ensure that there is no funny business going on More importantly verifying your code will allow your users to connect their Metamask wallet to etherscan and mint your NFTs from etherscan itself Before we can do this we will need an Etherscan API key Sign up for a free account here and access your API keys here Let s add this API key to our env file ETHERSCAN API lt YOUR ETHERSCAN API KEY gt Hardhat makes it really simple to verify our contract on Etherscan Let s install the following package npm install nomiclabs hardhat etherscanNext make adjustments to hardhat config js so it looks like this require nomiclabs hardhat waffle require nomiclabs hardhat etherscan require dotenv config const API URL PRIVATE KEY ETHERSCAN API process env This is a sample Hardhat task To learn how to create your own go to task accounts Prints the list of accounts async taskArgs hre gt const accounts await hre ethers getSigners for const account of accounts console log account address You need to export an object to set up your config Go to to learn more type import hardhat config HardhatUserConfig module exports solidity defaultNetwork rinkeby networks rinkeby url API URL accounts PRIVATE KEY etherscan apiKey ETHERSCAN API Now run the following two commands npx hardhat cleannpx hardhat verify network rinkeby DEPLOYED CONTRACT ADDRESS BASE TOKEN URI In our case the second command looked like this npx hardhat verify network rinkeby xaeCcbffcdF ipfs QmZbWNKJPAjxXuNFSEaksCJVdMDaKQViJBYPKBdpDEP Now if you visit your contract s Rinkeby Etherscan page you should see a small green tick next to the Contract tab More importantly your users will now be able to connect to web using Metamask and call your contract s functions from Etherscan itself Try this out yourself Connect the account that you used to deploy the contract and call the withdraw function from etherscan You should be able to transfer the ETH in the contract to your wallet Also ask one of your friends to connect their wallet and mint a few NFTs by calling the mintNFTs function ConclusionWe now have a deployed smart contract that lets users mint NFTs from our collection An obvious next step would be to build a web app that allows our users to mint NFTs directly from our website This will be the subject of a future tutorial If you ve reached this far congratulations You are on your way to becoming a master Solidity and blockchain developer We ve covered some complex concepts in this article and coming this far is truly incredible We re proud We would love to take a look at your collection Come say hi to us on our Discord Also if you liked our content we would be super grateful if you tweet about us follow us ScrappyNFTs and Rounak Banik and invite your circle to our Discord Thank you for your support Final code repository Scrappy SquirrelsScrappy Squirrels is a collection of randomly generated NFTs on the Ethereum Blockchain Scrappy Squirrels are meant for buyers creators and developers who are completely new to the NFT ecosystem The community is built around learning about the NFT revolution exploring its current use cases discovering new applications and finding members to collaborate on exciting projects with Join our community here |
2021-11-22 11:04:18 |
Apple |
AppleInsider - Frontpage News |
Apple again expands Israel research and development headquarters |
https://appleinsider.com/articles/21/11/22/apple-again-expands-israel-research-and-development-headquarters?utm_medium=rss
|
Apple again expands Israel research and development headquartersAlongside its existing R amp D center in Herzliya Pituach Israel Apple has signed a seven year lease in planned extension to a building Apple s existing building in Herzliya PituachApple originally opened a new research and development office in Herzliya Pituach north of Tel Aviv in February By April that year it was already planning to expand the site Read more |
2021-11-22 11:55:49 |
海外TECH |
Engadget |
UK will require new homes to have EV chargers starting in 2022 |
https://www.engadget.com/uk-announces-that-new-homes-must-have-ev-chargers-113524579.html?src=rss
|
UK will require new homes to have EV chargers starting in Electric vehicle EV charging stations will be required for all new homes and businesses in the UK starting in the government announced today The new measure aims to boost EV adoption in the nation by adding up to extra charging points each year nbsp nbsp quot This will mean people can buy new properties already ready for an electric vehicle future while ensuring charge points are readily available at new shops and workplaces across the UK ーmaking it as easy as refueling a petrol or diesel car today quot the press release states The UK government has already backed the installation of over charging points so the new rules would increase that by over percent in the first year alone Buildings like supermarkets and workplaces are included in the law along with large scale renovations that will have over parking spaces However details of the rules like specifications and power outputs of the installations have yet to be released nbsp Britain s opposition Labour party noted that London and the southeast part of the country have more charging points quot than the rest of England and Wales combined quot and the new law doesn t help in that regard It also said that it doesn t include any provisions that would make EVs more affordable for lower and middle income families the BBC reported The UK government aims to completely ban the sale of fossil fuel cars by ー years earlier than planned The government previously said that it s prepared to spend £ million about million on building EV charging infrastructure in the country |
2021-11-22 11:35:24 |
金融 |
RSS FILE - 日本証券業協会 |
会員の主要勘定及び顧客口座数等 |
https://www.jsda.or.jp/shiryoshitsu/toukei/kanjyo/index.html
|
顧客 |
2021-11-22 12:41:00 |
海外ニュース |
Japan Times latest articles |
Tokyo ‘Joker’ train attacker served new attempted murder warrant |
https://www.japantimes.co.jp/news/2021/11/22/national/crime-legal/joker-train-attack-murder/
|
Tokyo Joker train attacker served new attempted murder warrantKyota Hattori is suspected of trying to kill passengers including a year old woman by sprinkling approximately liters of oil in the train |
2021-11-22 20:04:53 |
ニュース |
BBC News - Home |
Social care: Boris Johnson defends his plan amid criticism over the cost cap |
https://www.bbc.co.uk/news/uk-politics-59365729?at_medium=RSS&at_campaign=KARANGA
|
people |
2021-11-22 11:41:24 |
ニュース |
BBC News - Home |
Covid death doctor Irfan Halim touched lives, brother says |
https://www.bbc.co.uk/news/uk-england-wiltshire-59371578?at_medium=RSS&at_campaign=KARANGA
|
halim |
2021-11-22 11:11:49 |
ニュース |
BBC News - Home |
Covid vaccines: How fast is progress around the world? |
https://www.bbc.co.uk/news/world-56237778?at_medium=RSS&at_campaign=KARANGA
|
programmes |
2021-11-22 11:32:20 |
LifeHuck |
ライフハッカー[日本版] |
雨にも負けない防水仕様! タフネス軽量スニーカー「The Mobrly」 |
https://www.lifehacker.jp/2021/11/machi-ya-the-mobrly-end.html
|
themobrly |
2021-11-22 21:00:00 |
サブカルネタ |
ラーブロ |
旭川ラーメン 味の鈴乃屋 塩篇/チャーハン篇 |
http://ra-blog.net/modules/rssc/single_feed.php?fid=193953
|
塩ラーメン |
2021-11-22 11:20:47 |
北海道 |
北海道新聞 |
習主席、南シナ海の安定を強調 フィリピンが中国の行動非難 |
https://www.hokkaido-np.co.jp/article/614575/
|
南シナ海 |
2021-11-22 20:17:00 |
北海道 |
北海道新聞 |
起訴状が届かず異例の公訴棄却 福岡県警が交付忘れ |
https://www.hokkaido-np.co.jp/article/614574/
|
公訴棄却 |
2021-11-22 20:17:00 |
北海道 |
北海道新聞 |
感染対策徹底、入場料徴収へ 支笏湖氷濤まつり、来年1月29日開幕 |
https://www.hokkaido-np.co.jp/article/614572/
|
感染対策 |
2021-11-22 20:13:00 |
北海道 |
北海道新聞 |
長期欠席議員は報酬ゼロに 維新大阪府議団が条例案 |
https://www.hokkaido-np.co.jp/article/614569/
|
長期欠席 |
2021-11-22 20:07:00 |
北海道 |
北海道新聞 |
全国感染者50人、今年最少 新型コロナ2人死亡 |
https://www.hokkaido-np.co.jp/article/614570/
|
新型コロナウイルス |
2021-11-22 20:08:00 |
北海道 |
北海道新聞 |
5Gの設備投資減税は延長へ 地方のデジタル化を後押し |
https://www.hokkaido-np.co.jp/article/614568/
|
設備投資 |
2021-11-22 20:06:00 |
北海道 |
北海道新聞 |
輝くイルミネーションと寒さ楽しんで 札幌 クリスマスに屋根なしバスツアー |
https://www.hokkaido-np.co.jp/article/614559/
|
札幌市内 |
2021-11-22 20:02:01 |
IT |
週刊アスキー |
Switch&PC『刀剣乱舞無双』に新プレイアブルキャラクター「面影(おもかげ)」の参戦が決定! |
https://weekly.ascii.jp/elem/000/004/075/4075848/
|
dmmgames |
2021-11-22 20:10:00 |
IT |
週刊アスキー |
“最終回”の向こうへ!『SAOアリブレ』新オープニングアニメ公開&2周年キャンペーンが開催中 |
https://weekly.ascii.jp/elem/000/004/075/4075849/
|
android |
2021-11-22 20:10:00 |
コメント
コメントを投稿