投稿時間:2023-05-13 22:05:49 RSSフィード2023-05-13 22:00 分まとめ(8件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
AWS AWSタグが付けられた新着投稿 - Qiita EC2のユーザーデータを使用してlinuxユーザーの追加を行ってみた https://qiita.com/betarium/items/ded0ecde7754ffc725e0 linux 2023-05-13 21:50:35
技術ブログ Developers.IO Windows 11 で SSH 鍵を生成し Backlog Git でクローンするまで https://dev.classmethod.jp/articles/generate-ssh-key-on-windows-11-and-clone-with-backlog-git/ backloggit 2023-05-13 12:19:35
海外TECH DEV Community Getting masked secrets out of CircleCI https://dev.to/mountainash/getting-masked-secrets-out-of-circleci-2fpp Getting masked secrets out of CircleCIIf you ve used environment variables in CircleCI you ll know the pain of a horrible UI Once a variable is added you can never see it again you can t even edit it blindly you need to delete the entire entry and re add it key amp value CircleCI also has no differentiation between a variable and a secret A basic public var like SUPPORT CONTACT sendspam public email com will only be seen again by in CircleCI Settings UI as SUPPORT CONTACT xxxx com or worse if you attempt to echo it in your build logs This makes it über hard to know what s being used in your builds and is a great sic form of lock in when you attempt to move away from CircleCI Here s a little script I devised for this very purpose which hasn t been blocked yet version jobs getout steps run command mkdir p tmp env gt gt tmp circleci env store artifacts path tmp circleci env destination artifact fileworkflows workflow jobs wantout name getout context org global my contextThe script above will dump all the env vars exposed to the running job into a file which will be added as an artifact You can then download the text file from the CircleCI webUI Pipeline gt Workflow gt Job You will need to list the name s of your contexts to expose their variables to the job If you don t use contexts you can remove the last lines of this snippet Ensure you rotate your secrets as this leaves a nice dump of secure items in what s likely a very insecure file storage location on the infrastructure of a company that s been proven to be insecure in the past Also your personal computer is also not a good place to leave secrets this is how CircleCI got themselves exposed PS for a vastly superior envvar UX checkout how GitHub Actions do it much more control and visibility Cover image by Dan Schiumarini 2023-05-13 12:34:16
海外TECH DEV Community Consistência de dados e padrão Outbox https://dev.to/rafaelpadovezi/consistencia-de-dados-e-padrao-outbox-188p Consistência de dados e padrão OutboxUm dos pontos mais importantes em todas aplicações que trabalha com escrita de dados égarantir a consistência dos dados Um exemplo básico éa criação de um pedido que possui itens Considerando um banco relacional os dados são armazenados em duas tabelas Orders e OrderItems Imagine que a aplicação realize um INSERT no banco na tabela Orders e recebe um erro na tentativa de fazer o INSERT na tabela OrderItems Dessa forma o sistema ficou inconsistente o usuário tem um pedido sem itens e isso pode inclusive impedir que ele consiga repetir o pedido O desejado éque o pedido seja salvo completamente ou que nada salvo Nos bancos relacionais a solução éo uso de transações BEGIN TRANSACTION INSERT INTO TABLE Orders INSERT INTO TABLE OrderItems COMMITCaso o segundo INSERT não seja concluído deve ser realizado o rollback da transação mantendo o comportamento de tudo ou nada O problema de escrita dupla dual write Agora vamos ampliar nosso cenário um microsserviço de Pedidos éresponsável por manter os dados de pedidos e notificar os outros sistemas sobre pedidos feitos Dessa forma ao receber um novo pedido deve ser feita uma escrita na tabela Orders no banco de dados e enviar uma mensagem order created para uma fila Como manter a consistência entre o banco de dados e o sistema de mensageria Se após inserir um registro no banco de dados o envio da mensagem para a fila não tiver sucesso as aplicações que esperam a mensagem ficam inconsistentes Invertendo a lógica e enviando a mensagem antes de salvar no banco de dados produz um problema maior pois as aplicações seguintes podem receber mensagens de operações que nunca foram registradas na aplicação que édona desse dado Manter a consistência dos dados em sistemas distribuídos éum grande desafio e diversas abordagens tem diferentes trade offs Comumente éa aceitável garantir que o sistema esteja consistente em algum ponto no futuro Essa abordagem échamada de Consistência Posterior eventual consistency Outbox PatternA ideia do outbox pattern éusar o banco de dados para garantir que a mensagem seráenviada As mensagens que serão enviadas para o sistema de mensageria devem ser armazenadas em uma tabela junto do status de envio Ao inserir um registro da tabela de Orders também deve se inserir a mensagem tudo dentro de uma transação BEGIN TRANSACTION INSERT INTO Orders INSERT INTO OutboxMessages message status COMMITEssa tabela OutboxMessages deve verificada periodicamente em busca de mensagens com o status pendente para que sejam enviadas para a fila Dessa forma tem se a garantia que a mensagem seráenviada ao menos uma vez Por que ao menos uma vez Porque o processo de envio da mensagem e a atualização do status de envio do registro do banco éuma escrita dupla e estásujeita a falhas A operação de atualização do status como enviado pode falhar e portanto durante a próxima busca de mensagens pendentes essa mensagem seria enviada novamente IdempotênciaConsiderando o problema anterior épossível que uma mesma mensagem seja enviada repetidamente para a fila Dessa forma énecessário que os sistemas que processam essas mensagens sejam idempotentes ou seja a execução de operações repetidas não podem afetar o resultado da primeira operação Algumas operações são idempotentes por natureza como atribuir um determinado valor para um campo de um registro de uma tabela Se executada múltiplas vezes o resultado final éo mesmo de se executar apenas uma vez Em outras situações não garantir a idempotência pode ser catastrófico Expandindo nosso exemplo considere uma aplicação que recebe mensagens de pedidos realizados e decrementa o estoque dos produtos vendidos Se a mensagem do pedido for duplicada o pedido abateria do estoque o dobro de produtos comprados Uma maneira de implementar idempotência para esses casos éutilizar novamente o banco de dados A aplicação que consome as mensagens deve possuir uma tabela para armazenar o id das mensagens processadas Ao executar a operação no banco de dados no nosso exemplo um UPDATE na tabela Products deve se inserir o id da mensagem na tabela de mensagens processadas As duas operações deve ser realizadas dentro de uma transação pois se a restrição de chave primária da tabela ProccessedMessages retornar erro ou seja a mensagem jáfoi processada a atualização do produto deve ser desfeita BEGIN TRANSACTION UPDATE Produtcs INSERT INTO ProccessedMessages Id COMMIT ImplementaçãoUsando C existem algumas opções de bibliotecas que implementam o padrão Outbox como CAP e Mass Transit Para idempotência eu criei o Ziggurat que implementa a solução descrita nesse texto Épossível ver um exemplo de implementação de CAP com Ziggurat aqui No python existe a biblioteca django outbox pattern que implementa o padrão outbox e também garante idempotência nos consumidores 2023-05-13 12:15:00
海外TECH DEV Community Python for All Ages: An Accessible Guide for Beginners https://dev.to/aradwan20/python-for-all-ages-an-accessible-guide-for-beginners-3bl9 Python for All Ages An Accessible Guide for BeginnersI IntroductionA Purpose of this ArticleB Overview of the Topics CoveredII Write Pythonic CodeA ComprehensionB Python LambdaC Function ArgumentsD Variable ArgumentsIII Python OOPA Understanding OOPB Classes and ObjectsC Everything is an ObjectD Python InheritanceE OOP ExamplesIV Exception HandlingA Python ExceptionsB Handling ExceptionsC Revise Exception HandlingV Managing FilesA File HandlingB DirectoriesC Creating ModulesD Python PackagesVI ConclusionA Recap of Topics CoveredB Next Steps for Learning PythonI IntroductionA Purpose of this ArticleMy main goal with this article is to introduce you to the world of Python programming in an engaging and straightforward manner We ll cover essential Python concepts and techniques with practical examples breaking down each topic into easy to understand explanations B Overview of the Topics CoveredIn this article we will cover the following topics Writing Pythonic code write clean efficient and idiomatic Python code using comprehensions lambda functions function arguments and variable arguments Python Object Oriented Programming OOP Understand the basics of OOP in Python including classes objects inheritance and the everything is an object principle Exception handling Get a handle on Python exceptions how to manage them properly and best practices to avoid common pitfalls Managing files Master file handling directories creating modules and using Python packages to organize and manage your code effectively Remember the aim is to present these concepts in a simple relatable manner so feel free to ask questions and seek clarification in the comments section Happy coding II Write Pythonic CodeIn this section we ll explore Pythonic coding techniques with hands on code examples A ComprehensionComprehensions help you create new data structures concisely We ll cover three types of comprehensions with code examples List Comprehensions Use a single line of code to create a new list Example Create a list of squares for numbers from to squares x for x in range print squares Set Comprehensions Create sets using a single line of code Example Create a set of even numbers from to even numbers x for x in range if x print even numbers Dictionary Comprehensions Build dictionaries with key value pairs using a single line of code Example Create a dictionary with numbers as keys and their squares as values number squares x x for x in range print number squares B Python LambdaLambda functions are small anonymous functions We ll cover their syntax use cases and limitations with code examples Lambda Functions Create simple one time use functions Example Sort a list of tuples by the second element pairs one two three sorted pairs sorted pairs key lambda x x print sorted pairs Use Cases and Limitations Lambda functions are best suited for simple operations Example Filter even numbers from a list using lambda numbers even numbers list filter lambda x x numbers print even numbers C Function ArgumentsWe ll explore different types of function arguments with code examples Default Arguments Set default values for function parameters Example Greet a user with a default name def greet name Guest print f Hello name greet greet Alice Keyword Arguments Make function calls more readable by specifying parameter names Example Print user details with keyword arguments def print user details age name print f Name name Age age print user details age name Bob Positional Arguments Pass a specific number of arguments in a particular order Example Calculate the product of two numbers def product x y return x yresult product print result D Variable ArgumentsLearn how to use args and kwargs to accept a varying number of arguments args Pass a variable number of positional arguments Example Calculate the sum of an unknown number of arguments def sum numbers args return sum args result sum numbers print result kwargs Pass a variable number of keyword arguments Example Print user details with an unknown number of attributes def print user details kwargs for key value in kwargs items print f key value print user details name Alice age city New York III Python OOPIn this section we ll explore Python s object oriented programming OOP concepts which will help you write more structured maintainable code A Understanding OOPWe ll introduce you to the fundamental concepts and benefits of OOP Object Oriented Programming Concepts All about classes objects inheritance encapsulation and polymorphism Benefits of OOP OOP can make your code more modular reusable and maintainable ultimately improving the quality of your projects B Classes and ObjectsWe ll explore how to define and work with classes and objects in Python Defining Classes Create a class in Python and define its attributes and methods using simple examples Example class Dog def init self name breed self name name self breed breed def bark self print f self name says woof Instantiating Objects Create instances of a class which are individual objects that you can interact with Example my dog Dog Buddy Golden Retriever my dog bark Class and Instance Variables See the difference between class variables which are shared among all instances and instance variables which are unique to each instance Example class Dog species Canis lupus familiaris Class variable def init self name breed self name name Instance variable self breed breed Instance variableC Everything is an ObjectLearn about Python s object model and built in functions for working with objects Python s Object Model Everything in Python is an object including functions modules and even simple data types like integers and strings The type and id Functions Use the type function to determine an object s class and the id function to get its unique identifier Example print type Output lt class int gt print id Output Unique identifier e g D Python InheritanceDive into inheritance in Python including single and multiple inheritance and method resolution order Single Inheritance Create subclasses that inherit attributes and methods from a parent class Example class Animal def speak self passclass Dog Animal def speak self print Woof Multiple Inheritance Create classes that inherit from multiple parent classes Example class A def method self print A class B def method self print B class C A B passc C c method Output A Method Resolution Order Determines the order in which to search for methods in a class hierarchy Example print C mro Output lt class main C gt lt class main A gt lt class main B gt lt class object gt E OOP ExamplesWe ll walk you through some practical examples to demonstrate OOP concepts in action Creating a Simple Class Hierarchy Build a class hierarchy that showcases inheritance and method overriding Example class Animal def speak self print The animal makes a sound class Dog Animal def speak self print The dog barks class Cat Animal def speak self print The cat meows dog Dog cat Cat dog speak cat speak Polymorphism and Method Overriding Polymorphism allows you to use different implementations of the same method in different subclasses Example def make sound animal animal speak make sound dog Output The dog barks make sound cat Output The cat meows IV Exception HandlingIn this section we ll explore Python exception handling which is essential for creating robust error resilient code A Python ExceptionsDiscover Python s built in exceptions and how to create custom ones Built in Exceptions Take a look of the common built in exceptions such as ValueError TypeError and FileNotFoundError and when they occur Example try int abc except ValueError print Oops A ValueError occurred Custom Exceptions Create and raise custom exceptions to handle specific error conditions Example class CustomError Exception passtry raise CustomError This is a custom error except CustomError as e print f Caught an exception e B Handling ExceptionsLearn how to use try and except blocks as well as finally and else clauses to manage exceptions in your code try and except Blocks Check how to catch and handle exceptions using try and except blocks Example try result except ZeroDivisionError print Oops You tried to divide by zero finally and else Clauses The use the finally clause to execute code regardless of whether an exception occurs and the else clause to run code when no exceptions are raised Example try result except ZeroDivisionError print Oops You tried to divide by zero else print No exceptions were raised finally print This code will always run C Revise Exception HandlingReinforce your understanding of exception handling with best practices and common pitfalls Best Practices Learn effective strategies for handling exceptions such as catching only specific exceptions using custom exceptions for better error reporting and providing meaningful error messages Common Pitfalls Be aware of common mistakes such as catching all exceptions which can make it difficult to identify and fix issues in your code Example of catching specific exceptions try Some code that might raise exceptionsexcept ValueError TypeError as e print f Caught an exception e V Managing FilesIn this section we ll explore managing files directories modules and packages in Python A File HandlingLearn how to work with files in Python including opening closing reading and writing Opening and Closing Files How to open and close files using the built in open function and the with statement Example with open example txt r as file Process the file Reading and Writing Files Understand how to read from and write to files using methods like read readline readlines write and writelines Example with open example txt r as file content file read with open output txt w as file file write Hello world File Modes and Buffering Search on Google these various file modes such as r w a x and their combinations with b and Example with open example txt rb as file Process the binary fileB DirectoriesLearn how to work with directories in Python including creating removing navigating and listing contents Creating and Removing Directories What to import when creating and remove directories os mkdir os makedirs os rmdir and os removedirs functions Example import osos mkdir new directory os rmdir new directory Navigating Directories Understand how to change the current working directory and get the current directory path using the os chdir and os getcwd functions Example import osos chdir path to directory print os getcwd C Creating ModulesDiscover how to create and import modules to organize your code into functions and classes Importing Modules Learn how to import custom and built in modules using the import statement Example import my modulemy module my function Organizing Code into Functions and Classes Understand how to structure your code using functions and classes within modules for better organization and code reusability D Python PackagesExplore how to create import distribute and install Python packages Creating and Importing Packages Learn how to create packages by organizing modules into directories and using init py files and how to import packages and their modules Example Directory structure my package init py my module py Importing from a packagefrom my package import my modulePackage Distribution and Installation Understand how to distribute and install Python packages using tools like setuptools and package repositories like PyPI VI ConclusionWe ll wrap up our Python learning journey with a recap of the topics covered and provide suggestions for the next steps to continue learning Python A Recap of Topics CoveredThroughout this article we ve explored various Python concepts Here s a brief recap of the topics we covered Write Pythonic Code We learned about comprehensions lambda functions function arguments and variable arguments Python Object Oriented Programming OOP We covered the basics of OOP classes and objects Python s object model inheritance and OOP examples Exception Handling We discussed Python exceptions handling exceptions and best practices Managing Files We explored file handling working with directories creating modules and Python packages B Next Steps for Learning PythonNow that you have a solid foundation in Python consider these suggestions to further expand your knowledge Dive deeper into Python s built in libraries and learn how to work with more advanced topics like networking web scraping and data analysis Explore popular Python frameworks like Django and Flask for web development or TensorFlow and PyTorch for machine learning Join online communities and forums to share your knowledge ask questions and learn from others Participate in coding challenges and hackathons to test your skills and learn from real world problem solving experiences Continue building projects and create a portfolio to showcase your work to potential employers or clients 2023-05-13 12:04:07
Apple AppleInsider - Frontpage News Daily Deals: Save $300 on Arlo Pro 4 camera bundle, 25% off a Samsung 32-inch 4K Smart Monitor, up to $50 off Oura rings, more https://appleinsider.com/articles/23/05/13/daily-deals-save-300-on-arlo-pro-4-camera-bundle-25-off-a-samsung-32-inch-4k-smart-monitor-up-to-50-off-oura-rings-more?utm_medium=rss Daily Deals Save on Arlo Pro camera bundle off a Samsung inch K Smart Monitor up to off Oura rings moreSaturday s top deals include off Parallels Desktop for Mac off a Klipsch Reference Cinema System and off a Lego Vespa Get off a inch Samsung K smart monitorThe AppleInsider crew scours the internet for stellar deals at online stores to curate a list of high quality bargains on trending tech items including discounts on Apple products TVs accessories and other gadgets We post the top deals daily to help you get more bang for your buck Read more 2023-05-13 12:09:44
ニュース BBC News - Home Ukraine's Zelensky in Rome to meet Pope Francis https://www.bbc.co.uk/news/world-europe-65581170?at_medium=RSS&at_campaign=KARANGA francisukraine 2023-05-13 12:46:54
ニュース BBC News - Home Turkey election: Opposition dares to dream of Erdogan defeat https://www.bbc.co.uk/news/world-europe-65568647?at_medium=RSS&at_campaign=KARANGA erdogan 2023-05-13 12:31:31

コメント

このブログの人気の投稿

投稿時間: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件)