投稿時間:2021-05-15 05:25:09 RSSフィード2021-05-15 05:00 分まとめ(33件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… Android版「Apple Music」アプリの最新ベータ版からロスレスオーディオストリーミングに関する情報が見つかる https://taisy0.com/2021/05/15/140446.html applemusic 2021-05-14 19:31:01
IT 気になる、記になる… 「iMac Pro」に続き、「Magic Mouse」や「Magic Keyboard」のスペースグレイモデルも在庫限りで販売終了へ https://taisy0.com/2021/05/15/140450.html magickeybo 2021-05-14 19:19:22
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Javascriptの多次元配列からレコードを取り出せない(lengthが0になる) https://teratail.com/questions/338387?rss=all Javascriptの多次元配列からレコードを取り出せないlengthがになるJavascriptで、配列からデータを取り出そうとして躓きました。 2021-05-15 04:32:33
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) MySQLで時間の合計を算出したい https://teratail.com/questions/338386?rss=all MySQLで時間の合計を算出したい前提・実現したいことタスク管理APP作成中でMySQLで項目ごとの時間を合計を計算したい発生している問題・エラーメッセージこちらのサイトを参考にしながら時間を一度秒に直した上で計算できないか考えているのですがその中で、totaltimemiを元に計算しているのですが→→などとかなり謎な時間になってしまっております。 2021-05-15 04:24:06
AWS AWSタグが付けられた新着投稿 - Qiita 新しいmacを買ってから、AWS CLIにprofileを設定するまで https://qiita.com/okada-yuka/items/9b1d81e2b4d55e334bfa 新しいmacを買ってから、AWSCLIにprofileを設定するまではじめに新しいmacで何もしていない状態なので、Homebrewのインストールなど、すでに済んでいる場合は飛ばして進めてくださいPythonのセッティングHomebrewをインストールpyenvをインストールPATHを通すpyenvでPythonをインストールPythonのバージョンを変更Pythonのバージョンを確認AWSCLIのインストールインストーラをダウンロードzipを解凍インストールプログラムを実行AWSCLIのバージョンを確認AWSCLIにprofileを設定Pythonのセッティング現在年月日時点、AWSCLIの推奨環境はPythonの以降またはPythonの以降、そしてPythonのサポートは年月日までです。 2021-05-15 04:53:05
海外TECH DEV Community True Is Not Always True In JavaScript https://dev.to/bibekkakati/true-is-not-always-true-in-javascript-2n7m True Is Not Always True In JavaScriptHello everyoneIn this article I will try to explain the behaviour of the boolean data type of JavaScript We often use if statements in JavaScript to check if a value that can be of any data type is true or false But do you know that these values are not really true or false rather they are considered as truthy or falsy values ExplanationLet s understand this with an example var val blog if val console log true So in the above code snippet we declared a variable val which is storing a string blog In general if statements expect a boolean expression or a boolean condition but here we are passing the variable val directly without any boolean expression And this if statement evaluates the value of val to true and execute its block But why WhyIn JavaScript any non zero number including the negative numbers and non empty strings are termed as truthy values and the truthy values are translated to boolean true when evaluated in a Boolean context So in our example as the value of the variable val is a string with data i e not empty it is considered as a truthy value which evaluates to true in the if statement condition And the values other than the truthy values are termed as falsy values falsy values in JavaScript falsenullundefinedNAN n ConversionConvert the truthy and falsy values to boolean true or false You can pass the truthy or falsy value to the Boolean and it will return true or false var val blog if Boolean val console log true Or you can use the following syntax to convert it to a pure boolean value var val blog if val console log true We know this truthy or falsy concept is not so impacting but it is always better to handle pure boolean values Originally published on blog bibekkakati meThank you for reading If you enjoyed this article or found it helpful give it a thumbs up Feel free to connect Twitter Instagram LinkedInIf you like my work and want to support it you can do it here I will really appreciate it 2021-05-14 19:40:08
海外TECH DEV Community DevSecOps -Automate & Secure https://dev.to/sidbhanushali/devsecops-automate-secure-5ae4 DevSecOps Automate amp SecureDevSecOps is the practice of integrating a security first mindset and methodologies into traditional DevOps CI CD environments Here are key best practices for organizations seeking to implement DevSecOps Being able to get code out the door fast secure and efficiently is the name of the game In a CI CD environment it s important to maintain speed as the main tenet but also to be aware of the security needed to bulk up your pipeline Without automation implementing security practices could be a major bottleneck in the pipeline and wouldn t be considered a priority for many organizations that rely on speed For security to be part of this workflow it needs to be automated for it to be considered a relevant factor in an environment that prioritizes speed Security controls and tests need to be embedded early and everywhere in the development lifecycle and they need to happen in an automated fashion because the culture of software deployment is changing rapidly Some organizations are pushing new versions of code into production almost times per day for a single app Not only this but adding automated security analysis within CI platforms can limit the introduction of vulnerable code earlier in the software development lifecycle However trying to run automated scans on your entire application source code each day can consume a lot of time and break your ability to keep up with daily changes One option is to run scans against recent or new code changes A growing number of test automation tools with a range of capabilities have become available for doing security analysis and testing throughout the software development lifecycle from source code analysis through integration and post deployment monitoring For example nmap and Metasploit which are tools to monitor servers and networks for vulnerabilities or known exploits can be integrated into said automation Cron JobsHowever all this depends on the type and frequency of the task to be automated There are certain tasks that need to run on an interval basis such as backing up databases updating the system performing periodic reboots and so on Such tasks in Linux are referred to as cron jobs Cron jobs are used for the automation of tasks to help in simplifying the execution of repetitive and sometimes mundane tasks Cron is a daemon that allows you to schedule these jobs which are then carried out at specified intervals A crontab file also known as a cron table is a simple text file that contains rules or commands that specify the time interval of execution of a task It hosts a set of rules that are analyzed and performed by the cron daemon The system crontab file is located at etc crontab and can only be accessed and edited by the root user The crontab file looks like so The basic syntax for a crontab file comprises columns represented by asterisks followed by the command to be carried out This format can also be represented as shown below minute hour day month day of week directory command outputThe first five fields in the command represent numbers that define when and how often the command runs A space separates each position which represents a specific value Lets see how to apply this to a linux systemTo create or edit a cron job as the root user run the command crontab eAll cron jobs being with a shebang header as shown bin bashThis indicates the shell you are using which for this case is bash shell Next specify the interval at which you want to schedule the tasks using the cron job format For example let s say we wanted to run a backup script every month when the system isn t actively in use root backup shThe command runs the first of every month at am Cron Jobs is a useful tool built into Linux systems that can automate specific tasks or scripts However Jenkins is a much more comprihenisve automation build tool that is more commonly used in the lifecycle Lets see how we can impliment best practices when using Jenkins Securing JenkinsAnother all in one automation tool is jenkins jenkins is an open source automation server It helps automate the parts of software development related to building testing and deploying facilitating continuous integration and continuous delivery Jenkins is an all in one tool to integrate automation into every stage of the CI CD process Since jenkins is a server based tool it is important to secure the Jenkins instance and have proper handling of users and credentials within it Jenkins does not come preconfigured with default security checks When creating users in Jenkins it s important to differentiate the access control that each user has Another important thing is to be mindful of the credentials and where they are stored Using Jenkins credentials provider users can bind their credentials to variables and use them in their jenkinsfile as to not expose sensitive data Here is an example of a credentials screen in jenkins that will impliment credentails binding Securing Linux ServersThe heart of any pipeline is a linux system Since Cron Jobs need a linux system to function on it s important to consider the security of the linux systems themselves that will be in charge of automation Securing the linux system itself is a critical step in DevSecOps Disable Root Login The first step in securing the system is securing the way people even log into the system to begin with Disabling root login is essential to strengthen your server security This is because keeping root login enabled can present a security risk and diminish the safety of small business cloud resources hosted on the server as hackers can exploit this credential to access the server Instead create a new user account and assign elevated sudo permissions so that you will still have a way of installing packages and performing other admin actions on the server User logins through Public Private key pairs One suggestion is to use good password hygiene meaning having a decent mix of numbers letters and special characters to prevent from password cracking However this can get messy to enforce and passwords can ultimately be cracked using large amounts of computing power A more secure way to grant access is through the use of public private key pairs for users generate on their local machine their keypair using ssh keygen t rsa Then they need to put the contents of their public key id rsa pub into ssh authorized keys on the server being logged into Key Rotation and or Configure Factor Authentication It is important to keep changing the private public key pairs as well as any other passwords or credentials needed to access a machine to prevent keys or passwords from being leaked Factor Authentication can be used in conjunction with SSH Secure Shell to enforce the requirement for a second credential when logging into the server To set up FA on a Debian server and Debian derived distributions you should install the libpam google authenticator package The package can display a QR code or produce a secret token that can be added to a software authentication device such as Google Authenticator Server Side antivirus IDS External software and programs for secuirty and defense should always be an extra layer not the only layer Many routers or firewalls will oftentimes have a preconfigured instance of an Antivirus IDS or some form of it The disadvantage to this is that it puts the burden on one sole piece of hardware If a phishing email with a malicious payload is slipped through the cracks then an IDS system that simply monitors the external perimeter is not much help Once someone is in they can make as much noise as they want since all the guards are patrolling the outside A solution to this could be a standalone IDS that sits on the internal network as part of a layered defense providing visibility within the network and around the important assets and internal files It can be configured to protect sensitive data without interfering with legitimate network traffic Disk encryption you can secure your data by configuring disk encryption to encrypt whole disks including removable media partitions as well as any other files There are many methods that can be used to achieve this One universal way to do this on all Linux systems is to install the cryptsetup package As always make sure root user login is disabled only users with advanced sudo privileges Volume level disk encryption helps protect users and customers from Data Theft or even accidental loss Encrypted hard disks make it very hard for hackers to gain access or read any sort of data on that hard disk Securing ECIn most cases the linux instance that will be running the automation would be running on a cloud compute instance lets say EC for example One benefit of using an EC is the diversity and flexibility it offers A tradeoff of this can be security There are steps that can be taken to secure an EC instance Security GroupsSecurity groups are the fundamental network security of AWS They control how inbound and outbound traffic is allowed into the EC Machine These control the opening and closing of network ports to allow for different protocols or servers to run on For example since the Jenkins servers default port is port you have to expose the port in the security group You can run Jenkins on a different port however that must be exposed as well VPC Controlling the network traffic to your EC instance is crutial to maintain its secuirty Configure your VPC and use private subnets for your instances if they should not be accessed directly from the internet A VPC is your own network in the cloud For example in each region there are availability zones A VPC is a private network within an AWS region and it would span all the availability zones physical centers in the region Subnets are sub networks inside the VPC span a single availability zone and are logical subdivisions of an IP network The practice of dividing a network into two or more networks is called subnetting AWS provides two types of subnetting one is Public which allows the internet to access the machine and another is private which is hidden from the internet Subnets could be compared to the different rooms in your apartment They are containers within your VPC that segment off a slice of the CIDR block you define in your VPC CIDR notation is a compact representation of an IP address and its associated network mask For example represents the IP address is the network prefix or equivalently its subnet mask Subnets allow you to give different access rules and place resources in different containers where those rules should apply You wouldn t have a big open window in your bathroom on the shower wall so people can see sensitive things much like you wouldn t put a database with secretive information in a public subnet allowing any and all network traffic You might put that database in a private subnet i e a locked closet Anything from outside of the VPC could connect to a public subnet but only containers inside a VPC can access a private subnet IAM Another sure proof way to manage the security of your EC Instance is through IAM IAM Is where users can manage their credentials By using IAM with Amazon EC you can control whether users in your organization can perform a task using specific Amazon EC instances It s important to lock away your access keys and consider them important numbers as if they were credit cards or social security numbers Similarly you wouldn t have one social security number for every user therefore you would not have one credential as a root user it s important to create individual users and grant them the least amount of permissions as needed Policy actions are classified as List Read Write Permissions management or Tagging For example you can choose actions from the List and Read access levels to grant read only access to your users 2021-05-14 19:36:26
海外TECH DEV Community Grokking Free Monads https://dev.to/choc13/grokking-free-monads-9jd Grokking Free MonadsIn this post I m going to try and demystify free monads and show you that they re not some strange abstract creature but in fact can be very useful for solving certain problems Rather than focusing on the theory our aim here will be to get a solid intuition about free monads you ll then find learning the theory much easier So in keeping with the rest of this series we ll discover the free monad ourselves by solving a real software problem Pre requisitesI try to keep these posts as independent from each other as possible but in this case there s not much getting around the fact that you re probably going to need to have already grokked monads If you haven t yet done so then have a browse through Grokking Monads and once you re done you ll be all set to continue here The ScenarioLet s say we work at an e commerce store and we need to implement a chargeUser function This function should take a UserId and an amount It should lookup the user s profile to get hold of the credit card then it should charge the user s card the specified amount If the user has an email address it should send them a receipt type EmailAddress EmailAddress of stringtype Email To EmailAddress option Body string type CreditCard Number string Expiry string Cvv string type TransactionId TransactionId of stringtype UserId UserId of stringtype User Id UserId CreditCard CreditCard EmailAddress EmailAddress let chargeUser amount float userId UserId TransactionId TODO Implement this as part of the domain modelOur main aim in this post is to be able to write the chargeUser function in our domain model By domain model we re referring to the very thing we re writing our program for in the first place In this case as we re an e commerce store that means our domain model includes things like user profiles products and orders Typically when we write our application we want to keep our domain model completely decoupled from any infrastructure or application layer code because those things are the incidental complexity that we have to solve Our domain model should be pure and abstract in the sense that if we were to use a different database or a different cloud provider the domain model should be unaffected It s easy to write types in our domain layer to represent the objects in the model without introducing any unwanted coupling but what about the functions like chargeUser On the one hand we know it s going to need to call external services so does that mean we should define it outside of the domain model where we have access to the database etc On the other hand it s not uncommon to want to take decisions in functions like this such as whether or not we should email the user a receipt and that logic definitely feels like domain logic that we d want to test independent of the database Functions as dataThere are several ways to make domain operations pure and agnostic to any infrastructure concerns We ve touched on one before in Grokking the Reader Monad One interesting way to do it though is to treat functions as if they were data What do we mean by functions as data The best way to understand this is to see some code Let s take the chargeUser function and write a data model to describe the operations it needs to perform type ChargeUserOperations LookupUser of UserId gt User ChargeCreditCard of float gt CreditCard gt TransactionId EmailReceipt of Email gt unit We ve created a type called ChargeUserOperations that has a case for each of the operations we want to perform as part of chargeUser Each case is parameterised by the function signature that we want it to have So instead of being functions that we call we ve just got some abstract data representing the functions that we want to invoke and we d like to use it like so let chargeUser amount userId TransactionId let user LookupUser userId let transactionId ChargeCreditCard amount user CreditCard match user EmailAddress with Some emailAddress gt let email To emailAddress Body TransactionId transactionId EmailReceipt email return transactionId None gt return transactionIdObviously this isn t going to work We can t simply write LookupUser userId and assign that to something of type User For starters LookupUser is expecting a function as an argument not a UserId This idea of functions as data is an interesting one though so let s see if we can find a way to make it work It doesn t really make sense to try and extract a return value from data All we can really do with data is create it So what about if we instead created each operation with another operation nested inside it kind of like a callback that would take the output of the current computation and produce a new output Something like this type ChargeUserOperation LookupUser of UserId User gt ChargeUserOperation ChargeCreditCard of float CreditCard TransactionId gt ChargeUserOperation EmailReceipt of Email unit gt ChargeUserOperation We ve made a couple of changes here Firstly each operation is now parameterised by a tuple instead of a function We can think of the tuple as the list of arguments to the function Secondly the final argument in the tuple is our callback What that s saying is that when you create an operation you should tell it which operation you d like to perform next that needs the result of this one Let s give this new format a try let chargeUser amount float userId UserId TransactionId LookupUser userId fun user gt ChargeCreditCard amount user CreditCard fun transactionId gt match user EmailAddress with Some emailAddress gt EmailReceipt To emailAddress Body TransactionId transactionId fun gt Hmmm how do we get out of this None gt Hmmm how do we get out of this Ok it s getting better We can see that this data structure is capturing the abstract logic of what the chargeUser function needs to do without actually depending on any particular implementation The only snag is we don t have a way to return a value at the end Each of our operations has been defined such that it needs to be passed another callback so how do we signal that we should actually just return a value What we need is a case in ChargeUserOperation that doesn t require a callback one that just returns a value Let s call it Return We also need to make ChargeUserOperation generic on the return type to encapsulate the fact that each operation returns some value but that the values returned by each operation might differ type ChargeUserOperation lt next gt LookupUser of UserId User gt ChargeUserOperation lt next gt ChargeCreditCard of float CreditCard TransactionId gt ChargeUserOperation lt next gt EmailReceipt of Email unit gt ChargeUserOperation lt next gt Return of nextWe ve chosen the name next for the generic parameter to signify the fact that it s the value returned by the next computation in the chain In the case of Return then it s just immediately returned We re now finally in a position to write chargeUser let chargeUser amount float userId UserId ChargeUserOperation lt TransactionId gt LookupUser userId fun user gt ChargeCreditCard amount user CreditCard fun transactionId gt match user EmailAddress with Some emailAddress gt EmailReceipt To emailAddress Body TransactionId transactionId fun gt Return transactionId None gt Return transactionId That s it We ve captured the logic of chargeUser in a completely abstract data structure We know that it s got no dependence on any infrastructure because we fabricated it purely out of data types We ve taken our domain modelling to the next level by modelling its computations as data too One thing to note is that chargeUser now returns ChargeUserOperation lt TransactionId gt This might seem weird but we can think of it this way chargeUser is now a function that produces a data structure which represents the the domain operation of charging and user and returning the TransactionId If you ve grokked it this far then you ve made the fundamental mental leap the fact that we re just representing a computation as data The rest of this post is just going to be dedicated to cleaning this up to make it easier to read and write chargeUser Things might get a bit abstract but just keep in mind the fact that all we re doing is trying to build this data structure to represent our computation Flattening the pyramid One problem with chargeUser in its current form is that we re back in nested callback hell a k a the Pyramid of Doom We already know that monads are useful at flattening nested computations so let s see if we can make ChargeUserOperation a monad The recipe for making something a monad is to implement bind for that type We start by defining the types for the function signature and use that to guide us In this case the signature is a gt ChargeUserOperation lt b gt gt ChargeUserOperation lt a gt gt ChargeUserOperation lt b gt So we re going to have to unwrap the ChargeUserOperation to get at the value a and then apply that the to the function we ve been passed to generate a ChargeUserOperation lt b gt Let s get stuck in let bind f a gt ChargeUserOperation lt b gt a ChargeUserOperation lt a gt match a with LookupUser userId next gt ChargeCreditCard amount card next gt EmailReceipt unit next gt Return x gt f xAs usual we ve used a pattern match to unwrap the ChargeUserOperation in order to get at the inner value In the case of Return it s a straight forward case of just calling f on the value x But what about for those other operations We don t have a value of type a to hand so how can we invoke f Well what we do have to hand is next which is capable of producing a new ChargeUserOperation when supplied with a value So what we can do is call that and recursively pass this new ChargeUserOperation to bind The idea being that by recursively calling bind we ll eventually hit the Return case at which point we can successfully extract the value and call f on it module ChargeUserOperation let rec bind f a gt ChargeUserOperation lt b gt a ChargeUserOperation lt a gt match a with LookupUser userId next gt LookupUser userId fun user gt bind f next user ChargeCreditCard amount card next gt ChargeCreditCard amount card fun transactionId gt bind f next transactionId EmailReceipt email next gt EmailReceipt email fun gt bind f next Return x gt f xThis might be a bit mind bending but another way to view it is that we re just doing exactly the same callback nesting that we were forced to do by hand when we previously wrote chargeUser Except now we ve hidden the act of nesting these operations inside the bind function Each call to bind introduces another layer of nesting and pushes the Return down inside this new layer For example if we had written LookupUser userId Return gt bind fun user gt ChargeCreditCard amount user CreditCard Return it would be equivalent to writing it in nested form like LookupUser userId fun user gt ChargeCreditCard amount user CreditCard Return With that we can easily write a computation expression called chargeUserOperation and use it to flatten that pyramid in chargeUser type ChargeUserOperationBuilder member Bind a f ChargeUserOperation bind f a member x Combine a b x Bind a fun gt b member Return x Return x member ReturnFrom x x member Zero Return let chargeUserOperation ChargeUserOperationBuilder let chargeUser amount float userId UserId chargeUserOperation let user LookupUser userId Return let transactionId ChargeCreditCard amount user CreditCard Return match user EmailAddress with Some emailAddress gt let email To emailAddress Body TransactionId transactionId do EmailReceipt email Return return transactionId None gt return transactionId If do is unfamiliar then it s basically just let except it ignores the result Which we don t care about when sending them email because it returns unit anyway Making data look like functions 🥸The function is looking pretty nice now but it s perhaps a bit unnatural to have to write LookupUser userId Return instead of just lookupUser userId It s also a bit annoying to have to constantly keep writing Return as the final argument to the ChargeUserOperation case constructors Well it s easy to fix that we can just write a smart constructor for each case that hides that detail away let lookupUser userId LookupUser userId Return let chargeCreditCard amount card ChargeCreditCard amount card Return let emailReceipt email EmailReceipt email Return let chargeUser amount float userId UserId chargeUserWorkflow let user lookupUser userId let transactionId chargeCreditCard amount user CreditCard match user EmailAdress with Some emailAddress gt do emailReceipt To emailAddress Body TransactionId transactionId return transactionId None gt return transactionId Nice Now the function perfectly expresses the logic of our operation It looks just like a regular monadic function except under the hood it s actually building up an abstract data structure that represents our desired computation rather than invoking any real calls to real infrastructure Factoring out a functorOur chargeUser function is looking pretty good now but there s some optimisations we can make to the definition of ChargeUserOperation Let s consider what would happen if we wanted to write a different computation We d have to write a data type with a case for each operation we want to support plus a case for Return and then finally implement bind for it Wouldn t it be nice if we could implement bind once for any computation type Let s take a look at the definition of bind for ChargeUserOperation again and see if we can refactor it to something a bit more generic let rec bind f a gt ChargeUserOperation lt b gt a ChargeUserOperation lt a gt match a with LookupUser userId next gt LookupUser userId fun user gt bind f next user ChargeCreditCard amount card next gt ChargeCreditCard amount card fun transactionId gt bind f next transactionId EmailReceipt email next gt EmailReceipt email fun gt bind f next Return x gt f xIf we mandate that each operation must be of the form Operation of inputs output gt Operation lt next gt then they only differ by parameter types which we could make generic How should we do this for ChargeCreditCard though because that currently has two inputs Well we can combine the inputs into a single tuple like this ChargeCreditCard of float CreditCard TransactionId gt ChargeUserOperation lt next gt The form of bind for each operation is now identical specifically it is Operation inputs next gt Operation inputs fun output gt bind f next output So really we actually only have two cases to consider either it s an Operation or it s a Return So let s create a type called Computation that encapsulates that type Computation lt op next gt Operation of op Return of nextWhich we can write bind for to turn it into a monad let rec inline bind f a gt Computation lt op b gt a Computation lt op a gt match a with Operation op gt Operation op gt map bind f Return x gt f xThe trick to making this work in the Operation case is to note that we require each Operation to be mappable That is we require it to be a functor Mapping an operation is just a case of applying the function to the return value to transform it into something else So by recursively calling bind f as we did when writing for this ChargeUserOperation we eventually hit the Return case get access to the return value and just apply the current op to it by calling map So now when we re writing our operations we ve reduced the task from having to implement bind to instead having to implement map which is an easier task For example we can express ChargeUserOperation like this type ChargeUserOperation lt next gt LookupUser of UserId User gt next ChargeCreditCard of float CreditCard TransactionId gt next EmailReceipt of Email unit gt next static member Map op f match op with LookupUser x next gt LookupUser x next gt gt f ChargeCreditCard x next gt ChargeCreditCard x next gt gt f EmailReceipt x next gt EmailReceipt x next gt gt f Unfortunately we can t eliminate any more boilerplate beyond here in F In other languages like Haskell it is possible to automatically derive the Map function for the operation functors but in F using FSharpPlus the best we can do today is write the static member Map ourselves FSharpPlus then provides us the map function which will automatically pick the correct one by calling this static member Map when mapping an instance of ChargeUserOperation through the use of statically resolved type parameters We just have one final change to make to the smart constructors Now that ChargeUserOperation is now just a functor we need to lift them up into the Computation monad by wrapping them in an Operation let inline lookupUser userId LookupUser userId Return gt Operationlet chargeCreditCard amount card ChargeCreditCard amount card Return gt Operationlet emailReceipt email EmailReceipt email Return gt Operationlet chargeUser amount float userId UserId computation let user lookupUser userId let transactionId chargeCreditCard amount user CreditCard match user EmailAddress with Some emailAddress gt do emailReceipt To emailAddress Body TransactionId transactionId return transactionId None gt return transactionId You just discovered the Free Monad The data type we called Computation is usually called Free the Operation case is often called Roll and the Return case is often called Pure Other than that though we ve discovered the basis of the free monad It s just a data type and associated bind function that fundamentally describes sequential computations If you re a C developer and you re familiar with LINQ then this might seem familiar to you LINQ provides a way to build up a computation and defer its evaluation until sometime later It s what allows LINQ to run in different environments such as in a DB because people are able to write interprets for it that turn the LINQ statements into SQL etc on the database server Should I use free monads You might be wondering whether to use free monads in F in your project On the one hand they provide an excellent means of abstraction when it comes to defining computations in a domain model They re also a joy to test because we can just interpret them as pure data and verify that for a given set of inputs we have produced the right data structure and hence computation no more mocking Another plus is that with free monads we ve actually achieved what object oriented programmers would call the interface segregation principle Each computation only has access to the operations it needs to do its work No more injecting wide interfaces into domain handlers and then having to write tests that verify we didn t call the wrong operation it s literally impossible under this design On the other hand it seems to be pushing F to the limits as it technically requires features like higher kinded types which F doesn t technically support So we have to resort to making heavy use of statically resolved type parameters to make it work You might also find them to be quite abstract although I hope that this post has at least helped to make their usage seem more intuitive even if the internal implementation is still quite abstract On balance I don t think there s a one size fits all answer here You re going to have to weigh up the pros and cons for your project and team and decide whether this level of purity is worth it in order to warrant overcoming the initial learning curve and potentially cryptic compiler errors when things don t line up If you re thinking of taking the plunge and giving them a try then I would recommend using FSharpPlus which has done all the hard work of defining the free monad machinery for you Also see the appendix at the end for a full example using FSharpPlus What did we learn ‍The name free monad might be cryptic and even misleading at first but the concept is relatively straight forward Free monads are just a data structure that represents a chain of computations that should be run sequentially By building a data structure we re able to leave it up to someone else to come along and interpret it in anyway they see fit They re “free to do it how they need to providing they respect the ordering of the computations in the data structure we have handed to them A free monad is just a way for us to describe our computation in very abstract terms We re placing the fewest restrictions possible on what the computation has to do and making no assumptions about how it should be done We ve completely decoupled the what from the how which is one of the fundamental pillars of good Domain Driven Design because it means that the domain model is a pure abstract representation of the problem at hand unburdened by the details of how it is hosted Next time We ve covered a lot in this post but we haven t talked about how we actually go about running these computations So far we ve just built some abstract representations of them in data Next time we ll see how we can actually interpret them to do some real work AppendixIf you want to see a complete top to bottom example of writing a free monadic workflow using FSharpPlus then I ve included one in the section below type ChargeUserOperation lt next gt LookupUser of UserId User gt next ChargeCreditCard of float CreditCard TransactionId gt next EmailReceipt of TransactionId TransactionId gt next static member Map op f match op with LookupUser x next gt LookupUser x next gt gt f ChargeCreditCard x next gt ChargeCreditCard x next gt gt f EmailReceipt x next gt EmailReceipt x next gt gt f let lookupUser userId LookupUser userId id gt Free liftFlet chargeCreditCard amount card ChargeCreditCard amount card id gt Free liftFlet emailReceipt email EmailReceipt email id gt Free liftFlet chargeUser amount float userId UserId monad let user lookupUser userId let transactionId chargeCreditCard amount user CreditCard match user EmailAddress with Some emailAddress gt do emailReceipt To emailAddress Body TransactionId transactionId return transactionId None gt return transactionId When writing the smart constructors here e g lookUser we pass the identity function id as the second argument The reason for this is because Free liftF maps the functor with Pure and then lifts it up with Roll So by using id and then writing Free liftF we end up with the desired Roll LookupUser userId Pure The other way to think of id here is that in the callback we re just going to return the value produced by this computation and not do anything else 2021-05-14 19:33:19
Apple AppleInsider - Frontpage News Space Gray Magic accessories listed as sold 'while supplies last' https://appleinsider.com/articles/21/05/14/space-gray-magic-accessories-listed-as-sold-while-supplies-last?utm_medium=rss Space Gray Magic accessories listed as sold x while supplies last x Tied to the now discontinued iMac Pro the Space Gray Magic Keyboard Mouse and Trackpad are showing while supplies last in Apple Store The Space Gray Magic accessories are being sold while supplies last When Apple released the iMac Pro it came with Space Gray accessories to match Now it appears as if Apple will discontinue the accessories along with the already discontinued iMac Pro Read more 2021-05-14 19:24:01
Apple AppleInsider - Frontpage News Apple Music for Android beta hints at lossless quality streaming https://appleinsider.com/articles/21/05/14/apple-music-for-android-beta-hints-at-lossless-quality-streaming?utm_medium=rss Apple Music for Android beta hints at lossless quality streamingCode within the latest beta version of Apple Music for Android corroborates rumors that lossless streaming might be coming soon to the platform Credit TechCrunchA report from earlier in May suggested that a high fidelity streaming option was in the works for Apple Music The option is rumored to provide higher quality audio streaming to users who pay an extra monthly fee Read more 2021-05-14 19:05:03
海外TECH Engadget California governor proposes $7 billion investment in public broadband https://www.engadget.com/california-public-broadband-infrastructure-7-billion-budget-proposal-193016903.html broadbandnewsom 2021-05-14 19:30:16
海外科学 NYT > Science How the United States Beat the Coronavirus Variants, for Now https://www.nytimes.com/2021/05/14/health/coronavirus-variants-united-states-of-america.html scientists 2021-05-14 19:01:31
海外科学 NYT > Science Biden Administration to Repeal Trump Rule Aimed at Curbing E.P.A.’s Power https://www.nytimes.com/2021/05/13/climate/EPA-cost-benefit-pollution.html clean 2021-05-14 19:49:45
金融 生命保険おすすめ比較ニュースアンテナ waiwainews 腎臓結石での給付金請求 http://seiho.waiwainews.net/view/12381 newsallrightsreserved 2021-05-15 04:46:40
海外ニュース Japan Times latest articles Time running out for Japanese prosecutors in ‘Don Juan’ murder case https://www.japantimes.co.jp/news/2021/05/14/national/crime-legal/don-juan-time-limit/ Time running out for Japanese prosecutors in Don Juan murder caseWhile police say they have circumstantial evidence against Saki Sudo no witnesses have come forward and there is an apparent lack of clear evidence 2021-05-15 04:26:24
海外ニュース Japan Times latest articles Suga Cabinet support rate falls to record 32.2% in Jiji poll https://www.japantimes.co.jp/news/2021/05/14/national/suga-cabinet-record-low/ coronavirus 2021-05-15 04:05:04
海外ニュース Japan Times latest articles Ozeki Terunofuji continues to shine under spotlight at Summer Basho https://www.japantimes.co.jp/sports/2021/05/14/sumo/basho-reports/terunofuji-continues-to-shine/ september 2021-05-15 04:12:12
ニュース BBC News - Home Covid: Indian variant could disrupt 21 June easing, PM says https://www.bbc.co.uk/news/uk-57122817 covid 2021-05-14 19:46:46
ニュース BBC News - Home Israel Gaza violence: Clashes spread to West Bank https://www.bbc.co.uk/news/world-middle-east-57123933 bankpalestinians 2021-05-14 19:00:49
ニュース BBC News - Home Martin Bashir: BBC religion editor leaves the corporation https://www.bbc.co.uk/news/entertainment-arts-57120603 health 2021-05-14 19:30:22
ビジネス ダイヤモンド・オンライン - 新着記事 ドンキとユニー、3月売上高のコロナ前比較でグループ企業2社に格差の理由 - コロナで明暗!【月次版】業界天気図 https://diamond.jp/articles/-/268846 前年同期 2021-05-15 04:55:00
ビジネス ダイヤモンド・オンライン - 新着記事 ライフ、マルエツ…コロナ特需に沸いた食品スーパーが「総崩れ」したワケ - コロナで明暗!【月次版】業界天気図 https://diamond.jp/articles/-/268847 前年同期 2021-05-15 04:50:00
ビジネス ダイヤモンド・オンライン - 新着記事 ビジネスマンこそ「絵画・芸術を鑑賞」すべき、2つの理由 - 小宮一慶の週末経営塾 https://diamond.jp/articles/-/270995 ビジネスマンこそ「絵画・芸術を鑑賞」すべき、つの理由小宮一慶の週末経営塾箱根の仙石原にあるポーラ美術館では、月日までレオナール・フジタ藤田嗣治の企画展「フジター色彩への旅」を開催しています。 2021-05-15 04:45:00
ビジネス ダイヤモンド・オンライン - 新着記事 韓国メディアで評価急落、「日本のコロナ対策」はどう報じられているのか - 元駐韓大使・武藤正敏の「韓国ウォッチ」 https://diamond.jp/articles/-/271113 韓国メディアで評価急落、「日本のコロナ対策」はどう報じられているのか元駐韓大使・武藤正敏の「韓国ウォッチ」韓国は日本のことを強く意識しており、日本に負けたくないという気持ちが強い。 2021-05-15 04:40:00
ビジネス ダイヤモンド・オンライン - 新着記事 飲食店で不快な接客を受けたときの対処法、評価される「低評価」の書き方 - 井の中の宴 武藤弘樹 https://diamond.jp/articles/-/270817 飲食店 2021-05-15 04:35:00
ビジネス ダイヤモンド・オンライン - 新着記事 プロ野球「自主退団」物語、育成選手の自信喪失からスキャンダルまで - from AERAdot. https://diamond.jp/articles/-/270679 fromaeradot 2021-05-15 04:30:00
ビジネス ダイヤモンド・オンライン - 新着記事 日本で限定わずか5台!?サーキット仕様の「BMW M5 CS」、そのお値段は? - 男のオフビジネス https://diamond.jp/articles/-/270691 限定 2021-05-15 04:25:00
ビジネス ダイヤモンド・オンライン - 新着記事 領有権争う2国が互いに土地を押しつけあう因果な事情とは? - おもしろ雑学 世界地図のすごい読み方 https://diamond.jp/articles/-/270341 世界地図 2021-05-15 04:20:00
ビジネス ダイヤモンド・オンライン - 新着記事 商品ブームで資源国に追い風、10年前の記憶再び - WSJ発 https://diamond.jp/articles/-/271262 追い風 2021-05-15 04:19:00
ビジネス ダイヤモンド・オンライン - 新着記事 瀬戸内海のサワラや生しらす、アナゴがうまい!淡路島旅の魅力 - 地球の歩き方ニュース&レポート https://diamond.jp/articles/-/270593 瀬戸内海のサワラや生しらす、アナゴがうまい淡路島旅の魅力地球の歩き方ニュースレポート瀬戸内の島々のなかでも最大の島・淡路島。 2021-05-15 04:15:00
ビジネス ダイヤモンド・オンライン - 新着記事 黒人喫煙者の約85%が使用するメンソールタバコが米国で禁止される方針 - ヘルスデーニュース https://diamond.jp/articles/-/271034 黒人 2021-05-15 04:10:00
ビジネス ダイヤモンド・オンライン - 新着記事 ひろゆきが自分のYouTube動画で「ビール」を飲んでいる意外な理由 - 1%の努力 https://diamond.jp/articles/-/270720 youtube 2021-05-15 04:05:00
ビジネス 東洋経済オンライン 保存めぐり注目「高輪築堤」が持つ歴史的価値 国内初の鉄道の遺構、日本近代化の生き証人 | 駅・再開発 | 東洋経済オンライン https://toyokeizai.net/articles/-/428343?utm_source=rss&utm_medium=http&utm_campaign=link_back 品川開発プロジェクト 2021-05-15 04:30:00

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

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

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