投稿時間:2021-07-09 00:34:29 RSSフィード2021-07-09 00:00 分まとめ(45件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT 気になる、記になる… 「Google Pixel 5a」がFCCを通過 https://taisy0.com/2021/07/08/142819.html google 2021-07-08 14:51:10
IT 気になる、記になる… 「Surface Duo 2」は今年9〜10月に発売か − 「Surface Duo」向けの「Android 11」アップデートも同時期に?? https://taisy0.com/2021/07/08/142816.html androi 2021-07-08 14:43:07
IT 気になる、記になる… 「iPhone 13」シリーズ用ケースの様々な検証写真 https://taisy0.com/2021/07/08/142810.html iphone 2021-07-08 14:27:36
AWS AWS Compute Blog Developing evolutionary architecture with AWS Lambda https://aws.amazon.com/blogs/compute/developing-evolutionary-architecture-with-aws-lambda/ Developing evolutionary architecture with AWS LambdaThis post shows how you can evolve a workload using hexagonal architecture It explains how to add new functionality change underlying infrastructure or port the code base between different compute solutions The main characteristics enabling this are loose coupling and strong encapsulation 2021-07-08 14:48:24
python Pythonタグが付けられた新着投稿 - Qiita 残プロ 第-37回 ~pythonでコンソールに画像を表示する~ https://qiita.com/R1nY1x1/items/a1ffba791f74987a868d 2021-07-08 23:53:00
python Pythonタグが付けられた新着投稿 - Qiita Pythonの日付date https://qiita.com/fastso/items/2f4a2edeabeed381a083 fromdatetimeimporttimedeltaddatetdtimedeltadaysprintdtd出力dateを文字列に変換するdateをISOフォーマットの文字列に変換する場合、isoformatメソッドを使用します。 2021-07-08 23:29:02
python Pythonタグが付けられた新着投稿 - Qiita python で c++ の関数拡張を作る https://qiita.com/tmiwa3030/items/1c4a8db8476117925a08 2021-07-08 23:09:00
js JavaScriptタグが付けられた新着投稿 - Qiita 【React】Warning: validateDOMNesting(...): <h2> cannot appear as a child of <h2>.【JavaScript】 https://qiita.com/GalaxyNeko/items/1e4cbbf7c44ab9890727 翻訳すると、「警告validateDOMNestinglthgtはlthgtの子として表示できません」と翻訳されましたWarningvalidateDOMNestinglthgtcannotappearasachildoflthgt該当のソースは以下です。 2021-07-08 23:50:44
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Mobile Ads SDK をインポートする時のiosプロジェクトとはなんですか? https://teratail.com/questions/348478?rss=all adsnbspsdknbsp 2021-07-08 23:59:20
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) MySQLとGoogleデータポータルを連携したいです https://teratail.com/questions/348477?rss=all MySQLとGoogleデータポータルを連携したいです初心者級の質問で恐縮です。 2021-07-08 23:58:37
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) python 株データのデータ型について https://teratail.com/questions/348476?rss=all python株データのデータ型についてstooqから株価データを取得し、infoメソッドでデータ型を確認したのですが、同じデータのはずなのに、なぜdftrainのVolumeはfloat型で、dftestのVolumeはint型なのでしょうか…。 2021-07-08 23:56:51
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) SQL における否定形の表現 https://teratail.com/questions/348475?rss=all access 2021-07-08 23:41:42
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Unity キャラクターに重力を与えると倒れてしまう https://teratail.com/questions/348474?rss=all Unityキャラクターに重力を与えると倒れてしまうCharacterControllerで移動、cinemachineを使いカメラの挙動を取っています。 2021-07-08 23:40:46
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) 微分方程式を解きたいが、初期値を設定できない https://teratail.com/questions/348473?rss=all 2021-07-08 23:38:36
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) UNITYのMeshのMaterialをスタート時にランダムで決定するやり方を教えてください。 https://teratail.com/questions/348472?rss=all UNITYのMeshのMaterialをスタート時にランダムで決定するやり方を教えてください。 2021-07-08 23:34:09
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) sqlのXORとORの違いを確認したいです。 https://teratail.com/questions/348471?rss=all 現状リファレンスを見た限り、XORは排他的論理和ということで片方のみの条件が一致していれば真ということだったのですが、ORとの違いとして「条件が両方一致したときに真になるのがOR。 2021-07-08 23:32:39
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) pandasのデータフレームでの差分の計算方法 https://teratail.com/questions/348470?rss=all pandasのデータフレームでの差分の計算方法今データフレームの差分の取り方について行き詰っています。 2021-07-08 23:05:49
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) Intelli j IDEA でJSONを使おうとしたが「シンボルなし」となる https://teratail.com/questions/348469?rss=all IntellijIDEAでJSONを使おうとしたが「シンボルなし」となる環境windowsnbspIntellinbspJnbspIdeaPlayframeworknbsp系やりたいことPlayframeworkにて、KeepanbspAPIへリクエストを出したいです。 2021-07-08 23:03:09
Program [全てのタグ]の新着質問一覧|teratail(テラテイル) レスポンシブルサイトのスクロールが場合によってきかない https://teratail.com/questions/348468?rss=all レスポンシブルサイトのスクロールが場合によってきかない前提・実現したいことレスポンシブルサイトでメニューバーを固定して内容をスクロールさせたいです。 2021-07-08 23:02:51
GCP gcpタグが付けられた新着投稿 - Qiita Google Cloud アップデート (7/1-7/7 2021) https://qiita.com/kenzkenz/items/0d502102f98501641871 GoogleCloudアップデートCloudSQLJunMySQLinnodbflushlogattrxcommitflagをサポートするようになったよDataflowJunGPUのサポートがGAになったよSecretManagerJunCloudAssetInventoryで分析するガイドを追加したよCloudArmorJun事前定義されたWAFルールでPOSTbodyのJSNをパースできるのがGAになったよVPCJunGoogleがサービスプロデューサのprivateservicesaccessconnection例えばCloudSQLとかを消すと、不要となる設定も一緒に消すのがGAになったよRFC以外のアドレスをPrivateServiceconnectendpointsで利用する際のビリングの問題を修正したよOperationsSuiteJunCloudLoggingLoggingbucketからCloudStoragebucketにコピーする機能がプレビューになったよLoggingとmetricsを統合したOpsAgentのがGAになったよCloudMonitoringダッシュボードにサンプルのダッシュボードが追加されたよAppEngineJunデプロイ時に各バージョンでユーザが管理するサービスアカウントを使える機能がプレビューになったよCronのリクエストがこれまでのからから来るようになったよ。 2021-07-08 23:48:59
技術ブログ Developers.IO AWSBackupでリストア動作失敗になったときの対処方法 https://dev.classmethod.jp/articles/atsnote-awsbackup-restore-jobs-failed/ awsbackup 2021-07-08 14:09:04
技術ブログ Developers.IO AWS WAFのロギング設定で”aws-waf-logs-“から始まる以外の配信ストリームを指定可能とする方法はあるのか確認してみた https://dev.classmethod.jp/articles/i-checked-if-there-is-a-way-to-specify-a-delivery-stream-other-than-starting-with-aws-waf-logs-in-the-aws-waf-logging-configuration/ awswaf 2021-07-08 14:05:16
海外TECH DEV Community Variables https://dev.to/eduardojuliao/variables-3bb1 VariablesA variable is a value that can change in your program Creating a variableThe structure to create a variable consists of lt Data Type gt lt Name gt lt Value gt Data TypeTells the program what type of variable it is these can be int decimal string char and others NameA unique name to identify it ValueThe value of the variable Some examplesint i decimal d float f double d string s string char c c boolean b true byte bt Notice that a string is defined by using doble quotes while a char is defined by using single quotes Array variablesWe can also create a variable type that is the array type these variables are a list of values of a certain type Once an array is created you can update its values re assign but not extend its size Creating an array lt Data Type gt name new or lt Data Type gt name new lt Data Type gt lt number of entries gt Arrays are defined by adding after the data type and can be assigned using one of the two forms Form lt Data Type gt lt Name gt new lt value gt lt valiue gt In this example you create an array that has a length of int arrayOfIntegers new In this form you don t need to specify the Form lt Data Type gt lt Name gt new lt Data Type gt lt number of entries gt In this example you create an array that has a length of int arrayOfIntegers new int When creating an array in this form the array will have entries and all set to its default value which in this case is Assigning valuesYou can assign values to an array by using its index which starts at and ends with its length arrayOfIntegers arrayOfIntegers arrayOfIntegers arrayOfIntegers ConstantsYou can create variables that cannot change after being initialized These types of variables are called constants Structureconst lt Data Type gt lt Name gt lt Value gt Exampleconst int constantIntegerValue 2021-07-08 14:49:47
海外TECH DEV Community Running Jaeger Locally: How to Get Started https://dev.to/aspecto/running-jaeger-locally-how-to-get-started-51g3 Running Jaeger Locally How to Get StartedIn this article you ll learn how to run Jaeger locally why and when you should do it as well as what are Jaeger s limitations when running locally Let s start with the basics a distributed tracing system is generally composed of client and backend components I will touch briefly on client components though most of this post is about backend components Client ComponentsThe client part is usually a set of libraries installed inside an application which “instrument it ーgenerating a “span object for each interesting event happening in runtime inside the service A modern and recommended open source client SDK that does that is OpenTelemetry Spans on the client alone are meaningless ーthey need to be accessible to a person who consumes them Consumers are usually dev ops teams monitoring a system or developers maintaining the system and adding new features Trace UsagesThere are many ways in which collected trace data can be used and provide value These are the common ones Aggregate spans to trace ーgroup all spans events which are part of the same trace logical operation arriving from different distributed services into a single entityQuery the collected data show me all traces in the last hour starting at endpoint GET users in service X Visualize the data ーusually in a graph or timelineFind errors exceptions s etc and investigate their root causeInvestigate performance bottlenecks Backend ComponentsTo fulfill the requirements above we need to set up backend components They are used to collect spans from client components process them store them in a database expose an API for the data and UI to view traces and perform queries Jaeger a CNCF graduated project is a popular open source project with backend components that does that and is easy to set up To use Jaeger in production it is recommended to install it in a cloud environment with load balancing auto scaling replications and all that jazz However it is sometimes enough to just run it locally in a lightweight and simple setup Running LocallyThe recommended approach for running Jaeger backend locally is to use docker docker run d name jaeger e COLLECTOR ZIPKIN HOST PORT p udp p udp p udp p p p p p jaegertracing all in one And access the UI in http localhost You can then configure an Opentelemetry Client SDK installation or OpenTelemetry Collector to use Jaeger exporter and send trace data to this local Jaeger import NodeTracerProvider from opentelemetry node import SimpleSpanProcessor from opentelemetry tracing import JaegerExporter from opentelemetry exporter jaeger const provider new NodeTracerProvider provider addSpanProcessor new SimpleSpanProcessor new JaegerExporter provider register This is how exporting data to local jaeger looks like in nodejs Running Local Jaeger Benefits Faster DebuggingIf you work on a service codebase e g fixing a bug developing a new feature or implementing integration to other services databases messaging systems etc most likely that this is what you do You start an instance of the service on your local dev stationSend traffic to it to test your changesValidate the behavior you were expectingBy instrumenting it locally you can debug development issues faster For example find the point in your app where an error occurred with less logging to console breakpoints etc An example of a trace in Jaeger showing error while accessing Redis key as a list the red underlines are not part of the Jaeger UI Running TestsWhen running your integration test suite locally ーif a test fails it can sometimes be easier to understand what went wrong by examining it in Jaeger UI where you can view highlighted errors and events organized into a hierarchical structure Instrumentation DevelopmentIf you are writing a new instrumentation library observing the tracing output in a UI can be much easier than browsing through textual logs You can browse the JS instrumentation package for more info and examples Running Local Jager LimitationsJaeger is free relatively easy to set up and will do a good job for most basic setups and tracing needs The UI and features set are quite basic and you may quickly find yourself in the need of more advanced features Other alternatives can give value and increase development productivity in the following cases Lack of End to End Visibility in Async MessagingWhen using async messaging systems generally there are two cases for traces The first one is when the message broker generates one trace Jaeger does a great job of displaying us with that one trace The second case common in batch processing scenarios is when the senders and receivers in message brokers like Kafka and AWS SQS generate multiple traces for example each receive starts a new trace In this case Jaeger will display these traces separately That makes it more complicated to track and debug complex transactions More advanced backends might have an out of the box solution for that and will detect it and merge those traces into a single logical flow Cross Environment TracesIf your organization works with Jaeger in production and let s say you want to use Jaeger to do your tests sending your local traces to the production Jaeger is highly suboptimal Not only can it pollute the production environment but it makes it difficult to find your traces within this trace jungle By running Jaeger locally you get an isolated playground for your tests and development However one major pitfall in this scenario is that your local Jaeger will show only the part of the trace generated from your local dev station It means you lose the context of how your traces communicate and affect downstream and upstream services i e production and staging In this case you won t have an isolated and local development session while seeing the full effect of your changes across the different environments Advanced SearchFree text search on all data or based on trace attributes For example if you want to search a token in the payload within specific traces Trace Data Processing and InsightsJaeger presents raw traces and highlights errors however generating insights based only on that data isn t trivial and quite complex Examples for such insights can be API breaking change detection aggregation of traces based on structure parameter journey in a trace dependency analysis comparison to baseline from production or staging etc Enhanced UIJaeger UI enumerates all attributes for a span in a long list It does not group or organizes related data show JSON content in a tree highlight common data like HTTP status code and other good stuff that makes our life easier The Bottom LineRunning local Jaeger offers great benefits It is easy to set up and when it comes to faster debug and running tests you get this extra confidence you might want when working locally Jaeger is a great tool and does an awesome job answering your basic tracing needs However when your work with services gets a bit more complex or when you want to take your productivity to the next level when working locally you might want to consider other alternatives If the limitations I mentioned above are a deal breaker for you if not now they might be in the future there are several vendors in the market supplying various solutions which enhance your tracing based workflow One that can help you overcome all these issues is Aspecto Aspecto gives you everything you get with Jaeger but with enhanced UI search and troubleshooting capabilities for local development and debugging It takes minutes to get started with it s free and OpenTelemetry based Think of it as Jaeger and Chrome DevTools fusion for your distributed applications 2021-07-08 14:33:22
海外TECH DEV Community Typeclasses in Python https://dev.to/wemake-services/typeclasses-in-python-3ma6 Typeclasses in PythonOriginally published in my blog Today I am going to introduce a new concept for Python developers typeclasses It is a concept behind our new dry python library called classes I will tell you in advance that it will look very familiar to what you already know and possibly even use Moreover we reuse a lot of existing code from Python s standard library So you can call this approach native and pythonic And it is still going to be interesting I am showing examples in different languages But before discussing typeclasses themselves let s discuss what problem they do solve Some functions must behave differentlyOk this one is a familiar problem to all of the devs out there How can we write a function that will behave differently for different types Let s create an example We want to greet different types differently yes hello world examples here we go We want to greet str instances as Hello string content MyUser instances as Hello again username Note that greet as a simple example does not really make much business sense but more complicated things like to json from json to sql from sql and to binary do make a lot of sense and can be found in almost any project But for the sake of implementation simplicity I m going to stick to our greet example The first approach that comes to our minds is to use isinstance checks inside the function itself And it can work in some cases The only requirement is that we must know all the types we will work with in advance Here s how it would look like dataclassclass MyUser object name strdef greet instance str MyUser gt str if isinstance instance str return Hello format instance elif isinstance instance MyUser return Hello again format instance name raise NotImplementedError Cannot greet type format type instance The main limitation is that we cannot extend this function for other type easily we can use wrapper function but I consiser this a redefinition But in some cases isinstance won t be enough because we need extendability We need to support other types which are unknown in advance Our users might need to greet their custom types And that s the part where things begin to get interesting All programming languages address this problem differently Let s start with Python s traditional OOP approach OOP extendability and over abstraction problemsSo how does Python solve this problem We all know that Python has magic methods for some builtin functions like len and len it solves exactly the same problem Let s say we want to greet a user dataclassclass MyUser object name str def greet self gt str return Hello again format self name You can use this method directly or you can create a helper with typing Protocol from typing extensions import Protocolclass CanGreet Protocol def greet self gt str It will match any object that has the greet method Mypy will also check that greet must return str def greet instance CanGreet gt str return instance greet And then we can use it print greet MyUser name example Hello again exampleSo it works Not really There are several problems First some classes do not want to know some details about themselves to maintain abstraction integrity For example class Person object def become friends self friend Person gt None def is friend of self person Person gt bool def get pets self gt Sequence Pet Does this Person pun intended deserve to know that some to json conversion exists that can turn this poor Person into textual data What about binary pickling Of course not these details should not be added to a business level abstraction this is called a leaky abstraction when you do otherwise Moreover I think that mixing structure and behavior into a single abstraction is bad Why Because you cannot tell in advance what behavior you would need from a given structure For abstractions on this level it is way easier to have behavior near the structure not inside it Mixing these two only makes sense when we work on a higher level like services or processes Second it only works for custom types Existing types are hard to extend For example how would you add the greet method to the str type You can create str subtype with greet method in it class MyStr str def greet self gt str return Hello format self But this would require a change in our usage print greet MyStr world Hello world print greet world fails with TypeError Monkey patchingSome might suggest that we can just insert the needed methods directly into an object type Some dynamically typed languages went on this path JavaScript in s and early s mostly popularized by jQuery plugins and Ruby still happening right now Here s how it looks String prototype greet function string return Hello string It is quite obvious that it is not going to work for anything complex Why Different parts of your program might use monkey patching of methods with the same name but with different functionality And nothing will workIt is hard to read because the original source does not contain the patched method and the patching location might be hidden deeply in other filesIt is hard to type for example mypy does not support it at allPython community is not used to this style it would be rather hard to persuade them to write their code like this and that s a good thing I hope that it is clear we won t fall into this trap Let s consider another alternative Extra abstractionsPeople familiar with things like django rest framework might recommend to add special abstractions to greet different types import abcfrom typing import Generic TypeVar Wrapped TypeVar Wrapped class BaseGreet Generic Wrapped Abstract class of all other def init self wrapped Wrapped gt None self wrapped wrapped abc abstractmethod def greet self gt str raise NotImplementedErrorclass StrGreet BaseGreet str Wrapped instance of built in type str def greet self gt str return Hello format self wrapped Our custom type dataclassclass MyUser object name strclass MyUserGreet BaseGreet MyUser def greet self gt str return Hello again format self wrapped name And we can use it like so print greet MyStrGreet world Hello world print greet MyUserGreet MyUser name example Hello again exampleBut now we have a different problem we have a gap between real types and their wrappers There s no easy way to wrap a type into its wrapper How can we match them We have to do it either by hand or use some kind of registry like Dict type Type BaseGreet And it is still not enough there will be runtime errors In practice it ends up like lt X gt is not json serializable as many of us might have seen it with drf s serializers when trying to serialize a custom unregistered type Typeclasses and similar conceptsLet s look at how functional languages and Rust people still argue whether it is functional or not handle this problem Some common knowledge All these languages don t have class concept as we know it in Python and of course there s no subclassingAll the languages below don t have objects as we do in Python they don t mix behavior and structure however Elixir has Alan Kay s real objects Instead these languages use ad hoc polymorphism to make functions behave differently for different types via overloadingAnd of course you don t have to know any of the languages below to understand what is going on ElixirLet s start with one of my favorites Elixir has Protocols to achieve what we want doc Our custom protocol defprotocol Greet do This is an abstract function that will behave differently for each type def greet data end doc Enhancing built in type defimpl Greet for BitString do def greet string do Hello string end doc Custom data type defmodule MyUser do defstruct name end doc Enhancing our own type defimpl Greet for MyUser do def greet user do Hello again user name endI am pretty sure that my readers were able to read and understand Elixir even if they are not familiar with this language That s what I call beauty Usage of the code above Using our Greet greet function with both our data types IO puts Greet greet world Hello world IO puts Greet greet MyUser name example Hello again exampleThe thing with Elixir s Protocols is that it is not currently possible to express that some type does support our Greet greet for Elixir s type checker But this is not a big deal for Elixir which is dynamically typed Protocols are very widely used they power lots of the language s features Here are some real life examples Enumerable allows to work with collections counting elements finding members reducing and slicingString Chars is something like str in Python it converts structures to human readable format RustRust has Traits The concept is pretty similar to Protocols in Elixir Our custom traittrait Greet fn greet amp self gt String Enhancing built in typeimpl Greet for String fn greet amp self gt String return format Hello amp self Defining our own typestruct MyUser name String Enhancing itimpl Greet for MyUser fn greet amp self gt String return format Hello again self name And of course due to Rust s static typing we can express that some function s argument supports the trait we have just defined We can express that greet function only accepts types that implement Greet trait fn greet instance amp dyn Greet gt String return instance greet pub fn main Using our greet function with both our data types println greet amp world to string Hello world println greet amp MyUser name example to string Hello again example See The idea is so similar that it uses almost the same syntax as Elixir Notable real life examples of how Rust uses its Traits Copy and Clone duplicating objectsDebug to show better repr of an object again like str in PythonBasically Traits are the core of this language it is widely used in cases when you need to define any shared behavior HaskellHaskell has typeclasses to do almost the same thing So what s a typeclass Typeclass is a group of types all of which satisfy some common contract It is also a form of ad hoc polymorphism that is mostly used for overloading I am a bit sorry for the Haskell syntax below it might be not very pleasant and clear to read especially for people who are not familiar with this brilliant language but we have what we have LANGUAGE FlexibleInstances Our custom typeclassclass Greet instance where greet instance gt String Enhancing built in type with itinstance Greet String where greet str Hello str Defining our own typedata MyUser MyUser name String Enhancing itinstance Greet MyUser where greet user Hello again name user Basically we do the same thing as we have already done for Rust and Elixir We define a Greet typeclass that has a single function to implement greetThen we define instance implementation for String type which is a built in alias for Char Then we define custom MyUser type with name field of String typeImplementing the Greet typeclass for MyUser is the last thing we doThen we can use our new greet function Here you can see that we can use Greet typeclass to annotate our types I have made this alias entirely for this annotation demo in real life we would just use greet directly greetAlias Greet instance gt instance gt StringgreetAlias greetmain do print greetAlias world Hello world print greetAlias MyUser name example Hello again exampleSome real life examples of typeclasses Show to convert things into user readable representationsFunctor Applicate and Monad are all typeclassesI would say that among our three examples Haskell relies on its typeclasses the heaviest It is important to note that typeclasses from Haskell and traits from Rust are a bit different but we won t go into these details to keep this article rather short But what about Python dry python classesThere s an awesome function in the Python standard library called singledispatch It does exactly what we need Do you still remember that we are finding a way to change the function s behavior based on the input type Let s have a look from functools import singledispatch singledispatchdef greet instance gt str Default case raise NotImplementedError greet registerdef greet str instance str gt str return Hello format instance Custom type dataclassclass MyUser object name str greet registerdef greet myuser instance MyUser gt str return Hello again format instance name Looks cool moreover it is in standard lib you even don t have to install anything And we can use it like a normal function print greet world Hello world print greet MyUser name example Hello again exampleSo what s the point in writing a completely different library like we did with dry python classes We even reuse some parts of singledispatch implementation but there are several key differences Better typingWith singledispatch you cannot be sure that everything will work because it is not supported by mypy For example you can pass unsupported types greet mypy is ok with that runtime will raise NotImplementedError In dry python classes we have fixed that You can only pass types that are supported from classes import typeclass typeclassdef greet instance gt str greet instance str def greet str instance str gt str return Iterable greet Argument to greet has incompatible type int expected str Or you can break the singledispatch signature contract greet registerdef greet dict instance dict key str gt int return instance key still no mypy errorBut not with dry python classes greet instance dict def greet dict instance dict key str gt int Instance callback is incompatible def instance builtins dict Any Any key builtins str gt builtins int expected def instance builtins dict Any Any gt builtins str singledispatch also does not allow defining generic functions singledispatchdef copy instance X gt X Default case raise NotImplementedError copy registerdef copy int instance int gt int return instance Argument to register of SingleDispatchCallable has incompatible type Callable int int expected Callable X reveal type copy Revealed type is X Should be int Which is again possible with dry python classes we fully support generic functions from typing import TypeVarfrom classes import typeclassX TypeVar X typeclassdef copy instance X gt X copy instance int def copy int instance int gt int okreveal type copy intAnd you cannot restrict singledispatch to work with only subtypes of specific types even if you want to Protocols are unsupportedProtocols are an important part of Python Sadly they are not supported by singledispatch greet registerdef greet iterable instance Iterable gt str return Iterable TypeError Invalid annotation for instance typing Iterable is not a classProtocols support is also solved with dry python classes from typing import Iterablefrom classes import typeclass typeclassdef greet instance gt str greet instance Iterable is protocol True def greet str instance Iterable gt str return Iterable print greet Iterable No way to annotate typesLet s say you want to write a function and annotate one of its arguments that it must support the greet function Something like def greet and print instance gt None print greet instance It is impossible with singledispatch But you can do it with dry python classes from classes import AssociatedType Supports typeclassclass Greet AssociatedType Special type to represent that some instance can greet typeclass Greet def greet instance gt str No implementation needed greet instance str def greet str instance str gt str return Hello format instance def greet and print instance Supports Greet gt None print greet instance greet and print world okgreet and print type error with mypy exception in runtime Argument to greet and print has incompatible type int expected Supports Greet ConclusionWe have come a long way from basic stacked isinstance conditions through OOP to typeclasses I have shown that this native and pythonic idea deserves wider recognition and usage And our extra features in dry python classes can save you from lots of mistakes and help to write more expressive and safe business logic As a result of using typeclasses you will untangle your structures from behavior which will allow you to get rid of useless and complex abstractions and write dead simple typesafe code You will have your behavior near the structures not inside them This will also solve the extendability problem of OOP Combine it with other dry python libraries for extra effect Future workWhat do we plan for the future There are several key aspects to improve Our Supports should take any amount of type arguments Supports A B C This type will represent a type that supports all three typeclasses A B and C at the same timeWe don t support concrete generics just yet So for example it is impossible to define different cases for List int and List str This might require adding runtime typecheker to dry python classesI am planning to make tests a part of this app as well We will ship a hypothesis plugin to test users typeclasses in a single line of codeStay tuned If you like this article you can Donate to future dry python development on GitHubStar our classes repoSubscribe to my blog for more content 2021-07-08 14:17:23
海外TECH DEV Community Empty List placeholder. SwiftUI https://dev.to/toni777772/empty-list-placeholder-swiftui-4b7e Empty List placeholder SwiftUIYear twenty twenty one Almost a month has passed since the WWDC As usual Apple presented many amazing features updates As expected updated SwiftUI framework But did not add placeholder for List view It s not big deal but it was one of my expectations from conference Okay let s do it ourselves The List is one of the most used view in apps When using the List devs also must handle the state of an empty data range and show a placeholder As an example consider a simple list of countries Show placeholder when data is empty Country model struct Country Identifiable let id UUID let name String So have any ideas on how to implement a placeholder First idea If elseThe first thing that comes to mind it s if else conditional statement struct ContentView View State var countries Country Data source var body some View if countries isEmpty Text No Countries Placeholder font largeTitle else List countries country in List countires Text country name font title Advantages the most simple and clear wayeasy to modify it works and shows the placeholder when neededeasy to use any view for placeholder Disadvantages the code looks cumbersomenot reusableIt works and sometimes it s enough But in production it would be nice to have a component that implements the logic of displaying a placeholder inside the component So goes to the next idea Second idea EmptyListImprove if else idea and move logic show hide placeholder to custom view call it EmptyList struct EmptyList lt Items RandomAccessCollection ListRowView View PlaceholderView View gt View where Items Element Identifiable private let items Items private let listRowView Items Element gt ListRowView private let placeholderView gt PlaceholderView Parameters items Source data for List Item must implement Identifiable protocol listRowView View displayed for each source Item placeholderView Placeholder View displayed when the items collection isEmpty init items Items ViewBuilder listRowView escaping Items Element gt ListRowView ViewBuilder placeholderView escaping gt PlaceholderView self items items self listRowView listRowView self placeholderView placeholderView var body some View if items isEmpty List List countires ForEach items item in self listRowView item else placeholderView Using the EmptyList is very easy First parameter data source second parameter list row view and finally third parameter placeholder view struct ContentView View State var countries Country Data source var body some View EmptyList countries Data items listRowView country in List row view Text country name font title placeholderView Text No Countries Placeholder font largeTitle Advantages code looks clean and clear easy to modify custom viewreusable in projectuse any view for placeholder Disadvantages list is embedded in EmptyList view and if want to add some ViewModifier s to the list need for more efforts and modify codeUsually I would have to say that this is all and say goodbye but is not all I want to share an idea of how I cook placeholder for lists in my projects Preferred idea ViewModifierCreate custom ViewModifier to manage placeholder call it EmptyDataModifier struct EmptyDataModifier lt Placeholder View gt ViewModifier let items Any let placeholder Placeholder ViewBuilder func body content Content gt some View if items isEmpty content else placeholder Uses EmptyDataModifier struct ContentView View State var countries Country Data source var body some View List countries country in Text country name font title modifier EmptyDataModifier items countries placeholder Text No Countries font title Placeholder That s it Also via extension can little bit improve the solution and limited apply EmptyDataModifier only for List extension List func emptyListPlaceholder items Any placeholder AnyView gt some View modifier EmptyDataModifier items items placeholder placeholder struct ContentView View State var countries Country Data source var body some View List countries country in Text country name font title emptyListPlaceholder countries AnyView ListPlaceholderView Placeholder Advantages code look clean and clear no need to create a custom List vieweasy to modifyreusable in projectuse any view for placeholder this way for can be used for any view placeholder Disadvantages no subjective opinion Instead of summaryIn my opinion the most suitable way to implement a placeholder is to use a custom ViewModifier I m sure sooner or later the Apple will add a placeholder for the List view Maybe this article will be as a request for this feature for Apple Who knows Source code Thanks for reading See you soon 2021-07-08 14:15:32
海外TECH DEV Community Diving Into DevSecOps (Part 2) w/ John Willis https://dev.to/linearb/diving-into-devsecops-part-2-w-john-willis-4ig3 Diving Into DevSecOps Part w John WillisThe second and final interview with John Willis on the Dev Interrupted podcast John Willis is a legendary DevOps speaker mentor and author of The DevOps Handbook In this special part DevSecOps series John takes us on a DevSecOps journey from the origin of the term all the way to how software developers at the team level can implement the practice Listen to the full episode Episode Highlights include What DevSecOps means at the team levelFirst steps for implementing DevSecOps strategies at your organizationWhy it s critical to start thinking about security more holisticallyThe difference between Security Compliance Governance amp RiskWhat is coming next for software development security Join the Dev Interrupted Discord ServerWith over members the Dev Interrupted Discord Community is the best place for Engineering Leaders to engage in daily conversation No sales people allowed Join the community gt gt 2021-07-08 14:11:19
Apple AppleInsider - Frontpage News Apple partners with the BBC to bring '9/11: Inside the President's War Room' https://appleinsider.com/articles/21/07/08/apple-partners-with-the-bbc-to-bring-911-inside-the-presidents-war-room?utm_medium=rss Apple partners with the BBC to bring x Inside the President x s War Room x Apple announces a new documentary Inside the President s War Room to be released on BBC One and Apple TV in September Inside the President s War Room covers the attack years laterThe documentary special will tell the story of through the eyes of the presidency in the hours after the attack It will be narrated by Jeff Daniels and provide unique insight into the dilemmas of those involved through first hand accounts Read more 2021-07-08 14:30:31
海外TECH Engadget Twitter's extended NFL deal adds live Spaces chats with players https://www.engadget.com/twitter-nfl-partnership-extension-144939988.html?src=rss Twitter x s extended NFL deal adds live Spaces chats with playersTwitter has once again renewed its deal with the NFL and this time there s more than just video shows and Moments to keep football fans happy The newly announced multi year extension includes a commitment to produce over live Spaces audio chats for the season You ll hear players and quot other NFL talent quot discuss regular season matches as well as major events like the draft and Super Bowl The new agreement also includes new highlights and more polls You can also expect familiar experiences that include on the field coverage and Moments This could be welcome news if you want to follow football on Twitter in between games not just during or after matches It may be particularly important for Twitter too This is the social network s first sports league of any kind to produce sponsored Spaces ーthe feature just got significant boosts to both its credibility and revenue It also helps Twitter compete against Clubhouse which unveiled its NFL deal in April Don t be surprised if Twitter rushes to land Spaces deals with other leagues especially if Clubhouse becomes more of a threat 2021-07-08 14:49:39
海外科学 NYT > Science Pfizer Vaccine in Israel: How It Works Against Delta Variant https://www.nytimes.com/2021/07/06/science/Israel-Pfizer-covid-vaccine.html delta 2021-07-08 14:38:51
金融 RSS FILE - 日本証券業協会 株券等貸借取引状況(週間) https://www.jsda.or.jp/shiryoshitsu/toukei/kabu-taiw/index.html 貸借 2021-07-08 15:30:00
海外ニュース Japan Times latest articles Olympics to bar fans in Tokyo area under new COVID-19 emergency https://www.japantimes.co.jp/news/2021/07/08/national/new-tokyo-virus-emergency/ decision 2021-07-08 23:24:22
ニュース BBC News - Home Covid-19: Amber list quarantine for fully vaccinated to end on 19 July https://www.bbc.co.uk/news/uk-57763173 amber 2021-07-08 14:26:41
ニュース BBC News - Home Tokyo Olympic Games: Spectators barred as state of emergency announced https://www.bbc.co.uk/news/world-asia-57760883 covid 2021-07-08 14:02:32
ニュース BBC News - Home Covid in Scotland: Nicola Sturgeon says surge in cases may be levelling off https://www.bbc.co.uk/news/uk-scotland-scotland-politics-57764863 sturgeon 2021-07-08 14:04:35
ニュース BBC News - Home Afghanistan: Most British troops have left - PM https://www.bbc.co.uk/news/uk-57746335 afghanistan 2021-07-08 14:34:13
ニュース BBC News - Home Contraceptive mini pill can be sold over the counter in UK https://www.bbc.co.uk/news/health-57384096 regulator 2021-07-08 14:38:09
ニュース BBC News - Home Barty beats Kerber to reach first Wimbledon final https://www.bbc.co.uk/sport/tennis/57766276 angelique 2021-07-08 14:40:27
ニュース BBC News - Home Osaka calls for privacy, empathy and personal days on return https://www.bbc.co.uk/sport/tennis/57767495 Osaka calls for privacy empathy and personal days on returnNaomi Osaka calls for privacy and empathy from the press when she returns saying she never wants her personal medical history to be scrutinised again 2021-07-08 14:31:18
ニュース BBC News - Home Lions 'optimistic' for Sharks rematch on Saturday https://www.bbc.co.uk/sport/rugby-union/57763970 Lions x optimistic x for Sharks rematch on SaturdayThe British and Irish Lions are optimistic they will play the Sharks again this weekend after their original opposition were forced to pull out of the fixture 2021-07-08 14:16:31
LifeHuck ライフハッカー[日本版] 6月、4つのメディアの読者が楽天市場で購入した「スポーツ・筋トレ・健康グッズ」ランキング https://www.lifehacker.jp/2021/07/2021-june-ranking-sports.html 体組成計 2021-07-08 23:30:00
北海道 北海道新聞 NY株、一時500ドル超安 世界で新型コロナ拡大懸念 https://www.hokkaido-np.co.jp/article/565009/ 新型 2021-07-08 23:17:00
北海道 北海道新聞 東京五輪、1都3県は無観客開催 緊急宣言再発令で転換 https://www.hokkaido-np.co.jp/article/564941/ 東京五輪 2021-07-08 23:04:25
北海道 北海道新聞 大坂、メンタルヘルス理解へ期待 米タイム誌に手記 https://www.hokkaido-np.co.jp/article/564999/ 日清食品 2021-07-08 23:01:00
仮想通貨 BITPRESS(ビットプレス) JVCEA反省会 本当に一ヶ月でコインを上場させることができるのか? with Kraken千野さん https://bitpress.jp/video/hansei/entry-12639.html 意見交換 2021-07-08 23:03:09

コメント

このブログの人気の投稿

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

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

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