IT |
ITmedia 総合記事一覧 |
[ITmedia Mobile] CIO、楽天スーパーSALEで急速充電器やモバイルバッテリーなどを最大75%オフ |
https://www.itmedia.co.jp/mobile/articles/2112/06/news150.html
|
itmediamobilecio |
2021-12-06 19:37:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia News] 訓練なしにWebサイトを最大2倍速く読めるように Chrome用拡張機能を無償公開 日本ユニシス |
https://www.itmedia.co.jp/news/articles/2112/06/news157.html
|
chrome |
2021-12-06 19:24:00 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
plotlyでゲージを二つ |
https://qiita.com/jamjam/items/2520b66762642212785f
|
環境ラズパイPythonplotlyGaugeはsubplotsでは複数の表示ができないみたいな気がするiframeをつかって二つのGaugeデータを、一つのWebページに表示します。 |
2021-12-06 19:51:23 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
【vue.js】Todoリストを作成する。 |
https://qiita.com/Quest_love33/items/30d7473ed9a760e0a8f9
|
returnthistodosfiltertodogtfilterのコールバック関数を定義returntodoitemindexOfselfquery指定された値が最初に現れたインデックスを返します。 |
2021-12-06 19:57:07 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
pythonでエクセルを保存したい |
https://teratail.com/questions/372538?rss=all
|
|
2021-12-06 19:59:26 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
Wix上で、入力形式のクイズを作るには |
https://teratail.com/questions/372537?rss=all
|
Wix上で、入力形式のクイズを作るには前提・実現したいことクイズを行う入力フォームを作りたいwixでクイズを実装したいと思っています。 |
2021-12-06 19:57:38 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
【Unity】Prefabで生成したオブジェクト内のTextMeshProの内容を取得したい |
https://teratail.com/questions/372536?rss=all
|
|
2021-12-06 19:22:41 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
【CSS】display: flex;でPCとSPで要素の内容を変える方法 |
https://teratail.com/questions/372535?rss=all
|
【CSS】displayflexでPCとSPで要素の内容を変える方法Flexboxで下記のようなレスポンシブレイアウトにする場合、どのようにするのが良いのでしょうかSPでのみボタンを幅にしたいのですが、うまくいきません。 |
2021-12-06 19:13:45 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
HTML、JavaScriptを用いて用語投入し、その用語のDBpediaページのリンクを表示したい。 |
https://teratail.com/questions/372534?rss=all
|
HTML、JavaScriptを用いて用語投入し、その用語のDBpediaページのリンクを表示したい。 |
2021-12-06 19:13:27 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
バブルソートで並び替えをした後に指定以外を0にする方法 |
https://teratail.com/questions/372533?rss=all
|
最初 |
2021-12-06 19:13:10 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
OpenCVを使ってカラー画像をガンマ補正した画像を作成したいです。 |
https://teratail.com/questions/372532?rss=all
|
OpenCVを使ってカラー画像をガンマ補正した画像を作成したいです。 |
2021-12-06 19:12:21 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
VBAの動作不良について教えてください。 |
https://teratail.com/questions/372531?rss=all
|
VBAの動作不良について教えてください。 |
2021-12-06 19:08:35 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
バブルソートで並び替えをした後に指定以外を0にする方法 |
https://teratail.com/questions/372530?rss=all
|
最初 |
2021-12-06 19:07:53 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
Unity カウントダウン 時報のように音を出したい |
https://teratail.com/questions/372529?rss=all
|
Unityカウントダウン時報のように音を出したい前提・実現したいことUnityのゲーム内で使用するカウントダウン機能を作っています。 |
2021-12-06 19:04:31 |
Azure |
Azureタグが付けられた新着投稿 - Qiita |
[Azure AD] SC-300 合格のための必須キーワード「エンタイトルメント管理とは」1/2 |
https://qiita.com/junichia/items/7ffa9d00907cb9778041
|
この記事で話題にしているのは「AzureADで管理されているアプリケーションに対するアクセスコントロール」であり、IAMとは別の機能であることに注意してください。 |
2021-12-06 19:11:40 |
海外TECH |
DEV Community |
Postman/Newman - Test my Application |
https://dev.to/jagankarunakaran/postmannewman-test-my-application-4il9
|
Postman Newman Test my ApplicationFunctional and Regression testing of the application by a developer will always enhance the quality of the code and also ensuring that the existing features are not broken As a developer working on the RESTFUL services the application extensively used to test REST API endpoints is Postman Postman is a standalone software testing API Application Programming Interface platform to build test design modify and document APIs Well documented Postman collection will always help any developer to use the application APIs in various environments on the go Other than documenting the APIs in postman it can also be used extensively like designing the test cases and validating the feature or flow of the application on a single run Postman Collections On the Postman application click the new option and select the Collection option Once the collection is created we will be able to add various scripts environment variables to be used to the collection Pre Request Scripts This option allows you to run the script before making the request For instance you can set the environment variables before making the request Variables This option allows the addition of the environmental values to be used in the collection New folder can be created inside the parent collection for each flow which includes all the requests needed to complete the particular flow For instance Create student flow can have requests like create student endpoint and get student endpoint Both the requests inside the collection will have the required test cases written inside the test tab This test should have all the test cases designed by the developer which is expected for an endpoint to be returned which ensures the endpoints are working as expected Newman tool Newman is a command line collection runner for Postman It allows you to effortlessly run and test a Postman collection directly from the command line Once the postman collection is created with all the flows needed for the application a developer can leverage Newman s tool to run the postman collection and validate the test cases Newman provides out of box reporting formats which include cli json HTML JUnit Newman can also be integrated into the CI CD pipelines to automate the validation of the application Installing Newman nodeJs has to be installed in your system based on your distribution Run the following command to install the npm package of newman globally npm install g newman Reference Application Source code for the sample spring application with CRUD operations and postman collection with the test cases can be found in the following link Postman Runner and Testing Github Run and Test the application Clone the above git repo and run the java application on your preferred IDE Import the collection to the postman and run the collection using a runner To run in CLI use the following command inside the postman directory through the terminal newman run file jsonTo run the test and display store the result use the following command newman run file json r cli References Newman NPMPostman Runner CollectionPostman Newman integration |
2021-12-06 10:55:34 |
海外TECH |
DEV Community |
How to create custom reusable ESLint, TypeScript, Prettier config for React apps |
https://dev.to/ramonak/how-to-create-custom-reusable-eslint-typescript-prettier-config-for-react-apps-5605
|
How to create custom reusable ESLint TypeScript Prettier config for React appsOriginally published on my personal blog IntroThere are many tools that help developers eliminate possible errors and bugs and in the end ship more robust and maintainable code Among them the most commonly used static code analysis tool is ESLint Another trendy tool is Prettier It makes your code look beautiful to developers eyes yours included And let s not forget about TypeScript It s a static type checker for JavaScript and it improves developer experience by a ton Plus we will publish our ESLint and Prettier config as an NPM package thus making it reusable and easily installable in any React project well generally in any Javascript project but it will contain react js React Native specific rules Usually when I start a new React project I add all the above mentioned tools manually one by one Finally I found a time to create my custom config package based on the most typical setup on projects that I m working worked on This blog post is a walkthrough of how I did it Also the blog post will cover how to install Husky and lint staged Basically it will ensure that we don t cheat and follow all the necessary rules So let s start Create a Node js modulenpm init yNow we have a project with a basic package json file Make sure that the module name begins with eslint config I named mine as eslint config ramonak package json name eslint config ramonak Add ESLintThe easiest way to add ESLint necessary dependencies and basic configuration is by running npx eslint initYou will be prompted to answer different questions Based on my typical type of projects I answered them like that It will install typescript eslint eslint plugin typescript eslint parser eslint eslint plugin react packages as dev dependencies in the project in your specific use case packages might be different depending on your answers And also it will add eslintrc file with the basic config Add PrettierRun npm i D prettier eslint config prettier eslint plugin prettierThis will install prettiereslint config prettier to turn off all rules that are unnecessary or might conflict with Prettiereslint plugin prettier runs Prettier as an ESLint rule and reports differences as individual ESLint issuesAdd plugin prettier recommended as the last extension in your eslintrc file extends other plugins plugin prettier recommended For the info it is short for extends prettier plugins prettier rules prettier prettier error arrow body style off prefer arrow callback off Now we can add our custom prettier options As this blog post s final goal is to create an NPM package I ll add a prettier config directly into the eslint config without making a separate prettierrc file But this might conflict with text editor extensions like prettier vscode for example as they read directly from prettierrc file Possible solutions might be Create prettierrc file in your project and copy the configuration from eslintrc file there Uninstall if already installed a prettier extension and config your text editor to use ESLint extension only for code formatting More on that here eslintrc rules prettier prettier error trailingComma es singleQuote true printWidth semi true You can customize your formatting preferences whatever you like The list of all possible options is here Add additional ESLint plugins optional There are numerous ESLint plugins available for you to add to your project I m going to add eslint plugin react hooks Also I like all imports to be nicely sorted Fot that let s add eslint plugin simple import sort npm i D eslint plugin react hooks eslint plugin simple import sortThen update eslintrc file extends plugin react hooks recommended plugins simple import sort other plugins omitted rules simple import sort imports error simple import sort exports error other rules omitted Feel free to add any custom rules based on your specific requirements Create index js fileWe need to add an entry point to our package So create index js file with the following content const eslintrc require eslintrc json module exports eslintrc Declare peer dependenciesAs it is stated in the official ESLint docs you should declare your dependency on ESLint in package json using the peerDependencies field So just copy all dev dependencies in the package json file to peerDependencies field package json peerDependencies typescript eslint eslint plugin typescript eslint parser eslint eslint config prettier eslint plugin prettier eslint plugin react eslint plugin react hooks eslint plugin simple import sort prettier TestProbably it s not a bad idea to test the ESLint config locally before sharing it with the world Link your eslint config module globally by running the following command at the root level of your eslint config folder npm linkThen in the project where you d like to test your eslint config run npm link lt name of your eslint config gt For example in my case I run npm link eslint config ramonakPlease note that you won t see any changes in the packages json file after running that command But your eslint config will be added into node modules folder Additionally you need to manually install all peer dependencies that are not present in your project from your eslint config package Something like this npm i D typescript eslint eslint plugin typescript eslint parser eslint config prettier eslint plugin prettier eslint plugin react eslint plugin react hooks eslint plugin simple import sort prettierThen you need to tell your project to use your custom eslint config For that in package json add or edit if already exists eslintConfig field eslintConfig extends ramonak your eslint config module name OR create eslintrc file with the following content extends ramonak your eslint config module name Now you can run linter npx eslint If you d like fixable errors to be fixed automatically run npx eslint fix PublishYou need an NPM account to be able to publish your eslint config package If you don t have it you can sign up here Once you are ready to publish just run npm publish Integration with VSCodeUninstall or disable any previously installed prettier extensions Install if haven t already ESLint extensionEdit VSCode settings by pressing CMD SHIFT P on Mac or Ctrl SHIFT P on Windows type settings and choose Preferences Open Settings JSON Edit or add the following settings Format a file on save editor formatOnSave true show eslint icon at bottom toolbar eslint alwaysShowStatus true turns on Auto Fix for all providers including ESLint editor codeActionsOnSave source fixAll true Remove editor defaultFormatter esbenp prettier vscode line if you had it before Now all fixable ESLint including Prettier formatting options errors will be fixed automatically on a file save BONUS Add Husky and lint stagedTo enforce linting rules compliance let s add Husky and lint staged These tools will automate the running of the linting scripts before each commit If there are any lint errors the code won t be committed And lint staged will help save our precious time as it will make run the lint script only for staged e g files that we updated and not on the whole project Install lint staged and husky by running just one command npx mrm lint stagedUpdate config in package json scripts other scripts omitted lint fix eslint fix add linting script lint staged js jsx ts tsx npm run lint fix run linting script only on JS and TypeScript files Now whenever you try to commit any JavaScript or TypeScipt files the linting script will run and if there are any unresolved errors these files won t be committed ConclusionIf you want to add ESLint TypeScript and Prettier config into your project without any additional tooling just follow steps and If your is goal is to add ESLint TypeScript and Prettier with Husky and lint staged use steps and And you are very welcome to use my custom eslint config and report any issues or make pull requests P S Development of my custom eslint config inspired by eslint config wesbos |
2021-12-06 10:53:32 |
海外TECH |
DEV Community |
How to run shell scripts in Java |
https://dev.to/coder4_life/how-to-run-shell-scripts-in-java-4cbd
|
How to run shell scripts in JavaRunning shell scripts from inside Java code using ProcessBuilder in a thread This solution works on Windows bat file and Unix sh file running example in both environments in video |
2021-12-06 10:49:43 |
海外TECH |
DEV Community |
How to become an App Developer in 2022 |
https://dev.to/javinpaul/how-to-become-an-app-developer-in-2022-56o1
|
How to become an App Developer in Disclosure This post includes affiliate links I may receive compensation if you purchase products or services from the different links provided in this article Hello Devs if you want to become an app developer in and want to learn Mobile application development and you wondering how to start then you have come to the right place Earlier I have shared essential skills for frontend developers and server side Java developers and here I will show you different technologies and combination of them you can learn to become an App developer Yes you heard it right its not just Android and iOS but you can also learn new tools and frameworks like React Native and Flutter to develop native looking Mobile apps in Mobile app development is a lucrative field for programmers as it has all kinds of opportunities from freelancing to working at large companies and launching your own apps like Angry Bird Flappy Bird or Pokemon Go and becoming an App millionaire In this article I am going to share technologies you can learn to become a mobile application developer or someone who wants to improve as a mobile application developer for Android and iOS platforms can learn in This list includes things like framework programming languages and platforms almost everything a mobile developer needs In particular I have included cross platform mobile development frameworks like Flutter and React Native programming languages like Kotlin Swift and Dart and platforms like Android and iOS which are essential for any mobile app developer in Though one of the most important things to note here is that you don t need to learn all the things I have mentioned here in fact all of them are presented here for informational purposes so that you can choose which technologies and platforms are suitable for you For example if you are interested in developing native iOS applications for iPhone and iPad they make most of the money on mobile apps then learning Swift and iOS is a good idea but if you are interested in the Android platform they have the highest reach then learning Kotlin and Android is a good option And if you are interested like me in developing cross platform native mobile apps both Android and iOS app from a single codebase then you should learn Flutter or React Native two of the leading frameworks for building a native mobile application Whatever you choose I have also provided links to some excellent resources which can help you to learn these technologies Btw this is in continuation of my articles about essential things for developers earlier I have shared about Things Web Developers Can Learn in and essential things for Java developers if you haven t read them already you can read them now Essential Skills App Developers can Learn in Without wasting any more of your time here is my list of some of the best frameworks programming languages and libraries you can learn to get into mobile application development React NativeIf there a best library or framework you can check out for developing native cross platform mobile apps then they React Native It uses React and JavaScript for producing high quality native mobile apps It s the right choice for all web developers who wants to become a mobile app developer and already familiar with technologies like JavaScript and React If you are one of them then I suggest you learn React Native in Also there are a lot of resources to learn React Native both free and paid but if you ask my recommendation I highly recommend you to check out Stephen Grider s The Complete React Native Hooks course one of my favorite resources to learn React Native online Stephen is one of the best instructors on Udemy and his teaching style is really great FlutterThis is another excellent framework for developing cross platform native mobile applications in Like Golang TensorFlow and Angular Flutter is also from Google which uses Dart another programming language from Google and provides SDK for developing a cross platform native mobile application It s always been challenging to release your app to different platforms like Android iOS and Windows Mobile as you need to maintain a separate codebase Flutter solves that problem by allowing you to create mobile apps for both iOS and Android devices using the same codebase Flutter has seen a lot of growth in the last years and it s now the framework for developing native mobile apps If you have already decided to learn Flutter and looking for a resource then I suggest you check out this Learn Flutter and Dart MasterClass by Maximilian of Acadmind on Udemy one of my favorite courses to learn Flutter in KotlinKotlin is a general purpose programming language from JetBrains the company behind tools like IntelliJIDEA Reshaper and PyCharm If you don t know Kotlin is the official programming language for developing Android applications as announced by Google a couple of years ago It s a beautiful JVM based programming language and compatible with Java another popular language for developing Android applications If you are serious about developing mobile apps for the Android platform the world s most popular mobile platform then you should learn Kotlin If you need a resource check out this Kotlin Fundamentals course from Pluralsight Swift Swift is another programming language from Apple which you can use to develop mobile applications for iOS iPhone and iPad macOS MacBook Prob watchOS Apple Watch tvOS Apple TV and beyond It s a simple elegant and powerful programming language full of modern features the developer loves Swift allows you to write safe code without compromising speed and performance If you are serious about developing mobile applications for Apple products like iPhone iPad and MacBook Pro then you should learn Swift in Swift also makes it easier to create and share a binary framework with others If you need a resource I recommend you to check out this iOS and Swift The Complete iOS App Development Bootcamp course from Angela Yu another great and practical instructor on Udemy Native ScriptIf somehow you didn t like React Native and Flutter and looking for alternatives then you can also check out Native Script NativeScript is a free and open source framework to develop a mobile application for both Apple iOS and Google s Android platform It allows you to build native mobile apps in both TypeScript and JavaScript and using Angular and Vuejs If you are a frontend developer and already know frameworks like Angular or Vuejs then Native Script can be the right choice for you NativeScript features deep integration with both Angular and Vuejs and allows you to write code on any language which translates into JavaScript like TypeScript or CoffeeScript If you need resources I suggest you check out this Native Script Angular Build Native iOS and Android Apps course by Maximilian Schwarzmuller on Udemy Android This is the latest version of the Android platform It was released in September last year and unlike the previous Android version it doesn t have any sweet names like KitKat Oreo or Lollipop If you are interested in the Android platform or already an Android developer you can learn Android to learn new features like Dark Themes Smart Reply Gesture navigation G Networks Enhanced location and privacy tools etc You can also optimize your apps for foldable and other large screen devices If you are an Android developer or want to learn Android in I suggest you learn Android the latest version of Android OS and if you need resources I recommend Android MsterClass course on Udemy iOSThis is the latest release of the popular iOS platform which powers the iPhone and iPad two of the most powerful devices of humankind iOS is the latest iOS release It also comes with exciting features developers have long been asking for For example with the iOS SDK your app can take advantage of Dark Mode Focus and notifications SwiftUI UIKit Keyboard layout guides Core Location UI Accessibility Augmented Reality and moreIf you are an iOS developer or want to become an iOS developer in I suggest you learn iOS and if you need resources check out this iOS MasterClass from Angela Yu on Udemy IonicThis is another framework for developing hybrid mobile applications using JavaScript Ionic also allows you to build cross platform mobile apps which means you can create an application for any platform using one codebase Ionic Framework is free and open source and provides a portable UI toolkit for developing high quality cross platforms apps for native iOS Android and the web all from the single codebase It also has an Ionic React that leverages React for building hybrid mobile apps If you want to learn Ionic in then I suggest you check out this Ionic MasterClass course on Udemy It s created by none other than Maximilian Schwarzmuller one of the best instructors on Udemy and Youtube DartIf you want to learn Flutter which you should if you are serious about building cross platform native mobile applications then learning Dart could be beneficial for you because Dart is the programming language that powers Flutter If you don t know Dart is a programming language from Google aimed at developer productivity Unlike Golang another programming language from Google Dart is in between Java and JavaScript and you can learn it quickly if you are familiar with any of this language If you want to learn Dart in and looking for a recommendation I suggest you go through this Flutter and Dart Masterclass course on Udemy XamarinIf you want to build a native mobile application with NET and C then there is no better choice than Xamarin Xamarin is a tried and tested platform and great for C and NET developer who wants to get into mobile application development By using Xamarin you can build native Android iOS tvOS watchOS macOS and Windows apps using NET with native API access If you want to learn Xamarin in and looking for resources I suggest you check out this Xamarin Forms Build Native Cross Platform Apps using C course by Mosh Hamedani on Udemy That s all about how to become a app developer in As I said you can either learn Android Kotlin iOS Swift Flutter Dart or simply React Native to become a professional app developer in You don t need learn all just choose the combo which suits your skill for example if you are a Java developer then learning Kotlin for Android development make sense Simply if you are JavaScript developer you should go for React Native For example if you want to build native mobile apps for iOS platforms then learn iOS and Swift and if you to develop for the Android platform then learn Kotlin and Android and if you want to build cross platform native mobile applications then learn Flutter and Dart in Other Programming and Tech Articles You may like The Complete Java Developer RoadMap Things Java Programmer Should Learn in The Frontend and Backend Developer RoadMap Programming languages You can Learn in The Complete DevOps Engineer RoadMap Frameworks Java and Web Developer should learn Top Java Frameworks to Learn in The Complete React Developer RoadMap Reasons to Learn Python in My favorite courses to learn AWS and Cloud Computing Best Courses to learn Data Structure and Algorithms Top Courses to learn iOS and Swift in JavaScript Frameworks and Libraries to learn in Courses you can join to become full stack developer Courses to learn SQL and Database in Thanks for reading this article so far If you like this article useful and find these technologies worth learning for mobile app development then please share it with your friends and colleagues If you have any questions or feedback then please drop a note P S If you are thinking to do just one thing right now then I highly recommend you for iOS development and join this Swift and iOS Masterclass from Angela Yu on Udemy This single step can make a big difference in your career |
2021-12-06 10:49:33 |
海外TECH |
DEV Community |
Adding Authorization to Your Node.js Application Using Cerbos |
https://dev.to/alexolivier/adding-authorization-to-your-nodejs-application-using-cerbos-496d
|
Adding Authorization to Your Node js Application Using CerbosAuthorization is critical to web applications It grants the correct users access to sections of your web application on the basis of their roles and permissions In a simple application adding in app authorization to your application is relatively straightforward But with complex applications comes a need to create different roles and permissions which can become difficult to manage In this tutorial you ll learn how to use Cerbos to add authorization to a Node js web application simplifying the authorization process as a result Setting Up the Node js ApplicationBefore we get started with Cerbos you ll need to create a new Node js application or use an existing one Let s set up a blog post Node js application as our example Defining User PermissionsThe blog post application will contain two roles member and moderator The member role will have the following permissions create a new blog post update blog posts created by the member delete blog posts created by the member view all blog posts created by all members view a single blog post created by any memberThe moderator role will have the following permissions view all blog posts created by all members view a single blog post created by any member disable and enable a malicious postMembers and moderators cannot perform any action if they are disabled Creating the Application Step Launch your terminal or command line tool and create a directory for the new application mkdir blogpost Step Move into the blog post directory and run the command belowーa package json file will be created npm init y Step Open the package json file and paste the following name blogpost version description main index js scripts start nodemon index js test mocha exit recursive test js keywords author license ISC dependencies cerbos express devDependencies chai chai http mocha nodemon Two main packages are in the dependencies section of thepackage jsonーCerbos and Express Cerbos is the authorization package responsible for creating roles and permissions Express is a Node js framework used to set up and create faster server side applications In the devDependencies there are four packages Chai Chai HTTP Mocha and Nodemon Chai Chai HTTP and Mocha are used to run automated test scripts during and after development Nodemon is used to ensure the application server is restarted whenever a change is made to any file during development Step Run npm install to install the packages in the package json Step Create the following files index js which contains the base configuration of the demo application routes js which contains all the routes needed in the demo application db js which exports the demo database For the sake of this demo you will be using an array to store the dataーyou can use any database system you desire authorization js which contains the Cerbos authorization logic touch index js routes js db js authorization jsThen paste the following codes in the respective files index jsconst express require express const router require routes const app express app use express urlencoded extended true app use express json app use posts router app use error req res next gt res status json code message error stack app listen gt console log App listening on port module exports app routes jsconst express require express const router express Router const db require db const authorization require authorization const checkPostExistAndGet id gt const getPost db posts find item gt item id Number id if getPost throw new Error Post doesn t exist return getPost router post async req res next gt try const title content req body const user id userId req headers await authorization userId create req body const newData id Math floor Math random title content userId Number userId flagged false db posts push newData res status json code data newData message Post created successfully catch error next error router get async req res next gt try const getPosts db posts filter item gt item flagged false const user id userId req headers await authorization userId view all res json code data getPosts message All posts fetched successfully catch error next error router get id async req res next gt try const getPost db posts find item gt item flagged false amp amp item id Number req params id const user id userId req headers await authorization userId view single res json code data getPost message Post fetched successfully catch error next error router patch id async req res next gt try const title content req body let updatedContent title content const user id userId req headers const postId req params id checkPostExistAndGet postId const tempUpdatedPosts db posts map item gt if item id Number postId updatedContent item updatedContent return updatedContent return item await authorization userId update updatedContent db posts tempUpdatedPosts res json code data updatedContent message Post updated successfully catch error next error router delete id async req res next gt try const user id userId req headers const postId req params id const post checkPostExistAndGet postId const allPosts db posts filter item gt item flagged false amp amp item id Number postId await authorization userId delete post db posts allPosts res json code message Post deleted successfully catch error next error router post flag id async req res next gt try let flaggedContent flagged req body flag const user id userId req headers const postId req params id checkPostExistAndGet postId const tempUpdatedPosts db posts map item gt if item id Number postId flaggedContent item flaggedContent return flaggedContent return item await authorization userId flag flaggedContent db posts tempUpdatedPosts res json code data flaggedContent message Post req body flag flagged unflagged successfully catch error next error module exports router db jsconst db users id name John Doe role member blocked false id name Snow Mountain role member blocked false id name David Woods role member blocked true id name Maria Waters role moderator blocked false id name Grace Stones role moderator blocked true posts id title Introduction to Cerbos content In this article you will learn how to integrate Cerbos authorization into an existing application userId flagged false module exports db The demo database includes five users consisting of three members and two moderators Among the three members there are two active members and one blocked member Among the two moderators one is an active moderator and the other is a blocked moderator In the meantime the authorization js will contain an empty scaffolding to see how the application works before integrating the Cerbos authorization package module exports async principalId action resourceAtrr gt Step The demo application has been successfully set up It s now time to see how the application looks before integrating the Cerbos authorization package Start the server with the command below npm run startYou should see the following in your terminal to indicate your application is running on port nodemon nodemon to restart at any time enter rs nodemon watching path s nodemon watching extensions js mjs json nodemon starting node index js App listening on port Testing the Application Without AuthorizationNow it s time to test the application You can use any HTTP client of your choice such as Postman Insomnia or cURL For this example we ll use cURL Make the following requestsーyou should find no restrictions Change the user ID from through and you should receive a valid response Create Postcurl location request POST http localhost posts header user id header Content Type application json data raw title Introduction to Cerbos content Welcome to Cerbos authorization package Update Postcurl request PATCH http localhost posts header user id header Content Type application json data raw title Welcome to Cerbos content things you need to know about Cerbos View All Postscurl request GET http localhost posts header user id View Single Postcurl request GET http localhost posts header user id Flag Postcurl request POST http localhost posts flag header user id header Content Type application json data raw flag true Delete Postcurl request DELETE http localhost posts header user id Integrating Cerbos AuthorizationAs things stand the application is open to authorized and unauthorized actions Now it s time to implement Cerbos to ensure users perform only authorized operations To get started a policy folder needs to be created to store Cerbos policies Cerbos uses these policies to determine which users have access to what resources In the blog post directory run the command below to create a directory called Cerbos This will contain the policy directory mkdir cerbos amp amp mkdir cerbos policiesNext switch to the policies folder and create two policy YAML files derived roles yaml and resource post yaml The derived roles yaml File DescriptionDerived roles allow you to create dynamic roles from one or more parent roles For example the role member is permitted to view all blog posts created by other members but is not allowed to perform any edit operation To allow owners of a blog post who are also members make edits on their blog post a derived role called owner is created to grant this permission Now paste the code below in your derived roles yaml derived roles yamlapiVersion api cerbos dev v derivedRoles name common roles definitions name all users parentRoles member moderator condition match expr request principal attr blocked false name owner parentRoles member condition match all of expr request resource attr userId request principal attr id expr request principal attr blocked false name member only parentRoles member condition match expr request principal attr blocked false name moderator only parentRoles moderator condition match expr request principal attr blocked false name unknown parentRoles unknown apiVersion is the current version of the Cerbos derived role derivedRoles contains the list of user roles that your application will be used for each role will be configured based on the needs of the application derivedRoles name allows you to distinguish between multiple derived roles files in your application that can be used in your resource policies derivedRoles definitions is where you ll define all the intended roles to be used in the application name is the name given to the derived roles generated for example a resource could be accessed by members and moderators With the help of derived roles it s possible to create another role that will grant permissions to the resource parentRoles are the roles to which the derived roles apply e g members and moderators condition is a set of expressions that must hold true for the derived roles to take effect For example you can create derived roles from members and moderators then add a condition that the derived roles can only take effect if members or moderators are active This can be done through the condition key For more information on conditions check the condition guide here The resource post yaml File DescriptionThe resource policy file allows you to create rules for parent derived roles on different actions that can be performed on a resource These rules inform the roles if they have permission to perform certain actions on a resource Paste the following code in your resource post yaml resource post yamlapiVersion api cerbos dev vresourcePolicy version default importDerivedRoles common roles resource blogpost rules actions view all effect EFFECT ALLOW derivedRoles all users actions view single effect EFFECT ALLOW roles moderator member actions create effect EFFECT ALLOW derivedRoles member only actions update effect EFFECT ALLOW derivedRoles owner moderator only condition match any of expr request resource attr flagged false amp amp request principal attr role member expr request resource attr flagged true amp amp request principal attr role moderator actions delete effect EFFECT ALLOW derivedRoles owner actions flag effect EFFECT ALLOW derivedRoles moderator onlyThe resource policy file contains the permissions each role or derived roles can have access to apiVersion is the version for the resource policy file resourcePolicy holds all the key attributes of the resource policy version is used to identify the policy that should be used in the application you can have multiple policy versions for the same resource importDerivedRoles is used to specify the type of derived roles you want to import into the resource policy file resource contains the resource you want to apply the roles and permissions to rules is where you will set the rules for different operations on the basis of user permissions actions are operations to be performed effect is to indicate whether to grant the user access to the operation based on the roles and derived roles and conditions if they exist derivedRoles contains the derived roles you formed in your derived roles yaml file roles are static default roles used by your application condition specifies conditions that must be met before access can be granted to the operation To ensure your policy s YAML files do not contain errors run this command in the blog post root directory If it doesn t return anything then it is error free docker run i t v pwd cerbos policies policies ghcr io cerbos cerbos compile policies Spinning Up the Cerbos ServerYou ve now successfully created the policy files that Cerbos will be using to authorize users in your application Next it s time to spin the Cerbos server up by running the below command in your terminal docker run rm name cerbos d v pwd cerbos policies policies p ghcr io cerbos cerbos Your Cerbos server should be running at http localhost Visit the link and if no error is returned the server is working fine Implementing Cerbos Into the ApplicationNow it s time to fill the empty scaffolding in the authorization js file const Cerbos require cerbos const db require db const cerbos new Cerbos hostname http localhost The Cerbos PDP instance module exports async principalId action resourceAtrr gt const user db users find item gt item id Number principalId const cerbosObject actions create view single view all update delete flag resource policyVersion default kind blogpost instances post attr resourceAtrr principal id principalId policyVersion default roles user role unknown attr user includeMeta true const cerbosCheck await cerbos check cerbosObject const isAuthorized cerbosCheck isAuthorized post action if isAuthorized throw new Error You are not authorized to visit this resource return true The cerbosObject is the controller that checks if a user has access to certain actions It contains the following keys Actions contains all of the available actions you ve created in the resource policy file Resource allows you to indicate which resource policy you want to use for the resource request from multiple resource policy files The policyVersion in the resource key maps to version in the resource policy file kind maps to resource key in the resource policy file Instances can contain multiple resource requests that you want to test against the resource policy file In the demo you are only testing the blog post resource Principal contains the details of the user making the resource request at that instance The cerbosCheck isAuthorized method is used to check if the user principal is authorized to perform the requested action at that instance Testing Cerbos Authorization with the Blog Post ApplicationYou have successfully set up the required roles and permissions for each operation in the CRUD blog post demo application It s now time to test the routes again and observe what happens using the table below as a guide for testing actionuser iduser roleuser statusresponsecreate view all view single and memberactiveOKAll ActionsmemberblockedNot authorizedAll ActionsmoderatorblockedNot authorizedUpdate its own postmemberactiveOKUpdate another user postmemberactiveNot authorizedThe above table displays a subset of the different permissions for each user implemented in the demo application You can clone the demo application repository from GitHub Once you ve cloned it follow the simple instructions in the README file You can run the automated test script to test for the different user roles and permissions ConclusionIn this article you ve learned the benefits of Cerbos authorization by implementing it in a demo Node js application You ve also learned the different Cerbos policy files and their importance in ensuring authorization works properly For more information about Cerbos you can visit the official documentation here |
2021-12-06 10:47:26 |
海外TECH |
DEV Community |
What's The Vim Runtime? A Guide With Examples |
https://dev.to/phantas0s/whats-the-vim-runtime-a-guide-with-examples-43id
|
What x s The Vim Runtime A Guide With ExamplesHave you ever wonder what was The Beginning of All Things In other words have you ever wonder what Vim is doing when you start it What files are sourced why and in what order If you don t really care I encourage you to reconsider your position Knowing what Vim is doing at startup lets you speed it up overwrites some defaults from the plugins you ve installed or even creates your own filetypes In short it gives you even more power to customize Vim to your precise needs In this article we ll look at two main ideas What happens during Vim s startup What are the runtime paths what s sourced from there and when This article assumes that you have some advanced knowledge about Vim If you don t you can read my series of article to learn Vim from the ground up More specifically a lot of knowledge in this article is built on Vim for Expert Users Take your headlamp and a good rope we ll go exploring today many paths in our filesystems Vim s StartupWhen you start Vim many things happen behind the curtain before your favorite cursor is displayed on the screen I describe here a simplified version trying to underline the most important steps Startup s OrderHere s what Vim will do when you run it Set the shell options useful for the command and for Vim s terminal Process the arguments given to the CLI Buffers are created for all files given as arguments The value of the environment variable VIMINIT an Ex command is executed Source the user s vimrc file The value of the environment variable EXINIT an Ex command is executed If the option exrc is set Vim will try to find and load a vimrc in the working directory Keep in mind however that setting exrc is not secure Source filetypes filetype plugins and indent plugins We ll see them below Source syntax highligting scripts Source plugin s scripts Load runtime s and plugin s scripts from the after folder Source the shada file for Neovim or the viminfo file for Vim Execute the options given to Vim affecting the startup Let s add more precisions If you want to run more than one command using VIMINIT you can separate them with the symbol Your vimrc file can be In Vimscript for Vim located at HOME vimrc In Lua or Vimscript for Neovim located in HOME config nvim init vim or XDG CONFIG HOME nvim init vim if XDG CONFIG HOME is set Setting the option exrc can be dangerous Vim can load potentially unsecure vimrc files you might have downloaded with other files You can use the option u lt another vimrc gt when you run Vim in your terminal to load another vimrc file instead of the default one You can also use of of these value instead of a vimrc for debug purposes NORC Don t load any vimrc but load your plugins NONE Don t load any vimrc nor plugins You can run any command using the options c or For example vim set shiftwidth echo hello Profiling Vim s StartupIf Vim does terrible things at startup and you don t understand how to fix it you can use the option V to have more details about the startup process If you re startup is too slow and you want to find the bottleneck you can profile it with vim startuptime lt file gt It will write every files loaded with timestamps in the file lt file gt Special Environment VariablesTwo environment variables are only defined when Vim starts VIM Used to locate various user files VIMRUNTIME Used to locate various support files for Vim We ll speak more about the runtime below You can look at the value of these variable with the command echo VIM for example If you define these environment variables in your shell Vim won t overwrite them Vim Help help startup help slow start help shell help VIM help VIMRUNTIME The Runtime PathThe runtime path is similar to the environment variable PATH in Unix based systems Vim will search in these paths to locate and source many different files during startup To see all of these paths you can look at the value of the option runtimepath by running the command set runtimepath If you use Vim it s likely that you ll see HOME vim as the first path of the list If you re a Neovim adept it will be HOME config nvim The subdirectories of the runtime paths have different meanings according to their names The Vimscript files inside these directories will be sourced at different times during startup sometimes in different ways Important Runtime PathsHere are some important runtime paths Vim will parse them in this order For Vim HOME vim VIM vimfiles VIM vimfiles after HOME vim afterFor Neovim XDG CONFIG HOME nvim or config nvim if XDG CONFIG HOME is not set XDG CONFIG HOME nvim after Subdirectories of the Runtime PathsAs I was writing above the configuration files in the runtime paths contains different things depending of the subdirectory they re in Here s an overview of the most useful of these subdirectories and how you can use them to customize Vim even further I encourage you to look at the default configuration files to understand the meaning of these subdirectories They are in the directory set in the variable VIMRUNTIME Don t forget that you can only read the value of VIMRUNTIME after launching Vim You can also find examples in my own dotfiles ftpluginThe subdirectory ftplugin for filetype plugin allow you to load pieces of configuration each time you open a buffer with a specific filetype For example let s say that you need a couple of mappings only for markdown files You can Open a markdown file and verify that the filetype is indeed markdown by running the command set filetype Create the file markdown vim in HOME vim ftplugin for Vim or XDG CONFIG HOME nvim ftplugin for Neovim Add options and mappings only for markdown files in there For example setlocal spell will enable spelling each time you open a markdown file You need to keep in mind however that each time a buffer with the filetype markdown is created the file ftplugin markdown vim will be sourced As a result you need to make sure that You re resetting any autocommand each time the file is sourced using an autocommand group and au Every mapping you re creating have the special argument lt buffer gt for example map lt buffer gt lt leader gt h echo hello You re using setlocal instead of set to set options You re using the buffer argument for any user command If you don t respect these rules your pieces of configuration won t only be loaded for the buffers with a precise filetype but for every buffer globally autoloadThe subdirectory autoload is also very useful It lets you load your custom functions when you call them instead of loading them when Vim starts As a result it can significantly speed up Vim s startup These functions need to begin with the path of the file they re written in for Vim to know where to find them when you call them For example you can create a new file autoload general vim and use it to declare a new custom function MyFunction This function needs to be called general MyFunction because it s declared in the file general vim To call it you can run call general MyFunction You can also create subdirectories in the directory autoload For example you can create the file autoload path to general vim In that case you need to call your function path to general MyFunction describing the location of the file itself I encourage you to put all your custom functions in the autoload subdirectory syntaxThe subdirectory syntax lets you create your own syntax files They re used for code highlighting for example You can first create a syntax group matching some regex and then you link your syntax group to highlight groups These highlight groups will decide of the text s color displayed Vim supports many syntaxes by default you can see them in the directory VIMRUNTIME syntax I never had to create my own syntax groups It s however good to know that you can do it in case you need it colorsYou can create highlight groups in the subdirectory colors Each file represents a different color scheme Again you ll find different examples in the directory VIMRUNTIME colors To change the color scheme of your highlighting you can use the command color lt my color scheme gt ftdetectHave you ever dreamed to create your own filetypes That s great because Vim is a dream machine You can create your filetypes in the subdirectory ftdetect For example if you have a bunch of file with the extension new and you want to create a filetype for them you can Create the file ftdetect new vimWrite au BufRead BufNewFile new set filetype new in it You can also link some filetypes with other ones For example I wanted the files with the extension yaml dist to have the yaml filetype So I ve Created the file ftdetect yaml dist vimWritten autocmd BufNewFile BufRead yml dist set filetype yaml in it compilerIn Vim you can use the command make to run a specific compiler depending of the filetype of your current buffer Under the hood Vim will search a file named after the filetype of your current buffer in the compiler directory For example if if you want to run the Golang compiler with precise options you can create the file compiler go vim and add whatever you need The Directory afterThe subdirectory after is a special one You can think of it as another runtime path in the runtime path where you can add the same subdirectories we saw above Everything in the after directory will be loaded after everything else You can also see it when you look at the order of the most important runtime path at the beginning of this section From there you can override anything you want indentation filetype plugins or even the external plugins you ve installed For example I can override Lisp indentation by creating the file after indent lisp vim and setting whatever options or variables I want to modify I didn t cover the subdirectory indent by the way but I m sure you can figure out its purpose The Runtime CommandIf you want to source manually some files from your runtime path you can use the command runtime lt file gt For example if you want to load every files from the colors subdirectory you can run runtime colors vim You can also use runtime with a bang to source everything Disabling Runtime FilesFinally if you want to debug one of your runtime files you can disable some of them by sourcing these specific files source VIMRUNTIME ftoff vim Disable the detection of filetypes source VIMRUNTIME ftplugin vim Enable ftplugin source VIMRUNTIME ftplugof vim Disable ftplugin source VIMRUNTIME indent vim Enable indentation source VIMRUNTIME indoff vim Disable indentation Vim Help help runtimepath help autoload help ftplugin help syntax help new filetype help after directory The Startup Has Been RevealedNow that you know what Vim s doing when it s starting you can add your pieces of configuration in the good runtime subdirectory for more flexibility You can also try to speed up your startup if you find it too slow What did we see in this article Vim load specific configuration files and environment variables at startupYou can use the options V or startuptime to get more details regarding Vim s startup The environment variable VIM and VIMRUNTIME are set during startup The subdirectories in the runtime path have a meaning sometimes affecting directly how they re loaded at startup and when The runtime path subdirectory after is a special one it s a runtime path too accepting the same subdirectories and you can overwrite every other loaded config files in there The command runtime allows you to manually load config files from your runtime paths I encourage you to experiment with all these configuration files to improve your config Personally I find the subdirectories autoload and ftplugin especially handy Learning to Play Vim A Fun Guide to Learn the Best EditorI began to write a very ambitious guide to learn Vim from the ground up Thanks to great feedback from my readers I ll be able to address the problems many beginners complain about when learning Vim For example How to navigate in multiple files and projects in Vim How to debug in Vim How to search find and replace This guide will explain the most useful vanilla functionalities as well as some powerful plugins which will enrich your experience Help me make an impact in the Vim world You can subscribe to the newsletter and tell me everything you want to see in the book Early bird discount guarantees I reply to every email personally so don t hesitate to ask as many questions as you want It s always a pleasure to help Last but not least I ve also written a book about building your own Mouseless Development Environment so if you re interested by that too click on this shiny link |
2021-12-06 10:46:37 |
海外TECH |
DEV Community |
PicoLisp Explored: The idx function |
https://dev.to/miatemma/picolisp-explored-the-idx-function-22fk
|
PicoLisp Explored The idx functionIn this post we will talk about a special kind of tree the binary search tree This post covers the fundamentals The purpose is to build the fundamentals for the really interesting parts which will be covered during the next posts Enhancing program execution speed with help of the cache and enum function A little bit of theoryWe will not to go to deep here but we need to know some basics in order to understand the rest of the post What is a binary tree A binary tree is a structure where each node can have up to two children left child and right child also called nodes A binary tree has some very convenient characteristics as we will see soon Let s look at the following example In total there are nodes For each node the left children are smaller than the node the right children are larger This is an example for a sorted tree It is also balanced because all layers are complete except for the lowest one A binary tree with n layers can store up to n entries Two layers nodesThree layers nodesFour layers nodes Why should I care about binary trees Binary trees enable extremely efficient searching processes Say we want to look up node We start at the root value lt gt go to left lt gt go left gt gt go right gt found it This means that if the tree is balanced and sorted every node can be reached within max log n binary steps Imagine you want to reach a specific items in a list of length n If you re unlucky your item is the very last one and you need to do n steps This means If you have Million entries to search in worst case it will take you steps in a binary tree but Mio steps in a normal list This should be enough for a motivation right Let s start Now let s plant a PicoLisp binary tree Simple index treesThe function that inserts a single item into a binary search tree is called idx for index Let s try to recreate the tree from the example only the first layers to keep it short Start the REPL by typing pil in the console and try off Tree declare empty tree gt NIL for X idx Tree X T loop through list and add items gt NILWe have two possibilities to check our Tree The default prints a list which follows the recursive syntax root left child right child A more graphical print out is possible using the function view with the T flag for binary trees Tree gt view Tree T This corresponds exactly to our example above Good Let s check its depth using the depth function depth returns two values the maximum depth of the longest branch and the average depth of all nodes depth Tree gt max depth average depth Worst case scenario Sorted listsIn our previous example we received a perfectly balanced tree which means that all layers were filled up before the next layer was started However this cannot be guaranteed as we will see in the next example Let s enter a sorted list for X idx Tree X T gt NIL view Tree T depth Tree gt depth average Oh no our tree almost looks like a list We lost our favorite binary tree feature the logarithmic search The idx function works best with random values Otherwise we need to improve the structure by balancing the tree during the insertion This can be done using the balanced function Balanced treesThe function balanced automatically creates balanced trees out of a sorted input list If the values are not sorted yet we can use sort function before we hand them over balance Tree sort view Tree T This looks much better right Now we can reach any of the nodes within max steps With this we have covered the fundamentals of binary trees in PicoLisp In the next posts we will solve the Tree Traversal Task from the Rosetta Code to get a feeling how binary tree search works Sources |
2021-12-06 10:42:29 |
海外TECH |
DEV Community |
Upload and Manage Files on Cloudinary with the Filepicker Widget |
https://dev.to/appsmith/upload-and-manage-files-on-cloudinary-with-the-filepicker-widget-1b9p
|
Upload and Manage Files on Cloudinary with the Filepicker WidgetMany internal tools especially administrative applications often require file uploading and file management features File pickers and file selectors therefore are some of the most used components in internal tool development Developers experience numerous challenges when it comes to implementing these features resulting in delayed operations This can easily be mitigated by using Appsmith to build and deploy applications quickly Appsmith has a dedicated filepicker widget that can be used to upload files to any of the developers preferred cloud storage services such as Cloudinary S among others In this short blog we re going to focus on one such widget the filepicker With this you can upload files from your local machines to any cloud storage via API You can upload files by implementing a POST API and reference the base or binary version in the post body Features of the Filepicker WidgetThe Allowed File Types properties allow us to restrict the types of files that a user of our application can upload The Maximum File Size attribute allows us to specify the total file size that a user can upload When the user selects files to be uploaded we can immediately use an API or utilize the S plugin to upload the file s base to our cloud storage The visibility property controls the widget s visibility on the page When the widget is switched off the widget will not be displayed when the app is published There is a parameter that allows us to specify the maximum number of files that a user is allowed to upload How Does the Filepicker Widget Work In this section we ll look at how the filepicker works First let s set up a new application to get started Create a new account on Appsmith it s free if you are an existing user log in to your Appsmith account Create a new application by clicking on the Create New button under the Appsmith dashboard We ll now see a new Appsmith app with an empty canvas and a sidebar with two directories Datasources and Widgets This is where we can connect to data sources and find all the widgets Now we re all set to explore how the filepicker widget works in Appsmith Drag and drop the filepicker widget as shown in the image below Now that we have our filepicker widget on the canvas we can customize the properties as desired After selecting our file s we get the following result How to manage files on Cloudinary using AppsmithFilepicker configurationWe ll go over each of the configurations accessible in the Appsmith filepicker one by one Label This is used to set the label of the Filepicker from the default “Select Files to any label of our choice Maximum No of files This allows us to specify the maximum number of files that a user is authorized to upload Maximum File Size This property allows us to specify the maximum file size that a user can upload Data Type This determines the data format of the files uploaded Allowed File Types Allows us to restrict the types of files that a user can upload Accepts an array of wildcardsimage exact mime types image jpeg or file extensions jpg image jpg jpeg png gif Required When turned on it marks user input as a required field and disables form submission until the input is made Visible Controls widget s visibility on the page When turned off the widget will not be visible when the app is published See the documentation to learn more Uploading single and multiple images to cloud storage via Filepicker using a Cloudinary APILet s now explore how to upload single or multiple files using filepicker to cloud storage using the Cloudinary API Setting up a data sourceWe ll need to connect to our data source by clicking on the Plus icon next to the data sources link in the sidebar then selecting Create New from the menu as shown below After this we should now choose the Create New API option This will take us to the screen shown below We renamed the data source from the default Api to Cloudinary API in the image above to have a clear description We will be making use of the Cloudinary API cloud name image upload where cloud name is our cloudinary username The API requires our Cloudinary cloud name and upload preset To get our cloud name and upload preset we follow the steps listed below The cloud name is obtained from our Cloudinary dashboard as shown below An upload preset can be found in the “Upload tab of our Cloudinary settings page which we access by clicking on the gear icon in the top right corner of the dashboard page We then click on the Upload tab on the settings page We scroll down to the bottom of the page to the upload presets section where we see our upload preset or the option to create one if we don t have any Adding the Cloudinary API URL and setting the header should look similar to what we have below Let s go to the Body tab and configure it as shown below We specified the file s to be uploaded as well as our upload preset in the image above and we configured our request body in a multipart structure Now that we ve finished configuring the API let s put it to the test before using it in our filepicker We will click on the FIlePicker Widget as shown below and select a file to be uploaded from our system Now let s head over to the API section the following is the test result Yay That works We ve successfully tested our API and got a valid response Upload images using FilepickerLet s upload a single image directly from our filepicker to cloud storage by connecting to the API Datasource we just created We will head over to the filepicker configuration and update the onFilesSelected property As seen below we can add a success alert to show when the image is successfully uploaded and when there is an issue after selecting our query to be conducted The response below shows a success alert after uploading our image to cloud storage utilizing the Cloudinary API directly from our filepicker widget We hope that you found this short guide helpful If you want to know how to upload or download files from S you can look at this document and follow this discussion To learn more about how to upload a file to a local server take a look at this discussion on our community forum Appsmith has more than UI widgets and these can cut your development time in half To know more head to our docs Did you get stuck somewhere We re happy to help Join us on Discord today Olubisi Idris Ayinde is a software engineer technical writer and community builder This article was written as part of the Appsmith Writers Program If you d like to write for Appsmith send an email expressing your interest to writersprogram appsmith com |
2021-12-06 10:42:02 |
海外TECH |
DEV Community |
Web3 - just your typical post! |
https://dev.to/inhuofficial/web3-just-your-typical-post-107h
|
Web just your typical post Ready to learn what web is Great let s begin It is blockchain NFTs etc This is the future of the web It solves all the problems with web development and if you don t know about web then you will not be able to get a job Learn web by building a NFT for no apparent reason or understanding the benefits what it is useful for where the problems are or anything of relevance at all Here it is in just one line of code because we all know dependencies do not count towards lines of code or complexity import NFT library with lines of code that does everythingimport additional library for no reasonmassive library make NFT asset See now you know how blockchain works it s easy right Now you can add Web to your CV Got questions Don t ask questions web is so well thought out that there are no questions Just join the cult and prepare to make figures a year Don t forget to tweet about it every hours and to write an overpriced page book that explains nothing so that new developers will buy it get a tiny bit of info and then buy your other crappy tutorials and guides We all know that student developers have money to burn And don t forget if anyone ever has the audacity to question you just remember to tell them that they are a dinosaur trying to stop the future of the web and a boomer To sum upI just taught you everything you need to know about NFTs and blockchain Now you can go and build the future of the web But if you need more information then make sure to Buy my book on Gumroad pages of super useful information Minimum price is as I am worth a page Follow me on Twitter I post every hour just to make sure you remember me Read my Blog I just copy paste my twitter threads into blog posts I don t bother to format them appropriately though so you can struggle to read them Buy my Course minutes on Web for most of it is just me reading from Wikipedia for you so you know it is good value for money Don t miss out I have exclusive web merch to show you are awesome for a water bottle is a bargain We all need merch to make us better developers Work with me I know how to turn a successful application into a super expensive blockchain powered disaster today Buy me a coffee Please I need coffee to keep coming up with variations of the same crap Support me on Patreon Only £ a month to support my crap I will even put your name at the end of my videos so you can become famous Fund my KickStarter We are using NFTs to prove ownership of NFTs it s genius You get a cheap T shirt if you pledge Venmo Me just give me money to show your appreciation for my ability to copy paste content CashApp Me Give me and I will follow you back GIVE ME MONEY please people are becoming aware of the hype so I don t have long to milk this crap The GiveawayOf course I can t leave this post without a giveaway I am giving away a free eBook worth well that is the price I made up for it it is actually worth about as it will waste minutes of your valuable time to one lucky person All you have to do is retweet this crap and clutter up everyone s feedFollow me so I can feed you more of this crapWrite a thousand word essay on how amazing I amHire a billboard in Time Square advertising my Web course Design a logo for my new site and transfer the copyright to meCreate a minute video on all the things you wish you knew about NFTs and make sure you mention me at least times as an expert in it Shave your left eyebrow on a live stream while reciting NFTs are life Blockchain is the future of everything How easy is that Oh and you can do it multiple times for multiple entries because I am a nice guy not because I need you to keep harassing people into thinking they have to know this shit Be cool my crypto cousins or some other inane way to refer to you to make you feel a shred of belonging and make you think I care End OK who rattled your cage this time angry man It all started a couple of weeks ago when Danny Thompson made a simple tweet learn web get paid Santa Danny Thompson dthompsondev Learn Web get paid PM Nov Most of the responses were people saying did you mean web and that is just depressing It is also very worrying as majority of the people who follow Danny are new developers looking to get jobs just starting out Then it got worse as it seemed that my twitter feed was rammed full of crap on Web that explains things by just linking to the same crap everyone else is quoting that explains nothing but shills some crappy book Then the final straw was a post I just saw in the DEV feed that contained about as much information as this post and claimed to be an ultimate guide which sent me into angry man mode To be clear I do love some of the things that Web will likely bring I believe web will be part of the future but it won t be the future I just don t want new developers to get consumed by web hype and lose focus on the stuff that will actually get them a job or buy crappy resources that offer no value p s I know i am writing troll stuff and cluttering the feed just passing the time before I announce something big later today |
2021-12-06 10:16:43 |
海外TECH |
DEV Community |
How to easily get started with ThreeJS - Part 3 |
https://dev.to/th3wall/how-to-easily-get-started-with-threejs-part-3-48j5
|
How to easily get started with ThreeJS Part Hi guys hope you are fine I m back after posting the second part of this series about how to get started on ThreeJS without pain If you haven t done it yet you can read the first and second part here How to easily get started with ThreeJS Part Davide Mandelli・Nov ・ min read tutorial threejs webgl javascript How to easily get started with ThreeJS Part Davide Mandelli・Nov ・ min read javascript tutorial webdev programming Small recapIn the second part we saw how to animate the cube how to change its geometry and how to change its material We arrived to this beautiful D animation The final code used to achieve this effect is the following script jsconst scene new THREE Scene const camera new THREE PerspectiveCamera window innerWidth window innerHeight camera position z scene add camera const textureLoader new THREE TextureLoader const matcapTexture textureLoader load const geometry new THREE TorusKnotGeometry const material new THREE MeshMatcapMaterial matcap matcapTexture const mesh new THREE Mesh geometry material scene add mesh const renderer new THREE WebGLRenderer renderer setSize window innerWidth window innerHeight const animate function window requestAnimationFrame animate mesh rotation x mesh rotation y renderer render scene camera animate document body appendChild renderer domElement In this last part we will see how to make our canvas responsive how to smoothly animate the camera and how to insert some HTML stuff to be much more presentable as a heading section We will style the page in order to look like this Let s make it responsiveIf we preview in the browser the result of the code provided in the small recap up here we could clearly see that the canvas is not responsive So how can we make it responsive First of all we need to add an event listener on the window resize method window addEventListener resize gt Then we need to handle the camera Inside our event listener we need to update the aspect of the camera and we do so by providing it the ratio between the window innerWidth and innerHeight Update the cameracamera aspect window innerWidth window innerHeight Every time we update a parameter of the camera we should communicate it to the camera The updateProjectionMatrix is a function of the PerspectiveCamera that updates the camera projection matrix It must be called after any change of parameters see it in ThreeJS docS So on the camera we call this method camera updateProjectionMatrix The last thing to do is to pass the new viewport sizes to the renderer renderer setSize window innerWidth window innerHeight and we re done Now our canvas is fully responsive and we can verify it by resizing the screen Here s the full event listener function window addEventListener resize gt Update the camera camera aspect window innerWidth window innerHeight camera updateProjectionMatrix Update the renderer renderer setSize window innerWidth window innerHeight Camera animations based on mouse positionNow that we added responsiveness to our canvas and our object it s time to bring some movements to the scene We re going to do a classic animation if we move the mouse on the left the camera will move to the left if we move the mouse on the right the camera will move to the right and the same applies to up amp down movements First of all we need to know where is the cursor We can store the cursor position in a variable const cursor x y Whenever the mouse will move the x and y values of the cursor will be updated So we add an event listener on the mousemove window addEventListener mousemove event gt update cursor values Inside the listener we will retrieve the cursor position with vanilla JS really easy The event parameter contains the position of the cursor on the X axis and on the Y axis cursor x event clientX cursor y event clientY Logging the values of the cursor we can see the coordinates that go from on the top left to the maximum viewport width and height to the bottom right But the kind of values we want to have are normalized values that go from to We can achieve this by dividing the cursor value by the current viewport width height cursor x event clientX window innerWidth cursor y event clientY window innerHeight Now that we have the values that floats from to we can add a little genius trick from Bruno let s subtract from each cursor values cursor x event clientX window innerWidth cursor y event clientY window innerHeight Why Because in this way you can look at the graph down here having the at the center the positive values will go to and the negative values will go to Now that we have coded the update for the cursor values we need to move the camera simultaneously Inside the animate function that is executed with the requestAnimationFrame we save the cursor values in two variables const cameraX cursor x const cameraY cursor y We assign these two values to the camera position camera position x cameraX camera position y cameraY As we can see previewing the result the camera is moving with a strange behavior when we move vertically If I move up the camera moves down and if I move down the camera moves up This is caused by a problem on the Y axis in ThreeJS the Y axis is positive going up in event clientY the Y axis is positive going down Usually the Y axis is positive going up but this might depend on the software technology we are using To fix this inconvenience I will put a minus inside the cameraY assignment const cameraX cursor x const cameraY cursor y lt This has changedNow if we preview we can finally see the correct camera movements event on the vertical axis Add easing to the animationsLet s now add some easing to the animations we re gonna recreate the famous ease animation The idea is to move the X or the Y toward the destination not straight to it but only for th of the length of the destination And repeating the th calculation on each next frame the th gets smaller and smaller and smaller This reproduces the classic ease animation We need the calculate the delta between the actual position cameraX Y and the destination camera position x y then we divide this delta number by This will be added on each frame to the camera position values So in order to apply this calc we need to modify the camera position assignments like the following camera position x cameraX camera position x camera position y cameraY camera position y You can now enjoy the real smoothness You can adjust that on your needs keep in mind that with an higher number you would have even more smoothness and with a lower number you would have an object that floats really fast but still with a small easing Setting up layoutAt this point we just need to setup the HTML and CSS of our landing page First of all we can open the index html file that we have created in part one We can add the classname three on the lt body gt tag and the following structure inside it lt index html gt lt section class content gt lt h class content title gt Hi I m Davide lt h gt lt p class content subtitle gt I m a Front End Developer lt br gt I m playing with ThreeJS for the very first time lt p gt lt div class content link wrp gt lt a class content link href gt lt svg class content link icon xmlns fill none viewbox gt lt g clip path url a gt lt path fill fff fill rule evenodd d M C c A c Z clip rule evenodd gt lt path gt lt g gt lt defs gt lt clippath id a gt lt path fill fff d M hvHz transform translate gt lt path gt lt clippath gt lt defs gt lt svg gt lt span class content link text gt ThWall lt span gt lt a gt lt a class content link href gt lt svg class content link icon xmlns fill none viewbox gt lt path fill fff d M a c a C a c a v a c a c A l Z gt lt path gt lt svg gt lt span class content link text gt ThWall lt span gt lt a gt lt div gt lt section gt Now you need the styling part I ll paste here the css generated from my SCSS code You need to insert it inside the styles css file styles css import url wght amp display swap html font size px webkit font smoothing antialiased moz osx font smoothing auto font family apple system BlinkMacSystemFont Segoe UI Helvetica Arial sans serif Apple Color Emoji Segoe UI Emoji Segoe UI Symbol scroll behavior smooth body position relative overflow x hidden margin display flex flex direction column align items center justify content center font family Poppins sans serif font size rem font weight background color fff color text align center h h h h h h p margin three position relative overflow hidden width vw min height vh height three content position absolute top left transform translateY margin top rem display flex flex direction column justify content center text align left mix blend mode difference webkit touch callout none webkit user select none khtml user select none moz user select none ms user select none user select none three content title font size px font weight background linear gradient deg ffbf ff ffb cbeee color deee background clip text webkit background clip text webkit text fill color transparent webkit box decoration break clone three content subtitle margin bottom rem font size px color fff three content link display inline flex align items center color inherit three content link last child margin left rem three content link hover content link icon three content link hover content link text opacity transform translateX px three content link wrp display flex align items center three content link icon width max width rem transition all s cubic bezier three content link text margin left rem display block text decoration underline font size px color fff transition all s cubic bezier media min width px three content title letter spacing rem three content link last child margin left rem three content link icon max width rem three content link text margin left rem font size px media min width px three content title font size px three content subtitle font size px three content link text font size px Once everything will be in place we should have the result that looks like this As we can see the object is centered and it would fit a lot better on the right so that it won t intersect with the text on the left In order to move it we need to adjust the cameraX inside the animate function const cameraX cursor x Beforeconst cameraX cursor x AfterSince we wanted to move the object on the right we have subtracted the to the camera so that it will always have an offset of Adding sequenced entrances with GSAPWe are at the very end and as ending we want to animate with GSAP the entrance of the elements in the page In order to animate our floating object we need to change how the canvas is attached to the body At the moment the canvas is attached automatically to the body by ThreeJS but we need to animate the canvas element on load so we need to already have it on the page at load time Inside the index html adjacent to the lt section class content gt inserted in the last paragraph we need to insert the canvas manually and give it an id or a classname lt canvas id world gt lt canvas gt At this point we can declare the variables for each element we want to animate const canvas document querySelector world const title document querySelector content title const subtitle document querySelector content subtitle const buttons document querySelectorAll content link We take the canvas variable and we pass it as a parameter to the renderer like this const renderer new THREE WebGLRenderer canvas canvas This will tell the renderer that the canvas to attach is the one passed to the canvas parameter so the one with the id world Now that the renderer knows what it has to display we can remove this line document body appendChild renderer domElement Then we need to pass two parameters to the material in order to let it be able to be transparent transparent trueopacity and we set them inside the material declarationconst material new THREE MeshMatcapMaterial matcap matcapTexture transparent true opacity Now we need to install GSAP and with NPM we can type the following command npm install gsapOnce installed we can import it on top of our script js file import gsap from gsap and we can declare a classic timeline like this one const tl gsap timeline paused true delay easing Back out tl from title opacity y from subtitle opacity y from buttons stagger each from start opacity y to material opacity As a very last step we call the timeline play trigger after the animate function tl play Mission accomplished Congratulations Final RecapI leave down here the full final script js code block so you can have a better look at it script jsimport as THREE from three import gsap from gsap const canvas document querySelector world const title document querySelector content title const subtitle document querySelector content subtitle const buttons document querySelectorAll content link const cursor x y const scene new THREE Scene const camera new THREE PerspectiveCamera window innerWidth window innerHeight camera position z scene add camera const textureLoader new THREE TextureLoader const matcapTexture textureLoader load const geometry new THREE TorusKnotGeometry const material new THREE MeshMatcapMaterial matcap matcapTexture transparent true opacity const mesh new THREE Mesh geometry material scene add mesh const renderer new THREE WebGLRenderer canvas canvas renderer setSize window innerWidth window innerHeight window addEventListener resize gt camera aspect window innerWidth window innerHeight camera updateProjectionMatrix renderer setSize window innerWidth window innerHeight window addEventListener mousemove e gt cursor x e clientX window innerWidth cursor y e clientY window innerHeight const tl gsap timeline paused true delay easing Back out tl from title opacity y from subtitle opacity y from buttons stagger each from start opacity y to material opacity const animate function window requestAnimationFrame animate mesh rotation x mesh rotation y const cameraX cursor x const cameraY cursor y camera position x cameraX camera position x camera position y cameraY camera position y renderer render scene camera animate tl play ConclusionI really hope that this mini series has helped you and as many people as possible and maybe inspired as Bruno Simon did with me when I saw the interview for the first time Please let me know if you appreciated the article and the whole mini series You can follow me on Twitter GitHub amp Hashnode Thanks for reading ThWall |
2021-12-06 10:13:23 |
海外TECH |
DEV Community |
About Azure AD authorization Integration Tests |
https://dev.to/alekshura/about-azure-ad-authorization-integration-tests-34c0
|
About Azure AD authorization Integration Tests IntroductionIt is obvious thing that during software creation life cycle the code quality and proper functionality are the must Besides of coding techniques like code reviews Merge Requests Pull Requests pair programming etc various testing approaches are the must also The QA teams or UAT tests are responsible for it at the end of coding process but before it the ones who responsible for code quality are of course developers An outcome of development is a “product ーproperly working peace of software and in the era of micro services teams can decide about development approaches Test Driven Development Behavioral Driven Development Acceptance Test Driven Development etc The “basic unit for testing code is unit test Coding techniques have changed during last years to make possible to cover you code methods in a classes or units of code by unit tests Dependency injection and IoC containers is a “standard the techniques become more and more similar in NET and Java ecosystems while it makes also possible convenient unit testing Next step is interaction testing of software components in a bigger functionality For example REST API method that reads data from another REST or asynchronously writes it to some Message Broker or Database All methods used in this “process are covered by Unit Tests but such overall “cooperation them starting from API entry point are not And here developers start to write Integration Tests or Integration Tests are already written if you use TDD or BDD End to End tests EE ーare the next degree of your software functional tests and it is very useful if they are automated during CI CD pipelines execution But of course it depends Load and stress testing that is another type of non functional tests that characterize the quality of you software While it is not a part of this post let me redirect you here And a little bit more about Unit vs Integration vs System vs EE Testing comparison from MS Azure AD authorization integration testsHere I concentrate on integration tests of Web API example with Azure AD authorization authentication and how to arrange it in a simple and readable way Lets imagine that we have CRUD API controller for some user notes for abstract documents It is simply a title and description for document that user stores something like this namespace Compentio Ferragosto Api Controllers using Microsoft AspNetCore Authorization using Microsoft AspNetCore Mvc using Microsoft Identity Web Resource using Compentio Ferragosto Notes using System Collections Generic using System Threading Tasks using System Authorize ApiController ApiConventionType typeof DefaultApiConventions RequiredScope RequiredScopesConfigurationKey AzureAd Scopes Route api notes public class NotesController ControllerBase private readonly INotesService notesService public NotesController INotesService notesService notesService notesService lt summary gt Returns list of notes lt summary gt lt returns gt lt returns gt HttpGet public async Task lt IEnumerable lt Note gt gt Get return await notesService GetNotes ConfigureAwait false lt summary gt Returns note by its id lt summary gt lt param name id gt lt param gt lt returns gt lt returns gt HttpGet id ApiConventionMethod typeof DefaultApiConventions nameof DefaultApiConventions Get public async Task lt Note gt GetNote string id return await notesService GetNote id ConfigureAwait false lt summary gt Method adds new note lt summary gt lt param name note gt lt param gt lt returns gt lt returns gt HttpPost ApiConventionMethod typeof DefaultApiConventions nameof DefaultApiConventions Post public async Task lt ActionResult lt Note gt gt Add FromBody Note note return await notesService AddNote note ConfigureAwait false lt summary gt Method updates the note lt summary gt lt param name id gt lt param gt lt param name note gt lt param gt lt returns gt lt returns gt HttpPut id ApiConventionMethod typeof DefaultApiConventions nameof DefaultApiConventions Put public async Task lt ActionResult lt Note gt gt Update string id FromBody Note note var noteToUpdate await notesService GetNote id ConfigureAwait false if noteToUpdate null return NotFound var updatedNote await notesService UpdateNote note ConfigureAwait false return Accepted updatedNote lt summary gt Method deletes the note lt summary gt lt param name id gt lt param gt lt returns gt lt returns gt HttpDelete id ApiConventionMethod typeof DefaultApiConventions nameof DefaultApiConventions Delete public async Task lt IActionResult gt Delete string id await notesService DeleteNote id ConfigureAwait false return Accepted The Azure Ad Scopes configured for access as user and access as admin Web API applications here consists of three tiers NotesControler NotesService and NotesRepository with MongoDB configured underneath The overall code you can find on the GitHub Compentio Ferragosto NotesThe integration tests for getting notes method could be like this public class NotesApiIntegrationTests IClassFixture lt WebApplicationFactory lt Api Startup gt gt private readonly WebApplicationFactory lt Api Startup gt factory private readonly NotesRepositoryMock notesRepositoryMock private const string notesBaseUrl api notes public NotesApiIntegrationTests WebApplicationFactory lt Api Startup gt factory factory factory notesRepositoryMock new Fact public async Task ShouldReturnListOfNotes Arrange var httpClient factory WithAuthentication WithService gt notesRepositoryMock Object CreateAndConfigureClient var mockedNotes NotesMocks Notes notesRepositoryMock MockGetNotes mockedNotes Act var response await httpClient GetAsync notesBaseUrl ConfigureAwait false var notes await response Content ReadFromJsonAsync lt IEnumerable lt Note gt gt ConfigureAwait false Assert response StatusCode Should Be HttpStatusCode OK response Content Headers ContentType ToString Should ContainAll application json charset utf notes Should BeEquivalentTo mockedNotes Fact public async Task ShouldBeUnauthorized Arrange var httpClient factory WithService gt notesRepositoryMock Object CreateAndConfigureClient Act var response await httpClient GetAsync notesBaseUrl ConfigureAwait false Assert response StatusCode Should Be HttpStatusCode Unauthorized notesRepositoryMock Verify notes gt notes GetNotes Times Never Fact public async Task ShouldBeForbidden Arrange var httpClient factory WithAuthenticationWithoutClaims WithService gt notesRepositoryMock Object CreateAndConfigureClient Act Func lt Task gt getNotesTask async gt await httpClient GetAsync notesBaseUrl ConfigureAwait false Assert await getNotesTask Should ThrowAsync lt System Net Http HttpRequestException gt notesRepositoryMock Verify notes gt notes GetNotes Times Never Few things here we should note WebApplicationFactory ーfactory for bootstrapping an application in memory for functional and integration tests httpClient ーHTTP client created using WebApplicationFactory extensions for authentication and mocking services ーcode snippets are below notesRepositoryMock ーmocks for repository WebApplicationFactory boostraps in memory HTTP web server but for our scenario with authorization and authentication that s not enough cause we need to check proper and invalid unauthorized and unauthenticated requests to our API To cover it I ve added WithAuthentication and WithAuthenticationWithoutClaims extensions methods for factory public static class WebApplicationFactoryExtensions public static WebApplicationFactory lt T gt WithAuthentication lt T gt this WebApplicationFactory lt T gt factory where T class return AddAuthentication lt T TestAuthenticationHandler gt factory public static WebApplicationFactory lt T gt WithAuthenticationWithoutClaims lt T gt this WebApplicationFactory lt T gt factory where T class return AddAuthentication lt T TestAuthenticationHandlerWithoutClaims gt factory private static WebApplicationFactory lt T gt AddAuthentication lt T TAuthHandler gt this WebApplicationFactory lt T gt factory where T class where TAuthHandler TestAuthenticationHandlerBase return factory WithWebHostBuilder builder gt builder ConfigureTestServices services gt services AddAuthentication Test AddScheme lt AuthenticationSchemeOptions TAuthHandler gt Test options gt public static WebApplicationFactory lt TFactory gt WithService lt TFactory TService gt this WebApplicationFactory lt TFactory gt factory Func lt IServiceProvider TService gt implementationFactory where TService class where TFactory class return factory WithWebHostBuilder builder gt builder ConfigureTestServices services gt services AddTransient implementationFactory public static HttpClient CreateAndConfigureClient lt T gt this WebApplicationFactory lt T gt factory where T class var client factory CreateClient new WebApplicationFactoryClientOptions AllowAutoRedirect false client DefaultRequestHeaders Authorization new AuthenticationHeaderValue Test return client These methods use different AuthenticationHandlers TestAuthenticationHandler for proper authentication and TestAuthenticationHandlerWithoutClaims for user that does not have required claims The handlers are below public class TestAuthenticationHandler TestAuthenticationHandlerBase public TestAuthenticationHandler IOptionsMonitor lt AuthenticationSchemeOptions gt options ILoggerFactory logger UrlEncoder encoder ISystemClock clock base options logger encoder clock protected override Claim CreateClaims gt new new Claim ClaimTypes Name Test user new Claim ClaimTypes NameIdentifier Guid NewGuid ToString new Claim access as user and TestAuthenticationHandlerWithoutClaims looks like public class TestAuthenticationHandlerWithoutClaims TestAuthenticationHandlerBase public TestAuthenticationHandlerWithoutClaims IOptionsMonitor lt AuthenticationSchemeOptions gt options ILoggerFactory logger UrlEncoder encoder ISystemClock clock base options logger encoder clock protected override Claim CreateClaims gt new new Claim ClaimTypes Name Test user and TestAuthenticationHandlerBase is public abstract class TestAuthenticationHandlerBase AuthenticationHandler lt AuthenticationSchemeOptions gt protected TestAuthenticationHandlerBase IOptionsMonitor lt AuthenticationSchemeOptions gt options ILoggerFactory logger UrlEncoder encoder ISystemClock clock base options logger encoder clock protected abstract Claim CreateClaims protected override Task lt AuthenticateResult gt HandleAuthenticateAsync var claims CreateClaims var identity new ClaimsIdentity claims Test var principal new ClaimsPrincipal identity var ticket new AuthenticationTicket principal Test var result AuthenticateResult Success ticket return Task FromResult result here it is important in TestAuthenticationHandler to use claim type as “ for Azure AD access as user scope In the TestAuthenticationHandlerWithoutClaims we do not add required in NotesController access as user scope and in test case ShouldBeForbidden in NotesApiIntegrationTests we expect Forbidden response ShouldBeUnauthorized method does not configured to use any authentication handler thus we expect Unauthorized error and obviously no any interaction with notesRepository Arrangevar httpClient factory WithService gt notesRepositoryMock Object CreateAndConfigureClient Actvar response await httpClient GetAsync notesBaseUrl ConfigureAwait false Assertresponse StatusCode Should Be HttpStatusCode Unauthorized notesRepositoryMock Verify notes gt notes GetNotes Times Never SummaryHere I ve covered three basic auth scenarios for API requests of one GET method OK Unauthorized Forbidden From my experience it is important always to keep such tests in code and execute them during CI CD pipelines since it prevents us from accidental which unfortunately occurs often removal of Authorize or RequiredScope controller attributes Obviously in a real web apps integration testing scenarios more test needed e g validation tests BadRequest Server unexpected errors empty lists or NotFound for one entity ect In the post I d like to show how we use WebApplicationFactory to arrange integration tests for different authorization scenarios For testing and mocks I ve used xUnitMoqFluent AssertionsBogusFor mocking also I propose to use “Fluent Mocking like this public class NotesServiceMock Mock lt INotesService gt public NotesServiceMock MockGetNotes IEnumerable lt Note gt notes Setup service gt service GetNotes ReturnsAsync notes return this public NotesServiceMock MockGetNote string noteId Note note Setup service gt service GetNote It Is lt string gt i gt i noteId ReturnsAsync note return this public NotesServiceMock MockAddNote Note note note Id Guid NewGuid ToString Setup service gt service AddNote note ReturnsAsync note return this public NotesServiceMock MockModifyNote Note note Setup service gt service GetNote It Is lt string gt i gt i note Id ReturnsAsync note return this Thank you and pleasure coding |
2021-12-06 10:09:32 |
海外TECH |
DEV Community |
How to Become a UX/UI Designer |
https://dev.to/markfusion/how-to-become-a-uxui-designer-101i
|
How to Become a UX UI DesignerThis blog post will provide you with tips on how to become a UI UX designer UI stands for user interface and UX stands for user experience Designing is about understanding people s needs and wants so that the design process satisfies them You should have an eye for both UI and UX in order to be successful as a Designer This article includes information on how to get your foot in the door of this field what it takes to succeed helpful tools and more You also checkout my Behance Portfolio and see at my works UI Design Deals With How Things Looksuch as buttons and images UI is about making the user s interaction accessible and easy to use You should know what colors work well together or fonts that can be read easily on a website so people don t get frustrated when trying to navigate your site Good UI design makes it clear where you are located on a certain page and provides an intuitive flow within pages of content This takes practice but is one of the most important parts of the Design If people cannot figure out your UI they will leave immediately which means less users for you An example of UI would be when you go on Facebook see your friend s post in the top right corner with their name and picture next to it which tells you who posted something You then click on that person s profile where there are big buttons instead of small ones which makes them easier to find under their photo along with other useful information such as how many friends they have or if they re online line status etc This provides a UI that is clearly set up and easy to navigate UX Deals More With How Something Works Than Just Looks LikeThe goal of user experience is to create positive customer experiences by considering the user s perspective UX designers need to know what works and don t work for users so they can design accordingly UI Designers should have some knowledge about UX because it is important that everything flows smoothly together UI without UX will lead to a poor experience and vice versa An example of UX would be if you were using a new social media platform with no friends on it but see many ads about accounts people can follow or how someone s friend found this site through another link and the UI was not designed well at all This could lead to frustration as there may be more pop ups that make it hard for users to find what they re looking for within the app so they quickly leave which impacts your business success income from advertisements etc UX deals with the overall design UI deals with specific elements such as buttons or colors In order for Designers to succeed in their careers both UI and UX are key components necessary Learning UI will help you understand how to make things look good and learning UX will help you understand how something works and what might not work well for users Keep in mind that UI is more about looks while UX is more about functionality but they both play a role in the overall design of a product Some Helpful Tools To Start WithOnce you have some knowledge about UI and UX start playing around with these tools to create designs They are all very popular among designers and can be used to mock up websites or apps Having a strong portfolio will show employers that you re serious about becoming a Designer and gives them a glimpse into your skillset It s also important to have a Portfolio because UI and UX Designers need to have good visual design skills FigmaThe first tool I d want to discuss is Figma which is without a doubt the greatest solution for creating Web Design You can use it to create anything from complicated UI designs to prototypes and user testing The nice thing about Figma is that it offers a free plan which is ideal for novices Alright so with Figma you can do almost everything that you want starting from logo and ending with a complete design for a fully working website with different pages One of the coolest features in Figma is that it doesn t require any powerful computer in other words you don t need to have good hardware for working with it everything that you need is RAM however if you have the slowest PC on this planet it will run Figma anyway By the way you don t even need to download something you can use it easily in your browser on any device that you want and as I said it s absolutely free Also there re many alternatives like Sketch Adobe XD InVision Studio and many many others but personally I think that Figma is the best one Adobe Photoshop amp IllustratorPhotoshop and Illustrator are both industry standard tools used by many Graphic Designers They can be used for print layouts web designing photo editing and more However they can also be quite expensive but if you re serious about designing and want to be a UI UX designer they are worth the investment Both of these tools can help you create UI designs for websites or apps as well as UX mock ups and wireframes well Photoshop more I would definitely recommend learning one first before trying to learn both at once because it is quite complicated Illustrator is also a great option for creating Logo because of this vector graphic technologyYou can use Photoshop and Illustrator in combination with UI amp UX design tools like Adobe XD which is a great option for beginners Practice Practice and Again Practice The most important thing on the road to becoming a great UX UI designer is Practice You can ignore all other advice and concentrate only on Practicing and trust me the results will make you happy You can ask me Where can I get ideas for my designs and the answer will be simple You can go surf the internet a little bit and find services that you re personally using or some interesting websites ideas After that you should attempt to create the redesign for them yourself Of course you should not look for sites like Apple or YouTube because there is way too much information animations and other things that would be difficult for novices This technique is best used by someone who doesn t know where to find design ideas but the ideal approach is if you were working on your own project and creating a design from scratch It will teach you to utilize your creativity and build things from the ground up ConclusionIn conclusion UI and UX Designers need to have a number of skillsets to be successful in their careers These include visual design skills an understanding of user experience principles technical knowledge about UI standards and coding languages as well as other things The first step for becoming a UI UX Designer is creating your own Portfolio website so that you can showcase your UI designs and UX UI projects You should definitely upload all of the work to a portfolio website like Behance Medium or Dribble there are many others You need to make sure that your Portfolio is not only filled with UI designs but also contains some other types of UI such as wireframes sitemaps and prototypes After that the next step is to improve your skills by practicing and learning new techniques The best way to do this is by attempting to redesign sites apps that you are familiar with or finding inspiration from other sources Last but not least continue reading articles and watching videos on UI amp UX Also checkout my Behance portfolio |
2021-12-06 10:09:08 |
Apple |
AppleInsider - Frontpage News |
'Dickinson' creator talks time travel episode |
https://appleinsider.com/articles/21/12/06/dickinson-creator-talks-time-travel-episode?utm_medium=rss
|
x Dickinson x creator talks time travel episodeAlena Smith creator of Apple TV drama Dickinson reveals why the show featured Emily Dickinson travelling in time Chloe Fineman as Sylvia Plath Anna Baryshnikov as Lavinia Dickinson and Hailee Steinfeld as Emily DickinsonNever a straightforward drama and never a historical series too keen to stick to precise history Dickinson has nonetheless surprised viewers with its lead character travelling from around to Written by Alena Smith and named after Dickinson s The Future never spoke it sees the poet and her sister meeting Sylvia Plath Read more |
2021-12-06 10:41:22 |
海外TECH |
Engadget |
Google Photos 'Locked Folder' feature rolling out to non-Pixel smartphones |
https://www.engadget.com/google-photos-locked-folder-feature-coming-to-non-pixel-smartphones-101058384.html?src=rss
|
Google Photos x Locked Folder x feature rolling out to non Pixel smartphonesAs it promised Google Photos is starting to roll out the Locked Folder feature to Samsung and other non Pixel phones Sammobile has reported The idea is that it keeps your most private photos away from your primary image set and offline as well It has only been available on the Pixel or later devices until now but is now rolling out to older Pixel models too The Verge noted nbsp Locked Folder immediately got tagged as the quot nude storage folder quot by pundits when it first launched at Google IO in May Whether you have those or other sensitive photos it stores them in a passcode or biometric secured spot so kids friends or others won t accidentally stumble across them To use the feature simply launch Google Photos go to quot Library quot then the quot Utilities quot section at the top Click on that and the feature should appear in a card provided you have the update from around November th nbsp It worked just fine for me on Samsung Galaxy S and Galaxy Fold devices and Android Central reported that it has also appeared on Oppo and OnePlus devices If you decide to use it bear in mind that your photos won t be backed up to the cloud so they ll disappear if you delete Google Photos or wipe lose your smartphone Google has more information about the feature here nbsp |
2021-12-06 10:10:58 |
海外TECH |
CodeProject Latest Articles |
Windows Hook Keylogger |
https://www.codeproject.com/Articles/5319291/Windows-Hook-Keylogger
|
keylogger |
2021-12-06 10:36:00 |
医療系 |
医療介護 CBnews |
若者の4割弱が「コロナ禍いつまで続くのか不安」-東京都が繁華街訪問者の意識調査結果を公表 |
https://www.cbnews.jp/news/entry/20211206184048
|
意識調査 |
2021-12-06 19:05:00 |
金融 |
金融庁ホームページ |
入札公告等を更新しました。 |
https://www.fsa.go.jp/choutatu/choutatu_j/nyusatu_menu.html
|
公告 |
2021-12-06 11:00:00 |
海外ニュース |
Japan Times latest articles |
U.S. to declare diplomatic boycott of Beijing Olympics, CNN says |
https://www.japantimes.co.jp/news/2021/12/06/world/u-s-boycott-beijing-olympics/
|
U S to declare diplomatic boycott of Beijing Olympics CNN saysSuch a move by Washington would be largely symbolic as few U S officials are likely to visit China due to its strict quarantine rules and |
2021-12-06 19:35:52 |
海外ニュース |
Japan Times latest articles |
First case of Japanese national infected with omicron variant confirmed |
https://www.japantimes.co.jp/news/2021/12/06/national/japanese-third-omicron-case/
|
First case of Japanese national infected with omicron variant confirmedThe third domestic case of the heavily mutated strain of the coronavirus was detected in a fully vaccinated man in his s who had recently |
2021-12-06 19:33:36 |
ニュース |
BBC News - Home |
Aung San Suu Kyi: Myanmar court sentences ousted leader to four years jail |
https://www.bbc.co.uk/news/world-asia-59544484?at_medium=RSS&at_campaign=KARANGA
|
myanmar |
2021-12-06 10:13:46 |
ニュース |
BBC News - Home |
Drug strategy to tackle 300,000 problem users, says PM |
https://www.bbc.co.uk/news/uk-59540781?at_medium=RSS&at_campaign=KARANGA
|
strategy |
2021-12-06 10:38:32 |
ニュース |
BBC News - Home |
Joni Mitchell and Bette Midler pick up Kennedy Center Honors |
https://www.bbc.co.uk/news/entertainment-arts-59546478?at_medium=RSS&at_campaign=KARANGA
|
biden |
2021-12-06 10:33:10 |
ニュース |
BBC News - Home |
Gough named Yorkshire cricket managing director |
https://www.bbc.co.uk/sport/cricket/59545490?at_medium=RSS&at_campaign=KARANGA
|
interim |
2021-12-06 10:22:56 |
ニュース |
BBC News - Home |
Conor Benn wants to face winner of Amir Khan v Kell Brook |
https://www.bbc.co.uk/sport/boxing/59511521?at_medium=RSS&at_campaign=KARANGA
|
fight |
2021-12-06 10:16:59 |
ニュース |
BBC News - Home |
Omicron: What are the new Covid rules for travelling to the UK? |
https://www.bbc.co.uk/news/explainers-52544307?at_medium=RSS&at_campaign=KARANGA
|
arrival |
2021-12-06 10:13:25 |
ビジネス |
不景気.com |
北九州の印刷業「小川印刷」に破産開始決定、負債1億円 - 不景気.com |
https://www.fukeiki.com/2021/12/ogawa-printing.html
|
有限会社 |
2021-12-06 10:42:30 |
ビジネス |
不景気.com |
東京のアクセサリー販売「キャロット・ハウス落合」に破産決定 - 不景気.com |
https://www.fukeiki.com/2021/12/carrot-house-mostri.html
|
東京都足立区島根 |
2021-12-06 10:24:56 |
サブカルネタ |
ラーブロ |
らーめん 五ノ神精肉店 -煮干編-@あきる野市<限定・大群煮干肉中華> |
http://ra-blog.net/modules/rssc/single_feed.php?fid=194334
|
らーめん五ノ神精肉店煮干編あきる野市lt限定・大群煮干肉中華gt訪問日メニュー大群煮干肉中華味醤油コメント今日紹介するのは、東秋留駅や拝島駅から遠く離れた睦橋通り沿いにある「五ノ神精肉店」。 |
2021-12-06 10:05:37 |
北海道 |
北海道新聞 |
道内企業倒産、11月も低水準 年間最少を更新へ |
https://www.hokkaido-np.co.jp/article/619758/
|
帝国データバンク |
2021-12-06 19:15:00 |
北海道 |
北海道新聞 |
厚真の古民家、旧山口邸 来春飲食店に 地元食材使用、民泊も |
https://www.hokkaido-np.co.jp/article/619750/
|
東部地震 |
2021-12-06 19:14:00 |
北海道 |
北海道新聞 |
室蘭市長、病院再編協議凍結表明 統合実現困難に |
https://www.hokkaido-np.co.jp/article/619754/
|
協議凍結 |
2021-12-06 19:11:00 |
北海道 |
北海道新聞 |
3回目接種前倒し 首相が所信表明 臨時国会召集 |
https://www.hokkaido-np.co.jp/article/619753/
|
国会召集 |
2021-12-06 19:09:00 |
IT |
週刊アスキー |
国土交通省、携帯電話の位置情報データを活用した実証実験事業の実施対象を決定 |
https://weekly.ascii.jp/elem/000/004/077/4077261/
|
位置情報 |
2021-12-06 19:30:00 |
IT |
週刊アスキー |
カプコンのゲーム音楽やSteamキーを販売する公式サイト「イーカプコン デジタルストア」が本日オープン! |
https://weekly.ascii.jp/elem/000/004/077/4077262/
|
steam |
2021-12-06 19:30:00 |
IT |
週刊アスキー |
PS4『Virtua Fighter esports』にてDLC 第2弾『龍が如く』シリーズコラボパックが12月8日に配信決定! |
https://weekly.ascii.jp/elem/000/004/077/4077260/
|
playstation |
2021-12-06 19:25:00 |
マーケティング |
AdverTimes |
楽天、公取が優越的地位の濫用を指摘 「送料込み」対応改善へ |
https://www.advertimes.com/20211206/article370658/
|
優越的地位の濫用 |
2021-12-06 10:40:51 |
コメント
コメントを投稿