id
int64
5
1.93M
title
stringlengths
0
128
description
stringlengths
0
25.5k
collection_id
int64
0
28.1k
published_timestamp
timestamp[s]
canonical_url
stringlengths
14
581
tag_list
stringlengths
0
120
body_markdown
stringlengths
0
716k
user_username
stringlengths
2
30
902,690
What you need to know to become an automation test engineer
QA used to consist of two types of testing, namely, manual testing and automation testing. Manual...
0
2021-11-19T06:45:17
https://dev.to/oswinlosper/what-you-need-to-know-to-become-an-automation-test-engineer-52e1
automation, testing, beginners, automationengineer
QA used to consist of two types of testing, namely, manual testing and automation testing. Manual testers main task was to do regression testing while automation tester was only focussed on writing code and scripts. The connection between the two was a rare thing, expect when the automation engineers wanted to explore additional test cases to automate. However in the world we live today, its different. Yes, both manual and automation testing is still important, I am still of the believe that automation is not there to replace manual testing, however the gap between manual and the automation world is getting smaller and smaller. Its important for manual and automation to work together, but most importantly, to make sure that both sides understands each other tasks. This is a strategy we implement at my current workplace, Wyzetalk, ever since we switched to this approach, workflow has been much more beneficial for all parties involved. When applying for new jobs, some companies requires that candidates to have experience in both manual and automation testing. This leaves the questions, where do I start to become a automation tester? What skills do I need for this? I was in the same boat years ago. I started of as a web designer, had no experience in automation testing. Thankfully, like all problems, it not a hard problem to solve, however it requires action on your part. There are 2 main focus areas to become a successful automation engineer. Keep in mind that requirements can depend on the role and can have additional requirements, but below is a list of basic requirements. ####Development Languages Number one, you need to know a specific language. Like mentioned above, this can depend on the role you are applying for, but most of the time when you know the popular languages like Java or Javascript, it should be enough You dont have to be a experienced developer but it would be good if you have enough knowledge to write automation tests and scripts. I would recommend the basic fundamentals. * Classes, objects, and methods * Inheritance * Strings, Integers * Interface concept and how to use it * Polymorphism * Arrays (single and multi-dimensional) * Override and overload * Access modifiers * Date class * Role of constructors These should be enough to start writing automation code. ####Framework for UI Automation testing Unit testing allows us to verify that different modules of our application are operating in the correct manner, but we also need to test applications from a UI end-to-end point. In a previous article I wrote about, I dive deeper into what you must consider in selecting a automation tool, below is a brief breakdown of breakdown in performing tests on a UI framework: * Creating a new project in your favorite IDE * Setting up dependencies in a build management system * Creating a base class for the framework * Setting up global properties for your project * Implementing the page-object model for your project * Writing test cases for your project * Grouping your test cases * Wiring up a tool for generating reports and screenshots for failed test cases * Running your test cases efficiently by using an automation tool * Analyzing the result of executed test cases ####Conclusion After you finished the framework, one important thing that people are not doing in the automation testing world, is to manage the automation suite, this must to be done in order for the automation tests to bring value and longevity to the quality of your project The specifics of writing UI automation code would depend on a platform (e.g mobile or desktop) and other factors, but this is basically what you need to focus your attention to. In a nut shell, write test and report on results of test cases. I hope this article will give you a better understand of what you need to do to make the switch to be a automation test engineer.
oswinlosper
902,853
Tales of the Autistic Developer – Order and Chaos
For those who don't know me, I'm autistic. I've been a developer for the better part of a decade. I...
10,892
2021-11-19T10:05:15
https://dev.to/baweaver/tales-of-the-autistic-developer-order-and-chaos-2o0p
mentalhealth, autism, adhd
For those who don't know me, I'm autistic. I've been a developer for the better part of a decade. I didn't find out I was ASD until 19, and didn't reconcile with that until years later. These posts will be a combination of advice I've given to those who are like me, as well as a letter of sorts to my past self who could have used a lot of it. I write these posts in the hopes that someone like me will find value in knowing a very simple and very important truth about ASD: *You are not alone, and you are loved.* ## Order and Chaos While I am most certainly autistic, I'm also ADHD, making for a very interesting mix of traits. My mind, quite simply, operates in a mode of constant chaos. It bounces from idea to idea as fast as something catches its fancy, and trying to tame it into some semblance of productivity has been my life's work. The irony then is that my entire existence is implementing systems of order by which to counteract that natural state of chaos, but the deeper irony? Both have become indispensable to my work, and how I think. ### A State of Chaos In my decade or more of experience in the industry I've come to a very simple truth: The hardest problems in technology are organizational, rather than technological. While solutions may certainly exist, discovering them, building consensus, and orchestrating the release ends up being an exercise in chaos more often than not. There are entire categories of problems that are well beyond the scope of a single engineer, and quite frankly should be despite the best efforts of some to do otherwise. The larger the problem the larger the surrounding context it involves, and by extension the more people will need to be involved to solve it properly. Bypassing this means bypassing critical context and insight, and potentially making very grave mistakes in the solutions you create. Simply put that's the critical gap between a Senior and a Staff engineer, but that's a story for another day. The point of this is that without a plan and systems of communication, organization, networking, and other methods of managing all that context you end up with chaos. A ship without a rudder sailing aimlessly into the distance. That might work well for the short term, but direction becomes critical if you want to do anything beyond floating in a loosely forward direction. Now this all brings up a very interesting question: how does someone with Autism / ADHD, both conditions known for not being great at all of the above, manage to survive past those levels? ### A Contradictory Existence As someone with Autism I like things to make sense, to have a natural order, and to fall into the right place. My life is dominated in many ways by a desire for order and rigor. Take me to any restaurant and I guarantee I'll order the same thing every time, and most of the owners will know me by name if I've lived somewhere for any decent amount of time. Consistency brings me peace of mind, and helps me to focus. You can imagine that 2020 and 2021 were not kind on that note, but again, a story for another day. Contradictorily and very ironically being ADHD means that my mind works in a state of disorder. I bounce between 10 ideas at any given time, find new hobbies everywhere, and can't focus to save my life. These two traits are at constant odds with each other in my head. In many cases it feels like I humor myself between the two of them depending on which trait dominates on a given day. Do I need to snap out of an obsession from my Autistic nature, or do I need to drill down and focus on one task and quit being capricious from my ADHD nature? ### Systems of Order The answer is that I use them both against each other, where one is weak I supplement the other's strength. I create systems of order in which I can succeed with ADHD, via calendars, notes, reminders, and anything else I can get a hold of to keep myself accountable. I have collections of notes spanning many years capturing insights, networks, communications, and more to make sure I can find the right people when I need to to get critical context. I create systems by which to capture and distill that information into useful documents, and further methods to distill that information into actionable content and executive summaries to inform those above me on a path forward. The simple truth is I do not trust myself to be responsible, so any system of order I make is explicitly to keep myself accountable to a task. Being autistic I find great comfort in order and certainty, in rote and repetition of tasks, which means I'm very good at creating order of chaos. What's interesting about that statement is the reverse: To get good at creating order of chaos, one has to be able to live in chaos and thrive in it first. ADHD's lack of a clear focal point and its tendency for capriciousness benefits me in that I'm far more comfortable with disorder and chaos than many without it. After all, my head works like that, even if I do like order more. The critical point is that I can recognize chaos for what it is, and in doing so start to implement systems of order on top of it to facilitate progress. The larger the chaos the more this ability shines, but there are certainly dangers in forms of chaos that I cannot comprehend nor manage, so knowing my limit is critical in stepping back and consulting others first. What's more interesting is that these systems of order allow something else entirely. ### The Cost of Freedom Through systems of order balancing chaos, I'm allowed a certain freedom of execution. I've created a solid foundation in which I can experiment, do as I will, and explore beyond scopes I may have been able to more early in my career. When I was much younger I did not have such systems of order, yet I yearned for freedom. Freedom to play, to explore, to do what I wanted to do. Many times, when given such freedom, it would be my undoing. If anything seeking freedom was what about got me fired in a few roles in the past, as I did not have nearly the support structure I needed to execute upon it. By creating systems of order that can sustain me, and networks by which I can execute through, I'm able to create greater freedoms by which myself and others can pursue tasks as we wish. The irony, and the cost of that freedom, are systems of organization to prevent chaos beyond our ability to manage from eroding our foundation and putting us in positions where tasks are quite literally impossible to achieve. I know, I've put myself in that position several times before, and it's not fun. That said, it was probably those very experiences that gave me the critical insight that there's a high cost to freedom, and the higher one goes and the wider scope that one executes at that cost grows with it. Consider a manager who creates systems of organization through Jira or Agile methodologies (it could be anything though, those are just examples). Through that newer engineers can execute tasks to move the team forward, but inside that framework they have the freedom to add tasks and propose new solutions, all because the team is still moving forward due to the manager's planning. That manager shields the team from chaos beyond their scope of view, and in doing so gives them the freedom to execute in their own scope. Of course as team members level up they'll become privy to far more of the chaos the team is wrapped up in, but preferably only when they're ready to face it. Extrapolate this to directors, department heads, GMs, VPs, C-levels, and more and you can see that the costs of organizing at each progressive level grow exponentially, but the freedom and clarity they provide by doing so to those under them grows with it. That's a pretty amazing power, and one I hope to have one day, but one I have a lot of work to do to get to. ### Superpower or Curse? I exist in a world somewhere between chaos and order, creating order of chaos, and living a life that allows me to survive chaos perhaps beyond what would otherwise be normal. While this may sound like some form of superpower, it's far more a precarious balancing act, and if I happen to slip and let one side dominate it does not end well for me. Should I let my Autistic nature dominate, I'll begin to lock down and go back to the familiar. Anything outside of that box won't happen, and I'll likely be like that for a week or two while I regain my composure. I start to jettison anything and everything not necessary to finish existing commitments, and will very much be in a state of Autistic burnout. Recovery from that is painful, and frequently I try and take a vacation when I find myself flirting too much with that line. Should I let my ADHD nature dominate I'll get nothing done. I'll be on an endorphin hunt looking for anything and everything that can give me just a bit of a rush. Whether that be shopping, smells, foods, experiences, new comics, books, games, or any of the above I want something to make me feel whole and "happy" again, despite that being impossible. ADHD burnout means that I'll be on a perpetual hunt for a new high, until I detox my mind and get back to a normal state. If you know me personally you'll notice that I have routines, whether that be coffee or food, that I tend to adhere to to satisfy my Autistic nature. You'll also notice the tendency of me pursuing new and novel hobbies on occasion, but in very limited quantities, to satisfy my ADHD nature. I can't ignore them, but neither can I let them win and dominate my life, which brings up the question if this is a superpower or a curse. Really though? It depends on the day. ### Closing Thoughts As I grow in my career my permanent fear is that I encounter chaos beyond my capacity requiring order that tips me beyond my limits. Thankfully I've had the support of many wise friends, mentors, elders, and family to guide me through those times. People who have been there, and seen the tops of the mountains I'm climbing, and that's made all the difference in the world. To even know it's possible, and that my ideals aren't wrong, is more valuable than gold to me. If there's one final lesson I could impart from this article it's that you're not in this alone, not now and not ever. There will be things beyond us, but there will also be people there with an outstretched hand if you look for them. We are not alone, not in the greatest chaos, nor in the most thorough systems of order we could imagine. Alone we will fail, but together we can achieve so much more, and that's a lesson I wish I had learned much earlier in my life.
baweaver
902,881
WordPress Vs Wix: 6 Points to Help You Choose the Best Platform
With 1.88 billion websites out there, it’s easy for you to get lost in the shuffle. This eventually...
0
2021-11-19T10:53:18
https://terasoltechnologies.com/wordpress-vs-wix-which-is-the-best/
webappdevelopment, cms, webdev, webdevelopmentplatfo
--- title: WordPress Vs Wix: 6 Points to Help You Choose the Best Platform published: True date: 2021-11-10 04:50:39 UTC tags: WebAppDevelopment,CMS,webdevelopment,Webdevelopmentplatfo canonical_url: https://terasoltechnologies.com/wordpress-vs-wix-which-is-the-best/ --- With 1.88 billion websites out there, it’s easy for you to get lost in the shuffle. This eventually drives marketers and business owners on an eternal struggle to seek new ways to increase their visibility online. However, most people are unaware that using a website builder that is SEO-friendly is one of the best ways to ensure your site is discovered. **So, it is time for WordPress vs Wix battle royale!** Both of these [CMS](https://terasoltechnologies.com/web-development/) platforms allow users to create websites from the ground up and serve the same noble goal: > To allow users to create attractive, functioning websites without having to be unduly sophisticated or technical. Both the platforms come with basic editors and templates to help you create a professional-looking website. It was previously impossible to compare Wix and WordPress.WordPress was the most popular CMS and had a larger market share than Wix. However, things are beginning to change. Making a comparison between Wix and WordPress is now tough, especially if you’re new to website development. When comparing Wix vs. WordPress, this article will focus on which is the better option for your business. Let’s take a look at Pricing, support, ease of use, support, community, and other factors in depth. We hope by the end of this article you will know which solution fits your business the best! ## What is Wix? ![Web development](https://terasoltechnologies.com/wp-content/uploads/2021/11/Web-development-1.png "WordPress Vs Wix: 6 Points to Help You Choose the Best Platform 17") Wix, founded in 2006, is one of WordPress’s most steadfast and early competitors. To begin, Wix is an all-in-one, drag-and-drop cloud-based web creation tool that is ideal for non-coders and beginners alike. It allows users to use online tools to develop effective [e-Commerce websites](https://terasoltechnologies.com/e-commerce-software-development/). With Wix, everything is pre-installed and ready for you to begin creating your website. ## What is WordPress? ![WordPress Development](https://terasoltechnologies.com/wp-content/uploads/2021/11/WordPress-Development-1.png "WordPress Vs Wix: 6 Points to Help You Choose the Best Platform 18") WordPress is a self-hosted open-source platform that allows you to develop considerably larger websites but necessitates a higher level of technical expertise. Initially, it was referred to as a blogging platform. Then, thanks to WordPress’s extensive ecosystem of plugins and themes, you may develop any type of website using WordPress. WordPress is also a viable option for multichannel retailers all around the world. So now we know what these platforms are, let’s compare them to know who wins the battle of WordPress vs Wix. ## Comparing These Platforms in 6 Key Categories Before we begin our comparison, let’s start with some facts- WordPress, unsurprisingly, powers roughly 60% of the internet. It is the high water-mark for enterprises, according to us. Whereas, Wix is one of the greatest website builders available, which is why it came in closer than you may expect. ### WordPress Vs Wix: Which one is Easy to Use? Any application which is simple to use is bound to gain popularity among its users. It may come as a surprise, but Wix outperforms WordPress in terms of simplicity of use. In comparison to Wix, WordPress may take a newbie longer to understand. When you begin working with Wix, you’ll notice that the signup process is incredibly straightforward. Wix evolves into a full-service site builder that anyone, including beginners, can use. Wix offers Wix ADI, an artificial intelligence technology that assists you in creating an online store from the ground up. Wix platform uses a drag-and-drop feature called Wix Editor to allow users to create a website in minutes without knowing how to code. With the WordPress CMS, you might feel intimated by the amount of work that needs to be done before you can get started. To modify your store with WordPress, you’ll need a good understanding of how elements in the admin dashboard work. Moreover, this platform also enables business owners to examine the underlying code to alter their websites. So, assuming you do not know coding or web development, Wix will suffice. To get around WordPress, you’ll need to learn some programming or hire a WordPress developer. (\*cough\* like [Terasol Technologies](https://terasoltechnologies.com/) \*cough\*) **Well! Wix wins the opening round!** ### WordPress Vs Wix: Which has better Customization? You can choose from hundreds of different website templates on the Wix platform. Wix includes a portfolio of roughly 80 distinct apps if you’re trying to incorporate some advanced website features. Each of them takes only a few seconds to add to your Wix site. **That’s a good place to start. Isn’t it? ** Even while [WordPress development](https://terasoltechnologies.com/web-development/), you may choose from thousands of different free and premium themes. You can also go through various themes on websites like Elegant Themes, ThemeForest, Themeisle, and others. There are also [WordPress plugins](https://wordpress.org/plugins/), which are comparable to Wix apps. WordPress is the king when it comes to plugins. There are WordPress security plugins that provide full lock-down protection for your website against thousands of potential hacking attempts. As a result of these factors, the second round of Wix vs WordPress is a landslide in **WordPress’ favor.** ### WordPress Vs Wix: Who is more Flexible? When comparing the versatility of WordPress vs Wix, keep in mind that WordPress is an open-source platform, whereas Wix is not. WordPress scripts are open to the public, and anyone with a basic understanding of programming can use them to create a plugin. Because of its versatility, the WordPress community is diverse. Wix, on the other hand, is a closed-source platform. Only Wix employees have access to the scripts, and those from outside the company are unable to create themes or plugins. Wix, on the other hand, has an App Market. The Wix App Market includes applications such as Scheduling Pro, Social Media Stream, Newsletter Signup Form, Form Builder, and many others. **So, our winner of this round is the open-source one: WordPress. ** ### WordPress Vs Wix: Support & Community Wix has a dedicated support team waiting to assist you. Wix provides a library of articles and video lessons that can help you with your issues. Because the apps are built-in, the support team will have a good notion of what issues you might have. When it comes to site support, WordPress differs significantly from Wix. WordPress is an open-source platform, it does not provide direct customer assistance beyond its huge knowledge base. However, because the community is so large, you’ll find various kinds of answers there. To find the best solution for your situation, you’d have to delve deep into those communities. This Round is a tie, as Wix has better support but WordPress surpasses Wix in Community Support. Let’s take a look at the scores! So the scores are 2-1 and in favor of WordPress. ### WordPress or Wix: Who is better with SEO? Wix website builder is developing with time. Still, Wix has a notable problem with website loading rates when it comes to SEO. They’ve been attempting to improve page load times in recent years by incorporating more advanced SEO tools, such as enhanced image compression and page caching. Even when they follow the best possible SEO procedures, many Wix site owners aren’t always satisfied with how quickly their pages load. You have complete freedom to handle SEO in whatever way you want with WordPress. Of course, there aren’t many SEO-specific tools integrated into the WordPress core platform. However, if you use the correct SEO plugin, your options for optimizing your site’s SEO will be nearly endless. You can also cache and minify your site pages using various plugins. This will improve the site’s speed and performance even more. In round five, WordPress triumphs over Wix once more. While Wix’s SEO solutions may be enough for new site owners, they are insufficient for sites that compete in highly competitive niches. You can master SEO using WordPress. ### WordPress Vs Wix: Which is better when it comes to Bucks? Spending money on your website, like any other investment, is a hazardous proposition. The question is whether the investment is worthwhile. In particular, when comparing WordPress vs Wix, the cost is an important factor to consider. Is Wix a free service? Yes, in fact. Although, the free plan does not have a custom domain and is ad-supported. If you choose the free plan, Wix advertising will appear in the header and footer of your website. Wix calculates rates based on a tiered system of monthly subscriptions that include a domain name and variable storage capacities. ![Wix Website builder](https://terasoltechnologies.com/wp-content/uploads/2021/11/image.png "WordPress Vs Wix: 6 Points to Help You Choose the Best Platform 19") WordPress is a free and open-source content management system. As a result, no money or installation fees are necessary. The only costs associated with developing a website using the WordPress CMS are the hosting plan and domain name. WordPress hosting will also set you back a significant sum of money. WordPress can be inexpensive or pricey depending on your requirements. Wix’s pricing is also good. This round can be classified as a tie. Why not, Both offer excellent value for money. ## So, Who Won the Battle- WordPress or Wix? ![WordPress or Wix](https://terasoltechnologies.com/wp-content/uploads/2021/11/WordPress-or-Wix-1.png "WordPress Vs Wix: 6 Points to Help You Choose the Best Platform 20") We compared WordPress and Wix based on a variety of factors. And the winner of this battle is WordPress. Yet after all of this time, it’s fair to say that deciding between WordPress or Wix is a matter of your business need. We would recommend Wix to anyone who is part of a small group or works alone. And if you’re working on a larger scale and can afford to pay engineers, though, WordPress is the way to go. WordPress is more adaptable and useful. We hope that after reading this extensive comparison of WordPress vs Wix, you will find it easy to choose the best platform that meets your needs. [Terasol Technologies](https://terasoltechnologies.com/) is a great option if you want to build a website on any of these platforms Wix or WordPress. Please do not hesitate to [contact us](https://www.terasoltechnologies.com/enquiryform/?source=kanikablog) if you have any questions or problems about WordPress or Wix. We’re happy to assist you!
terasol_app
902,892
Request for topics
I need to make a list of system design concepts that I must learn in depth and write about. Will you...
0
2021-11-19T10:34:03
https://dev.to/abh1navv/request-for-topics-1i5k
programming, discuss, watercooler, requestforpost
I need to make a list of system design concepts that I must learn in depth and write about. Will you be able to suggest a few topics? You can also suggest technologies and I can try to explain how they work behind the scenes or compare to each other. No language specific stuff please.
abh1navv
902,900
Progressive Web App Development: How to Cook PWA in 2022
When talking about web development, Progressive Web Apps have been a buzzword for a while. But will...
0
2021-11-19T11:00:15
https://dev.to/sergeyrykov/progressive-web-app-development-how-to-cook-pwa-in-2022-15g2
webdev, pwa, reactnative, flutter
When talking about web development, Progressive Web Apps have been a buzzword for a while. But will your company benefit from going down the PWA road? Read how and when you should use and should NOT use this technology now and in 2022. ##Introduction to PWA Progressive Web Apps (PWAs) are a fairly recent trend in web and mobile app development. Coined by Google engineer Alex Russell in 2015, the term refers to web applications that use “progressive” design approaches in order to behave and function similarly to native apps. What that specifically means may not be perfectly clear, as there is no precise definition of what does or does not make a progressive web app. However, there are some defining characteristics that are indicative of PWA design patterns. These include the use of ServiceWorkers (background scripts that run in the browser in order to provide features like push notifications) and app manifests (standardized JSON files that instruct the platform how to install and manage your app). There are also several common design themes that are often pointed to as being unique to PWA. ##Benefits and Drawbacks of PWA Employing progressive web app technology in an application’s development has many benefits, though there are also some drawbacks to consider. The main benefit of PWA design is that it is mostly platform-independent. This means that an app can be developed using a single codebase and deployed on several different platforms. Simplifying the development in this way reduces the time and resources necessary to get an app to market. Platform independence combined with the fact that PWAs are inherently installable makes an app’s rollout onto multiple platforms easy. Users can download and install PWAs just like they can with any native app, rather than relying on a browser to access them, making the user experience seamless and intuitive. PWAs also enjoy the benefits of modern website design in that they are responsive and lightweight. Modern web browsers allow developers to take advantage of design options that react to changing platforms and screen sizes to give users a consistent experience. The codebases of these modernized apps are smaller and their ability to run in a browser (rather than as a native app) makes them lightweight. An added benefit of PWAs as distinct web apps is that they are discoverable by search engine indexing. However, the major drawback to PWA design is that there are some limitations on platform and hardware support. Since PWAs run in a browser, they do not have direct access to all of the capabilities of a platform that a native app built using a platform’s SDK, would have access to. Some platforms also have restricted support for these apps, though support and capabilities are constantly evolving. ##Why Use PWA? Ultimately using PWA design in an application is for those who want to get an app in the hands of users quickly and affordably. This design is great for early-stage startups with limited funds who want to get an MVP app to market as soon as possible. But any company wishing to take advantage of an evolving trend in modern app development will also see similar benefits from PWA. ###BIG BRANDS THAT USE PWA PWAs are not just meant for small companies and cash-strapped startups. On the contrary, many global corporations are seeing tremendous results from switching to a PWA strategy for their users’ benefit. One major brand that raised a lot of attention by doing this is Twitter, which [designed its Twitter](https://blog.twitter.com/engineering/en_us/topics/open-source/2017/how-we-built-twitter-lite) Lite app with PWA in mind. Following the rollout of Twitter Lite, Twitter saw a [75% increase in tweets](https://developers.google.com/web/showcase/2017/twitter), a 65% increase in pages per session, and a 20% decrease in bounce rate. Forbes and Pinterest also designed PWAs for their businesses, with Forbes seeing a [43% increase in sessions](https://developers.google.com/web/showcase/2017/forbes) and a 100% increase in engagement. Pinterest’s PWA brought in a [44% increase](https://medium.com/dev-channel/a-pinterest-progressive-web-app-performance-case-study-3bd6ed2e6154) in user-driven ad revenue. These are just a few examples of companies adopting PWA design in their apps among other recognizable brands like [Uber](https://eng.uber.com/m-uber/) and [AliExpress](https://developers.google.com/web/showcase/2016/aliexpress) who have done the same. ##PWA Compared to Other Technologies PWAs are most easily compared to either native apps or web apps, existing somewhere in between the two. But there is a long list of specific technologies that lie on the spectrum between web and native which can also draw comparisons to PWA. ###PWA VS NATIVE APPS Comparing PWA directly to the general definition of native apps unveils a few differences. Namely, PWAs are built with lighter and simpler codebases (requiring only web languages rather than platform-specific SDK frameworks). ###PWA VS CROSS-PLATFORM APPS When compared to more hybrid technologies like React Native, PhoneGap or Flutter, there are certain details to highlight for cross-platform apps. For instance, React Native is made for building cross-platform native apps and achieves that with a single codebase, however usually it requires a broader skill set from your development team as they have to deal with various native controls and plugins which are written in different languages like Java or Objective-C (depends on the platform). PhoneGap apps are somewhat similar as well. These are just web apps that are wrapped in a native container, which has access to various platform APIs through a set of native plugins. Despite the huge list of available plugins, you might need something custom and will have to implement it on your own, again with the help of Android and iOS developers. PWAs are much simpler in this sense and are usually built just in JavaScript, utilizing modern frameworks like React, Angular and Vue. To sum it up, the PWAs most closely resemble the hybrid apps built with other cross-platform technologies. PWAs most likely will be cheaper in terms of development and future support, as you might need a smaller team without any specific or unique skills. The downside to PWAs is that they are limited by browser capabilities and may have poor support of some core features required for your app. ###PWA VS WEB APPS When compared to pure web applications, PWAs show several advantages. This is because web applications are strictly limited by the capabilities of the browser. That also means web apps do not offer the kind of installability that makes a PWA so convenient for users. While they can offer similar benefits, such as the responsive and lightweight design seen in many single-page applications (SPA), the key differentiator is a PWA’s standardized approach to simulating the native experience. PWA can also be compared to application frameworks like Electron and Flutter. Electron is strictly a web app framework with disadvantages in application size and security that make it generally unsuitable for PWA development. But Flutter is more similar to PWA. Both PWA and Flutter emphasize development in a single codebase with cross-platform native functionality. However, Flutter only uses the new Dart web language whereas a PWA can be written in any language, with many older languages offering more support. ##PWA Support from Major Platforms One of the most important things to evaluate about PWA is what kind of support major platforms provide. While PWA generally allows the development of applications that are perfectly capable of running on any platform, there are some limitations to what exactly different platforms will support. ![PWA Support Across Browsers and Platforms in 2021](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tw1dpmbus7g6sp4ilqbb.jpg) Data from [caniuse.com](https://caniuse.com), CC-BY 4.0 license ###PWA SUPPORT ON IOS For iOS devices, PWA support is somewhat limited. Even though the term “progressive web app” was only recently coined by Google, the origins of PWA can actually be traced back to the very first iPhone. Before Apple provided an SDK for iOS devices, the only apps available on iPhone were web apps. This is a decision that Steve Jobs himself was very insistent on. Of course, as developers asked for a more consistent workflow Apple eventually released their SDK along with the App Store. This evolution went along with Apple’s notoriously strict regulations for developers around user experience and the security of apps available in the App Store. These regulations unfortunately severely restricted the ability of developers to provide PWAs for iOS. As of iOS 11.3, however, PWAs are supported on the Apple platform. However, they must still be wrapped in native code and distributed via the app store. This limits some of the benefits of PWAs like a simplified codebase and easy installation. ###PWA SUPPORT ON ANDROID Android has much more thorough PWA support. This is mainly thanks to Android’s open-source approach which gives developers the freedom and flexibility to write and distribute apps however they wish. Android also provides PWAs with access to some native platform functionality such as push notifications, enabling developers to provide a more seamless native experience within their apps. ###BROWSER PWA SUPPORT Although most of the popular browsers support PWAs now, there is no 100% compatibility. ![PWA Features Support Comparison for Major Browsers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vcjk5oibqg6k8403rffx.jpg) Data from [caniuse.com](https://caniuse.com), CC-BY 4.0 license The browsers that chose NOT to support PWAs are: * Desktop Firefox * Internet Explorer * Facebook Mobile Browser Also, there is a caveat with Safari. Although it provides basic support for the PWAs, not all features are included. Safari does not support push notifications, so the user should install the app manually in order to add it to the home screen. In addition to this, in 2020 the WebKit, Safari’s engine [announced](https://webkit.org/tracking-prevention/) that they are not going to support many of the APIs that give access to the native functionality. Examples of such unsupported features are Web Bluetooth, Web MIDI API, Magnetometer API, Web NFC API among others. They say it’s for privacy reasons, but this hinders the evolution of PWAs on iOS. ##The Current State of PWA in 2021 Progressive web apps are by their nature an evolving trend. As such, new developments and added support by major platforms are constantly contributing to the growth of PWAs. While the imprecise definition of PWA makes it difficult to track an exact market share, estimates based on [Chrome web statistics](https://www.chromestatus.com/metrics/feature/timeline/popularity/990) put the current number of PWA-like page loads at about 19%. ![The Current State of PWA in 2021](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4cn3umyaml0hh7e2tcrs.jpg) A survey of e-commerce decision makers [revealed](https://www.statista.com/statistics/1174534/investing-pwa-ecommerce-companies-worldwide/) that 9% of e-commerce companies planned on investing in progressive web apps (PWA) in 2021. Additionally, 8% of e-commerce companies reported that they are already doing it, and 28% of companies did not have plans to invest in PWA in 2021. ![Share of E-commerce Companies Worldwide Planning on Investing in Progressive Web Apps (PWA) in 2021](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ldthyub4gaj0tsqjucre.jpg) Research [suggests](https://www.globenewswire.com/news-release/2021/02/08/2171664/0/en/Progressive-Web-Application-Market-Size-to-Reach-USD-10-44-Billion-by-2027-Global-Analysis-Statistics-Revenue-Industry-Demand-and-Trend-Analysis-Research-Report-by-Emergen-Research.html) that the financial value of the progressive web application market will reach a value of 10.77 billion dollars by 2027, representing annual growth of over 30% between now and that time. Current support for PWAs is fairly good though there are some limitations. Every major platform including iOS, Mac, Android, and PC now offers some level of PWA support. Android provides the best support, with iOS and Mac being the most limited. Apple’s strict control over the apps available on its platform is the biggest hindrance to PWA’s adoption on iOS. Developers and project owners considering PWA in their own applications should consider these limitations. The PWA market is steadily growing, along with platform support, so early adopters may find themselves ahead of their competitors. But it is tough to tell exactly how long this growth could take. Interestingly, earlier this year, Instagram Lite was rebuilt from PWA to a native Android app. The reason for this switch back is not clear, but there are some speculations that [Facebook did this](https://techcrunch.com/2021/03/10/facebook-targets-emerging-markets-with-instagram-lite-a-new-android-app-that-takes-up-just-2mb-in-170-countries/?guccounter=1&guce_referrer=aHR0cHM6Ly9tb2JpZGV2LmJpei9ibG9nL3doeS13aGVuLXVzZS1wcm9ncmVzc2l2ZS13ZWItYXBwLXB3YS1kZXZlbG9wbWVudA&guce_referrer_sig=AQAAADL7As3jhGP4EqMTVMMKPaQYkKtMFdadLc-VcLFyxUi__mkeTdPXilnPhMG2kk7UXoxzSyv4GW9odo_HIsWH-cqbtkpI_jUiHPYPG6TcYfoH2iSzMNBTcr-hI0NJMgAvOTN_pZdY8bb8AtQ6csIa4DWNMJu5LKr1E8EyhxbPgV-L) to test out their internal framework Bloks. ##What to Expect of PWAs in 2022? The bright side is that there are some significant improvements in the PWA market. One recent positive development for PWAs is a partnership between Microsoft and Google. Microsoft [recently announced](https://medium.com/pwabuilder/microsoft-and-google-team-up-to-make-pwas-better-in-the-play-store-b59710e487) that PWABuilder will be using Google’s Bubblewrap technology. PWABuilder is Microsoft’s development tool that makes writing PWAs easier and Bubblewrap helps developers package their apps for distribution on the Google Play app store. This announcement came along with the introduction of support for new features including native app shortcuts and advanced Android features now available through PWABuilder. The collaborative efforts of tech giants like Google and Microsoft are extremely promising for the future of PWA adoption. ##Should you use PWA in 2022 and beyond? The answer is YES, if your product strategy requires fast market entry and coverage of multiple platforms with a single codebase. Progressive web apps allow startup companies to quickly and easily develop and distribute a progressive web app and benefit from the minimal time and money needed to roll out the app in the case of limited resources. Encouraging the first time users to revisit the application and getting them engaged with the help of push notifications and in-app banners make PWAs the powerful tool for marketing strategy implementation. Larger corporations can also benefit from providing value to their users with limited access to high-performance platforms or who prefer a more streamlined, lightweight experience. PWA can be a choice for development of an enterprise software tied to a selected single platform to benefit from the important native features supported exactly by this platform. Other frequent use cases for PWA are when your application requires support of offline mode, or you need your legacy web application, for example, made with React, to be remade into PWA with the minimal time in comparison to building a new app from scratch, for example, in Flutter for Web. ###WHEN YOU SHOULD NOT USE PWA While there are some drawbacks of PWAs, these are minimal and mostly outweighed by their benefits. The biggest restriction for PWAs is their limited support on iOS, which obviously comprises a significant portion of the mobile app market share. There is some support, however, and Apple’s changing stance on PWA in the past shows that they are willing to evolve with it. Another limitation which can prevent you from using PWA is that your app can’t be published in the AppStore, however it’s easy to [list it on Google Play](https://chromeos.dev/en/publish/pwa-in-play) and already possible to [make it live in the Microsoft Store](https://developer.microsoft.com/en-us/microsoft-store/pwa/). At MobiDev, we start a project from the business analysis stage to identify the key product requirements and help a business owner understand which requirements may provide the most value to the business and which technology stack fits the project goals. ##Progressive Web App Development at MobiDev MobiDev’s web engineering team has gained significant experience in web application development, including progressive web applications, and we are eager to share the best practices we follow: ###8 RECOMMENDATIONS FOR PWA DEVELOPMENT 1. The PWA should feel like a native app – it’s a good practice to show splash screens during the application startup, the app should have a set of icons of different sizes that will be used on the home screen as the app logo and a properly configured theme. 2. Some browsers still do not have complete support of manifest.json, so you have to fallback to meta tags, e.g. to specify theme or tile colors in Safari or Microsoft Edge. 3. Make sure to always [promote the app installation](https://web.dev/customize-install/). The app installation or “add to home screen” functionality along with push notifications are the killer features that dramatically improve conversion rate and users re-engagement. 4. If your app needs the offline mode support or you simply want to use enhanced caching strategies in order to reduce the network traffic and decrease page load time – we’d recommend you to check out the official set of libraries from Google, which is specifically designed to solve these problems and ease the PWA development. 5. Whenever the new version of PWA app goes live we must let the user know about the available updates. We may achieve that by displaying custom in-app banners or notifications, prompting a user to update the application. Please note, that the ServiceWorker won’t automatically update until all the application windows or tabs that are using the previous version are closed. If we don’t show the banner, the user might not know about the updates for quite some time. 6. As we said, some users might not update the app right away and will be using the old versions. In this case, it’s absolutely crucial to have backwards compatible APIs on the server. 7. Make sure to thoroughly test the code, especially the app initialization logic. In case the app crashes during its initialization and it hasn’t yet established a subscription for the incoming ServiceWorker updates, the user’s device might be stuck with a buggy app version until it’s manually reinstalled. It’s recommended to always create some fallbacks to automatically unregister the active ServiceWorker in case of unhandled application errors – in this case you’ll be able to quickly deliver fixes to the end user. 8. The PWAs should be fast. You may test and debug the performance using [Lighthouse](https://developers.google.com/web/tools/lighthouse/) and other [Chrome DevTools](https://developer.chrome.com/docs/devtools/). Of course we are following all other best practices applicable to a regular web app development: * Create responsive and adaptive web applications that properly work on all platforms regardless if it’s mobile, tablet or desktop. * Follow the established code style in the team, or establish it yourself by configuring the pre-commit git hook which will invoke code linters and formatters. * Write strictly typed code if possible (e.g. using TypeScript). * Design component-based applications. Decouple UI and business logic. Create simple and reusable components that are easy to compose into a complex UI. * And of course perform code reviews and help each other!
sergeyrykov
902,927
Python Programming Bundle by O'Reilly
Python Programming Book Bundle by O’Reilly Want to improve your Python programming… or just getting...
0
2021-11-19T11:52:06
https://dev.to/haze/python-programming-bundle-by-oreilly-bjl
python, beginners, machinelearning, codenewbie
**[Python Programming Book Bundle by O’Reilly](https://www.humblebundle.com/books/python-programming-oreilly-books?partner=indiekings)** Want to improve your Python programming… or just getting started learning? Humble Bundle teamed up with O’Reilly for the newest bundle that will help you on your way. This coders’ package comes with $677 worth of eBooks for people of all experience levels, including Introducing Python, 2nd Edition; High Performance Python, 2nd Edition; as well as eBooks containing specialized knowledge like Web Scraping with Python, 2nd Edition; Test-Driven Development with Python, 2nd Edition; and many more. This bundle helps support Code for America, using the principles and practices of the digital age to improve how government serves the American public, and how the public improves government. The Python Programming Book Bundle by O’Reilly bundle launched on November 15, at 11:00 am PST and lasts through December 6, 2021, 2021. Pay what you want and support charity!
haze
903,131
How to customize Tailwind CSS Typography
Tailwind CSS Typography provides a set of prose classes you can use to style your markdown posts. But...
0
2021-11-19T16:09:56
https://ertas.dev/posts/how-to-customize-tailwind-css-typography/
beginners, css, webdev, tutorial
Tailwind CSS Typography provides a set of prose classes you can use to style your markdown posts. But sometimes the default styles are not enough to hit the mark. That's when Tailwind's customization API swoops in to save the day. If you don't know what Typography is, you should read [How to style markdown with Tailwind CSS](https://ertas.dev/posts/how-to-style-markdown-with-tailwind-css/) to learn more. Inline code styling that comes default with the plugin is one style that is replaced by many. It inserts back ticks before and after the inline code and makes it bold, instead of the more common approach: ` <p> Hello world! </p> ` The solution to this is customizing the `tailwind.config.js` file. This allows you to target specific Tailwind classes and adjust their default behavior. ```javascript // tailwind.config.js module.exports = { theme: { extend: { typography: { DEFAULT: { css: { 'code': { color: "#333", // You can also use @apply to inline existing utility classes "@apply bg-gray-50 text-gray-700": "", }, 'code::before': { content: '""' }, 'code::after': { content: '""' } } } }, }, }, plugins: [require("@tailwindcss/typography")], }; ``` Above example is only modifying the look of the inline code blocks. But the same method applies when altering different selectors. ```javascript // tailwind.config.js module.exports = { theme: { extend: { typography: { DEFAULT: { css: { color: '#333', a: { color: '#3182ce', '&:hover': { color: '#2c5282', }, }, }, }, } }, }, plugins: [ require('@tailwindcss/typography'), // ... ], } ``` You can also add new modifiers by creating a new key under `typography`. ```javascript // tailwind.config.js module.exports = { theme: { extend: { typography: { '3xl': { css: { fontSize: '1.875rem', h1: { fontSize: '4rem', }, // ... }, }, }, } }, plugins: [ require('@tailwindcss/typography'), // ... ], } ``` If you want to delve into more detail, you can check out the [repository](https://github.com/tailwindlabs/tailwindcss-typography).
oerts
903,306
Change Blindness
Designing interfaces always happens with a goal in mind, whether it’s a purchase, sending a form, or...
0
2021-11-22T12:46:57
https://www.itmagination.com/blog/ux-ui-change-blindness
ui, ux, design, psychology
--- title: Change Blindness published: true date: 2021-11-19 00:00:00 UTC tags: ui, ux, design, psychology canonical_url: https://www.itmagination.com/blog/ux-ui-change-blindness cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hseda95no0tiqjbbqfqk.png --- Designing interfaces always happens with a goal in mind, whether it’s a purchase, sending a form, or performing a calculation. A properly designed UI may influence an outcome of a task dramatically. The way it’s built may mean the difference between failure and success. It’s because in the midst of all tasks, schedules, and to-do lists — it’s too easy to miss a change. Were you ever in a situation where you wanted to attend a meeting on Teams that either already happened in the past, or one that is coming up in the future? If so, it might have been because you missed a change in time; especially in a situation when your calendar is frequently updated. **Our senses are relentlessly bombarded by the constant waves of triggers that can overwhelm our brains.** ## Change blindness is you missing new visual details added to an existing canvas. ### The Gorilla In The Room Daniel Simmons & Christopher Chabris have conducted an experiment at the University of Harvard, during which they showed everybody a video. In the video, you will see two teams playing with a ball. One is in black t-shirts, while the other team is in white t-shirts. Scientists asked participants to watch the video and count how many passes the two teams completed. Please watch the video, and let’s see if you will get the number right. {% youtube vJG698U2Mvo %} Now that you have watched the video, have you gotten the number correct? More importantly, though. Noticed anything unusual there? Maybe a gorilla? Watch the video again now. This time, don’t count the passes. During the original study, almost half of the participants did not notice the gigantic monkey. Did you? ### A Good Old Switcheroo In another experiment, a passer-by asked a stranger for directions. During the conversation, the person asking for directions was replaced by somebody else. Yet again, almost half of the “victims” did not notice the change. {% youtube VkrrVozZR2c %} Despite our best intentions, we can only focus on one task at a time (we're looking at you, people who talk over their phones while driving). ### Vans - Off The Mark Another example of Change Blindness is the now changed mobile version of Vans’ website. ![Vans's website](https://global-uploads.webflow.com/601be0f0f62d8b2e2a92b830/6197abc0b9125b023722eb82_MDRSZ1BOX9tPP9xd6lf4rBv1ZCU6PCaCQb2IKzRG9DE2AWKZbEQF7EITtI4B40Clq0TBPbGXn8OWBGXugy4-0RITQ4wyN0VL6i8IyYAvpwgv-yK6Thxv67VTAyBxj7jjjcCc4LHG.png) When a user chooses a size that is not available, the button label, saying “Add To Cart” changes to “Out Of Stock.” The difference was not visible enough, however, as the difference in text was not big enough. In the current version, if a shoe size is not available anymore, you may see it right away, and the button to add it to cart is disabled. ## What could be a factor in “change blindness”? What we say is transformed and interpreted by our brain. To make the world comprehensible, it has to prioritize what is the most important for us to reach our goal. On the flip side, it filters out anything that is unnecessary for us. Any pauses in our perception, such as when a website loads, or when we blink, will most likely not get picked up. Sadly, even the best designed communication, be it on buttons or progress bars, if noticed by your user, might mislead them. If we want to support your users in reaching their goals, you have to remember a few things. ## How can you design better interfaces? ### Changes need to be signaled clearly If we filter data too fast, the person on the other end might not notice the change. It is therefore necessary to appropriately accentuate the shift with the right alert that something happened, or that something is about to happen. Take a look at a notification you get when your phone battery is low. It is close to impossible to miss it, and probably after getting it, you started to frantically look for your charger. ![An graphic showing an alert saying "Low battery" "20% battery remaining"](https://global-uploads.webflow.com/601be0f0f62d8b2e2a92b830/6197ac0e2bce2e35ac24ea35_u9NdNjpeKSjZPUTBc4fI3BIhjjyL1HWnJZ3f-yihRL1HcyWbdnqYUI6RZP2Ei-NL5qwZWrh50HjaqDSyMFjHxPu7zu0yrAj441VQkIrS-1Wk21RrWsQ2qHZKbbII2VO4amTWCFnf.png) There is a good rule of thumb — your change will likely picked up if you will be able to notice it even if you lean back and squint your eyes. ### The right positioning A good practice is to design your interface to place key information close to the place where your users might be working on their task. For example. when somebody is filling out a form, make sure to display feedback right next to the place where somebody is editing data. ![A graphic showing a personal info form with errors below the text inputs](https://global-uploads.webflow.com/601be0f0f62d8b2e2a92b830/6197ac4b66833757bad74b38_A-Lcoxzczowk5K3xO3zvPQs7em-KZVDBMd1xFiC610LZQUV62r5iSeCHjZilO0UmxDxhKOg04kDLW9h8YrI8rd1rmYMLGLP-MvXFrLp6FTwR9UbA7zp6Txozl2xF6kjULf18lG2s.png) ### Animations Animated icons or feedback after an action moves somebody’s sight to the place where it is required. Thanks to that, any alterations will not go unnoticed. Remember not to overload your app with animations because there is a risk that a key shift will be missed among the chaos. **In conclusion**, remember that your users need clear communication when something changes on a page, especially if this is a critical alert. The ways you can avoid change blindness are through clear signals, good positioning of those signals, and animating this signals when appropriate to make sure that there is a clear change happening for the user. You can take a deeper dive into [Change Blindness in this piece published by the Nielsen Norman Group](https://www.nngroup.com/articles/change-blindness-definition/) and by checking out the dangers of change blindness in other cases like driving for example and how we are [overly confident in our abilities to track and respond to changes.](https://cognitiveresearchjournal.springeropen.com/articles/10.1186/s41235-019-0165-4#Sec36)
itmagination
903,332
🔓 How to Add Authorization to a Rails API Following TDD
Learn how to secure a Rails API with Auth0 by letting you drive by tests. When...
0
2021-11-19T18:40:46
https://dev.to/robertinoc_dev/how-to-add-authorization-to-a-rails-api-following-tdd-36b
rails, tdd, security
#### Learn how to secure a Rails API with Auth0 by letting you drive by tests. ### <br> When you're adding authorization to an application, there are two crucial questions: - Are users that shouldn't have access _actually_ out? - Are users that should have access _actually_ in? If you can't answer with certainty both questions, how can you claim to have a secure application? This is something that you can test manually, but a better alternative is test automation. Concretely, I think the best methodology to get there is using Test-Driven Development ([TDD](https://en.wikipedia.org/wiki/Test-driven_development)). This piece is about adding authorization to a [Ruby on Rails](https://rubyonrails.org/) API by following TDD. You can check out [this article to learn in detail how to secure a Rails API with Auth0](https://auth0.com/blog/secure-rails-api). Also, you can follow this article along with this [repository](https://github.com/auth0-blog/securing-api-rails). ## The TDD Cycle In its essence, TDD is about a loop with the three steps shown in the following picture: ![TDD loop](https://images.ctfassets.net/23aumh6u8s0i/3FjI42yPKNne2NmL01bPbf/08cd0fca38b916370207e3a16f1c174e/tdd.png) <p align="center">[[*Source: Thoughtworks*](https://www.thoughtworks.com/insights/blog/test-driven-development-best-thing-has-happened-software-design)]</p> - First, you make a test for a new feature. Initially, the **test will fail**. - Then, you write the minimum amount of code that **makes the test pass**. - Lastly, you **refactor** the code to make the implementation more solid. Simple, isn't it? It creates a feedback loop where you write code incrementally to fulfill the task at hand. Moreover, it ensures that you build testability, i.e., you write your code so that it can be tested. To show how to use TDD, let's add authorization to our application step by step, starting with tests. I will use [OAuth](https://auth0.com/docs/protocols/protocol-oauth2) to authorize requests to the API via Auth0. As I explained in [my previous article](https://auth0.com/blog/secure-rails-api), you can <a href="https://auth0.com/signup" data-amp-replace="CLIENT_ID" data-amp-addparams="anonId=CLIENT_ID(cid-scope-cookie-fallback-name)">sign up for a free Auth0 account</a>. Check it out to get [all the details about setting up Auth0](https://auth0.com/blog/secure-rails-api/#Creating-an-API-on-Auth0). ## The Starting Application Our journey starts with an API bootstrapped with Rails 6. It has three routes that need different levels of protection: - `/api/messages/public`: Public route. - `/api/messages/protected`: Requires a valid access token. - `/api/messages/admin`: Requires a valid access token. Since Auth0 uses JWT as its access token format, we can inspect it and make sure it has a `permissions` claim that contains the scope `read:admin-messages`. This [branch](https://github.com/auth0-blog/securing-api-rails/tree/starter) is the correct starting point. These are the baseline tests for the three routes: ```ruby # spec/api/messages_controller_spec.rb require 'rails_helper' describe Api::MessagesController, type: :controller do describe '#public' do subject { get :public, params: { format: :json } } it 'returns an accepted answer for the public endpoint' do subject expect(response).to be_ok message = 'The API doesn\'t require an access token to share this message.' expect(json_response!).to include('message' => message) end end describe '#protected' do subject { get :protected, params: { format: :json } } it 'returns an accepted answer for the protected endpoint' do subject expect(response).to be_ok message = 'The API successfully validated your access token.' expect(json_response!).to include('message' => message) end end describe '#admin' do subject { get :admin, params: { format: :json } } it 'returns an accepted answer for the admin endpoint' do subject expect(response).to be_ok message = 'The API successfully recognized you as an admin.' expect(json_response!).to include('message' => message) end end end ``` We're not enforcing authorization yet. The requests work, but that'll change soon enough. To launch the tests, move in the project's root folder and run the following command: ```shell ./go test ``` The `go` script allows you to execute different tasks, but we will use it here to run our tests. For now, we have a pleasant list of green tests, as you can see in the following screenshot: ![Green tests with unprotected endpoints](https://images.ctfassets.net/23aumh6u8s0i/5MNgIu9a2dQIHpWXCf2Lro/58ec0f5a6a59a3a05dd7d8248351b2df/green-tests-unprotected-endpoints.png) [Read more...](https://auth0.com/blog/authorization-for-rails-api-with-tdd/?utm_source=content_synd&utm_medium=sc&utm_campaign=rails)
robertinoc_dev
903,355
How to create Exam/Registration Number or pin in php/laravel
To create an exam Number pin in php/laravel. You can achieve that using this approach function...
0
2021-11-19T20:25:10
https://dev.to/jovialcore/how-to-create-examregistration-number-or-pin-in-phplaravel-5go4
laravel
To create an exam Number pin in php/laravel. You can achieve that using this approach ```php function reg_number($id) { $regNum = ''; $uniqueId = str_pad($id, 4, '0', STR_PAD_LEFT); $date = date('y'); $regNum = "SCH" . '\\' . $date . '\\' . $uniqueId; return $regNum; }; ``` The function accepts a single parameter. The function starts with an initialised $regum variable followed by a variable `$uniqueId` where we use str_pad() php native function that takes the first parameter which can be any positive integer, followed by a digit, for example, `4` that determines the number of zeros which is the 3rd parameter, `'0'` then the zeros (0s) are appended to the left by `STR_PAD_LEFT` A typical result is as follows: ```php echo str_pad(6, 4, '0', STR_PAD_LEFT); // 0006 ``` Next, we will need to get the last two digits in a typical calendar year with: ```php $date = date(y); echo $date; // 21 ``` Then actual variable, $regNum, is where we concatenate the school name, say `Sch` followed by a backslash then year as `$date` and lastly the unique id number as `$uniqueId` then we return `return $regNum`; Typical result is : ```php echo reg_number(6); // SCH\21\0006 ```
jovialcore
903,358
MongoDB Relationships using Mongoose in NodeJS
Pre-requisites: Basic Knowledge of Mongo &amp; Mongoose Watch This Video on Thinking...
0
2021-11-19T19:59:33
https://dev.to/alexmercedcoder/mongodb-relationships-using-mongoose-in-nodejs-54cc
mongodb, mongoose, node, database
#### Pre-requisites: - [Basic Knowledge of Mongo & Mongoose](https://youtube.com/playlist?list=PLY6oTPmKnKbaSCVF-Imd1hkQJvl8iLrV3) - [Watch This Video on Thinking Through Your Datas Structure](https://youtu.be/-rrVvYs1DkQ) ## Terminology **Schema** A description of the shape a unit of data should undertake. So for a house isn't the data, but a description of what the data of a house should look like. ```js const mongoose = require("mongoose") const houseSchema = new mongoose.Schema({ street: String, city: String, state: String, zip: String }) ``` **Schema** If we want to manage a collection of documents (a bunch of items) of this datatype we then declare a model. This creates a collection and becomes the conduit to add, update, delete and retrieve data from the collection. ```js const House = mongoose.model("House", houseSchema) // query for all houses House.find({}) ``` ## One to One Relationships One to One relationships are the simplest. Imagine that every house can only have one owner, and every owner can only own one house. This is a one to one relationship. everything is unique on both sides there really isn't a need for more than one collection. Instead we can nest one type of data in the other. ```js const mongoose = require("mongoose") const Owner = new mongoose.Schema({ name: String }) const houseSchema = new mongoose.Schema({ street: String, city: String, state: String, zip: String owner: Owner }) const House = mongoose.model("House", houseSchema) // Create a new house House.create({ street: "100 Maple Street", city: "Fort Townville", state: "New West Virgota", zip: "77777" owner: {name: "Alex Merced"} }) // query for all houses, will include the nested owner info House.find({}) ``` ## One to Many Let's see how we can refactor this to handle a Owner having many Houses, but Houses only having one owner. This is One to Many. So Owners are the "one" side of the relationship, and House is the "many" side. Typically what we do is track the one side from the many side (it's the house data that'll track the owner). With mongoose we have a special datatype that tells mongoose that the entries in that field are all objects _ids of documents in some other collection. See this at work below. The populate function when we query the data will make sure mongoose fetches the data from the related table and inserts where needed. Note: You do also have the option of nesting an arrya of House in the Owner schema, although there is a maximum size for one document that can cause scaling issues later if you try to nest too much data. ```js const mongoose = require("mongoose") const ownerSchema = new mongoose.Schema({ name: String }) const Owner = mongoose.model("Owner", ownerSchema) const houseSchema = new mongoose.Schema({ street: String, city: String, state: String, zip: String owner: {type: mongoose.Types.ObjectId, ref: "Owner"} }) const House = mongoose.model("House", houseSchema) // Create a Owner const alex = await Owner.create({name: "Alex Merced"}) // Create a new house House.create({ street: "100 Maple Street", city: "Fort Townville", state: "New West Virgota", zip: "77777" owner: alex }) // query for all houses, use populate to include owner info House.find({}).populate("owner") ``` ## Many to Many In all reality, houses can have many owners and owners can have many owners, so we truly have a many to many relationship. In this situation we create a third collection to track the different matches. ```js const mongoose = require("mongoose") const ownerSchema = new mongoose.Schema({ name: String }) const Owner = mongoose.model("Owner", ownerSchema) const houseSchema = new mongoose.Schema({ street: String, city: String, state: String, zip: String }) const House = mongoose.model("House", houseSchema) const houseOwnerSchema = { owner: {type: mongoose.Types.ObjectId, ref: "Owner"}, house: {type: mongoose.Types.ObjectId, ref: "House"} } const HouseOwner = mongoose.model("HouseOwner", houseOwnerSchema) // Create a Owner const alex = await Owner.create({name: "Alex Merced"}) // Create a new house const mapleStreet = await House.create({ street: "100 Maple Street", city: "Fort Townville", state: "New West Virgota", zip: "77777" owner: alex }) // Create record that the owner owns the house HouseOwner.create({owner: alex, house: mapleStreet}) // QUery for all houses owned by alex HouseOwner.find({owner: alex}).populate("house") //Query for all owners of the Maple Street House HoseOwner.find({house: mapleStreet}).populate("owner") ``` ## Conlusion Hopefully this helps in implementing relationships in your next application.
alexmercedcoder
903,368
hello
hello
0
2021-11-19T20:15:01
https://dev.to/rezahosseiniseo/hello-440h
hello
rezahosseiniseo
903,409
Internal Project Contribution
In this Release 0.3, there are 3 different requirements. And the second one is about Internal Project...
0
2021-11-19T21:12:03
https://dev.to/derekjxy/internal-project-contribution-4kcb
opensource, c, github, beginners
In this __Release 0.3__, there are 3 different requirements. And the __second one__ is about __Internal Project Contribution__. For this internal project contribution, I selected a repository that from `IPC144`. And the issue that I selected was about Audit a `MD` file. This `MD` file is about the knowledge that we learn in __IPC144__. And the topic I selected was `Two-Dimensional-Arrays`. The __reason__ I picked this topics was I thought this is an __interesting topic__ and I wanted to __review__ the two-dimensional-arrays __content__. ###Procedure Here is a checklist I created to this issue: ![Checklist](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a0gwlzpyyy83r3xhmxm7.png) What I did was just follow the checklist. The first time that I read through the `two-dimensional-arrays.md` file, I think that it looks good! But that doesn't right! Since there is an issue, it has to have some things to improve. So, I just read the `MD` file again and I found some problems. __Firstly__, I found that the sentences that in each paragraph was __break by two spaces__, which is not a normal way we do in our daily life. __Secondly__, I found that the image that the `MD` file using is __missing a alt text__. __Thirdly__, I found that the code examples in the `MD` file are __indented too much__. __Last but not least__, I found that there are __a few__ `<br />` inside the `MD` file. And I can't find any of of these problems above at the first time. __Since__ there were many __problems__ I listed out after the second time of reading. I began to make __improvements__. After solved the problems that I found at the second time of reading. I told myself, "Perhaps there are more improvement you can make after your third - forth times of reading." __Thus__, I read the `MD` again after I fixed those problems. However, I only found two more issues after my forth times of reading. __The first one__ was the `MD` file is lack of highlighting words. This is a reading for those students in IPC144, they are new to C language. And I believe that with some highlighting words, this documentation will be easier for them to read and learn! __The second one__ was the code example in the documentation again. I found that I can make some improvement to the for loop code with `{}` so that they look better. After these two improvements I made, I decided to make the `Pull Request`. I would like to ask help from other contributors. As long as I make the PR, they would have a chance to review my PR and they might come up with some better ideas to audit the `MD` file! __Surprisingly__, I got 3 more [suggestions](https://github.com/Seneca-ICTOER/IPC144/pull/108) from other contributors! __①__: A solution to make the imagine looks nicer in dark mode! ![Image_In_Dark_Mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ju7053kx76zjnn9ob7qe.png) __②__: Edit the alt text and Update the Frontmatter! ![Image_description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2fub7daaao1k1yu7g9j9.png) ![Frontmatter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96sutnccjbptup3ohq6l.png) __③__:Add admonition! ![Admonition](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vz25jax6okwiiqksmyl6.png) The suggestions above are really __good improvements__ for the `MD` file that I worked at. Therefore, I accepted the suggestions and update the `MD` file based on their ideas. __Finally__, I combined all the improvements I made and all the suggestions from other friendly contributors together to make the final `PR`. Fortunately, the owner of the repository __accepted my PR__ and `merged` it to the main repository __in a short time__! ###My Feelings This is an __interesting__ contribution. I'm really __happy__ that I can help to improve the documentation in the repository that belongs to my College. Also, I realized that __making contributions with other people__ is a very good way. Because _other people would see what you've missed at the first time_. And sometimes that could be a _small issue_, but sometimes that could be a __huge issue__. And no matter what, having someone else to help contributing on `Github` is always a __good thing__! Link to the origin Repo I worked:[ [IPC144](https://github.com/Seneca-ICTOER/IPC144) ]
derekjxy
908,376
Reminder — Join the GitHub Actions Hackathon 2021 on DEV ⏰
A reminder for those of you participating in the GitHub Actions Hackathon this year — or those considering it!
0
2021-11-25T00:11:29
https://dev.to/devteam/reminder-join-the-github-actions-hackathon-2021-on-dev-6h2
meta, actionshackathon21
--- title: Reminder — Join the GitHub Actions Hackathon 2021 on DEV ⏰ published: true description: A reminder for those of you participating in the GitHub Actions Hackathon this year — or those considering it! tags: meta, actionshackathon21 cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kewek3tv0gf03xftufuw.png --- #### **This year's GitHub Actions Hackathon on DEV closes on December 8th, 2021 @ midnight PST** _(i.e. 8 AM UTC the following day)_ --- It's been so much fun watching submissions come in for the **[2021 GitHub Actions Hackathon on DEV](https://dev.to/devteam/join-us-for-the-2021-github-actions-hackathon-on-dev-4hn4)**. I highly encourage all of you to check out all the submissions so far — impressive stuff! As a reminder, this contest challenges you to utilize GitHub Actions (either new or existing) to create a customized and _usable_ workflow across five categories (Maintainer Must-Haves, DIY Deployments, Interesting IoT, Phone Friendly, & Wacky Wildcards). The reward? DEV Community glory (signaled with a limited-edition badge) — oh, and a chunk of the $10,000 cash prize pool plus additional swag 🤑 ### **[>> Full details and participation rules here](https://dev.to/devteam/join-us-for-the-2021-github-actions-hackathon-on-dev-4hn4)** --- ### **Additional resources** > _If you have any questions about Actions, GitHub, or the hackathon in general, please refer to this help thread, which is being monitored by the GitHub and DEV teams_: {% link https://dev.to/devteam/github-actions-hackathon-2021-help-thread-1lk0 %} > _If all you need is some positive encouragement or if you want to connect with other participants, leave a comment in this thread_: {% link https://dev.to/devteam/share-your-github-actions-hackathon-2021-updates-57k %} --- ## Happy coding and enjoy this challenge! Two weeks remain!
graciegregory
910,310
Wa! My API on the npm!!!
Github repo: https://github.com/juuuuuuun/jun-ssg Npm package:...
0
2021-11-27T02:45:23
https://dev.to/juuuuuuun/wa-my-api-on-the-npm-1i94
npm, javascript, opensource
Github repo: https://github.com/juuuuuuun/jun-ssg Npm package: https://www.npmjs.com/package/jun-ssg #OverView Finally, the last lab 10!!! When I first started, I couldn't see the end of how to finish so many steps, but I can almost see the end with the semester :) The task of this lab is to check whether the partner and each other's npm package work well after uploading the SSG API, which we have been working on as a release and lab, to npm! #What I have done To meet the requirements of this lab, I chose npm. In addition, it was decided to set 1.0.0 as the release version based on the lab of the previous week for the release of the software. (1.0.1 as a modification of the current README) After that, the first thing I did was add the version part using git tag. First, in order to match the version with the git tag in package.json, `version` was set to 1.0.0. After that, through the code below ``` git tag -a v1.0.0 -m "my version 1.0.0" ``` Added version tag. Afterwards, it was confirmed that the version was added normally through `git show`, We confirmed that the version was successfully added to the Github repository through ``` git push origin 1.0.0 ``` ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fzg1tmg5440lkbl4migr.png) Finally, after signing up for npm ``` npm adduser ``` and ``` npm publish --public-access ``` Finally, all the process I can do is over..! Now, you can use the SSG API I made anywhere as long as there is an internet connection through the command below! :) ``` npm i jun-ssg ``` &nbsp; ##Partner's experience My great partner, Hung, tested my npm package and was a bit confused in the readme (difference between npm and git versions), but soon recognized the difference and successfully downloaded the package and actually ran it. Fortunately on his machine, my package worked just fine and produced a successful html output. However, he updated the Readme version because he felt confused in the Readme. &nbsp; ##My test about partner's npm package Unfortunately, there was a problem with the partner's npm package, so testing was delayed. Hung's npm package worked very well, contrary to what I thought (sorry Hung(人´З`)). ``` npm i osd600-ssg ``` I tried to download and run it simply through the above command, and I checked that all functions were working properly. :) However, in the README, in the case of the npm version, it would be better to distinguish more precisely the difference between the usage and the case of downloading and using it from Github. &nbsp; #With Closing Final Lab.. To be honest, this lab10 was easy to complete because there was no process of making something new or very difficult. However, this is not to say that I didn't learn anything or that I liked it because it was easy. With this lab10, the question I had been wondering about how many kinds of APIs were uploaded to npm and how easy it was to use was solved, and I was also able to learn the importance of version control and the meaning of each part. It was a strange but very satisfying experience for someone to test and use my project. I think it will be one of the most important parts of my career and developing my skills going forward.
juuuuuuun
910,370
Using async runtimes together
Using both Tokio and async-std together Option 1 using async-compat //...
0
2021-11-27T06:06:34
https://dev.to/toyster/using-async-runtimes-together-3la4
rust
## Using both Tokio and async-std together ### Option 1 using `async-compat` ``` rust // async-compat = "0.2.1" // async-std = {version = "1.10.0"} // tokio = { version = "1", features = ["full"] } use async_compat::Compat; async fn say_hello() { println!("Hello, world!"); } fn main() { async_std::task::block_on(Compat::new(async { tokio::spawn(async { say_hello().await; // some async function println!("this is also hello") }); })); } ``` ### Option 2 using async-std's `tokio1` runtime ``` rust // async-std = {version = "1.10.0", features = ["attributes", "tokio1"]} // tokio = { version = "1", features = ["full"] } async fn say_hello() { println!("Hello, world!"); } #[async_std::main] async fn main() { let t = tokio::spawn(async { say_hello().await; // some async function println!("this is also hello") }); t.await.unwrap() } ```
toyster
910,527
Make Custom Blade If Directive - Laravel
Let's start quickly if we want to define admin areas via If Directive We start User.php in...
0
2021-11-27T09:39:07
https://dev.to/morcosgad/make-custom-blade-if-directive-laravel-advanced-4g2c
laravel, php, programming, beginners
Let's start quickly if we want to define admin areas via If Directive We start User.php in Models ```php public function isAdmin(): bool { return $this->type === 'admin'; } ``` in blade use isAdmin() ```blade @if(auth()->user()->isAdmin()) For Admin @endif ``` To make the code more interesting in AppServiceProvider.php ```php public function boot() { Blade::if('admin', function(){ return auth()->user()->isAdmin(); }); } ``` in blade use @admin ```blade @admin For Admin @endadmin ``` We can check if the user is logged in or not by check() ```php public function boot() { Blade::if('admin', function(){ return auth()->check() && auth()->user()->isAdmin(); }); } ``` We can also use else ```blade @admin For Admin @else Not Admin @endadmin ``` I hope you enjoyed the code.
morcosgad
910,646
A look at the ch CSS unit
A while ago, I wrote about the [Tailwind typography plugin]. I was pretty blown away by how easy, and...
0
2021-11-27T12:53:52
https://daily-dev-tips.com/posts/a-look-at-the-ch-css-unit/
css
A while ago, I wrote about the [Tailwind typography plugin]. I was pretty blown away by how easy, and readable big text elements become. After researching their applied styles, I've noted the prose class actually goes off on the `ch` unit. ```css .prose { max-width: 65ch; } ``` This is based on the width of the 0 character for a specific font! Yes, so changing the font might affect this. And the result is that it actually makes a super readable width. ## Seeing the ch unit in action Let's give this a try and make a demo with it. For the HTML, we render two sections with different classes to represent the different fonts. ```html <section class="georgia"> <p>copy</p> </section> <section class="helvetica"> <p>copy</p> </section> ``` Let's add some basic styling so we can see these two sections under each other. ```css body { min-height: 100vh; display: flex; justify-content: center; align-items: center; flex-direction: column; margin: 0; } section { display: flex; align-items: center; } p { max-width: 65ch; } .georgia { font-family: Georgia, serif; } .helvetica { font-family: helvetica, sans-serif; } ``` As you can see, we use the same `max-width` value for both elements, but once we see the end result, the one is bigger. ![CSS ch unit in action](https://cdn.hashnode.com/res/hashnode/image/upload/v1637045759612/0DRii0KY2.png) The image above shows that the top element rendering the `Georgia` font is wider. This is caused by its `0` (zero) being wider than the Helvetica font set. You can also have a play with it yourself in this Codepen. {% codepen https://codepen.io/rebelchris/pen/BadGOag %} ## Extra reading Shawn wrote this great article using this `ch` unit and just 100 bytes of CSS to make anything look great! Here are his magic bytes: ```css html { max-width: 70ch; padding: 3em 1em; margin: auto; line-height: 1.75; font-size: 1.25em; } ``` You can read the [full article on Shawn's blog](https://www.swyx.io/css-100-bytes/). To wrap this up, the `ch` unit is super powerful yet a bit unpredictable as the size might change. I really like it, as I don't do static pixel design anyway, but I'm looking forward to hearing your thoughts on the `ch` unit! ### Thank you for reading, and let's connect! Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
dailydevtips1
910,715
Templatico -- A RESTful API template
For many self-taught front end developers, migrating from one stack to another could be very heart...
0
2021-11-27T15:50:17
https://dev.to/opeolluwa/templatico-a-restful-api-template-2l82
productivity, opensource, javascript, api
For many self-taught front end developers, migrating from one stack to another could be very heart breaking 😬. # Prologue Had my fair share of the ordeal when I tried spinning up a RESTful API with PHP in a Vue - PHP project. The worse part of the tale is dealing with CROS. ## Templatico to the rescue So lately, I lay hold of Node.js, tried building an API the end of the story is initializing a lil project that let you spin up RESTful API in spilt second. I look forward to having more contributors to make the project more robust and of easy use for all🙂💃 See the project on GitHub : [Templatico](https://GitHub.com/Opeolluwa/Templatico) Follow me on Twitter : [@_opeolluwa](http://Twitter.com/_opeolluwa)
opeolluwa
910,728
How to scale your social media cover graphics to LinkedIn, Facebook, YouTube, and Twitter
Today, we’ll look at how to quickly create multiple cover sizes for LinkedIn, Facebook, YouTube,...
0
2021-11-27T16:17:48
https://dev.to/raoufbelakhdar/how-to-scale-your-social-media-cover-graphics-to-linkedin-facebook-youtube-and-twitter-1ann
figmaplugin, design, figma, socialmedia
--- title: How to scale your social media cover graphics to LinkedIn, Facebook, YouTube, and Twitter published: true date: 2021-11-27 16:14:35 UTC tags: figmaplugin,design,figma,socialmedia canonical_url: --- ![](https://cdn-images-1.medium.com/max/1024/0*qucPI13xYBtubF2_.jpg) Today, we’ll look at how to quickly create multiple cover sizes for LinkedIn, Facebook, YouTube, and Twitter faster. ### What You Will Need You’ll need the following resources to follow along with this Figma tutorial: **Install Thumblisher Figma Plugin:** Before getting started, make sure to install Thumblisher Figma Plugin to your Figma editor to resize your social media graphics easily. [https://www.figma.com/community/plugin/1037826586645134259/Thumblisher](https://www.figma.com/community/plugin/1037826586645134259/Thumblisher) **Download Exercise File:** To access the social media templates we’ll use in this tutorial, duplicate the Social Media Exercice File: [https://www.figma.com/community/file/1045659071341514535/Social-Media-Exercice-File](https://www.figma.com/community/file/1045659071341514535/Social-Media-Exercice-File) Find more resources on [https://www.captain-design.com/](https://www.captain-design.com/) ### Watch Video Tutorial {% youtube FSExC6Zdo1w %} ### Before you go Feel free to visit our website [**captain-design.com**](https://www.captain-design.com/) where we are sharing generously, ready for commercial use [**Figma and HTML templates**](https://www.captain-design.com/). You’ll find three things to help you kickstart your next project’s design : - [**200+ free Figma templates**](https://www.captain-design.com/templates/) **.** - [**Free Html + Bootstrap 5 templates**](https://www.captain-design.com/templates/tag/html) **.** - [**Amazing Figma Plugins and UI kits**](https://www.captain-design.com/uikit/) _Originally published at_ [_https://www.captain-design.com_](https://www.captain-design.com/blog/how-to-scale-your-social-media-cover-graphics-to-linkedin-facebook-youtube-and-twitter-cover-sizes-in-figma/) _on November 27, 2021._
raoufbelakhdar
911,095
Day 51 of 100 Days of Code & Scrum: Company Website & Professional Blog
Happy Sunday, everyone! This week I will be focusing on fixing any remaining bugs and deploying my...
14,990
2021-11-28T07:43:48
https://dev.to/rammina/day-51-of-100-days-of-code-scrum-company-website-professional-blog-54lh
100daysofcode, beginners, javascript, productivity
Happy Sunday, everyone! This week I will be focusing on fixing any remaining bugs and deploying my company website, as well as working on my professional blog. I most likely will work on them in that order, because I don't want to get distracted and leave anything unfinished. I think imposing a deadline on myself helped me be more productive last week, so I will most likely do that again. ## Yesterday Just like I do every weekend, I did my 7th Weekly Sprint Review and Retrospective, in which I went over what I've managed to do well, what my shortcomings were, and what I could do better in the future. ## Today I set up my weekly Sprint Goals, which will focus on my **company website and professional blog**. ## Weekly Sprint Goals - fix the bugs in my company website. - deploy my company website after cleaning everything up. - after the website, learn Ghost so I can use it to build my professional blog. - continue to learn Next.js and Typescript by using concepts while I build my website or maybe just from reading documentations. - continue studying for Professional Scrum Master I (PSM I) certification. - continue networking, but allocate less time to this (coding is more important). Have a great week, everyone! ![Rammina Thank You Banner](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9ayfxxxaz2g2hfcqbsk.png) ### Resources/Recommended Readings - [Official Next.js tutorial](https://nextjs.org/learn/basics/create-nextjs-app?utm_source=next-site&utm_medium=nav-cta&utm_campaign=next-website) - [The Typescript Handbook](https://www.typescriptlang.org/docs/handbook/intro.html) - [The 2020 Scrum Guide](https://scrumguides.org/scrum-guide.html) - [Mikhail Lapshin's Scrum Quizzes](https://mlapshin.com/index.php/scrum-quizzes/) ### DISCLAIMER **This is not a guide**, it is just me sharing my experiences and learnings. This post only expresses my thoughts and opinions (based on my limited knowledge) and is in no way a substitute for actual references. If I ever make a mistake or if you disagree, I would appreciate corrections in the comments! <hr /> ### Other Media Feel free to reach out to me in other media! <span><a target="_blank" href="https://www.rammina.com/"><img src="https://res.cloudinary.com/rammina/image/upload/v1638444046/rammina-button-128_x9ginu.png" alt="Rammina Logo" width="128" height="50"/></a></span> <span><a target="_blank" href="https://twitter.com/RamminaR"><img src="https://res.cloudinary.com/rammina/image/upload/v1636792959/twitter-logo_laoyfu_pdbagm.png" alt="Twitter logo" width="128" height="50"/></a></span> <span><a target="_blank" href="https://github.com/Rammina"><img src="https://res.cloudinary.com/rammina/image/upload/v1636795051/GitHub-Emblem2_epcp8r.png" alt="Github logo" width="128" height="50"/></a></span>
rammina
911,208
H
javascript:(function(){document.head.innerHTML+='&lt;style&gt;.dark,.dark canvas,.dark img,.dark...
0
2021-11-29T14:09:06
https://dev.to/ksengine/h-iad
```javascript javascript:(function(){document.head.innerHTML+='<style>.dark,.dark canvas,.dark img,.dark picture,.dark video{filter:invert(100%) hue-rotate(180deg)}canvas,html,img,picture,video{transition:filter .3s ease-in-out}</style>';document.documentElement.classList.toggle('dark');})(); ```
ksengine
911,285
Introduction à FastAPI (Python) : Partie 3
Voici une série d'articles qui vous permettra de créer une API en Python avec FastAPI. Je vais...
15,594
2021-11-29T12:38:55
https://dev.to/ericlecodeur/introduction-a-fastapi-python-partie-3-35b5
python, fastapi, beginners
--- title: Introduction à FastAPI (Python) : Partie 3 description: published: true tags: python, fastapi, beginner cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/99gtao8ehviefokwiten.png series: FastAPI --- Voici une série d'articles qui vous permettra de créer une API en Python avec FastAPI. Je vais publier un nouvel article régulièrement et petit à petit vous apprendrez tout ce qu'il y a à savoir sur FastAPI Pour ne rien manquer suivez-moi sur twitter : https://twitter.com/EricLeCodeur <hr> ### "Create" Jusqu’à présent nous avons couvert le READ du CRUD, voyons maintenant le "Create". Ici il ne s'agit plus de lire des données mais d'en créer une nouvelle. Pour créer un nouveau produit nous devons envoyer de l'information au serveur, et pour ce faire nous aurons besoin d'utiliser l'action HTTP POST ```jsx POST www.example.com/products ``` L'action POST permet d'envoyer des données du navigateur vers le serveur. ### Exemple Nous allons faire un exemple et ajouter le produit "MacBook" à notre liste de produit existant. Voici le résultat visé : ```python products = [ {"id": 1, "name": "iPad", "price": 599}, {"id": 2, "name": "iPhone", "price": 999}, {"id": 3, "name": "iWatch", "price": 699}, {"id": 4, "name": "MacBook", "price": 1299}, ] ``` Pour faire un POST avec FastAPI voici le code que vous devez utiliser ```python @app.post("/products") def create_product(product: dict, response: Response): product["id"] = len(products) + 1 products.append(product) response.status_code = 201 return product ``` Reprenons ce code ligne par ligne: ```python @app.post("/products") ``` Ce code permet de spécifier à FastAPI que cette requête sera une action POST "/products" ```python def create_product(product: dict, response: Response): ``` Ce code permet de définir la fonction qui sera lancée lorsque le serveur va recevoir la requête "POST /products" La fonction contient deux paramètres, un pour le produit et l'autre pour une référence à l'objet réponse. À noter que lorsque l'on fait une action POST les données à envoyer devront être inclus dans le body de la requête et devront l'être en format texte JSON. Dans cet exemple on voit toute la puissance et facilité de FastAPI. FastAPI sait qu'il s'agit d'une requête POST, Il va donc automatiquement prendre le JSON qui se trouve dans le body de la requête, le convertir en dictionnaire Python et placer le résultat dans le premier paramètre (product). Nous pouvons donc ensuite utiliser ce paramètre "product" pour ajouter le produit à notre liste de produit. ```python product["id"] = len(products) + 1 products.append(product) ``` Une fois que le produit a été ajouté avec succès, il faut retourner le code d'état approprié. ```python response.status_code = 201 ``` Ce code permet de retourner le code d'état 201 (Created). Qui indique que le produit est bel et bien créé avec succès. Enfin, par convention le nouveau produit est toujours retourné avec la réponse. ```python return product ``` ### Tester une action HTTP Post Les navigateurs web ne permettent pas de lancer une requête POST. Donc il ne sera pas possible de tester ce nouvel API à partir du navigateur. Nous avons un premier API, nous devons maintenant le tester. Les navigateurs web ne permettent pas de lancer une requête POST. Donc il ne sera pas possible de tester ce nouvel API à partir du navigateur. Il existe plusieurs autres façons de le faire. Nous pourrions utiliser un logiciel comme Postman et tester nos requêtes à partir de Postman. Un des avantages de FastAPI c'est qui produit automatiquement la documentation de notre API. Cette documentation permet aux usagers de comprendre comment utiliser notre API, quels sont les chemins URL disponible et également de lancer des requêtes. Nous allons donc pouvoir utiliser la documentation afin de tester notre API Comme mentionné, dans le cas de notre API la documentation est créée automatiquement. Pour la consulter, lancer le serveur ```json $ uvicorn first-api:app --reload Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) ``` et visiter /docs : ```json http://127.0.0.1:8000/docs ``` La documentation va s'afficher à l'écran ! ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hxxdw49rih6ze1l6gagv.png) Pour tester un chemin URL c'est très simple, il suffit de cliquer sur le nom du chemin et FastAPI dévoilera une interface permettant de tester ce chemin. Par exemple si vous cliquez sur POST/products vous verrez apparaître ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q20zbu2epc5hd57ftcd3.png) Vous pouvez ensuite cliquer sur "Try it out", saisir les données à ajouter dans la section "Request body" (voir exemple ici bas) ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l090r5vjtuicjbkjo3dc.png) Les données sont en format texte JSON ```json {"name": "MacBook", "price": 1299} ``` Enfin appuyer sur "Execute", la doc envoyer la requête POST à votre serveur FastAPI Le code d'état de la réponse ainsi que la réponse en tant que tel seront également affichés dans la page. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i3qkm2uxeh2r2vtnwko2.png) Cette documentation automatique est encore une autre belle démonstration de la puissance et facilité de FastAPI. Si vous désirez, vous pouvez cliquer sur tous les chemins un après l'autre afin de les tester. ### Validation Reprenons le dernier exemple que nous avons créé ```python @app.post("/products") def create_product(product: dict, response: Response): product["id"] = len(products) + 1 products.append(product) response.status_code = 201 return product ``` La fonction @app.post() fonctionne mais comporte plusieurs lacunes. En fait, il n'y a aucune validation et aucun message d'erreur n'est retourné si cette validation ne passe pas. Par exemple, pour créer un nouveau produit nous avons besoin du "name" et "price". Que se passe-t-il si seulement le "name" est envoyé mais pas le "price" ? Ou bien que se passe-t-il si le "price" n'est pas un format numérique. Je pourrais vous donner encore plusieurs exemples mais je crois que vous comprenez le concept. Pour faire ces validations et retourner les messages d'erreurs associées, il faudrait ajouter pas mal de code à notre fonction. Et il faudrait répéter ce code pour chaque action et chaque ressource. Le tout viendrait compliquer de beaucoup notre application. Heureusement que FastAPI porte bien son nom soit "Fast" API. Il existe donc une façon très simple d'implanter un système de validation automatique. Ce système ce sont les schémas ! ### Les schémas Les schémas sont des modèles de données qui servent à FastAPI pour valider nos fonctions. Par exemple nous pourrions définir un schéma comme celui-ci: ```python from pydantic import BaseModel class Product(BaseModel): name: str price: float ``` Ce modèle de donnée est très simple à comprendre. Nous avons une entité "Product" qui contient les attributs "name" et "price". Nous pouvons même définir de quel type sont les attributs. Une fois que nous avons défini notre modèle de donné, nous pouvons modifier notre fonction @app.post() ```python @app.post ("/products") def create_product(new_product: Product, response: Response): product = new_product.dict() product["id"] = len(products) + 1 products.append(product) response.status_code = 201 return product ``` Nous avons remplacé le paramètre de type "dict" par un paramètre de type "Product". Une fois cette modification faite, si vous testez cette fonction, vous verrez que FastAPI applique maintenant la validation automatique et retournera une erreur si ce que vous envoyez ne respecte pas le modèle "Product' ### Put L'action PUT permet de modifier une ressource existante. Comme l'action POST, il faut envoyer les données à modifier avec la requête. Voici un exemple d'une fonction PUT ```python @app.put("/products/{id}") def edit_product(id: int, edited_product: Product, response: Response): for product in products: if product["id"] == id: product['name'] = edited_product.name product['price'] = edited_product.price response.status_code = 200 return product else: response.status_code = 404 return "Product Not found" ``` Ici il n’y a rien de vraiment nouveau. C'est exactement les mêmes concepts que nous avons découverts un peu plus tôt. ### Delete L'action DELETE permet de supprimer une ressource. Voici le code qui permet d'implanter cette action ```python @app.delete("/products/{id}") def destroy_product(id: int, response: Response): for product in products: if product["id"] == id: products.remove(product) response.status_code = 204 return "Product Deleted" else: response.status_code = 404 return "Product Not found" ``` ### Base de données Le code que vous venez de créer pour implémenter le CRUD est bien beau mais il manque tout même une notion importante et c'est de relier la ressource avec une base de données. La prochaine section va justement vous expliquer comment faire étape par étape. ## Conclusion C'est tout pour aujourd'hui, suivez-moi sur twitter : https://twitter.com/EricLeCodeur afin d'être avisé de la parution du prochain article.
ericlecodeur
911,380
hey my siser
bạn đang tìm kiếm hóa chất đánh bóng sàn hay là mài sàn bê tông công nghiệp. gọi chúng toi nay
0
2021-11-28T14:52:35
https://dev.to/johnbro32653445/hey-my-siser-561m
bạn đang tìm kiếm [hóa chất đánh bóng sàn](https://decocrete.eu/vn/giai-phap-danh-bong-be-tong/) hay là [mài sàn bê tông công nghiệp](https://decocrete.eu/vn/mai-san-be-tong/). gọi chúng toi nay
johnbro32653445
911,443
Living in the Shell #5; ls (List Files/Directories)
ls 🚚 Lists directory content. Long list (detailed format) -l cd ~...
15,637
2021-11-28T17:37:58
https://babakks.github.io/article/2021/11/28/ls-005-living-in-the-shell-ls.html
productivity, linux, bash, devops
## `ls` 🚚 Lists directory content. ## Long list (detailed format) `-l` ```sh cd ~ && ls -l ``` > ```text > drwxr-xr-x 5 babak babak 4096 Nov 1 12:49 Desktop > drwxr-xr-x 9 babak babak 4096 Nov 21 18:49 Documents > drwxr-xr-x 2 babak babak 20480 Nov 23 17:21 Pictures > ... > ``` ## Show directories first `--group-directories-first` ```sh cd ~ && ls --group-directories-first ``` ## List directory itself, not its content `-d` ```sh cd ~ && ls -lhd Documents ``` > ```text > drwxr-xr-x 9 babak babak 4.0K Nov 21 18:49 Documents > ``` ## List all files (include dot-files) `-a` ```sh cd ~ && ls -a ``` ## Print human-readable sizes `-h` ```sh cd ~ && ls -lh ``` > ```text > drwxr-xr-x 5 babak babak 4.0K Nov 1 12:49 Desktop > drwxr-xr-x 9 babak babak 4.0K Nov 21 18:49 Documents > drwxr-xr-x 2 babak babak 20K Nov 23 17:21 Pictures > ... > ``` ## Sort by time `-t` ```sh cd ~ && ls -lht ``` > ```text > drwxr-xr-x 2 babak babak 20K Nov 23 17:21 Pictures > drwxr-xr-x 9 babak babak 4.0K Nov 21 18:49 Documents > drwxr-xr-x 5 babak babak 4.0K Nov 1 12:49 Desktop > ``` ## Sort by size `-s` ```sh cd ~ && ls -lhs ``` ## Reverse sort order `-r` ```sh cd ~ && ls -lhsr ``` > ```text > drwxr-xr-x 2 babak babak 20K Nov 23 17:21 Pictures > drwxr-xr-x 9 babak babak 4.0K Nov 21 18:49 Documents > drwxr-xr-x 5 babak babak 4.0K Nov 1 12:49 Desktop > ```
babakks
911,551
Array initialisation and key data types in PHP
When initialising PHP array elements the order of the keys can result in changes to all the key...
0
2021-11-28T20:07:03
https://dev.to/michaelvickersuk/array-initialisation-and-key-data-types-in-php-1e5b
php
When initialising PHP array elements the order of the keys can result in changes to all the key types, even when you explicitly specify the key value/type. ```php $foo[0] = 'a'; $foo[1] = 'b'; $foo[2] = 'c'; $foo[3] = 'd'; // $foo has integer keys $bar[0] = 'a'; $bar[1] = 'b'; // $bar has integer keys $bar[3] = 'c'; // $bar now has string keys, because we skipped element 2 // this is despite us using an integer key $bar[2] = 'd'; // $bar still has string keys, despite it having element 2 // and it being declared with an integer key json_encode($foo) !== json_encode($bar); // True ```
michaelvickersuk
911,701
React FullCalendar snippet
Create a simple calendar using React and FullCalendar
0
2021-11-29T02:58:15
https://dev.to/eichgi/react-fullcalendar-snippet-ka3
react, fullcalendar
--- title: React FullCalendar snippet published: true description: Create a simple calendar using React and FullCalendar tags: react, FullCalendar, //cover_image: https://direct_url_to_image.jpg --- > This was originally published on https://eichgi.hashnode.dev/react-fullcalendar-snippet Hey folks, the following snippet is a basic example of what you can achieve with FullCalendar library for React. I hope you find my appointments calendar interesting, so let's dive into. Here you have the react component full calendar docs: [https://fullcalendar.io/docs/react](https://fullcalendar.io/docs/react) Once you have installed the package let's focus on the component: ``` <FullCalendar ref={calendar} fixedWeekCount={false} height={'auto'} locale={esLocale} plugins={[dayGridPlugin, interactionPlugin]} initialView={setCalendarViewByWidth()} headerToolbar={{ start: 'prev today next', center: 'title', end: 'newAppointment' }} footerToolbar={{ center: 'toggleMonth toggleWeek toggleDay', }} customButtons={{ newAppointment: { text: 'Nueva cita', click: () => { dateClickHandler(); }, }, toggleDay: { text: 'Hoy', click: () => { calendar.current.getApi().changeView('dayGridDay'); } }, toggleWeek: { text: 'Semana', click: () => { calendar.current.getApi().changeView('dayGridWeek'); } }, toggleMonth: { text: 'Mes', click: () => { calendar.current.getApi().changeView('dayGridMonth') } }, }} dateClick={e => dateClickHandler(e)} events={appointments} datesSet={async (dateInfo) => { await getEvents(dateInfo.startStr.split('T')[0], dateInfo.endStr.split('T')[0]); }} eventsSet={(events => { console.log('Events set: ', events); })} eventClick={e => eventsHandler(e)} /> ``` I will describe the props described in the snippet. These are the very basics functionalities you might need for a full dynamic calendar. - Make a reference for you calendar, it might be handy for working directly with the API ``` const calendar = useRef(null); ``` - I set my calendar in spanish by doing this, there are plenty of languages available, just dig into the docs to find the desired one. ``` import esLocale from '@fullcalendar/core/locales/es'; ``` - In order to interact with the events and have this dayGrid/monthGrid view it is important that you import the following plugins ``` import dayGridPlugin from '@fullcalendar/daygrid'; import interactionPlugin from '@fullcalendar/interaction'; ``` - You can customize the default buttons and their order by defining the following props. You can as well create your own buttons and defined them inside the toolbar as follows: ``` headerToolbar={{ start: 'prev today next', center: 'title', end: 'newAppointment' }} footerToolbar={{ center: 'toggleMonth toggleWeek toggleDay', }} ``` - As mentioned previously, this is the way you define custom buttons and their events: ``` customButtons={{ newAppointment: { text: 'Nueva cita', click: () => { dateClickHandler(); }, }, ... }} ``` - For every click inside the calendar you will set the event this way (where *e* contains the date information regarding the clicked date): ``` dateClick={e => dateClickHandler(e)} ``` - You place events into the calendar defining them with this prop: ``` events={[ { title: 'event 1', date: '2019-04-01' }, { title: 'event 2', date: '2019-04-02' } ]} ``` - When you need to know which are the dates the calendar is currently showing define the following prop: ``` datesSet={async (dateInfo) => { await getEvents(dateInfo.startStr.split('T')[0], dateInfo.endStr.split('T')[0]); }} ``` Every time you change the view you can request events from the backend like this. (Don't forget to create your own getEvents definition) - Now that you have events placed, you might need to interact with them for showing or modifying purposes. This props is handy when you need to access the event information: ``` eventClick={e => eventsHandler(e)} ``` Here you have it, simple react fullcalendar snippet. There are plenty of options in the docs so you can customize your own calendar. CSS, Events, formats, etc... you will find them here: [https://fullcalendar.io/docs#toc](https://fullcalendar.io/docs#toc)
eichgi
911,864
Node.js vs Python: Which Backend Technology To Choose?
Most programmers prefer a backend technology for their web app development projects. This preference...
0
2021-11-29T07:48:15
https://dev.to/vofox/nodejs-vs-python-which-backend-technology-to-choose-9mk
node, python
Most programmers prefer a backend technology for their web app development projects. This preference is majorly dependent on their training or expertise in a particular technology. While this might be acceptable, it’s often not the correct strategy to get the wanted results for companies. In general, both Node JS and Python are broadly utilized server-side technologies even though both of them were revealed on separate timelines and produced for diverse purposes. Python has been around since 1991 and was designed as a server-side programming language that could be absolutely deployed for mobile and web applications. In distinction, Node.js was founded in 2009 as a JavaScript runtime environment that reformed the usage of JavaScript on the server-side. ##Node.js Node.js is event-driven, it’s scalable and causes extraordinary performances to the project. Its asynchronous nature implements it to manage concurrent requests without blocking the I/O operations. Most development companies prefer to [hire Node.js developers](https://vofoxsolutions.com/hire/nodejs-developers-in-india). ##Python On the other side, Python is a full-fledged, high-level, and object-oriented programming language. Since it’s been available for almost 30 years, it has a ton of libraries, APIs, and ancillary tools ready. Python is favorable to numerous programming paradigms, and it’s broadly applied for business applications. ##Node.js vs Python: Which one is more popular? The prevalence of backend technology plays a decisive part in whether it’ll be practiced for your project. First off from the [software development companies](https://vofoxsolutions.com/software-development-company-india) viewpoint, the development team has to determine which language has a notable degree of expertise available in the market. And then from the POV of developers, a conclusion has to be given whether they are ready to pick up languages that are predominantly practiced by various companies. Looking at the reputation of websites, SimilarWeb reported that Node.js was recognized to be the most practiced tool in the first 10,000, 100,000, 1,000,000, and the ‘entire’ sections of websites listed on their popularity. As per the Stack Overflow 2019 survey, Python was the most ‘preferred’ programming language while Node.js was the most chosen tool among expert programmers. ##Scalability in Node.js vs Python Node.js gives you enough versatility to circumvent a core. This way, alternatively of producing a core and then scaling everything around it, you build a set of microservices and modules. When your application is scaled, these microservices and modules can dynamically operate their own processes. Hence, you can scale the app horizontally by attaching nodes to the current ones and you can extend it vertically by combining resources. Python has problems with threads. It’s modeled on the Global Interpreter Lock, which does not permit it to perform various threads at once. This indicates that you cannot run different processes before the sequentially historical process is completed. ##Learning trajectory & Syntax ease in Node.js vs Python The learning curve for Node.js is not that abrupt if you are previously accustomed to Javascript. Some people think that its installation and documentation are a bit complicated because of Node.js’ event-driven programming theory. This concept is the fundamental reason why Node.js is scalable and effective. Python’s USP has been its predominance and clear syntax. It is an accepted aspect that the length of code is comparatively smaller in Python when opposed to Node.js or other programming languages and runtime environments. Writing code in Python is just incredibly easy. ##Extensibility in Node.js vs Python If you’re practicing its older versions, Node.js can be matched with Babel for more regular front-end development. You can likewise practice Jasmine for unit-based testing or Log.io to handle the project. Webpack and PM2 can assist you with module bundling whereas Express is one of the popular frameworks applied with Node.js. Sublime Text is usually practiced with Python to write codes. Robot Framework assists in automated testing. And then there are modern Nodejs frameworks similar to Django and Web2Py, which attach a boatload of characteristics. ##Performance & Speed in Node.js vs Python With Node.js' non-blocking architecture, its execution process is easier and quicker. On top of this, there is yet one more perk that delivers Node.js a solid contender. That is it executes the code outside of the web browser. Python’s inherent architecture prevents multithreading and is a dilemma in this regard as well. It slows down the processing rate as processes don’t move parallelly. While Python’s syntax is straightforward to learn and complete, it is not agile enough for applications that generally recall data from the web server. ##Community in Node.js vs Python You may look at Node.js as a comparatively newer form of technology and might consider its community to be inadequate. However, you’d be astonished to learn that the Node.js community is considerably large and globally engaged with experienced Node.js Developers. It’s super straightforward to identify talent in the Node.js circles. Python, being the more traditional language of the two, normally has a greater community. From junior to senior-level givers, Python doesn’t have a shortage of expertise. One of the most important advantages of such a sizable community is the readiness to discover developers. And active support from these developers ends in sudden solutions and overall enhancement of the language. ##Error Handling Abilities in Node.js vs Python Node.js’ parallel-process running peculiarity can make obtaining defects and failures in the code a tiresome process. Python’s more uncomplicated syntax and absence of parallel processes come in helpful while considering the code for bugs and glitches. **Conclusion** Deciding between Node.js and Python can be complicated particularly when you want to develop a complete product and not just a team project. The characteristics and benefits of both parties can be terrifying and can cloud your decision. This is why the perfect way to deal with this difficulty is by focusing on the end-use of your output. List out all the characteristics of your product, and how you intend to manage them. And the language or runtime environment that sustains more aptness should be your pick.
vofox
911,899
Simple Python Program To Find IP Address
What is an Ip Address? An Internet Protocol address (Ip Address) is an identifier assigned to each...
0
2021-11-29T09:08:34
https://dev.to/jeremih/simple-python-program-to-find-ip-address-5p7
python, security, programming, tutorial
**What is an Ip Address?** An Internet Protocol address (Ip Address) is an identifier assigned to each computer and other device e.g., router, mobile, etc connected to a TCP/IP network that is used to locate and identify the node in communication with other nodes on the network. IP addresses are usually written and displayed in human readable format such as 192.168.55.10 in IPv4(32-bit IP address). Addresses in IPv4 are 32-bits long. This allows for a maximum of 4,294,967,296 (232) unique addresses. Addresses in IPv6 are 128-bits, which allows for 3.4 x 1038 (2128) unique addresses. In this article we will focus on how to get the Ip address of your computer in python. First of, you will have to import the python socket library and proceed to use this "IP=socket.gethostbyname(hostname)" then you print the value of the ip into the print() function in you code, the output of your IP address would be displayed as shown in the program below: """Python program to find Ip Address""" **import** socket hostname = socket.gethostname() IPAddr = socket.gethostbyname(hostname) _print_("Your Computer Name is:" + hostname) _print_("Your Computer IP Address is:" + IPAddr) OUTPUT: _Your Computer Name is: mycomputer Your Computer IP Address is:192.168.40.109_ **Conclusion** With python, there are lots of programs you can write and explore, this is just one of many of them. Get hands on with this simple script and see your results. And that's it! If you have any suggestions or questions for improvements please let me know in the replies below 😁
jeremih
911,905
Data Streaming for Microservices using NATS Streaming - Part 1
The goal behind Data streaming is to process and analyze in real-time, data that move from data...
15,934
2021-12-16T21:21:43
https://dev.to/musolemasu/data-streaming-for-microservices-using-nats-streaming-part-1-4nf1
eventbus, node, kubernetes, microservices
The goal behind Data streaming is to process and analyze in real-time, data that move from data sources to destinations. It is mostly used in microservices to ensure inter-services communication. In a microservice architecture, the recommendation is to build independent services that can be altered, updated or taken down without affecting the rest of the architecture. In this tutorial, we are going to learn how to use **NATS Streaming** in a Kubernetes Cluster. NATS Streaming is a data streaming system powered by [NATS](https://docs.nats.io/). We will build a Basketball Dunk Contest App with two services, a **Dunk Service** that will handle players registration and dunk shot attempts for registered players. And a **Statistic Service** which will be displaying the Dunk Contest statistic in real-time from data accompanying events messages. NATS Streaming here will be the events transporter between our two services. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vx0qzcgmg3lkexsf13a8.gif) Before we dive into the code, make sure you have the following in order to follow along with this tutorial: - Working knowledge of **Node.js / typescript**, **Docker**, **Kubernetes Objects**, - **Node.js** (preferably the latest LTS version), **Docker** [How to install docker on Ubuntu?](https://www.digitalocean.com/community/tutorials/how-to-install-and-use-docker-on-ubuntu-20-04) and local **Kubernetes Cluster** installed via Minikube, click [HERE](https://v1-18.docs.kubernetes.io/docs/tasks/tools/install-minikube/) to install minikube, - **Docker Hub** account, click [HERE](https://hub.docker.com/) to sign up, I will be coding in a Linux machine for the tutorial. #1. Project Structure ![Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/870i7hphl2l9eh9xzwdu.png) Let's set up our project, we will first work on a number of kubernetes objects related to the project. Run the following: ```bash $ mkdir dunk-contest $ cd dunk-contest/ $ mkdir kubernetes ``` These commands create the project directory `dunk-contest/` then navigate inside the directory to create another directory named `kubernetes/`. In `kubernetes/` directory, we are going to add new files with required configurations to build the following Kubernetes objects: 1. **Deployment** objects for the NATS Streaming Server, for the Dunk Service MongoDB database and for the Statistic Service MongoDB database, 2. **Service** objects for Pods running containers of NATS Streaming image, Mongo image for Dunk Service and for Statistic Service. ##1.1 Deployment and Service objects > Make sure to work this part of the tutorial in the `kubernetes/` directory! ###1.1.1 NATS Deployment and Service ![NATS DEPL SERV](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/shhnp61jyofxjmxx1ps9.png) - **Add a new YAML file named `nats-deployment.yaml` and put the configuration below:** ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: nats-deployment spec: replicas: 1 selector: matchLabels: app: nats template: metadata: labels: app: nats spec: containers: - name: nats image: nats-streaming:0.22.1 args: [ "-p", "4222", "-hbi", "5s", "-hbt", "5s", "-hbf", "2", "-SD", "-cid", "dunk-contest", ] ``` This config file will create a Pod running a container of `nats-streaming:0.22.1` docker image and a Deployment to monitor the Pod. Practically, this Pod will act as the project NATS Streaming Server exposing port `4222` to clients(Dunk Service and Statistic Service). - **Add a new YAML file named `nats-service.yaml` and put the configuration below:** ```yaml apiVersion: v1 kind: Service metadata: name: nats-service spec: selector: app: nats ports: - name: client protocol: TCP port: 4222 targetPort: 4222 ``` This config file will create a kubernetes object of kind Service, that other pods inside the kubernetes cluster will use to access the NATS streaming server Pod on port `4222`. ###1.1.2 MongoDB Deployment and Service ![Mongo depl serv](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9mop8hthjj107m54vl7v.png) Here we are going to add 4 new config files: - **1** `dunk-mongo-deployment.yaml`: ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: dunk-mongo-deployment spec: replicas: 1 selector: matchLabels: app: dunk-mongo template: metadata: labels: app: dunk-mongo spec: containers: - name: dunk-mongo image: mongo ``` With these configurations, kubernetes will create a Deployment object to monitor a MongoDB Pod of mongo docker image. This database will be dedicated to the Dunk Service. - **2** `dunk-mongo-service.yaml`: ```yaml apiVersion: v1 kind: Service metadata: name: dunk-mongo-service spec: selector: app: dunk-mongo ports: - name: db protocol: TCP port: 27017 targetPort: 27017 ``` Another config file that will create a kubernetes object of kind Service that will permit other pods in the cluster to access the mongo pod of the Dunk Service. - **3** `stats-mongo-deployment.yaml`: ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: stats-mongo-deployment spec: replicas: 1 selector: matchLabels: app: stats-mongo template: metadata: labels: app: stats-mongo spec: containers: - name: stats-mongo image: mongo ``` Kubernetes will use this set of configurations to create a Deployment object to manage the MongoDB Pod of mongo docker image. This mongo database will be dedicated to the Statistic Service only. - **4** `stats-mongo-service.yaml`: ```yaml apiVersion: v1 kind: Service metadata: name: stats-mongo-service spec: selector: app: stats-mongo ports: - name: db protocol: TCP port: 27017 targetPort: 27017 ``` Finally we have this config file to create a Service object that will expose the MongoDB Pod of the Statistic Service to other pods in the kubernetes cluster. Your `kubernetes/` directory tree structure should look like this by now: ```bash . ├── dunk-mongo-deployment.yaml ├── dunk-mongo-service.yaml ├── nats-deployment.yaml ├── nats-service.yaml ├── stats-mongo-deployment.yaml └── stats-mongo-service.yaml 0 directories, 6 files ``` Save all created files in the `kubernetes/` directory and make sure that your Kubernetes cluster is up and running. Open the terminal and run the following: ```bash $ minikube start ``` ![Minikube start](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nv1vctma55w9evu0edvv.png) Minikube quickly sets up a local Kubernetes cluster on macOS, Linux, and Windows. Now, let's tell Kubernetes to create objects using our configuration files. Run the command below in the `kubernetes/` directory: ```bash $ kubectl apply -f . ``` ![kubectl apply -f .](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pbcfbi7581qyxxgd9faa.png) At this moment, we must have 3 running pods, one for nats-streaming, for mongodb of the Dunk Service and one for mongodb of the Statistic Service. Verify it with this command: ```bash $ kubectl get pods ``` ![kubectl get pods](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dg1iev92wsejstfygyy9.png) We reached the point in the tutorial where we are going to build our two services and connect them to the Pods created in this part of the tutorial. Let's do it in the next points. ###1.2 Dunk Service Here we are going to build an express application, listening on port 4001 for connections. It will have two API endpoints, one `http://localhost:4001/dunk-contest/register` to handle POST request for players registration and the other `http://localhost:4001/dunk-contest/attempt/:playerName` to handle POST request for players dunk shots attempts. Navigate back to the project directory `dunk-contest/` and create a new directory named `dunk-service/`. In the `dunk-service/` directory, generate a `package.json` and install `ts-node-dev`, `typescript`, `express`, `@types/express`, `node-nats-streaming` and `mongodb` as dependencies: ```bash $ cd dunk-service/ $ npm init -y $ npm install ts-node-dev typescript express @types/express node-nats-streaming mongodb ``` Open the `package.json` file, replace the actual script section by the one below: ```json "scripts": { "start": "ts-node-dev src/index.ts" } ``` Save the file. In the same directory create a directory named `src/` ,in `src/` add a typescript file named `nats-connector.ts` and paste the following: ```Typescript import nats, { Stan } from "node-nats-streaming"; class NatsConnector { private _client?: Stan; get client() { if (!this._client) { throw new Error("Cannot access NATS Client before connecting!"); } return this._client; } connectToNats(clusterId: string, clientId: string, url: string) { this._client = nats.connect(clusterId, clientId, { url }); return new Promise<void>((resolve, reject) => { this.client.on("connect", () => { console.log(`DUNK SERVICE IS CONNECTED TO NATS STREAMING SERVER`); resolve(); }); this.client.on("error", (err) => { reject(err); }); }); } } export const natsConnector = new NatsConnector(); ``` Inside this file: - We define a variable `_client` of **Stan** type, a type imported from node-nats-streaming library, - We export an instance of NatsConnector class that has a method called `connectToNats()` - connectToNats() takes three parameters, the `clusterId`, the `clientId` and the `url`: 1. **clusterId**: This was set early in the NATS streaming server deployment configuration file. Dunk Service, here being a client will use it to connect to the NATS server, 2. **clientId**: An identifier for the Dunk Service as client to the NATS server, 3. **url**: The NATS Streaming server endpoint, that the Dunk Service will use to access resources in the NATS running pod. In connectToNats(), to `_client` we assign a function imported from `node-nats-streaming` called `connect()` on which we passe our three parameters as arguments. And connectToNats() returns a promise that resolve if `_client` get successfully connected to NATS server and reject if otherwise. Next, add another typescript file named `event-publisher.ts` and put the following: ```Typescript import { Stan } from "node-nats-streaming"; export class EventPublisher { private client: Stan; constructor(client: Stan) { this.client = client; } publishEvent(subject: string, data: any): Promise<void> { return new Promise((resolve, reject) => { this.client.publish(subject, JSON.stringify(data), (err) => { if (err) { return reject(err); } console.log("\x1b[36m%s\x1b[0m", `EVENT ${subject} PUBLISHED!`); resolve(); }); }); } } ``` In this one, we export the class `EventPublisher` that has a variable named `client` of type `Stan` just like in the NatsConnetor class. We have a method in this class called `publishEvent()` of two parameters: 1. **subject**: This is the name of the channel which events passe through and reach clients that had subscribed to, 2. **data**: the data or message accompanying published events. And `publishEvent()` returns a promise that resolve when events are successfully published and reject when there is a failure. After this, in `src/` directory, create a directory named `routes/`; add two new typescript files: - **1** `registerPlayerRoutes.ts` a middleware and put the code below: ```Typescript import { Router, Request, Response } from "express"; import { MongoClient } from "mongodb"; interface Players { NAME: string; HEIGHT: number; WEIGHT: number; EXPERIENCE: number; } const registerPlayerRouter = Router(); registerPlayerRouter.post( "/dunk-contest/register", async (req: Request, res: Response) => { const player: Players = { NAME: req.body.name, HEIGHT: req.body.height, WEIGHT: req.body.weight, EXPERIENCE: req.body.experience, }; const mongoClient = await MongoClient.connect( "mongodb://localhost:27017/dunk-service" ); const db = mongoClient.db(); const playerCollection = db.collection("players"); await playerCollection.insertOne(player); console.log("\x1b[36m%s\x1b[0m", "PLAYER REGISTERED WITH SUCCESS"); const newPlayer = await playerCollection.findOne({ NAME: req.body.name, }); console.table(newPlayer); res.send({}); mongoClient.close(); } ); export { registerPlayerRouter }; ``` In the `registerPlayerRoutes.ts` file above we did the following: - Imported `Router`, `Request` and `Response` from express; - Imported `MongoClient` from mongodb; - Implemented a POST request on `registerPlayerRouter.post("/dunk-contest/register")` to register players to the `players collection` in dunk-service MongoDB database and fetch the registered player. MongoClient is used here to connect this process to the appropriate MongoDB Pod. - **2** `attemptDunkRoutes.ts` and put the code below: ```Typescript import { Router, Request, Response } from "express"; import { MongoClient } from "mongodb"; import { natsConnector } from "./../nats-connector"; import { EventPublisher } from "./../event-publisher"; const attemptDunkRouter = Router(); attemptDunkRouter.post( "/dunk-contest/attempt/:playerName", async (req: Request, res: Response) => { const mongoClient = await MongoClient.connect( "mongodb://localhost:27017/dunk-service" ); const db = mongoClient.db(); const playerCollection = db.collection("players"); const playerFound = await playerCollection.findOne({ NAME: req.params.playerName, }); const dunkPoint: number = (playerFound?.HEIGHT * playerFound?.WEIGHT * playerFound?.EXPERIENCE * Math.random()) / 100; await new EventPublisher(natsConnector.client).publishEvent("Dunk-Shot", { PLAYER_NAME: playerFound?.NAME, DUNK_POINT: dunkPoint, }); res.send({}); mongoClient.close(); } ); export { attemptDunkRouter }; ``` With `attemptDunkRoutes.ts` we worked on a middleware, we did the following: - Imported `Router`, `Request` and `Response` from express; - Imported MongoClient from mongodb; - Imported `natsConnector`, an NatsConnector instance; - Imported the class `EventPublisher`; - Implemented a POST request on attemptDunkRouter.post( "/dunk-contest/attempt/:playerName") to attempt a dunk shots for a player found in the `players collection` by player's name got with `req.params.playerName`; - MongoClient is used here to connect this process to the appropriate MongoDB pod; - With `EventPlubilsher` class, we created a new instance that passes `natsconnector.client` as argument and calls `publishEvent` function to publish an event through the `Dunk-Shot` channel with `PLAYER_NAME` and `DUNK_POINT` as event message; - `DUNK_POINT` is number calculated with the player's HEIGHT, WEIGHT, EXPERIENCE and a random number. To wrap with service up, go ahead, move back to `src/` directory, add a typescript file named `index.ts` and paste the code below: ```Typescript import express from "express"; import { registerPlayerRouter } from "./routes/registerPlayerRoutes"; import { attemptDunkRouter } from "./routes/attemptDunkRoutes"; import { natsConnector } from "./nats-connector"; const app = express(); app.use(express.json()); app.use(registerPlayerRouter); app.use(attemptDunkRouter); const start = async () => { try { await natsConnector.connectToNats( "dunk-contest", "123", "http://localhost:4222" ); natsConnector.client.on("close", () => { process.exit(); }); } catch (error) { console.error(error); } app.listen(4001, () => { console.log("\x1b[36m%s\x1b[0m", "DUNK SERVICE LISTENING ON 4001"); }); }; start(); ``` In the `index.ts` file above we did the following: - Imported `express`, `Request` and `Response` from express; - Imported `registerPlayerRouter` and `attemptDunkRouter`, two middlewares; - Imported `natsConnector`, an instance of class NatsConnector that was created early; - Called the express function `express()` and puts new Express application inside the `app` variable (to start a new Express application); - Used the middlewares with `app.use(registerPlayerRouter)` and `app.use(attemptDunkRouter)`; - Wrote the `start` function to connect the Express application to NATS Streaming server and have it listens for connection on port 4001. Now generate a `tsconfig.json` file to compile your TypeScript code in JavaScript code. Open your terminal, navigate back to `dunk-service/` directory and run the command below: ``` $ tsc --init ``` Great, we are almost done with the Dunk Service, we shall come back later to fix some little things. The `dunk-service/` directory should look like the tree below: ```bash . ├── package.json ├── package-lock.json ├── src │   ├── event-publisher.ts │   ├── index.ts │   ├── nats-connector.ts │   └── routes │   ├── attemptDunkRoutes.ts │   └── registerPlayerRoutes.ts └── tsconfig.json 2 directories, 8 files ``` Let's perform a simple test to check the following: - Dunk Service connection to its dedicated MongoDB running pod; - Dunk Service connection to the Nats Streaming Server; In the steps below, do the test: **Step - 1: Access to NATS Streaming server Pod** Take your pod's name by running: ```bash $ kubectl get pods ``` ![get pods nats](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7qgf55e3wccaxszwfnuj.png) Copy your pod's name, you will use it in the command that is coming. Here we are going to make the NATS Streaming server pod running in the kubernetes cluster accessible in our local machine. Open the terminal, forward a local port on your machine to a port on your pod by running the following: ```bash $ kubectl port-forward <YOUR POD NAME> 4222:4222 ``` > Make sure to paste your pod's name where indicated in the command above. ![NATS service accessible in local m](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jriq474i68igppncih45.png) **Step - 2: Access to MongoDB pod dedicated to the Dunk Service** Take your pod's name by running: ```bash $ kubectl get pods ``` ![get pods mongo dunk](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ggmofpi1f9i7jqp6zqi.png) Copy your pod's name, you will use it in the command that is coming. Here we are going to make the MongoDB pod of Dunk Service running in the kubernetes cluster accessible in our local machine. Open another terminal and forward a local port on your machine to a port on your pod by running the following: ```bash $ kubectl port-forward <YOUR POD NAME> 27017:27017 ``` ![mongo pod accessible to local m](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jo5myuh00ulj7e7woy6y.png) **Step - 3: Start the Dunk Service (Express application)** Open a third terminal in the `dunk-service/` directory and run this command: ```bash $ npm start ``` ![npm start](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a8n1xmaxttlq5vg3i4by.png) By now, the Dunk Service must be connected to the NATS Streaming server pod and to its MongoDB pod. **Step - 4: Open your API Client and do these tests** - **Test - 1.** POST request on http://localhost:4001/dunk-contest/register Make a `POST` request, with HEADERS `Content-Type: application/json` and a BODY of : ```json { "name": "LeBron", "height": 2.18, "weight": 105, "experience": 5 } ``` - **Test - 2.** POST request on http://localhost:4001/dunk-contest/attempt/LeBron Hopefully, you will have a similar output in your terminals as below: ![Dunk Service test](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sksoi1js4jyudrw9e1hn.gif) #2. Conclusion In this part of the tutorial, we started to build our Dunk Contest Application with the purpose of learning how to use NATS Streaming in a microservice architecture in a Kubernetes Cluster set and running in our local machines. The completed Application should have featured two services, the Dunk Service and Statistic Service streaming data using NATS Streaming. In the process, we started a NATS Streaming Server running in the kubernetes cluster and two MongoDB Pods, each dedicated to a specific service. We also started the Dunk Service, which successfully registered players in its MongoDB Pod and successfully published an event to the NATS Streaming Server; event consisting of a dunk shot of a registered player. Please stay tuned for more important NATS Streaming practices that we are going to implement in part 2 of this tutorial as we will be completing our Dunk Contest Application. If you have questions, comments, feel free to reach out here or on my [Twitter](https://twitter.com/MusoleMasu); I will be more than happy to answer and [Here](https://github.com/musole-masu/dunk-contest), you may find the project code. See you soon. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/teb6kowik1px0p2kvjbm.png)
musolemasu
911,927
JavaScript Online Interpreter
Learn JavaScript Online with this JS REPL
0
2021-11-29T10:14:26
https://dev.to/jcubic/javascript-online-interpreter-2dci
javascript, learn
--- title: JavaScript Online Interpreter published: true description: Learn JavaScript Online with this JS REPL tags: javascript, learn, //cover_image: https://direct_url_to_image.jpg --- I've created this [JavaScript REPL](https://try.javascript.org.pl/) using [jQuery Terminal](https://terminal.jcubic.pl/) and my few other Open Source projects. It have split view where you can read Book about JavaScript. By default, it points to [Eloquent Javascript](https://eloquentjavascript.net/). In first version you were not able to use `let` and `const` (you couldn't use those variables in next command) because of limitations of `eval` function. I was able to fix the issue, you can find the solution inside the code that I made with help from someone on Reddit.
jcubic
911,967
PHP 8: Constructor Property Promotion
Introduction If you have been a software engineer for a while, you know that software...
0
2021-11-29T10:38:06
https://worldclassibro.hashnode.dev/php-8-constructor-property-promotion
php, tutorial
## Introduction If you have been a software engineer for a while, you know that software engineers love using scary names to describe simple things. The term *constructor property promotion* should not scare you because you might be using it in your codebase already without realizing it has a fancy name. Here are the things you will achieve after reading this article. 1. You will be able to refactor a PHP class to use constructor property promotion instead of using the default syntax used when setting class properties in the constructor function. 2. You will know the different ways of accessing class properties after setting them using the constructor property promotion syntax. 3. You will know the common mistakes that lead to errors when using the constructor property promotion syntax in your PHP class and how to avoid them. Interested? Let's move 🚀 ### Prerequisites 1. A basic understanding of Object-Oriented Programming in PHP 2. You must have PHP 8 installed to enjoy this feature in your code or project. Alternatively, you can test this feature on [phpsandbox](https://phpsandbox.io/n/standard) by selecting PHP8 as your preferred version ### What is Constructor Property Promotion? 🤔 Constructor property promotion is a feature introduced in PHP 8 that allows values passed to a constructor to be automatically set as class properties without the need to write the assignment statement in the body of the constructor. For a better understanding of the concept, let's take a look at the way values were assigned to class properties before the introduction of the constructor property promotion feature in PHP8. #### Before constructor property promotion 🥱 Before constructor property promotion was introduced, here’s how you will typically set the `firstName` and `lastName` properties passed to the `Employee` class through the constructor. ``` <?php class Employee { protected $firstName, $lastName; public function __construct(string $firstName, string $lastName) { $this->firstName = $firstName; $this->lastName = $lastName; } } $employee = new Employee('Ibrahim', 'Alausa'); ``` In the code above, we are declaring the properties `firstName` and `lastName` without any initial value. Then, in the body of the constructor, we set the `firstName` and `lastName` properties to the value passed to the constructor. In this example, that is **Ibrahim **as the value of the `firstName` property and **Alausa **as the value of the `lastName` property. #### The new way for the cool programmers 😎 Now, let's rewrite the `Employee` class to use constructor property promotion. Let's see what our code will look like in this case ``` <?php class Employee { public function __construct(protected string $firstName, protected string $lastName) { } } $employee = new Employee('Ibrahim', 'Alausa'); ``` That's it. Yes. Isn't this beautiful? Just in case your answer is **NO ** well, that was a rhetorical question, my friend. It is beautiful. #### What exactly is different By adding an access modifier (protected, private, etc) to each parameter in the constructor, PHP understands that you are trying to “promote” the constructor parameter to a class property. ### Important points to note when working with constructor property promotion #### 1. Accessing class properties 🔐 Within the constructor, promoted properties can be accessed with or without the `$this` keyword since they are still within the function scope where they were declared. Let's see what our code will look like in this case ``` <?php class Employee { public function __construct(protected string $firstName, protected string $lastName) { var_dump($firstName); Ibrahim ✔️ var_dump($this->firstName); Ibrahim ✔️ } } $employee = new Employee('Ibrahim', 'Alausa'); ``` Run the code [here]( https://phpsandbox.io/e/x/ymalo?layout=EditorPreview&defaultPath=%2F&theme=dark&showExplorer=no&openedFiles=) to see for yourself. However, once you are outside the constructor, you need to use the `$this` keyword to access all promoted properties so that PHP understands that you are referring to the `firstName` or `lastName` property of the class and not an undefined variable or a variable that may have been declared using the same name. ``` <?php class Employee { public function __construct(protected string $firstName, protected string $lastName) { } public function getUndefinedFirstName() { var_dump($firstName); // Output: Undefined variable '$firstName' ❌ } public function getWrongFirstName() { $firstName = 'John'; var_dump($firstName); // Output:John ❌ } public function getFirstName() { var_dump($this->firstName); // Output:Ibrahim ✔️ } } $employee = new Employee('Ibrahim', 'Alausa'); ``` Run the code [here](https://phpsandbox.io/e/x/nuuvz?layout=EditorPreview&defaultPath=%2F&theme=dark&showExplorer=no&openedFiles= ) to see for yourself. <br/> #### 2. You don't have to promote all constructor parameters. Mix 'em up 🥂 Let’s assume that for some reason, we need to append `Fname_` to every value passed to our Employee class as the first name and we want to do that cleanly. We don’t need to promote the `firstName` property. Let's see what our code will look like in this case. ``` <?php class Employee { protected $firstName; public function __construct(string $firstName, protected string $lastName) { $this->firstName = "Fname_$firstName"; } public function getFirstName() { var_dump($this->firstName); // Output:Fname_Ibrahim ✔️ } } $employee = new Employee('Ibrahim', 'Alausa'); ``` Run the code [here](https://phpsandbox.io/e/x/gmycf?layout=EditorPreview&defaultPath=%2F&theme=dark&showExplorer=no&openedFiles=) to see for yourself. <br/> #### 3. You either want to promote a property or you don't. Make a choice 🤦‍♂️ This means that you can't declare a class property above the constructor and still try to promote that property in the constructor parameter list. Let's see what our code will look like in this case. Remember, this will throw an error. ``` <?php class Employee { protected $firstName; public function __construct(protected string $firstName, protected string $lastName) //Cannot redeclare Employee::$firstName ❌ { $this->firstName = $firstName; } } $employee = new Employee('Ibrahim', 'Alausa'); ``` Run the code [here]( https://phpsandbox.io/e/x/rgawi?layout=EditorPreview&defaultPath=%2F&theme=dark&showExplorer=no&openedFiles=) to see for yourself. <br/> #### 4. You can set default values for promoted properties 😐 If one or more values in the constructor are optional, a default value can be set for that property. Let's see what our code will look like in this case. ``` <?php class Employee { public function __construct(protected string $firstName, protected string $lastName='N/A') { } public function getLastName() { var_dump($this->lastName); //Output: N/A ✔️ } } $employee = new Employee('Ibrahim'); ``` Run the code [here]( https://phpsandbox.io/e/x/wayaz?layout=EditorPreview&defaultPath=%2F&theme=dark&showExplorer=no&openedFiles=) to see for yourself. <br/> ### Quick Recap 1. The constructor property promotion feature only works with PHP8.0 and above. 2. To promote a constructor parameter to a class property, the constructor parameter should have an access modifier like public, private, etc. 3. Since the constructor parameters are both parameters and class properties, you can access the promoted properties in the constructor with or without the `$this` keyword. However, class properties must be accessed with the `this` keyword outside the constructor function. 4. Not all parameters need to be promoted. Mix 'em up and enjoy the best of both worlds. 5. While trying to enjoy the best of both worlds, remember that you can't declare a class property above the constructor and still try to promote that property in the constructor parameter list. 6. Default values can be set for promoted properties in the constructor. ### It's a wrap 🎉 PHP8 comes with a lot of amazing features that will make you write shorter and cleaner code. If you can, upgrade your version and start using it today. Thanks for sticking with me till the end. If you have any suggestions or feedback, kindly drop them in the comment section. Enjoy the rest of your day...bye 😊.
tosinibrahim96
912,006
Ubuntu System Is Broken After Accidentally Uninstalling Many Packages in Ubuntu?
aptreinstall I accidentally removed all the packages starting with the name jpeg with: sudo...
0
2021-12-14T05:05:41
https://stackallflow.com/ubuntu/ubuntu-system-is-broken-after-accidentally-uninstalling-many-packages-in-ubuntu/
ubuntu
--- title: Ubuntu System Is Broken After Accidentally Uninstalling Many Packages in Ubuntu? published: true date: 2021-11-29 06:13:35 UTC tags: Ubuntu canonical_url: https://stackallflow.com/ubuntu/ubuntu-system-is-broken-after-accidentally-uninstalling-many-packages-in-ubuntu/ --- <header> <p><span style="font-size: 1.2em; color: initial;">apt</span><span style="font-size: 1.2em; color: initial;">reinstall</span></p> </header> I accidentally removed all the packages starting with the name `jpeg` with: ``` sudo apt-get remove jpeg* ``` This screwed up a lot of things, removed Unity, Firefox, Flash player etc. I somehow managed to recover the desktop and unity but then a lot of things are still buggy. For example `.rpm` files and `.tag.gz` just won’t open up at all. What I want is a way to fix everything that’s amiss. Something that is the equivalent of a ‘repair installation’ with a windows disc. Any tips, anyone? #### Accepted Answer You can install the `ubuntu-desktop` task: ``` sudo apt-get install ubuntu-desktop^ ``` This will install all the packages of the standard Ubuntu Desktop you have removed. It won’t restore packages you had installed that are not part of the standard desktop (i.e. it will reinstall Unity and Firefox, but not Flash player). To install those packages, you can look into `/var/log/apt/history.log` and see exactly what you had removed. **Note:** installing the `ubuntu-desktop^` _task_ is not the same as installing the `ubuntu-desktop` _package_. The first will give APT some hints to resolve dependencies involving virtual packages, the latter will give APT the freedom to choose packages (and will end up installing useless stuff like `ubiquity`). **Why has the problem happened?** `apt-get remove jpeg*` will **not** remove all packages starting with `jpeg`. It will instead remove all packages containing `jpe` in their name. This is because apt-get works with regular expression, so that _jpeg\*_ means: everything containing _jpe_ followed by zero or more _g_. The post [Ubuntu System Is Broken After Accidentally Uninstalling Many Packages in Ubuntu?](https://stackallflow.com/ubuntu/ubuntu-system-is-broken-after-accidentally-uninstalling-many-packages-in-ubuntu/) appeared first on [Stack All Flow](https://stackallflow.com).
stackallflow
912,010
Best Way to Cache Apt Downloads on a Lan in Ubuntu?
networking I have multiple Ubuntu machines at home and a pretty slow internet connection, and...
0
2021-12-14T05:06:04
https://stackallflow.com/ubuntu/best-way-to-cache-apt-downloads-on-a-lan-in-ubuntu/
ubuntu
--- title: Best Way to Cache Apt Downloads on a Lan in Ubuntu? published: true date: 2021-11-29 06:14:56 UTC tags: Ubuntu canonical_url: https://stackallflow.com/ubuntu/best-way-to-cache-apt-downloads-on-a-lan-in-ubuntu/ --- <header> <p><span style="font-size: 1.2em; color: initial;">networking</span></p> </header> I have multiple Ubuntu machines at home and a pretty slow internet connection, and sometimes multiple machines need to be updated at once (especially during new Ubuntu releases.) Is there a way where only one of my machines needs to download the packages, and the other machines can use the first machine to get the debs? Does it involve setting up my own local mirror? Or a proxy server? Or can it be made simpler? #### Accepted Answer I did some research into a bunch of solutions and some Ubuntu developers came up with a proxy configuration (based on Squid) for 10.04 and later. It’s called `squid-deb-proxy`. It only requires a machine to act as the server. Large organizations usually run their own full mirrors but for most people the on demand mirroring is enough. ### Why squid-deb-proxy? - No editing of files on the client side. - Use zeroconf so that clients were “zero config” - Use an existing, solid proxy solution instead of writing a new tool. - Easy to set up for a typical Linux administrator. ### Server Config On the machine you want to act as a server install the tool with: `sudo apt-get install squid-deb-proxy avahi-utils` Now start the service bits: ``` sudo start squid-deb-proxy ``` And the avahi bits (You don’t need this if you’re on 12.04+): ``` sudo start squid-deb-proxy-avahi ``` This will install the proxy server (which listens to port 8000 by default) and the avahi tools needed for the server to advertise itself on your network via zeroconf. ### Client Config On _each of the computers_ that you want to use the cache (the clients, and the server itself so it can use the cache too), you need to install the client side tool that let’s apt look for the server automatically, have them click here: or via command line: ``` sudo apt-get install squid-deb-proxy-client ``` **Optional** : For maximum efficiency you should set one machine to automatically download updates, so that when your other machines need it it’s already in the cache. You can do this by going to System->Administration->Update Manager, then click on the “Settings…” button, in the Update tab set it to automatically download all the updates. ![alt text](https://i.stack.imgur.com/YANi1.png) ### Caching 3rd Party Sources By default the cache is set up to only cache official Ubuntu repositories. To add more you need to add them to the list of sources at `/etc/squid-deb-proxy/mirror-dstdomain.acl`. This is where you can add ppa.launchpad.net, or other services you might use. After making changes to this file, you must run `sudo restart squid-deb-proxy` in order for the changes to be effective. ### Manual Config If for some reason you do not want to use zeroconf (for network reasons or whatever), you can manually set a client to use the proxy by editing `/etc/apt/apt.conf` and adding the following stanza, (replace the 0.0.0.0 with the IP address of the server): ``` Acquire { Retries "0"; HTTP { Proxy "http://0.0.0.0:8000"; }; }; ``` ### Firewall In case you are using a firewall, avahi uses 5353 over addresses 224.0.0.0/4 and requires a rule that looks like this: ``` # Specifically port 5353 which avahi uses -A INPUT -i eth2 -d 224.0.0.0/4 --dport 5353 -j ACCEPT # OR # Wide open so all local broadcasting works -A INPUT -i eth2 -d 224.0.0.0/4 -j ACCEPT ``` Next, you need to open TCP port 8000 for the actual communication through the proxy. Something more or less like this: ``` -A INPUT -i eth2 -p tcp -m tcp --dport 8000 -d 192.168.0.1 -s 192.168.0.0/24 --syn -j ACCEPT ``` These rules are just to help you. They will probably not match your setup one to one. (i.e. wrong interface, wrong private network IP addresses, etc.) ### Confirming it Works First tail the log on the server so you can look at it: `tail -F /var/log/squid-deb-proxy/access.log` and then run an update on any machine that has the client installed; the log should start to scroll with entries like this: ``` 1307310795.647 32 192.168.1.106 TCP_MISS/302 768 GET http://us.archive.ubuntu.com/ubuntu/dists/natty-proposed/universe/i18n/Translation-en.xz - DIRECT/141.210.26.10 text/html 1307310795.683 34 192.168.1.106 TCP_MISS/302 752 GET http://us.archive.ubuntu.com/ubuntu/dists/natty/main/i18n/Translation-en_US.lzma - DIRECT/141.210.26.10 text/html 1307310795.716 32 192.168.1.106 TCP_MISS/302 746 GET http://us.archive.ubuntu.com/ubuntu/dists/natty/main/i18n/Translation-en.lzma - DIRECT/141.210.26.10 text/html 1307310795.750 32 192.168.1.106 TCP_MISS/302 764 GET http://us.archive.ubuntu.com/ubuntu/dists/natty/multiverse/i18n/Translation-en_US.lzma - DIRECT/141.210.26.10 text/html 1307310795.784 32 192.168.1.106 TCP_MISS/302 758 GET http://us.archive.ubuntu.com/ubuntu/dists/natty/multiverse/i18n/Translation-en.lzma - DIRECT/141.210.26.10 text/html 1307310795.817 32 192.168.1.106 TCP_MISS/404 657 GET http://us.archive.ubuntu.com/dists/natty-proposed/multiverse/i18n/Translation-en_US.xz - DIRECT/141.210.26.10 text/html ``` Which means the clients see the cache but are missing it, which is expected since it hasn’t cached anything yet. Each subsequent run should show up as TCP\_HIT. You can find the squid cache files themselves in `/var/cache/squid-deb-proxy`. ### Using it From then on all the machines on your network will check the cache before hitting the outside network to fetch packages. If there are new packages available then the first machine will download it from the net, after that subsequent requests for that package will come from the server to the clients. ### TODO We still need to enable apt to just use an advertised cache on the network out of the box and by default so you don’t need to install the client piece. We also need to fix [the bug](https://bugs.edge.launchpad.net/ubuntu/+source/squid-deb-proxy/+bug/545830) that 403’s deb’s not in the mirror list. The post [Best Way to Cache Apt Downloads on a Lan in Ubuntu?](https://stackallflow.com/ubuntu/best-way-to-cache-apt-downloads-on-a-lan-in-ubuntu/) appeared first on [Stack All Flow](https://stackallflow.com).
stackallflow
912,133
JavaScript News and Updates of November 2021
Hello everyone! Welcome to a new edition of my monthly news digest dedicated to the latest...
0
2021-11-29T14:07:10
https://dev.to/plazarev/javascript-news-and-updates-of-november-2021-1li6
javascript, html, webdev, news
Hello everyone! Welcome to a new edition of my monthly news digest dedicated to the latest developments in JavaScript. The last month of autumn brought several exciting releases and useful info for the web community. This time, you will learn about the latest programming trends from the State of the Octoverse 2021 survey, become familiar with a new product and updates from DHTMLX, estimate changes in Angular and TypeScript, get a foretaste of new capabilities in ASP.NET Core, and find out how JS now can be used in Excel. Besides, I also prepared a pack of articles with useful guides and tips on various JavaScript issues. Let’s roll! ## New Tools and Updates ### Key Takeaways from State of the Octoverse 2021 ![New survey from GitHub](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/txu860f63esque24d8nn.jpg) It is time to explore key trends in the software development world highlighted in the latest edition of GitHub's State of the Octoverse. In 2021, this popular annual survey includes valuable insights based not only on traditional analysis of the platform’s repositories but also on responses from more than 12,000 developers. The response to a typical question on the most popular programming language remains the same during the past several years. It is JavaScript followed by Python (2nd) and Java (3-rd). Here we can also mention that TypeScript retained its position in the top 4, while PHP dropped from 3rd to 6th place compared to 2020. The survey also includes some other interesting facts. For instance, more than 16 million developers joined GitHub in 2021, increasing the total number of GitHub users to 73 million. The productivity of the dev community is now comparable with prepandemic levels. Almost half of the interviewed developers (47%) want to have a hybrid working schedule (home +office) after the pandemic is over. Check out the [full report](https://octoverse.github.com/) to get more useful information from GitHub. ### What’s New in Angular 13 ![Angular 13 release](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c3cpdnng1nivszgdi0md.jpg) Angular is one of the most well-known tools in the JavaScript ecosystem. Despite its complexity, this framework still remains a preferred choice for many programmers, especially for those who work on enterprise-scale apps. The Angular development team from Google continues working on the improvement of this product to keep it competitive with other popular JS frameworks. Early this month, Angular was finally updated to version 13. This major update comes with a range of useful changes and enhancements for empowering the coding capabilities of web developers. The most notable goodies of this release are the removal of the View Engine, modernized Angular Package Format (APF), simplified API for dynamic creation of components, and support for persistent build cache. Learn more about these and other novelties introduced in v13 by visiting the [Angular blog](https://blog.angular.io/angular-v13-is-now-available-cce66f7bc296). ### Introducing DHTMLX Kanban Board v1.0 ![DHTMLX Kanban](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojbloiiswbblhr0ptnvj.png) DHTMLX is well-known in the web development community for providing high-quality JavaScript libraries for various business purposes. Recently, the company has expanded the product line of JavaScript for project management with a new promising tool - [JavaScript Kanban board](https://dhtmlx.com/docs/products/dhtmlxKanban/). It is written in pure JS and CSS to cover all needs of developers in the workflow visualization. DHTMLX Kanban has an intuitive drag-and-drop interface including three main parts: toolbar, board with cards, and editor. All these elements can be easily configured and customized to meet specific project requirements. JavaScript Kanbans built with DHTMLX can be complemented with numerous useful features such as filtering & searching, swimlanes, setting task priority, adding attachments, tracking of time and deadlines, and much more. Numerous localization options help to adjust the Kanban interface to any location. This Kanban library is also notable for its high compatibility. It can be integrated with popular JS frameworks and any server-side technology (Go and Node.js backends are included by default). But more interestingly, developers have an opportunity to combine the Kanban component with other popular DHTMLX products, namely Gantt and Scheduler. Thus, devs get everything they need to build a multifunctional solution for project management with DHTMLX. If you are interested to learn more detailed information about DHTMLX Kanban, read the [release article](https://dhtmlx.com/blog/releasing-dhtmlx-kanban-board-v-1-0/). ### New .NET Update Boosts ASP.NET Core Capabilities ![New capabilities in ASP.NET Core](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vlza89of0pxszymkxev7.jpg) Microsoft rolled out a long-awaited major update of the .NET cross-platform development platform to version 6. This release includes multiple features and improvements for the whole .NET architecture, including ASP.NET Core. This performant web framework is a successor to ASP.NET that allows building feature-packed UIs, IoT apps, and backend services. From now on, ASP.NET Core supports many useful features such as hot reload, minimal APIs, asynchronous data streaming, null-state analysis, JS modules, and more. Moreover, single-page applications based on ASP.NET Core now have a more flexible pattern that can be utilized with other popular JS frameworks. Find more details on new additions to ASP.NET Core in this [blog post](https://devblogs.microsoft.com/dotnet/announcing-asp-net-core-in-net-6/). ### JavaScript is Now Available in Excel ![New JS API in Excel](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pxcgr2wcxoxyuhl580js.jpg) Excel is probably the first thing that comes to mind when talking about software solutions for working with tabular data. At some point, almost every PC user resorts to this tool and its super handy formulas. Moreover, Excel now also supports JavaScript. This month, Microsoft released a new JavaScript API that will expand the customization capabilities of developers with Excel. It will be possible to create custom data types and related functions within Excel or extend existing ones for achieving various business goals. Learn more about this novelty in this [blog post](https://docs.microsoft.com/en-us/office/dev/add-ins/reference/overview/excel-add-ins-reference-overview). ### Meet Minor Updates of DHTMLX Components ![DHTMLX Spreadsheet](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9lh3lhbll8k81qpn92ct.png) If you want to close the issue of convenient editing and formatting data in a web app, the new DHTMLX Spreadsheet 4.2 is exactly what you need. The most notable part of this release is the appearance of several new types of Excel functions, expanding the list of available formulas from 40 to 170. The DHTMLX development team also added support for boolean operators and a new default number format - Date. In addition, end-users now can easily regulate the size of spreadsheet rows right from the UI and adjust the positioning of text in cells with the new Vertical Align button. Want to learn more? Here is the full [release article](https://dhtmlx.com/blog/dhtmlx-spreadsheet-4-2-with130-new-functions-boolean-operators-date-format-row-resizing-much/). Moreover, web developers now can also take advantage of DHTMLX Vault 4.1. This JavaScript file uploader was enriched with 3 important features: inline editing, keyboard navigation, and the ability to disable file preview. This [blog post](https://dhtmlx.com/blog/dhtmlx-vault-4-1/) offers more details on these features. ### Highlighting TypeScript 4.5 ![TypeScript 4.5 release](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pck5fg0tjr2o40gdzpet.jpg) TypeScript is justly regarded as a promising technology that may one day reach the level of JavaScript in popularity or even higher. That is why Microsoft dedicates significant efforts to unleash the full potential of this programming language. The recent TypeScript update to version 4.5 is another step in this direction. With a new utility type Awaited and modified Promise object, developers get greater opportunities for asynchronous programming. Starting from v4.5, built-in types can be updated separately from the compiler. It is also possible to use template string types as discriminants in unions and disable unused imports. Two EcmaScript proposals, namely "Ergonomic brand checks" and "Import assertions", were also implemented. It was also planned to include the ESM (ECMAScript modules) support for Node.js in this update, but it was temporarily removed due to some implementation issues. To get more details on this release, pay a visit to the [Microsoft blog](https://devblogs.microsoft.com/typescript/announcing-typescript-4-5/#preserve-value-imports). ## Useful Tips and Articles ### Using React Hooks in Web Applications Introduced in v16.8, hooks has become a real game-changer for programmers who use React framework for building web applications. They give access to the state of a component and other capabilities of React without writing classes. Hooks allow writing concise, reusable, and easy to debug code. If you want to deepen your understanding of React hooks, explore their practical application, and learn how to create custom hooks, check out this useful [article](https://www.smashingmagazine.com/2021/11/useful-react-hooks/). ### Avoiding Common Mistakes with JavaScript Promises Sometimes developers get carried away with using too many complex nested callbacks in their code. It may lead to a serious issue known as callback hell that makes code unmanageable. But fortunately, JavaScript has a special Promise object that helps to avoid this problem by providing an effective way for working with asynchronous operations. But when using JS promises something can also go wrong. The author of this [article](https://blog.bitsrc.io/5-common-mistakes-in-using-promises-bfcc4d62657f) describes five common mistakes in utilizing JavaScript promises and how to get rid of them in your coding practice. ### How to Implement Microservices in Node.js Usage of microservices can be considered as an alternative to a standard monolithic approach in web application architecture. While a monolithic app comes as a single unit, solutions based on microservices are divided into multiple independent parts. The implication here is that any changes introduced in the monolithic codebase affect the whole system i.e. a new version of the product should be released. The microservice architecture does not have this problem but like any technology, it also has some drawbacks. This [article](https://frontegg.com/blog/implementing-microservices-in-nodejs) offers a deeper insight into using microservices, their pros and cons, and a guide on implementing this type of architecture with Node.js. ### Creating a Blockchain with JavaScript In recent years, the whole world of high technologies has been buzzing about blockchain. In essence, this innovative technology is designed for securely storing any kind of data. It became the heart of almost all cryptocurrencies. The demand for blockchain developers is skyrocketing, so you can make your first steps in this field right now. The YouTube channel Simply Explained provides a great collection of [videos](https://www.youtube.com/playlist?list=PLzvRQMJ9HDiTqZmbtFisdXFxul5k0F-Q4) that explain the main operating principles of blockchains and help to build a simple version of your own blockchain with JavaScript. ### Dealing with Trojan Source Attacks in JavaScript Code This month, cyber security researchers from the University of Cambridge revealed a remarkable report dedicated to a new type of source code attack and supply chain attack named Trojan Source. This technique exploits Unicode-based bidirectional control characters to inject malware into source code comments. The main issue here is that these harmful elements are very unlikely to be discovered during the code review. Thus, it is entirely possible that you can get in trouble without suspecting a thing by simply copying benign-looking code from StackOverflow or GitHub. This [article](https://snyk.io/blog/how-to-detect-mitigate-trojan-source-attacks-javascript-eslint/) offers useful recommendations on how to prevent Trojan Source attacks using ESLint.
plazarev
912,144
Legacy: alarming symptoms and problems
Author: Victoriia Zaripova Introduction The purpose of this post is to give non-IT...
0
2021-11-29T14:21:08
https://typeable.io/blog/2021-11-29-legacy
management, legacy, development
Author: Victoriia Zaripova ## Introduction The purpose of this post is to give non-IT specialists a basic insight into the hazards of obsolete computer systems and code, and the way they may harm the business. You might have heard the word **"legacy"** – usually with a negative connotation – from the technical staff. This term is used to denote the methods, technologies, and computer systems or application software that are declared to be obsolete due to some reason. However, does this legacy always have negative implications for the business, is it mandatory to get rid of it and how can you understand that it really creates problems? As a rule, the developers, analysts, testers, and support staff are those who face the legacy issues most often, which is evidenced by the broad experience of our own team. For end-users, these issues usually remain under the bonnet, and for CEOs they are concealed behind report figures without showing any logic behind them. ![Having legacy code is like driving a fancy-looking car with dieing engine](https://typeable.io/images/legacy1.jpg) Basically, the situation, on the whole, reminds of the permanent tuning of outside appearance and interior in a car where the engine is at its last gasp but the passengers suspect nothing. Sooner or later, this automotive marvel is bound to die somewhere between point A and point B, but until that time the car will make a positive impression, especially if the passenger compartment is extremely comfortable and the suspension – or, speaking straight out, the frontline – allows driving over potholes almost smoothly. However, there is also no point in replacing your tried and tested tractor with a trendy smart right on the spot. Everything depends on the objectives and current state of the issue ## How can you understand that legacy is a hindrance? Here is the list of **alarming symptoms and issues** you can notice even without being a professional: ### Lack of well-defined and clear documentation for the supported business processes Perhaps, now the documentation seems to be of no importance since each of your employees is a real pro who can explain the entire business process from A to Z at any moment and knows the information system they are using inside out. However, the real-life experience usually shows that this is far from being the case. Moreover, even the terms used by the personnel in different departments differ significantly. The most basic example is the attempt to build the business process for supply agreements approval. Lawyers treat the term “agreement” quite differently from accountants, and both departments focus on entirely different stages of the agreement approval. ![Well-organised BPM is important](https://typeable.io/images/legacy2.jpeg) Today, businesses are more willing to recognize the value of transparent and well-organized business processes and you’ll have little difficulty in finding a post on the advantages of this approach. Here is an example: [Benefits of BPM | 11 Massive Advantages of Business Process Management](https://kissflow.com/workflow/bpm/benefits-of-business-process-management-bpm/). Besides, this article is also notable for the studies it’s based on, in particular, the [study](https://www.horsesforsources.com/digital-workforce-to-shine_041820) of 2020 stating that the outbreak of COVID made businesses invest more in the business process automation and altered their assessment of how important it is to change the obsolete processes. ### Rigidity in improvements Due to some reasons you are not able to integrate easily and quickly with the leading services, timely scale up or flexibly modify the software and, consequently, always miss the boat of market opportunities. Just believe, this is not a chain of tragic accidents, but a disturbing symptom. This symptom is especially clearly seen in governmental institutions where rigidity is embedded in the work format, and where all changes require long-term approval. For instance, excess expenses of the US government for the IT infrastructure in 2019 (over 70 billion dollars) triggered the internal [investigation](https://www.gao.gov/products/gao-19-471#summary) showing that obsolete software is the key issue. Nevertheless, commercial companies whose way of operation implies flexibility and openness to new technologies also suffer from the legacy. Airline companies, banks, insurance companies, and retailers sooner or later turn out to be unable to overcome the rigidity of obsolete software. As a result, their operation becomes unstable, they are not able to bring new products and services to market or even stably support the existing ones. For example, in August 2016 Delta Air Lines faced an unexpected failure of the booking, check-in and boarding systems which always seemed to be reliable, which resulted in an hours-long downtime and cancellation of more than 2000 flights. This and other cases are described in the post ["Legacy systems are problems for boardrooms not computer geeks"](https://www.ft.com/content/5bf9de84-d665-11e6-944b-e7eb37a6aa8e), *Financial Times, Jan. 31, 2017*. ![Over 2000 flights have once been cancelled bacuase of obsolete software](https://typeable.io/images/legacy3.jpeg) ### Low spirits in the IT team and loss of users’ loyalty One would think that the legacy cannot affect the team morale. There is no secret, as any modification of legacy systems resembles a patch on the A-bomb – most probably it won’t go off but you wouldn’t like to touch it again if you can help it. Specialists in obsolete languages and technologies don’t come cheap – one has only to think about the [Y2K problem](https://en.wikipedia.org/wiki/Year_2000_problem). Novices, on the other hand, try to patch the old environment with something new, so with time, all this becomes a monstrous zoo of technologies where not every specialist would dare to plunge. As the result, the users complain more and more about the problems and the product development is hindered. Moreover, the personnel are more likely to leave as they’ll be demotivated and not willing to dig through the problems of obsolete monstrous code with documentation missing or passed over as verbal folklore. ![Dealing with legacy code is discouraging for the developers](https://typeable.io/images/legacy4.jpg) Of course, no one is indispensable, but you should remember that selection and adaptation of a new staff member come at a price and the more complex and intricate the project is, the more time it will take the new employee to become up to speed (while being paid for work with the old code!). Meanwhile, the rest of the team will have to solve business-critical problems. And now imagine that dramatic market changes (and they’ve always been dramatic recently) require an immediate response. It’s not necessary to imagine for yourself, you can just read what situation the businesses are facing today: [The coronavirus (COVID-19): business impact](https://www.accenture.com/us-en/about/company/coronavirus-business-economic-impact). ## Standard solutions Thus, we’ve found out that legacy is not just a problem for the IT department but also a potential threat to the company stability and growth. Let’s consider standard solutions for this situation: 1. *Ignore* – this path can be costly if you already see the problems listed above but it can be optimal in some cases. In the long run, if the business pathway is unchangeable, it’s better to rely on the trusted comrade-in-arms with whom you went through fire and water; 2. *Replace it with completely new software* – sometimes this path is the only possible solution because the legacy, like a disease, can infect the environment very quickly. 3. *Replace gradually/component-wise* – this way is usually the revolution from below, when the IT department systematically performs refactoring of the home system, but it usually requires almost boundless tenacity and consistency; 4. *Reengineering of business processes and the software* – this path is perhaps the most radical, practical, and effective but it’s labour-intensive and needs the deliberate commitment of the management. ## Conclusion As you can see, legacy can do harm to the business, not only to the programmers’ nerves. You can deal with the legacy in different ways, and different ways will work for specific cases. In our next post, we’ll describe in more detail when and what way should be selected and will also tell how technical tools can help you to work with the legacy.
fiercekatie
912,406
100 Languages Speedrun: Episode 09: Ada
Ada is an old programming language created to enforce "safe" programming. It is best known for tiny...
15,607
2021-11-29T17:14:07
https://dev.to/taw/100-languages-speedrun-episode-09-ada-34og
ada, programming
Ada is an old programming language created to enforce "safe" programming. It is best known for tiny accident when such a "safe" Ada program blew up Ariane 5 rocket in 1996, costing approximately $370m. If we take ratio of losses due to programming language issues to number of people coding in a given language, Ada would likely rank as the absolute least safe of all languages. Sure, SQL injections cost $billions, but SQL is used by 10000x as many people as Ada, so an average SQL programmer is doing a lot less damage than an average Ada programmer. If that doesn't prove that TDD is more important than "static safety", then I don't know what will. Also, as an old language Ada is fairly difficult to run on modern operating systems, so we'll be using Docker to run it. It is named after Ada Lovelace, who is often called a "first programmer", [which is a considerable exaggeration](https://twobithistory.org/2018/08/18/ada-lovelace-note-g.html), but let's leave all that historical stuff behind and explore the language itself. ### Hello, World! Let's start with `hello_world.adb`: ```ada with Ada.Text_IO; procedure Hello_World is begin Ada.Text_IO.Put_Line("Hello, World!"); end Hello_World; ``` As I couldn't find any compiler running on OSX, we'll run it with Docker: ``` $ docker run --rm -i -t -v $(pwd):/source nacyot/ada-gnat:apt gnatmake hello_world.adb gcc-4.6 -c hello_world.adb gnatbind -x hello_world.ali gnatlink hello_world.ali $ docker run --rm -i -t -v $(pwd):/source nacyot/ada-gnat:apt ./hello_world Hello, World! ``` One thing that's already notable is `end Hello_World`. Yes, Ada, for "safety" reasons, requires every `end` to specify what it's ending. I know it sounds like a joke, but people who created Ada were absolutely serious about it. In some cases you're allowed to skip saying what you're ending, but we're trying to write Ada the way it was meant to be written. ### Fibonacci Here's Fibonacci in Ada: ```ada with Ada.Text_IO; procedure Fibonacci is function Fib(I: Integer) return Integer is begin if I <= 2 then return 1; else return Fib(I-1) + Fib(I-2); end if; end Fib; begin for I in 1..20 loop Ada.Text_IO.Put_Line(Integer'Image(Fib(I))); end loop; end Fibonacci; ``` Let's run it: ``` $ docker run --rm -i -t -v $(pwd):/source nacyot/ada-gnat:apt gnatmake fibonacci.adb gcc-4.6 -c fibonacci.adb gnatbind -x fibonacci.ali gnatlink fibonacci.ali $ docker run --rm -i -t -v $(pwd):/source nacyot/ada-gnat:apt ./fibonacci 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 ``` There's a lot to unpack here: * where's those extra spaces coming from? Ada thinks it's unsafe to convert `7` to `"7"`. In some weird idea of consistently since `-7` converts to `-7`, 7 converts to ` 7` with extra space where plus/minus sign would go. * at least Ada has loops over ranges like `for I in 1..20 loop`, it's baffling people make languages even today which don't have that * `Integer'Image` syntax for function in a package looks really weird, especially since we also have more familiar `.` on the same line. ### FizzBuzz And finally we get to the FizzBuzz, and it's surprisingly convoluted in Ada. We need to strip that extra space. Well, surely Ada would have strings in its standard library, right? You wish. It its drive for "safety", it provides fixed-width strings only. So you can do this: ```ada S: String := "one"; S := "two"; ``` But not this: ```ada S: String := "one"; S := "three"; ``` Or even this: ```ada S: String := "three"; S := "one"; ``` Nope, it's not maximum string length (like with SQL `varchar` columns), it must literally be exactly the same length. Fortunately while local variables are crazy like that, function arguments aren't so we're finally able to write a FizzBuzz: ```ada with Ada.Text_IO; procedure FizzBuzz is function LStrip(S: String) return String is begin if S(S'First) = ' ' then return S(S'First+1 .. S'Last); else return S; end if; end LStrip; begin for I in 1..100 loop if I mod 3 = 0 and I mod 5 = 0 then Ada.Text_IO.Put_Line("FizzBuzz"); elsif I mod 3 = 0 then Ada.Text_IO.Put_Line("Fizz"); elsif I mod 5 = 0 then Ada.Text_IO.Put_Line("Buzz"); else Ada.Text_IO.Put_Line(LStrip(Integer'Image(I))); end if; end loop; end FizzBuzz; ``` I'll skip all the minor weirdness like `=` for equality check, `()` for substring, indexing starting from 1, `S'First` and `S'Last`, and so on. ### Should you use Ada? Only if you're trying to sabotage Blue Origin. Otherwise, no. If you're really exceedingly safety-obsessed, there's Rust for you. Otherwise, just about any modern properly memory-managed language (so all except C and C++) with decent TDD will do just fine. ### Code [All code examples for the series will be in this repository](https://github.com/taw/100-languages-speedrun). [Code for the Ada episode is available here](https://github.com/taw/100-languages-speedrun/tree/master/episode-09-ada).
taw
912,423
Learn Python
Python Python is an interpreted high-level general-purpose programming language. Its...
0
2021-11-29T17:52:44
https://easyawslearn.blogspot.com/2021/11/learn-python.html
programming, beginners, tutorial, python
## **Python** Python is an interpreted high-level general-purpose programming language. Its design philosophy emphasizes code readability with its use of significant indentation. Its language constructs as well as its object-oriented approach aim to help programmers write clear, logical code for small and large-scale projects. It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented and functional programming. It is often described as a "batteries included" language due to its comprehensive standard library. It was created by Guido van Rossum, and released in 1991. It is used for: web development (server-side), software development, mathematics, system scripting. [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s7fwblbz1pr4z97sreku.jpg)](https://youtu.be/25J4Ruv7E_U) **What can Python do?** Python can be used on a server to create web applications. Python can be used alongside software to create workflows. Python can connect to database systems. It can also read and modify files. Python can be used to handle big data and perform complex mathematics. Python can be used for rapid prototyping, or for production-ready software development. **Why Python?** Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). Python has a simple syntax similar to the English language. Python has syntax that allows developers to write programs with fewer lines than some other programming languages. Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. Python can be treated in a procedural way, an object-oriented way or a functional way. [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5xhnddhekdd4r0px9t8r.jpg)](https://www.youtube.com/watch?v=6YVS-qUxukc&t=74s) ## Python Installation: Many PCs and Macs will have python already installed. [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltb2ok6th4n2axx6acvl.jpg)](https://www.youtube.com/watch?v=ycTc1zAR_iA&t=4s) To check if you have python installed on a Windows PC, search in the start bar for Python or run the following on the Command Line `(cmd.exe): C:\Users\Your Name>python --version` To check if you have python installed on a Linux or Mac, then on linux open the command line or on Mac open the Terminal and type: ` python --version` ## Python Syntax and Comments: [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vsfir2fyznpssihhd9zk.jpg)](https://www.youtube.com/watch?v=ncbTQeqUb90&t=49s) Python syntax can be executed by writing directly in the Command Line: `>>> print("Hello, World!") Hello, World!` Or by creating a python file on the server, using the .py file extension, and running it in the Command Line: C:\Users\Your Name>python myfile.py Python Indentation: Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code. Example: ``` if 5 > 2: print("Five is greater than two!") ``` **Single-Line Comments:** Comments can be used to explain Python code. Comments can be used to make the code more readable. Comments can be used to prevent execution when testing code. Comments start with a #, and Python will ignore them: Example ``` #This is a comment print("Hello, World!") ``` **Multi-Line Comments: **Example ``` """ This is a comment written in more than just one line """ print("Hello, World!") ``` ## Python Variable and Data Types: Variables are containers for storing data values. [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xcnqabo09koy7lna64ra.jpg)](https://www.youtube.com/watch?v=raShdX__8BE&t=5s) **Creating Variables:** Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Example ``` x = 5 y = "John" print(x) print(y) ``` **Get the Type:** You can get the data type of a variable with the type() function. Example ``` x = 5 y = "John" print(type(x)) print(type(y)) ``` **Case-Sensitive: **Variable names are case-sensitive. Example ``` This will create two variables: a = 4 A = "Sally" #A will not overwrite a ``` **Built-in Data Types:** In programming, data type is an important concept. Variables can store data of different types, and different types can do different things. Python has the following data types built-in by default, in these categories: `Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview` ## Python Conditions and If statements: Python supports the usual logical conditions from mathematics: Equals: a == b Not Equals: a != b Less than: a < b Less than or equal to: a <= b Greater than: a > b Greater than or equal to: a >= b [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7l34rff5a8d2yq8ox9ia.jpg)](https://www.youtube.com/watch?v=BasLA6W7Yhs) These conditions can be used in several ways, most commonly in "if statements" and loops. An "if statement" is written by using the if keyword. Example **If statement:** ``` a = 33 b = 200 if b > a: print("b is greater than a") ``` **Indentation:** Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose. **Elif:** The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". Example ``` a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") ``` **Getting the Data Type:** You can get the data type of any object by using the type() function: Example Print the data type of the variable x: ``` x = 5 print(type(x)) ``` ## Python Loops: Python has two primitive loop commands: while loops for loops **The while Loop:** [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojvvhvrwl4qqwyd5d992.jpg)](https://www.youtube.com/watch?v=89aw4fD9YeQ&t=19s) With the while loop we can execute a set of statements as long as a condition is true. Example ``` Print i as long as i is less than 6: i = 1 while i < 6: print(i) i += 1 ``` **Python For Loops:** A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k2q12l58b0qq0jft3kj6.jpg)](https://www.youtube.com/watch?v=cSdunnrI0ds) Example Print each fruit in a fruit list: ``` fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) ``` **Looping Through a String:** Even strings are iterable objects, they contain a sequence of characters: Example Loop through the letters in the word "banana": ``` for x in "banana": print(x) ``` ## Break, Continue, and Pass: [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxjp3vf0r689jrcm1fov.jpg)](https://www.youtube.com/watch?v=css_ijwXOHw) **Break Statement:** With the break statement we can stop the loop before it has looped through all the items: Example Exit the loop when x is "banana": ``` fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break ``` **Continue Statement:** With the continue statement we can stop the current iteration of the loop, and continue with the next: Example Do not print banana: ``` fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) ``` **Pass Statement:** for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. Example ``` for x in [0, 1, 2]: pass ``` ## Python For Else: The else keyword in a for loop specifies a block of code to be executed when the loop is finished: [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o6dmp15jgsx0jir45oxh.jpg)](https://www.youtube.com/watch?v=1-woqHzS9n0&t=2s) Example Print all numbers from 0 to 5, and print a message when the loop has ended: ``` for x in range(6): print(x) else: print("Finally finished!") ``` ## Python Functions: A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iyelhy1m4x2qkm0rj1ql.jpg)](https://www.youtube.com/watch?v=Qy6bVkOegwU&t=37s) **Creating a Function:** In Python a function is defined using the def keyword: Example ``` def my_function(): print("Hello from a function") ``` **Calling a Function:** To call a function, use the function name followed by parenthesis: Example ``` def my_function(): print("Hello from a function") my_function() ``` **Arguments:** Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma. The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name: Example ``` def my_function(fname): print(fname + " Refsnes") my_function("Emil") my_function("Tobias") my_function("Linus") ``` **Number of Arguments:** By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less. Example This function expects 2 arguments, and gets 2 arguments: ``` def my_function(fname, lname): print(fname + " " + lname) my_function("Emil", "Refsnes") ``` **Default Parameter Value:** The following example shows how to use a default parameter value. If we call the function without argument, it uses the default value: Example ``` def my_function(country = "Norway"): print("I am from " + country) my_function("Sweden") my_function("India") my_function() my_function("Brazil") ``` ## Python Lambda: A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression. [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9pm4jz3fejx5vr2fb8p.jpg)](https://www.youtube.com/watch?v=VkGBzKq7dRs&t=3s) **Syntax:** `lambda arguments : expression` The expression is executed and the result is returned: Example Add 10 to argument a, and return the result: ``` x = lambda a : a + 10 print(x(5)) ``` **Why Use Lambda Functions?** The power of lambda is better shown when you use them as an anonymous function inside another function. Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number: `def myfunc(n): return lambda a : a * n` Use that function definition to make a function that always doubles the number you send in: Example ``` def myfunc(n): return lambda a : a * n mydoubler = myfunc(2) print(mydoubler(11)) ``` ## Python Arrays: Note: Python does not have built-in support for Arrays, but Python Lists can be used instead. [![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wtxyj8x4elk5o0dxseoh.jpg)](https://www.youtube.com/watch?v=G7z19LQcH3g) **What is an Array?** An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: `car1 = "Ford" car2 = "Volvo" car3 = "BMW"` However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number. Access the Elements of an Array: You refer to an array element by referring to the index number. Example Get the value of the first array item: ``` x = cars[0] ``` **Adding Array Elements:** You can use the append() method to add an element to an array. Example Add one more element to the cars array: ``` cars.append("Honda") ``` **Removing Array Elements:** You can use the pop() method to remove an element from the array. Example Delete the second element of the cars array: ``` cars.pop(1) ``` You can also use the remove() method to remove an element from the array. Example Delete the element that has the value "Volvo": **cars.remove("Volvo")**
s3cloudhub
912,493
The Successful Programmer | P-PL.com
The world needs more successful programmers. More specifically, the world needs more people that...
0
2021-11-29T20:13:21
https://dev.to/tgrimes/the-successful-programmer-p-plcom-4o0a
programming, productivity, career, codequality
The world needs more successful programmers. More specifically, the world needs more people that embody the _mindset_ and attitudes of skilled and successful programmers. Programmers are problem solvers. Programmers embrace and learn from failures. Programmers persevere and innovate the world around them. Successful programmers make the world a far better place. Modern programming started in the era of punch cards and working on green screen terminals. Back then, programming was pretty difficult to learn; syntax was nothing like it is today. By the way, the reason screens were green back then is because the fluorescent green on black background was easier on your eyes and allowed you to work longer hours. Hollywood ran with idea and that's why hackers are depicted with green on black terminal windows, no other reason. As time has passed, a multitude of new languages to write code have emerged, syntax has become far more intuitive, and technology has advanced in some wild ways. Yet, be that the case, there are some things that have never changed since the dawn of the industry: the mentality of the successful programmer. I'd like to make one clarification before I proceed. Above, where I mention "successful programmers," I'd like to make a distinction: Successful in this case does not refer to the wealth a programmer has, his position at the top of the ladder within his organization, or the any type of worldly gain procured through his job as a programmer. Success here is simply defined as the individual who has embodied the characteristics we are about to talk through and is successfully employing them in his life at a whole. Successful programmers embody many attitudes and traits; we will touch on 5 of them here: -Problem Solve -Persevere -Embrace and Learn from Failure -Finish the Job -Innovate the World Around You _____________________________________________________________ **Problem Solving** Programming is a process of solving problems. Solutions are arrived at through clear and logical thinking, analyzing complex concepts down to their most fundamental parts. A program goes from concept to operation in stages: analysis -> design -> implementation -> verification/testing -> production and maintenance. This very process has been repeated over the years by millions of programmers, generation to generation, with only one goal: Solve problems. In a world where you can solve most your life's problems through Google search and Facebook friends, in a world that is obsessed with social media and entertainment, we have lost the problem solving spirit of our youth; the mindset that many famous programmers attribute their success to: Programmers are problem solvers. They know how to think about a problem, and more importantly, how to approach it. The programmer realizes that specialization is not enough. Creativity and intelligence is not enough. Original thinking is not enough. The "thing" that wraps all of this up together and makes it work... is the ability for the programmer to think about the problem in the correct manner. In your programming career (hobby or professional) you will undoubtedly run into something that has never been done before; this is where the fun begins. Programmers have to be able to take an idea and think of ways it can be implemented in code. To do this, you will need the ability to quickly understand concepts that most people wouldn't understand unless they were told directly. For instance, say you are implementing some sort of data editor/browser; it doesn't matter how elegant you want to make it look or how nice your user interface is, the bare minimum you have to do is take some data and display it in a window. How could you do this? Well, there are numerous ways; which way would you choose? The answer most likely depends on the type of data. For instance, if you were writing an RSS reader, you would probably implement a tree data structure first on paper (or in your head) to represent the hierarchy of each node. Then there are different ways of rendering this list; you could use a text list with some CSS styling, or a table. What about radio buttons? If it is set up as an editor, then it needs to be able to add, edit, delete data. What if it is web based? How would you get the contents of a text file into it? These are all questions that have been asked before and answers found; if you don't know what those solutions are then you must research them or come up with them yourself. This is the cunning of the programmer. _____________________________________________________________ **Perseverance** Programmers persevere through the most difficult situations possible. However, perseverance is not just about hard problems; it is also about not giving up after the first blow. There are so many programmers that give up when their Kickstarter fails to yield any funds, or if they can't get the attention of venture capitalists for their new start-up (even though some VC's flat out deny anyone who asks) but why did these people fail? It is because they were unable to persevere. They could not weather the storm and they gave up when things got rough; this is where perseverance comes in. Not giving up is difficult because of the reasons behind failure can be more than just a lack of skill or being unfamiliar with the task at hand, but sometimes it is personal (injury) or circumstantial (no money). If you are a programmer, then perseverance is your bread and butter. You should always be ready to learn from failure and use it to improve yourself; this will allow you to tackle many different problems, even if they seem insurmountable at first glance. _____________________________________________________________ **Learning from Failure** Learning from Failure is a high level skill that not everyone can readily posses. There are many examples of how people fail. The key here is to embrace the failure in order to progress forward; learn from your mistakes and continually improve: The Wright Brothers and their failed glider, Edison's almost-failed light bulb, Jobs' IBM career and his next venture (NeXT/Apple), Musk and SpaceX, the list goes on. Failure is a part of life. Everyone fails (except for those that never try) and the skill that separates the successful from everyone else is failure's ability to drive them forward. If you cannot accept your failures or learn from them, then you will be stuck spinning your wheels on a "dead end" path. The simplest example I can give would be someone who keeps failing at the same concept or task over and over again. They keep doing it wrong, they keep trying to do it right, but they are stuck in this failure loop that continually drives them nowhere. This is where a programmer can break out of the cycle; if you were able to learn from your mistakes then you could think about the problem differently and approach it another way. To put it simply: failing is not a necessary evil; it can be turned around and used to your advantage if you know how to handle it right. The programming world is full of people like this; people who keep trying to do something, but can never seem to get past the hump. They are stuck and they are unable to get out of it. It could be that they don't know how to learn from their failure; this is a skill you have to possess in order to continually improve. _____________________________________________________________ **Finish the Job** Successful programmers are extremely dedicated to the tasks in store for them; they finish what they start. Whether this is an epic, multi-year quest to create a web application that will bring new data into your company's production database or a simple one-night hack job to just get your resume working; programmers always complete their assigned work. This is because successful programmers do not just focus on completing tasks, but they are also dedicated to their craft. If you spend time learning how to program and write code and then someone comes along with a small task for you; it may be tempting to jump right in and start helping (You'll find over time that programmers are extremely helpful to one another; the community is a great one to become a part of). Knowing how much workload you can handle, however is an important trait. Its critical to recognize when you're taking on too much. This is where the debate comes in about whether or not you should say "no" to helping someone out. The bottom line is this: The world is full of unfinished projects... I can't even begin to count the number of coders/programmers who start a project and then let fall head first in the "Incomplete Abyss." Don't get into a habit of starting a project and then failing to finish. Finish what you start and complete your work. The reward at the end is always worth it, and the habit you will begin forming is incredibly advantageous in this industry. _____________________________________________________________ **Innovate the World Around You** This is an important characteristic of anyone in the software development industry. In a world where technology changes every day, and new languages are created as fast as advances in computers allow; programmers must be on the forefront of building something new and innovative. This doesn't mean you have to start your own company and create your own product or service. You can still be successful in the industry without doing this. What I mean by "Innovate" is that you should make changes to yourself and your habits, and build something new that will better your life and the lives of others. If you fail at a project or task in front of you, consider it as an opportunity to learn something new. If you see a simple (or complex) problem in your day to day life, ask yourself a few questions: 1) How big is this "problem"? 2) Can I solve this problem with code/technology? 3) If I do solve the problem with code/tech, will my solution help or benefit people around me who have the same or similar problems? This right here, is the basis for any innovation. Passion and drive to solve that problem are the ingredients for a great outcome. _____________________________________________________________ **Conclusion** The goal here is to isolate some very finite, yet complex character traits that you can begin to think about on your journey through the wonderful world that is programming. No matter what project you encounter, task you take on, or dreams you decide to build, if you embody and take action on these mentalities, you are setting yourself on the best course... a successful one. The Successful Programmer. If you are interested in becoming a better programmer, learning a new language, or want some second opinions on the code you're writing, head over to P-PL.com and sign up! It's free to sign up and we've got experts ready to help you!
lambdatechnologyinc
912,533
KAFKA + KSQLDB + .NET #1
Hi, I'm Ricardo Medeiros, .NET back end developer @vaivoa, and today I'm going to walk you through...
0
2021-11-30T17:19:05
https://dev.to/jjackbauer/kafka-ksqldb-net-19kc
kafka, ksqldb, microservices, docker
Hi, I'm [Ricardo Medeiros](https://github.com/jjackbauer), .NET back end developer @vaivoa, and today I'm going to walk you through using ksqlDB to query messages produced in kafka by a .NET/C# producer. For this example, I will be deploying my enviroment as containers, described in a docker compose file, to ensure easy reproducibility of my results. The source code used in this example is avaliable [here](https://github.com/jjackbauer/ksqlDBDemo). ## Services First, let's talk about the docker compose environment services. the file is avaliable [here](https://github.com/jjackbauer/ksqlDBDemo/blob/main/docker-compose.yml). ### .NET API Producer Automaticaly generated .NET api with docker compose service ``` ksqldbdemo: container_name: ksqldbdemo image: ${DOCKER_REGISTRY-}ksqldbdemo build: context: . dockerfile: Dockerfile ``` This producer service needs the .NET generated dockerfile shown below: ``` FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base WORKDIR /app EXPOSE 80 EXPOSE 443 FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build WORKDIR /src COPY ["ksqlDBDemo.csproj", "."] RUN dotnet restore "ksqlDBDemo.csproj" COPY . . WORKDIR "/src/" RUN dotnet build "ksqlDBDemo.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "ksqlDBDemo.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "ksqlDBDemo.dll"] ``` ### ZooKeeper Despite not been necessary since Kafka 2.8, ZooKeeper coordinates kafka tasks, defining controllers, cluster membership, topic configuration and more. In this tutorial, it's used the confluent inc. ZooKeeper image, due to it's use in the reference material. It makes Kafka more reliable, but adds complexity into the system. ``` zookeeper: image: confluentinc/cp-zookeeper:7.0.0 hostname: zookeeper container_name: zookeeper ports: - "2181:2181" environment: ZOOKEEPER_CLIENT_PORT: 2181 ZOOKEEPER_TICK_TIME: 2000 ``` ### Kafka Kafka is an event streaming plataform capable of handling trillions of events a day. Kafka is based on the abstraction of an distributed commit log. Initialiy developed at LinkedIn in 2011 to work as a message queue, but it has evolved into a full-fledge event streanming platfmorm. Listed as broker in the services, is the core of this tutorial. It's configuration is tricky, but using it as follows worked well in this scenario. ``` broker: image: confluentinc/cp-kafka:7.0.0 hostname: broker container_name: broker depends_on: - zookeeper ports: - "29092:29092" environment: KAFKA_BROKER_ID: 1 KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181' KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:29092,PLAINTEXT_HOST://localhost:9092 KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1 KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0 KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1 KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1 ``` ### ksqlDB ksqlDB is a database built to allow distributed stream process applications. Made to work seamsly with kafka, it has a server that runs outside of kafka, with a REST API and a CLI application that can be run separatly and it's used in this tutorial. #### ksqlDB Server In this example, it's used the confluent inc image of the ksqlDB server, once more, due to it's widespread usage. ``` ksqldb-server: image: confluentinc/ksqldb-server:0.22.0 hostname: ksqldb-server container_name: ksqldb-server depends_on: - broker ports: - "8088:8088" environment: KSQL_LISTENERS: http://0.0.0.0:8088 KSQL_BOOTSTRAP_SERVERS: broker:29092 KSQL_KSQL_LOGGING_PROCESSING_STREAM_AUTO_CREATE: "true" KSQL_KSQL_LOGGING_PROCESSING_TOPIC_AUTO_CREATE: "true" ``` #### ksqlDB CLI The same goes for the ksqlDB CLI service, that also use the confluent inc image. ``` ksqldb-cli: image: confluentinc/ksqldb-cli:0.22.0 container_name: ksqldb-cli depends_on: - broker - ksqldb-server entrypoint: /bin/sh tty: true ``` ### Kafdrop Kafdrop is a Web UI for viewing kafka topics and browsing consumer groups. It makes kafka more accessible. ``` kafdrop: container_name: kafdrop image: obsidiandynamics/kafdrop:latest depends_on: - broker ports: - 19000:9000 environment: KAFKA_BROKERCONNECT: broker:29092 ``` ## Tutorial Now it's the time that you have been waiting, let's make it work! ### Enviroment For this tutorial, you'll need a [docker desktop](https://docs.docker.com/get-docker/) installation, either it's on a Linux distribution or on Windows with WSL and [git](https://git-scm.com/downloads). ### Cloning the project A Visual Studio project is avaliable [here](https://github.com/jjackbauer/ksqlDBDemo), it has docker support and already deploys all the services needed for this demo in the IDE. However, you will be fine if you don't want or can't use Visual Studio. Just clone it, running the following comand on the terminal and directory of your preference: ``` $ git clone https://github.com/jjackbauer/ksqlDBDemo.git ``` Use the following command to move to the project folder: ``` $ cd /ksqlDBDemo ``` And, in the project folder, that contains the docker-compose.yml run the following command to deploy the services: ``` $ docker compose up -d ``` after this command, make sure that all services are running. Sometimes services fall, but it is okay. In order to see if everything is running ok, it's possible to see the services running in docker desktop, as shown bellow: ![Docker Desktop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3uakexrf3p7atec8q7k9.PNG) Or you can execute the following command: ``` $ docker ps ``` Which should output something like this: ``` CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES b42ce9954fd9 ksqldbdemo_ksqldbdemo "dotnet ksqlDBDemo.d…" 2 hours ago Up 2 hours 0.0.0.0:9009->80/tcp, 0.0.0.0:52351->443/tcp ksqldbdemo 0a0186712553 confluentinc/ksqldb-cli:0.22.0 "/bin/sh" 2 hours ago Up 2 hours ksqldb-cli 76519de6946e obsidiandynamics/kafdrop:latest "/kafdrop.sh" 2 hours ago Up 2 hours 0.0.0.0:19000->9000/tcp kafdrop 11c3a306ee01 confluentinc/ksqldb-server:0.22.0 "/usr/bin/docker/run" 2 hours ago Up 2 hours 0.0.0.0:8088->8088/tcp ksqldb-server 07cef9d69267 confluentinc/cp-kafka:7.0.0 "/etc/confluent/dock…" 2 hours ago Up 2 hours 9092/tcp, 0.0.0.0:29092->29092/tcp broker 3fa1b9a60954 confluentinc/cp-zookeeper:7.0.0 "/etc/confluent/dock…" 2 hours ago Up 2 hours 2888/tcp, 0.0.0.0:2181->2181/tcp, 3888/tcp zookeeper ``` ### WEB API Now, with all services up and running, we can access the WEB API Swagger to populate our Kafka topics. The code is very simple and it's avaliable in the [repository](https://github.com/jjackbauer/ksqlDBDemo). The WEB API swagger is deployed at [http://localhost:9009/swagger/index.html](http://localhost:9009/swagger/index.html). As shown in the image bellow, it has two endpoints and they create events that could be created by indepent microservices. One for creating an event that creates a userName in the system and another that takes an Id and generates a three digit code. ![Swagger Geral](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/99l7s38ffu0tx1gon62r.PNG) Then you can create an User with the user name of your choise, as shown: ![Request Create user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mxlhjsmfeei7wnym834g.PNG) And it will have an assigned unique Id, as demonstrated: ![Response create user](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3g06gff8025nxw6gze9v.PNG) Now, you can get a three digit code for your user Id as displayed: ![Get Code Request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6yoezrw53wibte9baiaj.PNG) And a random code is generated for the selectd, as we can observe in the image that follows: ![Get Code Response](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azp6yri8cy4x4day7vyu.PNG) ### Kafdrop We can use the kafdrop UI the check if everything is okay. Kafdrop is deployed at [http://localhost:19000/](http://localhost:19000/). There, you will find all the brokers and topics avaliable. It should look like this: ![Kafdrop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y9v29cx12cqw5cnp19sr.PNG) ### KSQL CLI After all that, you'll be able to create your streams of data and query it using ksqlDB. On your preferential terminal, use the command: ``` docker exec -it ksqldb-cli ksql http://ksqldb-server:8088 ``` #### Creating streams And then you are in the ksql CLI and are free to create your streams and queries. First, let's create a stream for each one of our topics: ``` CREATE STREAM stream_user (Name VARCHAR, Id VARCHAR) WITH (kafka_topic='demo-user', value_format='json', partitions=1); ``` ``` CREATE STREAM stream_code (Id VARCHAR, code INT) WITH (kafka_topic='demo-code', value_format='json', partitions=1); ``` #### Create a materialized view You can join the client data with the most recent randomized code. to achieve this, you must create a materialized view table, that joins both streams as seen in the ksqldb script that follows: ``` CREATE TABLE currentCodeView AS > SELECT user.Name, > LATEST_BY_OFFSET(code.code) AS CurrentCode > FROM stream_code code INNER JOIN stream_user user > WITHIN 7 DAYS ON code.Id = user.Id > GROUP BY user.Name >EMIT CHANGES; ``` #### Making a push query After that, we can query this materialized view: ``` SELECT * FROM currentCodeView EMIT CHANGES; ``` This push query keep on running until you hit cntrl+c to cancel it. ## Conclusions In this tutorial it's demonstrated that in a kafka + ksqlDB enviroment, you can make SQL queries and also join on data that comes from different events, which is one of most complexities envolved with microsservices systems. And it is what ksqlDB solves by enabling SQL operations over Kafka topics. It's my goal to explore the possibilites allowed by this ecosystem and I hope to bring more knowledge on this topic in another articles here. Any sugestions, comments or corrections, fell free to reach me out at [LinkedIn](https://www.linkedin.com/in/rmedio/). {% user jjackbauer %} ## References [ksqlDB Quickstart](https://ksqldb.io/quickstart.html?_ga=2.218008467.482211024.1638022122-847939024.1633623088&_gac=1.142412294.1634140787.EAIaIQobChMIjOL6pt_H8wIVmcWaCh1KbwgwEAEYASAAEgLBFvD_BwE) [ksqlDB Overview](https://docs.confluent.io/platform/current/ksqldb/index.html#ksql-home) [Kafka .NET Client] (https://docs.confluent.io/clients-confluent-kafka-dotnet/current/overview.html) [ksqlDB Documentation - Data Types Overview](https://docs.ksqldb.io/en/latest/reference/sql/data-types/) [KSQL and ksqlDB](https://docs.ksqldb.io/en/latest/operate-and-deploy/ksql-vs-ksqldb/) [Welcome to Apache ZooKeeper](https://zookeeper.apache.org/) [What is ZooKeeper & How Does it Support Kafka?](https://dattell.com/data-architecture-blog/what-is-zookeeper-how-does-it-support-kafka/) [What is Apache Kafka®?](https://www.confluent.io/what-is-apache-kafka/?utm_medium=sem&utm_source=google&utm_campaign=ch.sem_br.nonbrand_tp.prs_tgt.kafka_mt.xct_rgn.latam_lng.eng_dv.all_con.kafka-general&utm_term=apache%20kafka&creative=&device=c&placement=&gcli d=Cj0KCQiA7oyNBhDiARIsADtGRZYDVaYjkPkoJQHNrz_xBodIq2P8ztwb8g3OTiRG_wMHXyzof1nqKEMaAoT_EALw_wcB) [ksqlDB - The database purpose-built for stream processing applications](https://ksqldb.io/) [An overview of ksqlDB](https://ksqldb.io/overview.html) [CREATE TABLE AS SELECT](https://docs.ksqldb.io/en/latest/developer-guide/ksqldb-reference/create-table-as-select/) [How to join a stream and a stream](https://kafka-tutorials.confluent.io/join-a-stream-to-a-stream/ksql.html) [Time and Windows in ksqlDB Queries](https://docs.ksqldb.io/en/latest/concepts/time-and-windows-in-ksqldb-queries/) [Time operations](https://docs.ksqldb.io/en/latest/reference/sql/time/) ![linha horizontal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n8bndcx2jkn1jz1dy98v.png) # Disclaimer A VaiVoa incentiva seus Desenvolvedores em seu processo de crescimento e aceleração técnica. Os artigos publicados não traduzem a opinião da VaiVoa. A publicação obedece ao propósito de estimular o debate. ![logo vaivoa](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1wmziqv74ghhgyi9p0om.png)
jjackbauer
912,621
My top 5 Cyber Monday & Techy Tuesday deals for designers & devs (including refunds & USP)
Every year, Black Friday sneaks up on everyone. It’s one of those holidays that comes without warning...
0
2021-11-29T20:51:32
https://dev.to/developereyes/my-top-5-cyber-monday-techy-tuesday-deals-for-designers-devs-including-refunds-usp-58ca
productivity, css, deals, offers
Every year, Black Friday sneaks up on everyone. It’s one of those holidays that comes without warning while you’re busy munching on your Thanksgiving feast and planning for Christmas. Black Friday just passed and now Cyber Monday is on us, with Techy Tuesday looming on the horizon! Today (and tomorrow perhaps) is probably the last day to stack your gifts for Christmas. To help alleviate some pressure, we have determined the top deals for YOU, the designer and the developer. As a matter of fact, there are so many great deals out there that it would be nearly impossible to compile them all in just one post. Therefore, I’ve done my fair share of the heavy lifting and put together lists with specific products in mind that tied into certain themes such as design tools or development platforms for example and provide you with a wealth of great information so that you can plan and save accordingly during this joyous time! ## 1. Writecream - Useful for job/internship applications & content creation ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tagdzsypalmo0roxo9u6.png) [Writecream](https://www.writecream.com) is an A.I-powered app for generating blog articles, YouTube videos & podcasts in seconds—using just a product name and description; in addition, you can also use Writecream to generate personalized compliments for cold emails and LinkedIn sales **Why should you get it:** If you have a website or YouTube channel, this can be useful for generating content easily. The personalized compliments—that can be generated using a LinkedIn profile or website—can improve your chances of getting that job, internship or project (most of the job/internship/project applications are non-personalized, including a personalized compliment at the top betters your chances) **Cost:** $59 **Trial:** Yes, available **Offer/Coupon:** Get lifetime access to Writecream for a one-time price of $59. Sufficient for generating 20 blog articles, 20 YouTube videos, or generating 200 personalized compliments. No coupon code required. **Validity:** November 19, 2021 to December 31, 2021 **Refund Period:** 60-days **Deal Link:** [https://www.writecream.com/lifetime-deal/](https://www.writecream.com/lifetime-deal/) ## 2. Creative Tim – UI Kits ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ob628o8c7ro64fddetsj.png) [Creative Tim](https://www.creative-tim.com) specializes in building high-quality UI kits for various frameworks, including bootstrap, angular, vue.js, react, laravel and more. **Why should you get it:** Useful for developers who want to easily put together a website, without diving their toes into user interface and experience. The UI kits has plenty of choices for each element—for example, you will find at least five variations of how the menu bar **Cost:** $119 - $349 (discount included) **Trial:** No, not available **Coupon:** 80% off on all products. Includes a lifetime deal of $349. What you get depends on the product you opt for. Kindly refer to the deal link below for more information. No coupon required **Validity:** November 19, 2021 to November 30, 2021 **Refund Period:** 24 hours **Deal Link:** [https://www.creative-tim.com/campaign](https://www.creative-tim.com/campaign) ## 3. Static App – Host static websites in one-click ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pm28f5863a6fjfpgjall.png) [Static App](https://static.app) is your one-click website hosting solution for static websites. It will make the website live, provide it with a personal domain name, ensure secure HTTPS connection through a viable SSL certificate, store your media content and offer you a helpful back-end where you can easily manage files **Why should you get it:** Easily deploy a static website in one-click. Useful if you put together a quick website having your portfolio. Includes a domain name, SSL certificate, code editor, and file manager **Cost:** $5 - $15 (discount not included) **Trial:** Yes, available **Coupon:** 30% off on all monthly plans. What you get depends on the plan you opt for. Kindly refer to the deal link below for more information. Use coupon BLACK at checkout **Validity:** November 19, 2021 to November 30, 2021 **Refund Period:** Non-refundable **Deal Link:** [https://static.app](https://static.app) ## 4. Feeda – Product Feedback Tool ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fo2azj9gnlpajnxd2sl.png) [Feeda](https://feeda.io/) collects product feedback from customers and stores it, getting insights on how to improve products. It helps entrepreneurs measure their success in understanding what users expect of them. **Why should you get it:** Useful for designers who want to collect user feedback and improve UX. Also useful for keeping customers in the loop about feature updates **Cost:** $9 - $19 (discount included) **Trial:** Yes, available **Coupon:** 30% off on all monthly plans. What you get depends on the plan you opt for. Kindly refer to the deal link below for more information. No coupon code required **Validity:** November 19, 2021 to November 30, 2021 **Refund Period:** 20 days **Deal Link:** [https://feeda.io/](https://feeda.io/) ## 5. Siter – No-Code Web Design Tool and Website Builder ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ccovnpvmag935x7vit84.png) [Siter](https://siter.io/) is the new, interactive online editor of sites for fellow designers. A graphical environment to make and manage e-commerce and complex projects without having to go straight into coding, it's easy to use and has lots of settings to help artists create layouts including images, buttons, polygons, maps and icons along with editable content which allows designers to work out costs on their designs almost instantly. **Why should you get it:** Useful for UI/UX designers to design layouts and interfaces. Includes collaboration features for teams. **Cost:** $9 - $12 (discount not included) **Trial:** Yes, available Coupon: 30% off on all monthly plans. What you get depends on the plan you opt for. Kindly refer to the deal link below for more information. Use coupon BLACK at checkout **Validity:** November 19, 2021 to November 30, 2021 **Refund Period:** Non-refundable **Deal Link:** [https://siter.io/](https://siter.io/) ## Conclusion These were my top five picks. I have tried to cater to different use-cases, ranging from job/internshp applications to generating blog articles/videos and making portfolio websites. I hope my research efforts helped you save time. If you are lazy like me and reading this on Techy Tuesday, all these deals are still applicable, with some even going beyond. Happy holidays!
developereyes
912,659
Microservices: The Static Contract Pitfall and how to avoid it
Hi everyone! I would like to show you how The Static Contract pitfall could drive APIs to unexpected...
0
2021-11-30T16:16:16
https://dev.to/abarran03/microservices-architecture-the-static-contract-pitfall-2hnn
microservices, beginners, architecture
Hi everyone! I would like to show you how *_The Static Contract pitfall_* could drive APIs to unexpected issues, and how versioning helps to avoid them. For that purpose I will be using *_O'Reilly's Microservices Antipatterns and Pitfalls_* and Microsoft site related to *_RESTful web API design_*. References were added at bottom. ## But what is a pitfall? According to Richards (2016) a pitfall is > something that was never a good idea, even from the start. And that is the case for *_The Static Contract pitfall_*. This assumption leads APIs to be not flexible enough for contract changes in front of client applications. ## The Static Contract Pitfall Imagine having a REST API endpoint consumed by three different client applications, but one of them needs an extension of a service published. So, the API provider in order to deploy the new changes, requires to check compatibility with the others consumers. Ups! Something goes wrong, the changes imply modifying a JSON contract, then consumers will be impacted and none of them would adapt to those modifications at the same time. ![Many clients consume an API endpoint, and changing this service could be complicated](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gltyq1c4uqlkg5ren0io.PNG) It happens all the time, contracts between providers and consumers are not static. They change very often by adding new features to microservices. However, there are some strategies to keep those issues away and implement backward compatibility without breaking all clients. ## Versioning strategies ### Header versioning This type of versioning allows to manage the API version by adding the version number in a custom HTTP Header. It requires that client applications use this header to specify which service version will be consumed. Besides, it is important to consider server-side cache in case every request was stored, here using a proxy could help to reduce duplicated cache data. In the next example is showed the creation of a new order using an *_api-version_* specified in the *_Custom-Header_*. ``` POST https://enterprise.domain.com/orders/123 Custom-Header: api-version=1 ``` ### URI versioning This technique consist in defining the version of an API in the uniform resource identifier (URI). It makes very clear to know which version will be consumed for client applications. For instance, choosing a version of a service used to retrieve an order could be done by *_v1_* or any custom standard. It is relevant to mention that this implementation makes harder to follow [HATEOS](https://en.wikipedia.org/wiki/HATEOAS) constraint because all links associated to resources should have defined their correct version number. ``` GET https://enterprise.domain.com/v1/orders/123 ``` ### Query string versioning Regarding to this versioning strategy, the version goes in the query string parameter. In that case, it is recommended to establish a default version number when a client misses sending this parameter. The following example uses *_?version=3_* as query string. ``` GET https://enterprise.domain.com/orders/123?version=3 ``` As URI strategy, the previous approach has the same issue related to implementation of HATEOS. ### MediaType versioning Finally, very closed to header versioning practice, MediaType needs to be sent in the *_Accept Content Type Header_*. Provider is responsible for handling all possible format responses with their defined versions. For example, deleting an order could be performed if version were specified in *_Accept header_* along format response required. ``` DELETE https://enterprise.domain.com/orders/123 Accept: application/vnd.enterprise.domain.com.v2+json ``` ## tl;dr | Versioning strategy | Location|Some Considerations | --------- |:---------:| -------:|-------:| | Header| Custom HTTP header | Server-side cache issues| | URI| Properly as part of URI |Very simple and clear which version is used<br>Makes harder to implement HATEOAS| | Query String| Query string param of URI | Should be defined a default version value <br> Makes harder to implement HATEOAS| | Mediatype| Accept Http header| Handle all possible format responses with their defined versions <br> Server-side cache issues| ## Conclusion Microservices have became an extended practice in software architecture, from those implementations have emerged many lesson to learn and for this reason there are several antipatterns and pitfalls to take in consideration. Learning from the experience of the others and having in mind those best practices is crucial to build a strong architecture. Here is important to evaluate the options and choose the best one according to context. ##References Richards, M. (2016). Microservices Antipatterns and Pitfalls. CA: O’Reilly Media. Microsoft (2021). RESTful web API design. Retrieve from https://docs.microsoft.com/en-us/azure/architecture/best-practices/api-design
abarran03
912,667
How to migrate from LaunchDarkly to ConfigCat
Coming from LaunchDarkly? This post will show you a simple &amp; straight forward way to migrate your...
0
2021-11-30T00:43:38
https://configcat.com/blog/2021/11/26/how-to-migrate-from-launchdarkly-to-configcat
Coming from LaunchDarkly? This post will show you a simple & straight forward way to migrate your feature flags from LaunchDarkly to [ConfigCat](http://configcat.com/) <div style="display: 'flex'; justify-content: 'center'"> <img src="https://configcat.com/blog/assets/2021-11-16-migrate-from-launchdarkly/cc-question-mark.png" alt="cc-question-mark" width="200"/> </div> --- ## Step 1: Get LaunchDarkly Access Token Please follow the following steps in order to get your token. 1. Login to LaunchDarkly 2. Navigate to [authorization page](https://app.launchdarkly.com/settings/authorization) 3. Create an access token: ![ld-account-settings](https://configcat.com/blog//assets/2021-11-16-migrate-from-launchdarkly/ld-account-settings.png) 4. Once this pops up, just fill in the name and leave the rest as per the image and hit "Save token" (I use the name "migrate-access-token" for better clarity on the usage of the token) ![ld-create-access-token](https://configcat.com/blog//assets/2021-11-16-migrate-from-launchdarkly/ld-create-access-token.png) 5. Once you hit save, you will be presented with this image. Please do copy & save the access token. ![ld-created-access-token](https://configcat.com/blog//assets/2021-11-16-migrate-from-launchdarkly/ld-created-access-token.png) Hold on to this token. We will be using it later. ## Step 2: Get ConfigCat Base64 encoded authorization header 1. Login to [ConfigCat](http://configcat.com/) 2. Navigate to your account's [public api credentials](https://app.configcat.com/my-account/public-api-credentials) 3. Once there, click on "add credentials" and add any name you want (I used the name "migrate-from-launchdarkly" as the name, for better clarity of the usage of the token) ![cc-public-api-credentials](https://configcat.com/blog//assets/2021-11-16-migrate-from-launchdarkly/cc-public-api-credentials.png) ![cc-public-api-credentials-generate](https://configcat.com/blog//assets/2021-11-16-migrate-from-launchdarkly/cc-public-api-credentials-generate.png) 4. Once you hit "generate", copy the Base64 encoded authorization header. This is the only value we need (make sure the value you copy includes `Basic `). ![cc-public-api-credentials-generated](https://configcat.com/blog//assets/2021-11-16-migrate-from-launchdarkly/cc-public-api-credentials-generated.png) Hold on to this base 64 string. We will be using this string later. ## Step 3: Get Your Organisation ID for ConfigCat This organisation ID will be the organisation that you want to migrate your feature flag to. So, be certain it is the correct organisation ID. To get the ID: 1. Navigate to [https://app.configcat.com/organization](https://app.configcat.com/organization) 2. Note that the URL will change into: `https://app.configcat.com/organization/xxx` 3. Your organisation ID is `xxx` Hold on to your ConfigCat organisation ID. We will be using it later ## Step 4: Use [this repository](https://github.com/tlkiong/migrate-ld-cc) [This repository](https://github.com/tlkiong/migrate-ld-cc) makes it easy for you to migrate from LaunchDarkly to [ConfigCat](http://configcat.com/) using just one command with some configuration. 1. Clone [this repository](https://github.com/tlkiong/migrate-ld-cc) to your local 2. Run `npm install` to install all dependencies 3. Copy `.env.sample` file into `.env` file in the same location 4. Fill in the data in `.env` file as you have received in Step 1 to Step 3 above. For example: ``` LAUNCH_DARKLY_READER_ACCESS_TOKEN=thisisyourtoken CONFIG_CAT_API_AUTH_HEADER=thisisyourauthheader CONFIG_CAT_ORG_ID=thisisyourorgid CONFIG_CAT_PLAN=free ``` 5. Run `npm run migrate` on your terminal. 6. In your ConfigCat site, navigate to [products](https://app.configcat.com/product). There you should see `from launchdarkly` config under `Configs` section: ![cc-products](https://configcat.com/blog//assets/2021-11-16-migrate-from-launchdarkly/cc-products.png) 7. Click on the `from launchdarkly` config and you should see all your feature flags from launchdarkly in here. Congratulations! You have migrated over from LaunchDarkly to [ConfigCat](http://configcat.com/) using just one command with some configuration.
tlkiong
929,311
Working With Web Feeds: It’s More Than RSS
Working With Web Feeds: It’s More Than RSS was first published on Farai's Codelab. Between...
0
2021-12-17T17:52:22
https://codelab.farai.xyz/elsewhere/making-great-feeds/
webfeeds
--- title: Working With Web Feeds: It’s More Than RSS published: true date: 2021-12-17 17:50:43 UTC tags: [webfeeds] canonical_url: https://codelab.farai.xyz/elsewhere/making-great-feeds/ --- _[Working With Web Feeds: It’s More Than RSS](https://codelab.farai.xyz/elsewhere/making-great-feeds/) was first published on [Farai's Codelab](https://codelab.farai.xyz/)._ * * * > Between Google Chrome experimenting with “following” sites, along with a growing frustration of how social media platforms limit a creator’s reach to their fans through algorithmic feeds, there’s been renewed interest in RSS feeds and they’re primed for a comeback as we get into 2022. > > You may have heard whispers that “RSS in dead” around the web, but the truth is that they are still widely used as virtually every podcast uses one. Maybe you used to be an RSS fan and need to get re-acquainted with it. Or maybe you’re like Chris here at CSS-Tricks and still love RSS. Whatever the case, RSS is a web technology like any other, and there are best practices for how to create and curate a feed. > > That’s exactly what I’m going to walk you through in this article. Let’s talk about the different kinds of feeds, how to implement them, and what strategies you can use to get the most out of your feed content. This post took far longer than I expected to write, but it’s finally finished. It only took 3 months instead of 6 this time. Thanks again to the CSS Tricks team for helping me with this! I plan on adding commentary, but that’ll be an exclusive post. _See [Working With Web Feeds: It’s More Than RSS on css-tricks.com](https://css-tricks.com/working-with-web-feeds-its-more-than-rss/)_ * * * Thanks for reading! If you liked this post, consider [supporting my work](https://codelab.farai.xyz/support/) by: - sharing my work, - reffering me for a job (or hire me for freelance work), - sponsoring me on [Patreon](https://patreon.com/faraixyz), - [buying Me A Coffee](https://www.buymeacoffee.com/faraixyz), - [buying Me A Ko-Fi](https://ko-fi.com/faraixyz), - [sending me a tip on Paypal](https://paypal.me/fgandiya), - [buy something on Amazon with my affiliate link](https://amazon.com/?tag=faraixyz00-20) (I’ll earn a commision on this as an Amazon affiliate), - or [buy a domain on Namecheap with my affiliate link](https://shareasale.com/r.cfm?b=467188&u=2110247&m=46483&urllink=www%2Enamecheap%2Ecom%2F&afftrack=). You can also [subscribe to my newsletter](https://buttondown.email/faraiscodelab). Have feedback? Send an email to [gandiyafarai+feedback at gmail dot com](mailto:gandiyafarai+feedback@gmail.com?body%3dHey%2bI%2bread%2bthat%2bpost%2band%2bI%2bthought%2bit%2bwas%2bamazing%2521%2bAnd%2byet%252C%2bI%2breally%2bthink%2bthat%25E2%2580%2594I%2btotally%2bdidn%2527t%2buse%2bthe%2bprepopulated%2bemail.%26subject%3dFeedback%2bon%2bWorking%2bWith%2bWeb%2bFeeds%253A%2bIt%25E2%2580%2599s%2bMore%2bThan%2bRSS)
faraixyz
912,674
A Tour of myPrayerJournal v3: Bootstrap Integration
NOTE: This is the third post in a series; see the introduction for information on requirements and...
0
2021-12-01T03:35:17
https://blog.bitbadger.solutions/2021/a-tour-of-myprayerjournal-v3/bootstrap-integration.html
fsharp, giraffe, htmx, bootstrap
--- title: A Tour of myPrayerJournal v3: Bootstrap Integration published: true date: 2021-11-29 16:51:00 UTC tags: fsharp,giraffe,htmx,bootstrap canonical_url: https://blog.bitbadger.solutions/2021/a-tour-of-myprayerjournal-v3/bootstrap-integration.html --- _NOTE: This is the third post in a series; see [the introduction](https://blog.bitbadger.solutions/2021/a-tour-of-myprayerjournal-v3/introduction.html "A Tour of myPrayerJournal v3: Introduction | The Bit Badger Blog") for information on requirements and links to other posts in the series._ Many modern Single Page Application (SPA) frameworks include (or have plugins for) <abbr title="Cascading Style Sheets">CSS</abbr> transitions and effects. Combined with the speed of not having to do a full refresh, this is one of their best features. One might not think that a framework like [htmx](https://htmx.org/ "htmx"), which simply swaps out sections of the page, would have this; but if one were to think that, one would be wrong. Sadly, though, I did not utilize those aspects of htmx while I was migrating myPrayerJournal from v2 to v3; however, I will highlight the htmx way to do this in [last section of this post](#css-transitions-in-htmx "CSS Interactivity with htmx | A Tour of myPrayerJournal v3: Bootstrap Integration | The Bit Badger Blog"). myPrayerJournal v2 used a [Vue](https://vuejs.org/ "Vue.js") plugin that provided Bootstrap v4 support; myPrayerJournal v3 uses [Bootstrap](https://getbootstrap.com/ "Bootstrap") v5. The main motivation I had to remain with Bootstrap was that I liked the actual appearance, and I know how it works. The majority of my “learning” on this project dealt with htmx; I did not want to add a UI redesign to the mix. Before we jump into the implementation, let me briefly explain the framework. ## About Bootstrap Bootstrap was originally called Twitter Bootstrap; it was the CSS framework that Twitter developed in their early iterations. It was, by far, the most popular framework at the time, and it was innovative in its grid layout system. Long before there was browser support for the styles that make layouts much easier to develop, and more responsive to differing screen sizes, Bootstrap’s grid layout and size breakpoints made it easy to build a website that worked for desktop, tablet, or phone. Of course, there is a limit to what you can do with styling, so Bootstrap also has a JavaScript library that augments these styles, enabling the interactivity to which the modern web user is accustomed. Version 5 of Bootstrap continues this tradition; however, it brings in even more utility classes, and supports Flex layouts as well. It is a mature library that continues to be maintained, and the project’s philosophy seems to be “just enough” - it’s not going to do everything for everyone, but in the majority of cases, it has exactly what the developer needs. It is not a bloated library that needs tree-shaking to avoid a ridiculous download size. It is, by far, the largest payload in the initial page request: - Bootstrap - 48.6 kB (CSS is 24.8 kB; JavaScript is 23.8 kB, deferred until after render) - htmx - 11.8 kB - myPrayerJournal - 4.4 kB (CSS is 1.2 kB, JavaScript is 3.2 kB) However, this gets the entire style and script, and allows us to use their layouts and interactive components. But, how do we get that interactivity from the server? ## Hooking in to the htmx Request Pipeline htmx provides [several events](https://htmx.org/reference/#events "Events | Reference | htmx") to which an application can listen. In myPrayerJournal v3, [I used `htmx:afterOnLoad`](https://github.com/bit-badger/myPrayerJournal/blob/3/src/MyPrayerJournal/wwwroot/script/mpj.js#L72 "myPrayerJournal v3 htmx:afterOnLoad function") because I did not need the new content to be swapped in yet when the function fired. There are `afterSwap` and `afterSettle` events which will fire once those events have occurred, if you need to defer processing until those are complete. There are two different Bootstrap script-driven components myPrayerJournal uses; let’s take a look at toasts. ## A Toast ~~to~~ Via htmx [Toasts](https://getbootstrap.com/docs/5.1/components/toasts/ "Toasts | Bootstrap") are pop-up notifications that appear on the screen, usually for a short time, then fade out. In some cases, particularly if the toast is alerting the user to an error, it will stay on the screen until the user dismisses it, usually by clicking an “x” in the upper right-hand corner _(even if the developer used a Mac!)_. Bootstrap provides a host of options for their toast component; for our uses, though, we will: - Place toasts in the bottom right-hand corner; - Allow multiple toasts to be visible at once; - Auto-hide success toasts; require others to be dismissed manually. There are several different aspects that make this work. ### The Toaster Just like <abbr title="In Real Life">IRL</abbr> toast comes out of a toaster, our toasts need a place from which to emerge. In the [prior post](https://blog.bitbadger.solutions/2021/a-tour-of-myprayerjournal-v3/the-user-interface.html#%E2%80%9CNew-Page%E2%80%9D-in-htmx "A Tour of myPrayerJournal v3: The User Interface | The Bit Badger Blog"), I mentioned that the footer does not get reloaded when a “page” request is made. There is also an element above the footer that also remains across these requests - defined here as the “toaster” (my term, not Bootstrap’s). ```fsharp /// Element used to display toasts let toaster = div [ _ariaLive "polite"; _ariaAtomic "true"; _id "toastHost" ] [ div [ _class "toast-container position-absolute p-3 bottom-0 end-0"; _id "toasts" ] [] ] ``` This renders two empty `div`s with the appropriate style attributes; toasts placed in the `#toasts` `div` will display as we want them to. ### Showing the Toast Bootstrap provides `data-` attributes that can make toasts appear; however, since we are creating these in script, we need to use their JavaScript functions. The message coming from the server has the format `TYPE|||The message`. Let’s look at [the showToast function](https://github.com/bit-badger/myPrayerJournal/blob/3/src/MyPrayerJournal/wwwroot/script/mpj.js#L9 "myPrayerJournal v3 showToast function") (the largest custom JavaScript function in the entire application): ```javascript const mpj = { // ... showToast (message) { const [level, msg] = message.split("|||") let header if (level !== "success") { const heading = typ => `<span class="me-auto"><strong>${typ.toUpperCase()}</strong></span>` header = document.createElement("div") header.className = "toast-header" header.innerHTML = heading(level === "warning" ? level : "error") const close = document.createElement("button") close.type = "button" close.className = "btn-close" close.setAttribute("data-bs-dismiss", "toast") close.setAttribute("aria-label", "Close") header.appendChild(close) } const body = document.createElement("div") body.className = "toast-body" body.innerText = msg const toastEl = document.createElement("div") toastEl.className = `toast bg-${level === "error" ? "danger" : level} text-white` toastEl.setAttribute("role", "alert") toastEl.setAttribute("aria-live", "assertlive") toastEl.setAttribute("aria-atomic", "true") toastEl.addEventListener("hidden.bs.toast", e => e.target.remove()) if (header) toastEl.appendChild(header) toastEl.appendChild(body) document.getElementById("toasts").appendChild(toastEl) new bootstrap.Toast(toastEl, { autohide: level === "success" }).show() }, // ... } ``` Here’s what’s going on in the code above: - Line 4 splits the level from the message - Lines 6-20 (`let header`) create a header and close button if the message is not a success - Lines 22-24 (`const body`) create the body `div` with attributes Bootstrap’s styling expects - Lines 26-30 (`const toastEl`) create the `div` that will contain the toast - Line 31 adds an event handler to remove the element from the DOM once the toast is hidden - Lines 32 and 34 add the optional header and mandatory body to the toast `div` - Line 35 adds the toast to the page (within the `toasts` inner `div` defined above) - Line 36 initializes the Bootstrap JavaScript component, auto-hiding on success, and shows the toast _(If you’ve never used JavaScript to create elements that are added to an HTML document, this probably looks weird and verbose; if you have, you look at it and think “well, they’re not wrong…”)_ So, we have our toaster, we know how to put ~~bread~~ notifications in it - but how do we get the notifications from the server? ### Receiving the Toast The code to handle this is part of the `htmx:afterOnLoad` handler: ```javascript htmx.on("htmx:afterOnLoad", function (evt) { const hdrs = evt.detail.xhr.getAllResponseHeaders() // Show a message if there was one in the response if (hdrs.indexOf("x-toast") >= 0) { mpj.showToast(evt.detail.xhr.getResponseHeader("x-toast")) } // ... }) ``` This looks for a custom HTTP header of `X-Toast` (all headers are lowercase from that `xhr` call), and if it’s found, we pass the value of that header to the function above. This check occurs after every htmx network request, so there is nothing special to configure; “page” requests are not the only requests capable of returning a toast notification. There is one more part; how does the toast get to the browser? ### Sending the Toast The last paragraph gave it away; we set a header on the response. This seems straightforward, and is in most cases; but [once again, POST-Redirect-GET](https://blog.bitbadger.solutions/2021/a-tour-of-myprayerjournal-v3/the-user-interface.html#POST-Redirect-GET "A Tour of myPrayerJournal v3: The User Interface | The Bit Badger Blog") (P-R-G) complicates things. Here are the final two lines of the successful path of [the request update handler](https://github.com/bit-badger/myPrayerJournal/blob/3/src/MyPrayerJournal/Handlers.fs#L503 "myPrayerJournal v3 request update handler"): ```fsharp Messages.pushSuccess ctx "Prayer request updated successfully" nextUrl return! seeOther nextUrl next ctx ``` If we set a message in the response header, then redirect (remember that `XMLHttpRequest` handles redirects silently), the header gets lost in the redirect. Here, `Messages.pushSuccess` places the success message (and return URL) in a dictionary, indexed by the user’s ID. Within the function that renders every result (partial, “page”-like, or full results), this dictionary is checked for a message and URL, and if one exists, it includes it. (If it is returned to the function below, it has already been removed from the dictionary.) ```fsharp /// Send a partial result if this is not a full page load (does not append no-cache headers) let partialStatic (pageTitle : string) content : HttpHandler = fun next ctx -> backgroundTask { let isPartial = ctx.Request.IsHtmx && not ctx.Request.IsHtmxRefresh let! pageCtx = pageContext ctx pageTitle content let view = (match isPartial with true -> partial | false -> view) pageCtx return! (next, ctx) ||> match user ctx with | Some u -> match Messages.pop u with | Some (msg, url) -> setHttpHeader "X-Toast" msg >=> withHxPush url >=> writeView view | None -> writeView view | None -> writeView view } ``` A quick overview of this function: - Line 4 determines if this an htmx boosted request (a “page”-like requests) - Line 5 creates a rendering context for the page - Line 6 renders the view to a string, calling `partial` or `view` with the page rendering context - Lines 10-13 are only executed if a user is logged on, and line 12 is the one that appends a message and a new URL > **_A quick note about line 12:_** the `>=>` operator joins Giraffe `HttpHandler`s together. An `HttpHandler` takes an `HttpContext` and the next function to be executed, and returns a `Task<HttpContext option>` (an asynchronous call that may or may not return a context). If there is no context returned, the chain stops; the function can also return an altered context. It is good practice for an `HttpHandler` to make a single change to the context; this keeps them simple, and allows them to be plugged in however the developer desires. Thus, the `setHttpHeader` call adds the `X-Toast` header, the `withHxPush` call adds the `HX-Push` header, and the `writeView` call sets the response body to the rendered view. The new URL part does not actually make the browser do anything; it simply pushes the given URL onto the browser’s history stack. Technically, the browser receives the content from the P-R-G as the response to its POST; as we’re replacing the current page, though, we need to make sure the URL stays in sync. Of note is that not all toasts are this complex. For example, the “cancel snooze” handler return looks like this: ```fsharp return! (withSuccessMessage "Request unsnoozed" >=> Components.requestItem requestId) next ctx ``` …while the `withSuccessMessage` handler is: ```fsharp /// Add a success message header to the response let withSuccessMessage : string -> HttpHandler = sprintf "success|||%s" >> setHttpHeader "X-Toast" ``` No dictionary, no redirect, just a single response that will show a toast. You made it - the toast section is toast! There is one more interesting interaction, though; that of the modal dialog. ## Modal Dialogs Bootstrap’s [implementation of modal dialogs](https://getbootstrap.com/docs/5.1/components/modal/ "Modal | Bootstrap") also uses JavaScript; however, for the purposes of the modals used in myPrayerJournal v3, we can use the `data-` attributes to show them. Here is the view for a modal dialog that allows the user to snooze a request (hiding it from the active list until the specified date); this is rendered a single time on the journal view page: ```fsharp div [ _id "snoozeModal" _class "modal fade" _tabindex "-1" _ariaLabelledBy "snoozeModalLabel" _ariaHidden "true" ] [ div [ _class "modal-dialog modal-sm" ] [ div [ _class "modal-content" ] [ div [ _class "modal-header" ] [ h5 [ _class "modal-title"; _id "snoozeModalLabel" ] [str "Snooze Prayer Request" ] button [ _type "button"; _class "btn-close"; _data "bs-dismiss" "modal"; _ariaLabel "Close" ] [] ] div [ _class "modal-body"; _id "snoozeBody" ] [] div [ _class "modal-footer" ] [ button [ _type "button"; _id "snoozeDismiss"; _class "btn btn-secondary"; _data "bs-dismiss" "modal" ] [ str "Close" ] ] ] ] ] ``` Notice that `#snoozeBody` is empty; we fill that when the user clicks the snooze icon: ```fsharp button [ _type "button" _class "btn btn-secondary" _title "Snooze Request" _data "bs-toggle" "modal" _data "bs-target" "#snoozeModal" _hxGet $"/components/request/{reqId}/snooze" _hxTarget "#snoozeBody" _hxSwap HxSwap.InnerHtml ] [icon "schedule"] ``` This uses `data-bs-toggle` and `data-bs-target`, Bootstrap attributes, to show the modal. It also uses `hx-get` to load the snooze form for that particular request, with `hx-target` targeting the `#snoozeBody` `div` from the modal definition. Here is how that form is defined: ```fsharp /// The snooze edit form let snooze requestId = let today = System.DateTime.Today.ToString "yyyy-MM-dd" form [ _hxPatch $"/request/{RequestId.toString requestId}/snooze" _hxTarget "#journalItems" _hxSwap HxSwap.OuterHtml ] [ div [ _class "form-floating pb-3" ] [ input [ _type "date"; _id "until"; _name "until"; _class "form-control"; _min today; _required ] label [ _for "until" ] [ str "Until" ] ] p [ _class "text-end mb-0" ] [ button [ _type "submit"; _class "btn btn-primary" ] [ str "Snooze" ] ] ] ``` Here, the form uses `hx-patch` to submit the data to the snooze endpoint. The target for the response, though, is `#journalItems`; this is the element that holds all of the prayer request cards. Snoozing a request will remove it from the active list, so the list needs to be refreshed; this will make that happen. Look back at the modal definition; at the bottom, there is a “Close” button. We will use this to dismiss the modal once the update succeeds. In the Giraffe handler to snooze a request, here is its `return` statement: ```fsharp return! (withSuccessMessage $"Request snoozed until {until.until}" >=> hideModal "snooze" >=> Components.journalItems) next ctx ``` Notice that `hideModal` handler? ```fsharp /// Hide a modal window when the response is sent let hideModal (name : string) : HttpHandler = setHttpHeader "X-Hide-Modal" name ``` Yes, it’s another HTTP header! One can certainly get carried away with custom HTTP headers, but their very existence is to communicate with the client (browser) outside of the visible content of the page. Here, we’re passing the name “snooze” to this header; in our `htmx:afterOnLoad` handler, we’ll consume this header: ```javascript htmx.on("htmx:afterOnLoad", function (evt) { const hdrs = evt.detail.xhr.getAllResponseHeaders() // ... // Hide a modal window if requested if (hdrs.indexOf("x-hide-modal") >= 0) { document.getElementById(evt.detail.xhr.getResponseHeader("x-hide-modal") + "Dismiss").click() } }) ``` The “Close” button on our modal was given the `id` of `snoozeDismiss`; this mimics the user clicking the button, which Bootstrap’s `data-` attributes handle from there. Of all the design choices and implementations I did in this conversion, this part strikes me as the most “hack”y. However, I did try to hook into the Bootstrap modal itself, and hide it via script; however, it didn’t like initializing a modal a second time, and I could not get a reference to it from the `htmx:afterOnLoad` handler. Clicking the button works, though, even when it’s done from script. ## CSS Transitions in htmx This post has already gotten much longer than I had planned, but I wanted to make sure I covered this. - When htmx requests are in flight, the framework makes it easy to [show indicators](https://htmx.org/docs/#indicators "Request Indicators | Docs | htmx"). - I mentioned swapping and settling when discussing the events htmx exposes. The way this is done, [CSS transitions](https://htmx.org/docs/#css_transitions "CSS Transitions | Docs | htmx") will render as expected. They have [a host of examples](https://htmx.org/examples/animations/ "Animations | Examples | htmx") to spark your imagination. As I was keeping the UI the same, I did not end up using these options; however, their presence demonstrates that htmx is a true batteries-included SPA framework. * * * Up next, we’ll step away from the front end and [dig into LiteDB](https://blog.bitbadger.solutions/2021/a-tour-of-myprayerjournal-v3/the-data-store.html "A Tour of myPrayerJournal v3: The Data Store | The Bit Badger Blog").
danieljsummers
912,791
Anyone else keen to try Jetbrains Fleet?
Jetbrains about to release a VSCode competitor and it is looking really nice
0
2021-11-30T04:43:50
https://dev.to/noncototient/anyone-else-keen-to-try-jetbrains-fleet-3ag
vscode, webdev, jetbrains, ide
--- title: Anyone else keen to try Jetbrains Fleet? published: true description: Jetbrains about to release a VSCode competitor and it is looking really nice tags: vscode, webdev, jetbrains, ide --- Jetbrains announced today they are developing a completely new IDE from scratch called Jetbrains Fleet. I've always liked their IDEs but hated how slow and resource heavy they were, especially on laptops, and thus stuck with VSCode. The new one is looking really nice and fast, though. Announcement: https://news.ycombinator.com/item?id=29377412 Homepage: https://www.jetbrains.com/fleet/ Quick overview: https://www.youtube.com/watch?v=ow5kdhDa_pk P.S.: Not affiliated with them, just excited to try it.
noncototient
912,804
Digital Marketing Courses in Panchkula
PPC fame Is the best Institute providing Digital Marketing courses in Panchkula. SEO Training/PPC...
0
2021-11-30T05:47:51
https://dev.to/rawatraveena/digital-marketing-courses-in-panchkula-2f8b
PPC fame Is the best Institute providing Digital Marketing courses in Panchkula. SEO Training/PPC Training/ Google AdWords Course/ Social Media Marketing/Ethical. Being leaders in the Digital Marketing training space, we grab our management as trainers & career makers very seriously. PPC fame Institute Digital Marketing Training in Panchkula set benchmarks in training. Classification With management, capability, Integrity & big worth https://ppcfame.com/digital-marketing-course-panchkula/
rawatraveena
912,925
Using v-model with objects in Vue3
Motivation When I was using Vue2 along with vue-class-component and vue-property-decorator...
0
2021-11-30T20:42:24
https://dev.to/blindkai/objects-and-v-model-in-vue3-1l9h
vue
## Motivation When I was using Vue2 along with [`vue-class-component`](https://github.com/vuejs/vue-class-component) and [`vue-property-decorator`](https://github.com/kaorun343/vue-property-decorator) it was easy to synchronize `v-models` between components simply using [`@ModelSync()`](https://github.com/kaorun343/vue-property-decorator#-modelsyncpropname-string-event-string-options-propoptions--constructor--constructor---decorator). When Vue 3 came out with its [Composition API](https://v3.vuejs.org/guide/composition-api-introduction.html) another way was needed to achieve the same result as if Class Component was used. ## Implementation If you're already familiar with the capabilities of [Composition API](https://v3.vuejs.org/api/composition-api.html#composition-api), then simply use [`computed`](https://v3.vuejs.org/api/computed-watch-api.html#computed) within [`setup`](https://v3.vuejs.org/guide/composition-api-introduction.html#setup-component-option) to update the [`modelValue`](https://v3.vuejs.org/guide/component-custom-events.html#v-model-arguments) whenever it changes. 1) In child component define a model property with the default value ```vue import { defineComponent } from 'vue'; <script> export default defineComponent({ name: 'FancyComponent', props: { modelValue: { // Declare the property type: Object, default: () => ({}), // Do not forget about default value }, } }); </script> ``` 2) In `setup()` define a computed property and expose it: ```vue <template> <div> <input v-model="theModel.foo" /> <!-- Usage of model --> </div> </template> <script> import { defineComponent, computed } from 'vue'; export default defineComponent({ name: 'FancyComponent', emits: ['update:modelValue'], // The component emits an event props: { modelValue: { type: Object, default: () => ({}), }, }, setup(props, { emit }) { const theModel = computed({ // Use computed to wrap the object get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }); return { theModel }; } }); </script> ``` 3) In parent component use `v-model` directive: ```vue <template> <FancyComponent v-model="someObject" /> </template> ``` ## TypeScript In the case of using TypeScript, there is one minor addition to the code above. [`PropType<T>`](https://v3.vuejs.org/guide/typescript-support.html#annotating-props) is used it order to annotate the model type. ```vue <script> import { defineComponent, computed, PropType } from 'vue'; interface OurModelType { foo: string; } export default defineComponent({ name: 'FancyComponent', emits: ['update:modelValue'], props: { modelValue: { type: Object as PropType<OurModelType>, // Type Annotation default: () => ({}), }, }, setup(props, { emit }) { const theModel = computed({ get: () => props.modelValue, set: (value) => emit('update:modelValue', value), }); return { theModel }; } }); </script> ``` And it's all you need to know to pass reactive objects into your custom components as `v-model`.
blindkai
912,947
Top 5 Last Mile Delivery Management Software
Last mile delivery management software is a critical component for the supply chain. Whether you're...
0
2021-11-30T09:37:51
https://dev.to/sanmeet2323/top-5-last-mile-delivery-management-software-13ha
lastmiledelivery, managementsoftware, ecommerce
Last mile delivery management software is a critical component for the supply chain. Whether you're an ecommerce retailer or manufacturer, last mile delivery management software can help make it easier and more efficient for your team to plan routes, optimize routing times based on traffic conditions, and provide visibility into package deliveries from start to finish. We've compiled these [top 5 best last mile delivery management and tracking software](https://www.clickpost.ai/blog/top-10-best-last-mile-delivery-software) providers that we recommend for any ecommerce business out there looking for a solid solution. **Best 5 Last Mile Delivery Management Software** Last Mile Delivery Management Software is what the name implies; it is software that helps with dispatch and delivery of goods sold via an online store. As eCommerce continues to grow, there will always be a need for these types of solutions. The following Best Last Mile Delivery Management Software listed here offer great features and are very reliable when shipping items from one place to another. Based on research conducted by our team, here are the 5 Last Mile Delivery Management solutions that prove beneficial for the growth of any size ecommerce business. **1)ClickPost** ClickPost is a software that offers the Best Last Mile Delivery Management Software application for eCommerce shipping. ClickPost is an advanced cloud-based logistics application that helps improve delivery choices, support last mile logistics and cut your costs. It provides flexible routing to deliver packages more efficiently and faster than ever before. Being one of the top rated delivery management software; ClickPost also provides a number of advanced level features. Some of the popular ones include:- branded tracking page, ecommerce return management, NDR management, reduction in RTO(%), shipment tracking and improving the overall customer experience. **2)MetaPack Last Mile Delivery Management Software** MetaPack helps you finalize your end-to-end delivery process by providing a GPS tracking device to real-time delivery notifications. This system offers a variety of ways for you to improve your business through better management of your last mile deliveries. MetaPack Last Mile Delivery Management Software solution helps retailers manage their business processes which include internet orders, order picking and packing, warehousing, ePicking and Delivery tasks like Accounting, Tracking & reporting. This software is used by many Top eCommerce companies in the Asia & Europe market for Best performance results in their logistics operations. **3)Aftership Last Mile Delivery Management Software** Aftership helps a company to manage the delivery process in an easy way. The software allows you to monitor and optimize the delivery process, propose new suppliers and routes based on real-time data, improve customer satisfaction and increase sales volume. It provides full visibility of your deliveries for both international & local shipping needs. You can track all your shipments - from picking up at a collection point or warehouse right through until it's delivered - online using our unique interactive shipment map. Here are some of its key features for online store owners. **-Facility of Notification:** In any case like change in delivery date or address, Aftership will send you a notification email with all updated details regarding shipments. It also helps to get track status using our mobile application. **-Track Your Parcel Realtime:** The real-time 1st/2nd/3rd Party Carrier tracking service feature of aftership is easy to use and helps an online seller to track shipments without visiting the respective parcel shipping provider website. **4)Easyship** Easyship comes at the 4th place in this category of Best Last Mile Delivery Management Software. It creates an automated streamlined shipping experience for your international and domestic customers. It saves your time and money on international deliveries through advanced features that give you full control over your orders throughout their entire journey to your doorstep. Options such as innovative automated label printing capabilities, integration with popular delivery services around the world, free shipping notifications & more are included as standard with every account from Easyship. **5)Shipwell Last Mile Delivery Management Software** Shipwell is an American startup, founded in 2016 by Gregory Price. The company initially offered a web-based service bureau delivery management software that enabled shipping carriers to process shipments through the USPS. After its Initial Public Offering (IPO) in March 2019, Shipwell opened up their services for businesses of all sizes to handle their own deliveries, using its last mile delivery software technology. The platform provides visual dashboards and real-time analytics so small business owners can track deliveries on all devices. With Shipwell's app, business owners don't have to manage multiple third party apps at once - they can access everything directly from one place across iOS or Android mobile phones, tablets or smartwatches. **Final Conclusion** This list and reviews of the top 5 best last mile delivery management software is determined by different factors for each business. It’s important to find the right one that fits your needs. Here are 5 of the most popular options available today, as well as some reviews from various sources and what they had to say about it. If you want a great tool that will help keep track of all your deliveries in real-time, make sure this list has something for you. For more information on these tools or if you need additional assistance finding the best fit for your company, contact us.
sanmeet2323
912,960
The Top Project Management Tools and Methodologies We’ve Ever Worked With
Project Management is all about managing and organizing everything you need to achieve a business...
0
2021-11-30T10:03:31
https://dev.to/fireartd/the-top-project-management-tools-and-methodologies-weve-ever-worked-with-1bef
agile, devops, webdev, leadership
<p class="wow fadeIn" data-wow-delay=".05s"><strong>Project Management is all about managing and organizing everything you need to achieve a business goal &ndash; on time and on budget, of course. Be it software development, running a marketing campaign, or landing on Mars &ndash; you need to apply specific project management tools and techniques for success.</strong></p> <figure id="attachment_17189" class="wp-caption aligncenter wow fadeIn" data-wow-delay=".05s"><img class="wp-image-17189 size-full" src="https://fireart.studio/wp-content/uploads/2021/11/pm-tools.jpg" sizes="(max-width: 952px) 100vw, 952px" srcset="https://fireart.studio/wp-content/uploads/2021/11/pm-tools.jpg 952w, https://fireart.studio/wp-content/uploads/2021/11/pm-tools-300x223.jpg 300w, https://fireart.studio/wp-content/uploads/2021/11/pm-tools-768x570.jpg 768w, https://fireart.studio/wp-content/uploads/2021/11/pm-tools-576x428.jpg 576w, https://fireart.studio/wp-content/uploads/2021/11/pm-tools-260x193.jpg 260w, https://fireart.studio/wp-content/uploads/2021/11/pm-tools-640x475.jpg 640w, https://fireart.studio/wp-content/uploads/2021/11/pm-tools-450x334.jpg 450w" alt="" width="952" height="707" /> <figcaption id="caption-attachment-17189" class="wp-caption-text">Taken from&nbsp;<a href="https://dribbble.com/Fireart-d" target="_blank" rel="nofollow">Dribbble</a></figcaption> </figure> <p class="wow fadeIn" data-wow-delay=".05s">All projects are different. There are no perfect or universal project management systems and project control techniques for every type of project. Also, no system would fit every leader and be comfortable for all the team members. Nevertheless, many practical approaches, methods, and standards have been created in project management that may be adopted in any company for good. Let&rsquo;s discuss some of the most popular of them today.</p> <h2 class="wow fadeIn" data-wow-delay=".05s">Agile</h2> <blockquote class="wow fadeIn" data-wow-delay=".05s"> <p><strong>Agile is a flexible iterative-incremental approach to project and product management focused on the dynamic formation of requirements and ensuring their implementation as a result of constant interaction within self-organizing working groups consisting of specialists of various profiles.</strong></p> </blockquote> <p class="wow fadeIn" data-wow-delay=".05s">There are many methods based on&nbsp;<a href="https://www.apm.org.uk/resources/find-a-resource/agile-project-management/" target="_blank" rel="nofollow">Agile PM</a>&nbsp;ideas, the most popular of which are Scrum and Kanban.</p> <p class="wow fadeIn" data-wow-delay=".05s">PM approaches may be very different from each other. They differ in scope, detail, self-sufficiency, and formalization. It&rsquo;s possible to call them methods for convenience. Still, all of them contain the standards, concepts, methods, and frameworks used in project management either separately or in a mix. The idea is to provide the broadest overview of existing approaches in project management that may help everyone with their project planning,&nbsp;<a href="https://www.projectmanager.com/critical-path-method#:~:text=In%20project%20management%2C%20the%20critical,whole%20project%20will%20be%20delayed." target="_blank" rel="nofollow">critical path</a>&nbsp;and so much more.</p> <p class="wow fadeIn" data-wow-delay=".05s">Here are some of the most popular&nbsp;<a href="https://fireart.studio/blog/top-smart-team-building-skills-how-to-work-better-earn-more/" target="_blank" rel="noopener">Agile project management</a>&nbsp;methods and tools to help you understand and organize Agile, as well as teach you how to properly apply Scrum and Kanban in practice so that you make a leap forward in your career or business.</p> <p class="wow fadeIn" data-wow-delay=".05s">This path will require the leader to change not only knowledge and perseverance, but also serious administrative resources and costs. Fortunately, there are out-of-the-box practice kits that make the Agile transformation of an organization easier. These sets include the Scrum framework, the Kanban Method, and many others &ndash; Crystal, LeSS, SAFe, Nexus.</p> <h3 class="wow fadeIn" data-wow-delay=".05s">Scrum</h3> <p class="wow fadeIn" data-wow-delay=".05s"><a href="https://fireart.studio/blog/discovering-scrum-artifacts-and-their-commitments/" target="_blank" rel="noopener">Scrum</a>&nbsp;is an agile framework, created in 1986, and is considered the most structured of the agile family. It combines elements of the classic process and the ideas of an agile project management approach. The result is a very balanced combination of flexibility and structure.</p> <p class="wow fadeIn" data-wow-delay=".05s">Scrum breaks down the project into parts (Sprints) that can immediately be used by the Customer to obtain value, called the product backlog.</p> <blockquote class="wow fadeIn" data-wow-delay=".05s"> <p><em>&nbsp;For example:</em></p> <p><em>A website with a part of the functionality or a program that is already working, delivered may be the result of a Scrum. After that, the project team proceeds to the next Sprint. The duration of the Sprint is fixed, but the team chooses it independently at the beginning of the project, based on the project and its own productivity.</em></p> </blockquote> <p class="wow fadeIn" data-wow-delay=".05s">To many, Scrum may be difficult to implement &ndash; a new process, new roles, many delegations, and a completely new organizational structure. But it is a flexible and yet structured approach to project delivery that, unlike Agile&rsquo;s vague and general principles, will prevent work from going the wrong way from the start.</p> <h3 class="wow fadeIn" data-wow-delay=".05s">Kanban</h3> <p class="wow fadeIn" data-wow-delay=".05s">Created by Toyota engineer&nbsp;<a href="https://www.leansixsigmadefinition.com/glossary/taiichi-ohno/" target="_blank" rel="nofollow">Taiichi Ono</a>&nbsp;in 1953, Kanban is very similar to an industrial production scheme. All you&rsquo;ve got is a piece of metal at the start, and there are metallic details ready at the end. In Kanban product management, the product increment is passed forward from stage to stage, and at the end, it is prepared for delivery.</p> <p class="wow fadeIn" data-wow-delay=".05s">Most interesting is that in Kanban, it is allowed to leave an unfinished task at one of the stages if its priority has changed and there are other urgent tasks to do.</p> <blockquote class="wow fadeIn" data-wow-delay=".05s"> <p><em>For example:</em></p> <p><em>An unedited blog post left without a publication date, or a piece of feature code that might not be included in the final product are all fine for Kanban&nbsp;</em><em>pm methods.</em></p> </blockquote> <p class="wow fadeIn" data-wow-delay=".05s">Kanban is much less strict than Scrum. It does not limit sprint times. There are no roles other than the product owner. Kanban even allows a team member to conduct multiple tasks simultaneously, which Scrum does not. Also, meetings on the status of the project are not regulated in any way &ndash; you may do it as you like, or you may skip it at all.</p> <p class="wow fadeIn" data-wow-delay=".05s">Your Kanban system may be as flexible as you want it to be. In many ways, Kanban is a visualization of an agile idea. It&rsquo;s good for a reasonably dedicated team with good communication. But unlike Scrum, Kanban doesn&rsquo;t have clear deadlines, which is excellent for motivated and highly experienced teams.</p> <h3 class="wow fadeIn" data-wow-delay=".05s">APF</h3> <p class="wow fadeIn" data-wow-delay=".05s">If you appeal to&nbsp;<a href="https://www.lucidchart.com/blog/what-is-adaptive-project-framework" target="_blank" rel="nofollow">APF</a>, it is Adaptive Project Framework, also known as Adaptive&nbsp;Project Management&nbsp;(APM). This approach accommodates the unknown factors that can crop up during a project.</p> <p class="wow fadeIn" data-wow-delay=".05s">It is used to prepare the teams to foresee unexpected changes and respond accordingly without a blink of an eye.</p> <p class="wow fadeIn" data-wow-delay=".05s">The method will be perfect for those who have no issues with regular communication with stakeholders at every level which allows the teams to effectively adapt.</p> <h3 class="wow fadeIn" data-wow-delay=".05s">XP</h3> <p class="wow fadeIn" data-wow-delay=".05s">This is a so-called Extreme Programming (XP), which is an agile project management framework used in&nbsp;<a href="https://fireart.studio/services/" target="_blank" rel="noopener">software development</a>. XPM stands for extreme project management accordingly.</p> <p class="wow fadeIn" data-wow-delay=".05s">In a nutshell, XP is one of the agile methodologies, which allows advocating iterative development, frequent releases, and a high level of customer involvement in the process. It&rsquo;s similar to Scrum, only XP is a lot more prescriptive and opinionated. That&rsquo;s why it won&rsquo;t just do for self-sufficient and independent teams.</p> <h2 class="wow fadeIn" data-wow-delay=".05s">Event Chain Methodology</h2> <p class="wow fadeIn" data-wow-delay=".05s">Tools used in project management are not limited to popular agile pm tools and techniques. You may also apply other methods to organize your pm activities perfectly.</p> <blockquote class="wow fadeIn" data-wow-delay=".05s"> <p><strong>A network analysis technique focusing on identifying and managing events and the relationship between them (event chains) that may affect project schedules is another excellent way to succeed.</strong></p> </blockquote> <p class="wow fadeIn" data-wow-delay=".05s">More about event chain methodology, its advantages and disadvantages read on&nbsp;<a href="https://www.knowledgehut.com/tutorials/project-management/event-chain-methodology" target="_blank" rel="nofollow">Knowledgehut.</a></p> <h2 class="wow fadeIn" data-wow-delay=".05s">PERT</h2> <p class="wow fadeIn" data-wow-delay=".05s">What is a PERT in Project Management? Many people confuse the PERT technique with the PERT chart, so to understand the comprehensive definition of a PERT chart, we&rsquo;ll start by explaining both terms.</p> <blockquote class="wow fadeIn" data-wow-delay=".05s"> <p><strong>PERT is the Program Evaluation Review Technique, or project evaluation and review technique. PERT is a technique for creating a PERT chart. And the PERT diagram is a visual diagram and the result of using the PERT technique. That is, the PERT technique is the process, and the PERT diagram is the result.</strong></p> </blockquote> <p class="wow fadeIn" data-wow-delay=".05s">The PERT chart as one of the project monitoring tools and techniques allows project managers to learn important information about the work schedule: task dependencies, estimated task time, and minimum project lead time. But this is not the most convenient and understandable tool.</p> <p class="wow fadeIn" data-wow-delay=".05s">PERT and the critical path method work scheduling techniques that project managers may use to view task dependencies and estimate project lead times.</p> <h2 class="wow fadeIn" data-wow-delay=".05s">RUP</h2> <p class="wow fadeIn" data-wow-delay=".05s">The Rational Unified Process (RUP) is a software development methodology created by&nbsp;<a href="https://www.ibm.com/products/rational-software-architect-designer" target="_blank" rel="nofollow">Rational Software</a>, a division of IBM.</p> <p class="wow fadeIn" data-wow-delay=".05s">RUP focuses on an iterative development model. At the end of each iteration (lasting 2-6 weeks), the team must achieve the goals planned for this iteration, create or modify the&nbsp;<a href="https://fireart.studio/blog/4-ux-artifacts-to-help-you-craft-beautiful-websites/" target="_blank" rel="noopener">design artifacts</a>, and get an intermediate, but workable version of the product.</p> <p class="wow fadeIn" data-wow-delay=".05s">Iterative development allows you to quickly respond to changing requirements, identify and eliminate risks at the early stages of a project, as well as constantly monitor the quality of the product being developed. The complete product development lifecycle here consists of four phases, each of which includes one or more iterations.</p> <h2 class="wow fadeIn" data-wow-delay=".05s">Prince2</h2> <p class="wow fadeIn" data-wow-delay=".05s">The British government has long appreciated the effectiveness of project management, and in 1989 the British PRINCE2 methodology was successfully created. The name comes from the &ldquo;Projects IN Controlled Environments version 2&rdquo; acronym.</p> <p class="wow fadeIn" data-wow-delay=".05s">Unlike flexible agile methods, PRINCE2 does not take an iterative approach to the project. Compared to other products, PRINCE2 is like a hybrid of the classic project management approach and a focus on quality.</p> <h2 class="wow fadeIn" data-wow-delay=".05s">WBS</h2> <blockquote class="wow fadeIn" data-wow-delay=".05s"> <p><em>Work breakdown structure (WBS) in project management is a&nbsp;method for completing complex, multi-step projects</em></p> <p><em>(Wrike.com )</em></p> </blockquote> <p class="wow fadeIn" data-wow-delay=".05s">It is important to understand that WBS collects the deliverables, not the tasks that need to be completed to obtain those deliverables.</p> <p class="wow fadeIn" data-wow-delay=".05s">WBS is extremely useful in project planning and here&rsquo;s why:</p> <ul class="wow fadeIn" data-wow-delay=".05s"> <li>WBS &ndash; if not the only, but certainly the most effective way to visually reflect the entire scope of the project.</li> <li>Breaking it down into smaller chunks means work can be done simultaneously by different team members, leading to better team productivity and easier project management.</li> <li>WBS focuses not on the process, but on the expected result, and creates the right message.</li> </ul> <p class="wow fadeIn" data-wow-delay=".05s">Ideally, the customer or his representative and the whole team participate in the development of WBS, which allows:</p> <p class="wow fadeIn" data-wow-delay=".05s">a) to provide a unified understanding of the project results and their scope,</p> <p class="wow fadeIn" data-wow-delay=".05s">b) to see the importance and contribution of individual elements to the overall result.</p> <p class="wow fadeIn" data-wow-delay=".05s">With the help of WBS, you can justify the need for finances or human resources. WBS helps to prevent risks and changes, or at least significantly reduce their likelihood and impact.</p> <p class="wow fadeIn" data-wow-delay=".05s">At the WBS level, it is already possible to define and agree on the control points of the project. Both decisions about continuing the project after the next stage and controlling human and financial resources costs are included.</p> <h2 class="wow fadeIn" data-wow-delay=".05s">Waterfall</h2> <p class="wow fadeIn" data-wow-delay=".05s">The waterfall is a classic methodology in the world of product development. It has existed for more than half a century. It is also called a cascade software development process model, in which the development process looks like a flow, sequentially passing through the phases of requirements analysis, design, implementation, testing, integration, and support.</p> <p class="wow fadeIn" data-wow-delay=".05s">The flow of processes, meeting deadlines, completing tasks in a waterfall model is often best displayed by a&nbsp;<a href="https://www.gantt.com/" target="_blank" rel="nofollow">Gantt Chart</a>&nbsp;or horizontal bar chart.</p> <h2 class="wow fadeIn" data-wow-delay=".05s">CPM</h2> <blockquote class="wow fadeIn" data-wow-delay=".05s"> <p><em>The critical path method (CPM) is a technique where you may identify tasks that are necessary for project completion and determine their scheduling time. It focuses primarily on discovering the most essential tasks in the project timeline, identifying their dependencies, and picking the best timeline for their completion.</em></p> <p><em>(<a href="https://asana.com/ru/resources/critical-path-method" target="_blank" rel="nofollow">Asana</a>)</em></p> </blockquote> <p class="wow fadeIn" data-wow-delay=".05s">CPM may provide precious insights on planning various projects, allocating resources they require and scheduling necessary tasks.</p> <p class="wow fadeIn" data-wow-delay=".05s">As you see, there are plenty of methods to rely on during your PM routine. There&rsquo;s a range of valuable tools to apply in this or that methodology to optimize the teamwork and communication with other project participants.</p> <h2 class="wow fadeIn" data-wow-delay=".05s">Leading Project Management Tools</h2> <p class="wow fadeIn" data-wow-delay=".05s">Now let&rsquo;s discuss the most curious and practical part of project management &ndash; analytical techniques in project management and the tools to apply in everyday work to track progress, communicate with the team, report and analyze, and much more.</p> <h3 class="wow fadeIn" data-wow-delay=".05s">Jira</h3> <p class="wow fadeIn" data-wow-delay=".05s">One of the oldest and best project management techniques ever created for effective project management of all levels. It&rsquo;s been powerful project management software for teams of all sizes and the best development tool for agile teams for so long.</p> <p class="wow fadeIn" data-wow-delay=".05s">Free&nbsp;<a href="https://www.atlassian.com/software/jira" rel="nofollow">Jira Software</a>&nbsp;is designed so that everyone on your development team can plan, track and release excellent software or any other project. Though, not quite suitable for marketing teams, it&rsquo;s more used by hard developers.</p> <figure id="attachment_17190" class="wp-caption aligncenter wow fadeIn" data-wow-delay=".05s"><img class="wp-image-17190" src="https://fireart.studio/wp-content/uploads/2021/11/jira.png" sizes="(max-width: 938px) 100vw, 938px" srcset="https://fireart.studio/wp-content/uploads/2021/11/jira.png 1155w, https://fireart.studio/wp-content/uploads/2021/11/jira-300x211.png 300w, https://fireart.studio/wp-content/uploads/2021/11/jira-1024x722.png 1024w, https://fireart.studio/wp-content/uploads/2021/11/jira-768x541.png 768w, https://fireart.studio/wp-content/uploads/2021/11/jira-607x428.png 607w, https://fireart.studio/wp-content/uploads/2021/11/jira-274x193.png 274w, https://fireart.studio/wp-content/uploads/2021/11/jira-640x451.png 640w, https://fireart.studio/wp-content/uploads/2021/11/jira-450x317.png 450w" alt="" width="938" height="662" /> <figcaption id="caption-attachment-17190" class="wp-caption-text">Source: Atlassian JIRA official page</figcaption> </figure> <h3 class="wow fadeIn" data-wow-delay=".05s">Asana</h3> <p class="wow fadeIn" data-wow-delay=".05s">Asana is a marketing favorite.&nbsp; From project management tools and methodologies, this one makes the small stuff to the big picture. It helps organize work so that the teams know what to do and see how via a user-friendly interface.</p> <p class="wow fadeIn" data-wow-delay=".05s">Prices are more than affordable. They vary from basic $0 forever to Premium $10, 99 and Business $24, 99 monthly. More about it is&nbsp;<a href="https://asana.com/pricing" rel="nofollow">here</a>.</p> <p class="wow fadeIn" data-wow-delay=".05s">&nbsp;</p> <figure id="attachment_17191" class="wp-caption aligncenter wow fadeIn" data-wow-delay=".05s"><img class="wp-image-17191 " src="https://fireart.studio/wp-content/uploads/2021/11/asana.jpg" sizes="(max-width: 908px) 100vw, 908px" srcset="https://fireart.studio/wp-content/uploads/2021/11/asana.jpg 1365w, https://fireart.studio/wp-content/uploads/2021/11/asana-300x183.jpg 300w, https://fireart.studio/wp-content/uploads/2021/11/asana-1024x625.jpg 1024w, https://fireart.studio/wp-content/uploads/2021/11/asana-768x469.jpg 768w, https://fireart.studio/wp-content/uploads/2021/11/asana-701x428.jpg 701w, https://fireart.studio/wp-content/uploads/2021/11/asana-316x193.jpg 316w, https://fireart.studio/wp-content/uploads/2021/11/asana-640x391.jpg 640w, https://fireart.studio/wp-content/uploads/2021/11/asana-450x275.jpg 450w, https://fireart.studio/wp-content/uploads/2021/11/asana-1200x732.jpg 1200w" alt="" width="908" height="554" /> <figcaption id="caption-attachment-17191" class="wp-caption-text">Source: Asana official page</figcaption> </figure> <h3 class="wow fadeIn" data-wow-delay=".05s">Trello</h3> <p class="wow fadeIn" data-wow-delay=".05s">This is another Atlassian product, cloud-based small team project management software developed by Fog Creek Software. Trello uses a project management paradigm known as Kanban, which you&rsquo;ve already familiarized yourself with, a technique that Toyota originally popularized in the 1980s for supply chain management.</p> <figure id="attachment_17192" class="wp-caption aligncenter wow fadeIn" data-wow-delay=".05s"><img class="wp-image-17192 " src="https://fireart.studio/wp-content/uploads/2021/11/tre.png" sizes="(max-width: 917px) 100vw, 917px" srcset="https://fireart.studio/wp-content/uploads/2021/11/tre.png 1902w, https://fireart.studio/wp-content/uploads/2021/11/tre-300x210.png 300w, https://fireart.studio/wp-content/uploads/2021/11/tre-1024x718.png 1024w, https://fireart.studio/wp-content/uploads/2021/11/tre-768x539.png 768w, https://fireart.studio/wp-content/uploads/2021/11/tre-1536x1077.png 1536w, https://fireart.studio/wp-content/uploads/2021/11/tre-610x428.png 610w, https://fireart.studio/wp-content/uploads/2021/11/tre-275x193.png 275w, https://fireart.studio/wp-content/uploads/2021/11/tre-640x449.png 640w, https://fireart.studio/wp-content/uploads/2021/11/tre-450x316.png 450w, https://fireart.studio/wp-content/uploads/2021/11/tre-1200x842.png 1200w, https://fireart.studio/wp-content/uploads/2021/11/tre-1283x900.png 1283w" alt="" width="917" height="643" /> <figcaption id="caption-attachment-17192" class="wp-caption-text">Trello Interface from Trello</figcaption> </figure> <h3 class="wow fadeIn" data-wow-delay=".05s">Zoho Projects</h3> <p class="wow fadeIn" data-wow-delay=".05s"><a href="https://www.zoho.com/projects/" target="_blank" rel="nofollow">Zoho Projects</a>&nbsp;is cloud-based project management software that helps teams to efficiently plan, track, collaborate, and achieve project goals.</p> <p class="wow fadeIn" data-wow-delay=".05s">A great alternative to Asana, you may check out the&nbsp;<a href="https://www.zoho.com/projects/zohoprojects-pricing.html" target="_blank" rel="nofollow">pricing page</a>&nbsp;here.</p> <figure id="attachment_17193" class="wp-caption aligncenter wow fadeIn" data-wow-delay=".05s"><img class="wp-image-17193 " src="https://fireart.studio/wp-content/uploads/2021/11/zoho.png" sizes="(max-width: 961px) 100vw, 961px" srcset="https://fireart.studio/wp-content/uploads/2021/11/zoho.png 1311w, https://fireart.studio/wp-content/uploads/2021/11/zoho-300x186.png 300w, https://fireart.studio/wp-content/uploads/2021/11/zoho-1024x633.png 1024w, https://fireart.studio/wp-content/uploads/2021/11/zoho-768x475.png 768w, https://fireart.studio/wp-content/uploads/2021/11/zoho-692x428.png 692w, https://fireart.studio/wp-content/uploads/2021/11/zoho-312x193.png 312w, https://fireart.studio/wp-content/uploads/2021/11/zoho-640x396.png 640w, https://fireart.studio/wp-content/uploads/2021/11/zoho-450x278.png 450w, https://fireart.studio/wp-content/uploads/2021/11/zoho-1200x742.png 1200w" alt="" width="961" height="595" /> <figcaption id="caption-attachment-17193" class="wp-caption-text">Source: Zoho webpage</figcaption> </figure> <h3 class="wow fadeIn" data-wow-delay=".05s">Wrike</h3> <p class="wow fadeIn" data-wow-delay=".05s">Check out&nbsp;<a href="https://www.wrike.com/" target="_blank" rel="nofollow">Wrike&rsquo;s</a>&nbsp;all-in-one project management platform to get started doing better and smarter, which promises a new level of teamwork efficiency. Simple and similar to Asana or Zoho Projects, it&rsquo;s a great tool for a start.</p> <figure id="attachment_17194" class="wp-caption aligncenter wow fadeIn" data-wow-delay=".05s"><img class="wp-image-17194 " src="https://fireart.studio/wp-content/uploads/2021/11/wrike.png" sizes="(max-width: 954px) 100vw, 954px" srcset="https://fireart.studio/wp-content/uploads/2021/11/wrike.png 1230w, https://fireart.studio/wp-content/uploads/2021/11/wrike-300x205.png 300w, https://fireart.studio/wp-content/uploads/2021/11/wrike-1024x701.png 1024w, https://fireart.studio/wp-content/uploads/2021/11/wrike-768x526.png 768w, https://fireart.studio/wp-content/uploads/2021/11/wrike-625x428.png 625w, https://fireart.studio/wp-content/uploads/2021/11/wrike-282x193.png 282w, https://fireart.studio/wp-content/uploads/2021/11/wrike-640x438.png 640w, https://fireart.studio/wp-content/uploads/2021/11/wrike-450x308.png 450w, https://fireart.studio/wp-content/uploads/2021/11/wrike-1200x821.png 1200w" alt="" width="954" height="653" /> <figcaption id="caption-attachment-17194" class="wp-caption-text">Wrike&rsquo;s</figcaption> </figure> <h3 class="wow fadeIn" data-wow-delay=".05s">ProofHub</h3> <p class="wow fadeIn" data-wow-delay=".05s"><a href="https://www.proofhub.com/" target="_blank" rel="nofollow">ProofHub</a>&nbsp;is a project planning software with every tool your team needs to get work done faster, together. No per-user fee. Free trial. No learning curve. &ndash; That&rsquo;s how they position their tool.</p> <p class="wow fadeIn" data-wow-delay=".05s">Check out&nbsp;<a href="https://www.proofhub.com/pricing" target="_blank" rel="nofollow">their plans</a>&nbsp;here.</p> <figure id="attachment_17195" class="wp-caption aligncenter wow fadeIn" data-wow-delay=".05s"><img class="wp-image-17195 " src="https://fireart.studio/wp-content/uploads/2021/11/ph.png" sizes="(max-width: 968px) 100vw, 968px" srcset="https://fireart.studio/wp-content/uploads/2021/11/ph.png 1091w, https://fireart.studio/wp-content/uploads/2021/11/ph-300x221.png 300w, https://fireart.studio/wp-content/uploads/2021/11/ph-1024x755.png 1024w, https://fireart.studio/wp-content/uploads/2021/11/ph-768x566.png 768w, https://fireart.studio/wp-content/uploads/2021/11/ph-581x428.png 581w, https://fireart.studio/wp-content/uploads/2021/11/ph-262x193.png 262w, https://fireart.studio/wp-content/uploads/2021/11/ph-640x472.png 640w, https://fireart.studio/wp-content/uploads/2021/11/ph-450x332.png 450w" alt="" width="968" height="714" /> <figcaption id="caption-attachment-17195" class="wp-caption-text">Source: Proof Hub page</figcaption> </figure> <h3 class="wow fadeIn" data-wow-delay=".05s">Basecamp</h3> <p class="wow fadeIn" data-wow-delay=".05s"><a href="https://basecamp.com/" target="_blank" rel="nofollow">Basecamp</a>&nbsp;is a public-cloud-based tool for project management, collaboration, and task setting that puts everything you might need to get work done in a single place. It&rsquo;s the calm, organized way to manage projects, work with clients, communicate with the team, and so much more.</p> <figure id="attachment_17196" class="wp-caption aligncenter wow fadeIn" data-wow-delay=".05s"><img class="wp-image-17196 " src="https://fireart.studio/wp-content/uploads/2021/11/basecamp.jpg" sizes="(max-width: 953px) 100vw, 953px" srcset="https://fireart.studio/wp-content/uploads/2021/11/basecamp.jpg 1269w, https://fireart.studio/wp-content/uploads/2021/11/basecamp-300x199.jpg 300w, https://fireart.studio/wp-content/uploads/2021/11/basecamp-1024x678.jpg 1024w, https://fireart.studio/wp-content/uploads/2021/11/basecamp-768x508.jpg 768w, https://fireart.studio/wp-content/uploads/2021/11/basecamp-647x428.jpg 647w, https://fireart.studio/wp-content/uploads/2021/11/basecamp-292x193.jpg 292w, https://fireart.studio/wp-content/uploads/2021/11/basecamp-640x424.jpg 640w, https://fireart.studio/wp-content/uploads/2021/11/basecamp-450x298.jpg 450w, https://fireart.studio/wp-content/uploads/2021/11/basecamp-1200x794.jpg 1200w" alt="" width="953" height="630" /> <figcaption id="caption-attachment-17196" class="wp-caption-text">Source: Basecamp webpage</figcaption> </figure> <h2 class="wow fadeIn" data-wow-delay=".05s">Wrapping Up</h2> <p class="wow fadeIn" data-wow-delay=".05s">There are so many helpful project management strategies and techniques to apply in the everyday struggle for better results and time management.&nbsp; Every event or task dependency, jobs to be done, or other either design or development deliverables may be included in a simple task management system you prefer to use in your work. CCT, WBS, or CPM are no longer strange terms. And the leading project management tools may perfectly fit the methodology applied in your product management.</p> <p class="wow fadeIn" data-wow-delay=".05s">Though it all may seem such a mess to understand, it still helps to come up with more effective work solutions when you&rsquo;re a PM or need to perform the role for some reason.</p> <p class="wow fadeIn" data-wow-delay=".05s">Feel free to ask for help with any product management issue from&nbsp;<a href="https://fireart.studio/product-design-development-company/" target="_blank" rel="noopener">agile professionals</a>.</p>
fireartd
913,195
Templates vs UI Blocks
Starting out in the front-end development can be quite complicated with so many different options out...
0
2021-11-30T14:14:26
https://dev.to/harishash/templates-vs-ui-blocks-3i6m
productivity, beginners, programming, codenewbie
Starting out in the front-end development can be quite complicated with so many different options out there. They range from selecting a base framework to choosing between different CSS Libraries. But one thing remains constant. To get work done as fast as possible, most of us do lean towards the use of pre-made templates or ui blocks. So the question arises here, which should be used for the best productivity? Templates or UI Blocks? #Templates ![Web Templates](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ykhuqyu72b0ntdggm4ya.png) Web Templates are pre structured web pages that allow developers to create full-fledged websites by injecting them with their own content. Templates are usually sold as complete web pages or websites and they follow a single structure across all pages. Developers can fast track their workflow by using templates since they don’t have to start anything from scratch. They help those developers a lot who are on tight deadlines and want to please the clients. ##Pros: - It can save a huge amount of time - No need to spend a lot of money on building everything from scratch - There’s a huge market out there so you’re probably covered with whatever idea of the website you have in mind - Easier to switch to a new template since not much time and effort was spent on the first one ##Cons: - Affects the learning curve - Not good for the brand identity - Very restricted in terms of your creative decisions - Code quality is not always up to the mark - No unique identity, your website can be similar to several other Brands - Host a lot of useless code if a section is not being used #UI Blocks ![UI Blocks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/obtcz96nendk94lh9i9q.png) UI Blocks are basically snippets of code that make up a specific component that builds up a specific section. Unlike templates, code snippets are mostly used for just one section of the website. Developers can use these UI blocks within their existing projects just for one section that they do not want to develop from scratch. Let’s look at some of the Pros and cons of using code blocks: #Pros: - Easily customisable - Do not affect the learning curve as much as templates - Mostly Free - Not as restricting as templates - No redundant or useless code - Easy to integrate into existing projects - Less set up time #Cons: - Difficult to find the perfect code block - Market is lesser than Templates - Hard to find supported frameworks #Conclusion Coming from the perspective of a beginner, I would personally take the side of UI blocks. It gives me the chance to develop new components from scratch that will help me in learning development, all while fast tracking my workflow. I can easily integrate a UI block into any of my projects so I can be done with my task. I can set up the easier sections myself and use the UI blocks for complex sections until I’m better equipped to tackle those. The only problem I was having with UI blocks was that it's hard to find the perfect code snippet online that supports the framework I’m currently using. Even if I found a UI block that fits my design preferences, it would not be in the current framework I’m using. Fortunately this problem was solved by [blox](https://www.vsblox.com/) since it gives me access to many different ui blocks within vs code and each of that ui block is supported for different frameworks including React, Angular and Vue. But I'd love to hear what's your take on this topic. Comment down below what you think about Templates VS UI Blocks. Happy Developing!
harishash
913,202
Cross browser speech synthesis - the hard way and the easy way
When I implemented my first speech-synthesis app using the Web Speech API I was shocked how hard it...
0
2021-12-07T10:42:24
https://dev.to/jankapunkt/cross-browser-speech-synthesis-the-hard-way-and-the-easy-way-353
webdev, browser, javascript, standards
When I implemented my first speech-synthesis app using the [`Web Speech API`](https://wicg.github.io/speech-api/) I was shocked how hard it was to setup and execute it with cross-browser support in mind: - Some browsers don't support [speech synthesis](https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis) at all, for instance IE (at least I don't care :man_shrugging:) and Opera (I do care :angry:) and a few more mobile browsers (I haven't decided yet, whether I care or not :thinking:). - On top of that, each browser implements the API differently or with some specific quirks the other browsers don't have **Just try it yourself** - go to and execute the [MDN speech synthesis example](https://mdn.github.io/web-speech-api/speak-easy-synthesis/) on different browsers and different platforms: - Linux, Windows, MacOS, BSD, Android, iOS - Firefox, Chrome, Chromium, Safari, Opera, Edge, IE, Samsung Browser, Android Webview, Safari on iOS, Opera Mini You will realize that this example will only work on a subset of these platform-browser combinations. Worst: when you start researching you'll get shocked how quirky and underdeveloped this whole API still is in 2021/2022. **To be fair:** it is still labeled as experimental technology. However, it's almost [10 years](https://www.w3.org/2005/Incubator/htmlspeech/XGR-htmlspeech-20111206/) now, since it has been drafted and still is not a living standard. This makes it much harder to leverage for our applications and I hope this guide I will help you to get the most out of it for as many browsers as possible. --- ## Minimal example Let's approach this topic step-by-step and start with a minimal example that all browsers (that generally support speech synthesis) should run: ```js if ('speechSynthesis' in window) { window.speechSynthesis.speak( new SpeechSynthesisUtterance('Hello, world!') ) } ``` You can simply copy that code and execute it in your browser console. If you have basic support you will hear some "default" voice speaking the text `'Hello, world!'` and it may sound natural or not, depending on the default "voice" that is used. --- ## Loading voices Browsers may detect your current language and select a default voice, if installed. However, this may not represent the desired language you'd like to hear for the text to be spoken. In such case you need to load the list of voices, which are instances of `SpeechSynthesisVoice`. This is the first greater obstacle where browsers behave quite differently: **Load voices sync-style** ```js const voices = window.speechSynthesis.getVoices() voices // Array of voices or empty if none are installed ``` Firefox and Safari Desktop just load the voices immediately in sync-style. This however would return an empty array on Chrome Desktop, Chrome Android and **may** return an empty Array on Firefox Android (see next section). **Load voices async-style** ```js window.speechSynthesis.onvoiceschanged = function () { const voices = window.speechSynthesis.getVoices() voices // Array of voices or empty if none are installed } ``` This methods loads the voices async, so your overall system needs a callback or wrap it with a `Promise`. Firefox Desktop does not support this method at all, although it's defined as property of `window.speechSynthesis`, while Safari does not have it at all. In contrast: Firefox Android loads the voices the first time using this method and on a refresh has them available via the sync-style method. **Loading using interval** Some users of older Safari have reported that their voices are not available immediately (while `onvoiceschanged` is not available, too). For this case we need to check in a constant interval for the voices: ```js let timeout = 0 const maxTimeout = 2000 const interval = 250 const loadVoices = (cb) => { const voices = speechSynthesis.getVoices() if (voices.length > 0) { return cb(undefined, voices) } if (timeout >= maxTimeout) { return cb(new Error('loadVoices max timeout exceeded')) } timeout += interval setTimeout(() => loadVoices(cb), interval) } loadVoices((err, voices) => { if (err) return console.error(err) voices // voices loaded and available }) ``` --- ## Speaking with a certain voice There are use-cases, where the default selected voice is not the same language as the text to be spoken. We need to change the voice for the "utterance" to speak. ### Step 1: get a voice by a given language ```js // assume voices are loaded, see previous section const getVoicebyLang = lang => speechSynthesis .getVoices() .find(voice => voice.startsWith(lang)) const german = getVoicebyLang('de') ``` Note: Voices have standard language codes, like `en-GB` or `en-US` or `de-DE`. However, on Android's Samsung Browser or Android Chrome voices have underscore-connected codes, like `en_GB`. Then on Firefox android voices have three characters before the separator, like `deu-DEU-f00` or `eng-GBR-f00`. However, they all start with the language code so passing a two-letter short-code should be sufficient. ### Step 2: create a new utterance We can now pass the voice to a new `SpeechSynthesisUtterance` and as your precognitive abilities correctly manifest - there are again some browser-specific issues to consider: ```js const text = 'Guten Tag!' const utterance = new SpeechSynthesisUtterance(text) if (utterance.text !== text) { // I found no browser yet that does not support text // as constructor arg but who knows!? utterance.text = text } utterance.voice = german // ios required utterance.lang = voice.lang // // Android Chrome required utterance.voiceURI = voice.voiceURI // Who knows if required? utterance.pitch = 1 utterance.volume = 1 // API allows up to 10 but values > 2 break on all Chrome utterance.rate = 1 ``` We can now pass the utterance to the speak function as a preview: ```js speechSynthesis.speak(utterance) // speaks 'Guten Tag!' in German ``` ### Step 3: add events and speak This is of course just the half of it. We actually want to get deeper insights of what's happening and what's missing by tapping into some of the utterance's events: ```js const handler = e => console.debug(e.type) utterance.onstart = handler utterance.onend = handler utterance.onerror = e => console.error(e) // SSML markup is rarely supported // See: https://www.w3.org/TR/speech-synthesis/ utterance.onmark = handler // word boundaries are supported by // Safari MacOS and on windows but // not on Linux and Android browsers utterance.onboundary = handler // not supported / fired // on many browsers somehow utterance.onpause = handler utterance.onresume = handler // finally speak and log all the events speechSynthesis.speak(utterance) ``` ### Step 4: Chrome-specific fix Longer texts on Chrome-Desktop will be cancelled automatically after 15 seconds. This can be fixed by either chunking the texts or by using an interval of "zero"-latency pause/resume combination. At the same time this fix breaks on Android, since Android devices don't implement `speechSynthesis.pause()` as pause but as cancel: ```js let timer utterance.onstart = () => { // detection is up to you for this article as // this is an own huge topic for itself if (!isAndroid) { resumeInfinity(utterance) } } const clear = () => { clearTimeout(timer) } utterance.onerror = clear utterance.onend = clear const resumeInfinity = (target) => { // prevent memory-leak in case utterance is deleted, while this is ongoing if (!target && timer) { return clear() } speechSynthesis.pause() speechSynthesis.resume() timer = setTimeout(function () { resumeInfinity(target) }, 5000) } ``` Furthermore, some browser don't update the `speechSynthesis.paused` property when `speechSynthesis.pause()` is executed (and speech is correctly paused). You need to manage these states yourself then. --- ## Issues that can't be fixed with JavaScript: All the above fixes rely on JavaScript but some issues are platform-specific. You need to your app in a way to avoid these issues, where possible: - All browsers on Android actually do a cancel/stop when calling `speechSynthesis.pause`; pause is simply not supported on Android :-1: - There are no voices on Chromium-Ubuntu and Ubuntu-derivatives unless the browser is started with a flag :-1: - If on Chromium-Desktop Ubuntu and the very first page wants to load speech synthesis, then there are no voices ever loaded until the page is refreshed or a new page is entered. This can be fixed with JavaScript but it can lead to very bad UX to auto-refresh the page. :-1: - If voices are not installed on the host-OS and there are no voices loaded from remote by the browser, then there are no voices and thus no speech synthesis :-1: - There is no chance to just instant-load custom voices from remote and use them as a shim in case there are no voices :-1: - If the installed voices are just bad users have to manually install better voices :-1: --- ## Making your life easier with `EasySpeech` Now you have seen the worst and believe me, it takes ages to implement all potential fixes. Fortunately I already did this and published a package to NPM with the intent to provide a common API that handles most issues internally and provide the same experience across browsers (that support `speechSynthesis`): {% github jankapunkt/easy-speech %} You should give it a try if you want to implement speech synthesis the next time. It also comes with a DEMO page so you can easy test and debug your devices there: https://jankapunkt.github.io/easy-speech/ Let's take a look how it works: ```js import EasySpeech from 'easy-speech' // sync, returns Object with detected features EasySpeech.detect() EasySpeech.init() .catch(e => console.error('no speech synthesis:', error.message) .then(() = > { EasySpeech.speak({ text: 'Hello, world!' }) }) ``` It will not only detect, which features are available but also loads an optimal default voice, based on a few heuristics. Of course there is much more to use and the full API is also documented via JSDoc: https://github.com/jankapunkt/easy-speech/blob/master/API.md If you like it leave a star and please file an issue if you found (yet another) browser-specific issue. --- ## References - https://wicg.github.io/speech-api/#tts-section - https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis - https://gist.github.com/alrra/6741915 - https://github.com/ubershmekel/audio-language-tests - https://stackoverflow.com/questions/33889107/speech-synthesis-in-chrome-for-android-not-loading-voices - https://stackoverflow.com/questions/49506716/speechsynthesis-getvoices-returns-empty-array-on-windows - https://stackoverflow.com/questions/21947730/chrome-speech-synthesis-with-longer-texts - https://stackoverflow.com/a/34130734 - https://stackoverflow.com/a/68060634 - https://stackoverflow.com/a/48056986 - https://bugs.chromium.org/p/chromium/issues/detail?id=582455 - https://stackoverflow.com/a/65883556
jankapunkt
913,439
How to easily get started with ThreeJS - Part 3
Hi guys, hope you are fine! 🙂 I'm back after posting the second part of this series about how to get...
15,589
2021-12-06T10:13:23
https://dev.to/th3wall/how-to-easily-get-started-with-threejs-part-3-48j5
javascript, tutorial, webdev, programming
Hi guys, hope you are fine! 🙂 I'm back after posting the second part of this series about how to get started on ThreeJS without pain. If you haven't done it yet, you can read the first and second part here 👇🏼 {% link https://dev.to/th3wall/how-to-easily-get-started-with-threejs-part-1-go7 %} {% link https://dev.to/th3wall/how-to-easily-get-started-with-threejs-part-2-387f %} --- ##Small recap In the [second part](https://dev.to/th3wall/how-to-easily-get-started-with-threejs-part-2-387f), we saw how to animate the cube, how to change its geometry and how to change its material. We arrived to this beautiful 3D animation: ![Final Torus Knot effect](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/prrughxs2yvw56iainoa.gif) The final code used to achieve this effect is the following: ```js // script.js const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight); camera.position.z = 3; scene.add(camera); const textureLoader = new THREE.TextureLoader(); const matcapTexture = textureLoader.load("https://bruno-simon.com/prismic/matcaps/3.png"); const geometry = new THREE.TorusKnotGeometry(0.5, 0.2, 200, 30); const material = new THREE.MeshMatcapMaterial({ matcap: matcapTexture }); const mesh = new THREE.Mesh(geometry, material); scene.add(mesh); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); const animate = function () { window.requestAnimationFrame(animate); mesh.rotation.x += 0.01; mesh.rotation.y += 0.01; renderer.render( scene, camera ); }; animate(); document.body.appendChild(renderer.domElement); ``` In this last part we will see how to make our canvas responsive, how to smoothly animate the camera and how to insert some HTML stuff to be much more presentable as a heading section. We will style the page in order to look like this: [https://th3wall-threejs.netlify.app](https://th3wall-threejs.netlify.app) --- ##Let's make it responsive If we preview in the browser the result of the code provided in the small recap up here, we could clearly see that the canvas is not responsive. So, how can we make it *responsive*? First of all, we need to add an **event listener** on the window **'resize'** method: ```js window.addEventListener('resize', () => { }) ``` Then, we need to handle the camera. Inside our event listener, we need to update the **aspect** of the camera, and we do so by providing it the ratio between the window innerWidth and innerHeight: ```js //Update the camera camera.aspect = window.innerWidth / window.innerHeight; ``` Every time we *update* a parameter of the camera, we should communicate it to the camera. The "**updateProjectionMatrix**" is a function of the *PerspectiveCamera* that updates the camera projection matrix. It must be called after any change of parameters. ([see it in ThreeJS docS](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera.updateProjectionMatrix)) So, on the camera we call this method: ```js camera.updateProjectionMatrix(); ``` The last thing to do is to pass the new viewport sizes to the renderer: ```js renderer.setSize(window.innerWidth, window.innerHeight); ``` and we're done! Now our canvas is fully responsive and we can verify it by resizing the screen. Here's the full event listener function: ```js window.addEventListener('resize', () => { //Update the camera camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); //Update the renderer renderer.setSize(window.innerWidth, window.innerHeight); }) ``` --- ##Camera animations based on mouse position Now that we added responsiveness to our canvas and our object, it's time to bring some movements to the scene. We're going to do a classic animation: if we move the mouse on the *left* the camera will move to the *left*, if we move the mouse on the *right* the camera will move to the *right*, and the same applies to up & down movements. First of all we need to know **where is the cursor**. We can store the **cursor position** in a variable: ```js const cursor = { x: 0, y: 0 }; ``` Whenever the mouse will move, the *x* and *y* values of the cursor will be updated. So we add an event listener on the *mousemove*: ```js window.addEventListener('mousemove', event => { // update cursor values }); ``` Inside the listener we will retrieve the cursor position with vanilla JS, really easy. The *event* parameter contains the position of the cursor on the *X*-axis and on the *Y*-axis: ```js cursor.x = event.clientX; cursor.y = event.clientY; ``` Logging the values of the cursor we can see the coordinates that go from 0 (on the top left) to the maximum viewport width and height (to the bottom right). But the kind of values we want to have are **normalized** values, that go **from 0 to 1**. We can achieve this by *dividing the cursor value by the current viewport width/height*: ```js cursor.x = event.clientX / window.innerWidth; cursor.y = event.clientY / window.innerHeight; ``` Now that we have the values that floats from 0 to 1, we can add a little genius *trick from Bruno*: let's **subtract 0.5 from each cursor values**. ```js cursor.x = event.clientX / window.innerWidth - 0.5; cursor.y = event.clientY / window.innerHeight - 0.5; ``` Why? Because in this way (you can look at the graph down here) having **the 0 at the center**, the *positive* values will go to *+0.5* and the *negative* values will go to *-0.5* ![Example axis representation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ldhii6qhe2b5mlo4qlrr.jpg) Now that we have coded the update for the cursor values, we need to move the camera simultaneously. Inside the *animate* function, that is executed with the requestAnimationFrame, we save the cursor values in two variables: ```js const cameraX = cursor.x; const cameraY = cursor.y; ``` We assign these two values to the camera position: ```js camera.position.x = cameraX; camera.position.y = cameraY; ``` As we can see previewing the result, the camera is moving with a strange behavior when we move vertically. If I move *up*, the camera moves *down* and if I move *down*, the camera moves *up*. ![Y Axis issue](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/740ljeuspw5i0qexvhec.gif) This is caused by a problem on the **Y-axis**: - in *ThreeJS* the Y-axis is *positive* going *up*; - in *event.clientY* the Y-axis is *positive* going *down*; Usually the Y-axis is positive going up, but this might depend on the software/technology we are using. To fix this inconvenience I will put **a - (minus)** inside the *cameraY* assignment: ```js const cameraX = cursor.x; const cameraY = - cursor.y; // <-- This has changed ``` Now if we preview we can finally see the correct camera movements event on the vertical axis ![Camera movements fixed](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/317090vz6fti5uhc4v3c.gif) --- ##Add easing to the animations Let's now add some *easing* to the animations: we're gonna recreate the famous **ease** animation. The idea is to move the X (or the Y) toward the destination not straight to it but only for 1/10th of the length of the destination. And repeating the 1/10th calculation on each next frame, the 1/10th gets smaller and smaller and smaller... This reproduces the classic ease animation. ![1/10 of the delta explanation schema](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxjo8qir2guce5lfdhx9.jpg) We need the calculate the **delta** between the actual position (*cameraX/Y*) and the destination (*camera.position.x/y*), then we divide this delta number by 10. This will be added on each frame to the camera position values. So in order to apply this calc, we need to modify the camera position assignments like the following: ```js camera.position.x += (cameraX - camera.position.x) / 10; camera.position.y += (cameraY - camera.position.y) / 10; ``` You can now enjoy the real smoothness! ![Smoothness achieved](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/82ixymoypog3g48wvcyi.gif) > You can adjust that /10 on your needs: keep in mind that with an **higher number** you would have even **more smoothness** and with a lower number you would have an object that floats really fast but still with a small easing. --- ##Setting up layout At this point we just need to setup the HTML and CSS of our landing page. First of all we can open the *index.html* file that we have created in [part one](https://dev.to/th3wall/how-to-easily-get-started-with-threejs-part-1-go7). We can add the classname "three" on the `<body>` tag and the following structure inside it: ```html <!-- index.html --> <section class="content"> <h2 class="content__title">Hi, I'm Davide</h2> <p class="content__subtitle">I'm a Front End Developer <br />I'm playing with ThreeJS for the very first time. </p> <div class="content__link--wrp"> <a class="content__link" href="https://github.com/Th3Wall"> <svg class="content__link--icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewbox="0 0 55 56"> <g clip-path="url(#a)"> <path fill="#fff" fill-rule="evenodd" d="M27.5.5387C12.3063.5387 0 12.8449 0 28.0387c0 12.1687 7.8719 22.4469 18.8031 26.0906 1.375.2406 1.8907-.5844 1.8907-1.3062 0-.6532-.0344-2.8188-.0344-5.1219-6.9094 1.2719-8.6969-1.6844-9.2469-3.2313-.3094-.7906-1.65-3.2312-2.8187-3.8843-.9626-.5156-2.3376-1.7875-.0344-1.8219 2.1656-.0344 3.7125 1.9937 4.2281 2.8187 2.475 4.1594 6.4281 2.9907 8.0094 2.2688.2406-1.7875.9625-2.9906 1.7531-3.6781-6.1187-.6875-12.5125-3.0594-12.5125-13.5782 0-2.9906 1.0656-5.4656 2.8188-7.3906-.275-.6875-1.2375-3.5062.275-7.2875 0 0 2.3031-.7219 7.5625 2.8188 2.1999-.6188 4.5375-.9282 6.875-.9282 2.3374 0 4.675.3094 6.875.9282 5.2593-3.575 7.5625-2.8188 7.5625-2.8188 1.5125 3.7813.55 6.6.275 7.2875 1.7531 1.925 2.8187 4.3656 2.8187 7.3906 0 10.5532-6.4281 12.8907-12.5469 13.5782.9969.8593 1.8563 2.5093 1.8563 5.0875 0 3.6781-.0344 6.6344-.0344 7.5625 0 .7218.5156 1.5812 1.8906 1.3062A27.5454 27.5454 0 0 0 55 28.0387c0-15.1938-12.3062-27.5-27.5-27.5Z" clip-rule="evenodd"></path> </g> <defs> <clippath id="a"> <path fill="#fff" d="M0 0h55v55H0z" transform="translate(0 .5387)"></path> </clippath> </defs> </svg> <span class="content__link--text">Th3Wall</span> </a> <a class="content__link" href="https://twitter.com/Th3Wall25"> <svg class="content__link--icon" xmlns="http://www.w3.org/2000/svg" fill="none" viewbox="0 0 55 46"> <path fill="#fff" d="M54.8923 6.0116a22.9167 22.9167 0 0 1-6.474 1.776 11.3622 11.3622 0 0 0 4.9569-6.2402c-2.1794 1.272-4.5948 2.1978-7.166 2.7134a11.2752 11.2752 0 0 0-18.5074 3.0528 11.2754 11.2754 0 0 0-.706 7.2184C17.6229 14.0897 9.3202 9.5866 3.7583 2.785a11.0506 11.0506 0 0 0-1.5262 5.6718c0 3.9188 1.9937 7.3631 5.0141 9.3867a11.2384 11.2384 0 0 1-5.1058-1.4117v.1375a11.2821 11.2821 0 0 0 9.0429 11.0619 11.449 11.449 0 0 1-5.0691.1948 11.3113 11.3113 0 0 0 10.5508 7.8306 22.6124 22.6124 0 0 1-13.9837 4.824c-.8938 0-1.7853-.0527-2.6813-.1536a32.0718 32.0718 0 0 0 17.3181 5.0623c20.7465 0 32.0788-17.1783 32.0788-32.0489 0-.4813 0-.9625-.0344-1.4438A22.7684 22.7684 0 0 0 55 6.0574l-.1077-.0458Z"></path> </svg> <span class="content__link--text">Th3Wall25</span> </a> </div> </section> ``` Now you need the styling part: I'll paste here the css generated from my SCSS code. You need to insert it inside the *styles.css* file: ```css /* --- styles.css --- */ @import url("https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&display=swap"); html { font-size: 16px; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: auto; font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji, Segoe UI Symbol; scroll-behavior: smooth; } body { position: relative; overflow-x: hidden; margin: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; font-family: "Poppins", sans-serif; font-size: 1rem; font-weight: 400; background-color: #fff; color: #000; text-align: center; } h1, h2, h3, h4, h5, h6, p { margin: 0; } .three { position: relative; overflow: hidden; width: 100vw; min-height: 100vh; height: 100%; } .three .content { position: absolute; top: 50%; left: 5%; transform: translateY(-50%); margin-top: 1rem; display: flex; flex-direction: column; justify-content: center; text-align: left; mix-blend-mode: difference; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .three .content__title { font-size: 26px; font-weight: 800; background: linear-gradient(270deg, #ffb04f 40%, #ff8961, #ff50b8, #cb5eee); color: #9d8eee; background-clip: text; -webkit-background-clip: text; -webkit-text-fill-color: transparent; -webkit-box-decoration-break: clone; } .three .content__subtitle { margin-bottom: 1.5rem; font-size: 14px; color: #fff; } .three .content__link { display: inline-flex; align-items: center; color: inherit; } .three .content__link:last-child { margin-left: 1rem; } .three .content__link:hover .content__link--icon, .three .content__link:hover .content__link--text { opacity: 0.65; transform: translateX(5px); } .three .content__link--wrp { display: flex; align-items: center; } .three .content__link--icon { width: 100%; max-width: 1.5rem; transition: all 0.4s cubic-bezier(0.6, -0.05, 0.01, 0.99); } .three .content__link--text { margin-left: 0.5rem; display: block; text-decoration: underline; font-size: 14px; color: #fff; transition: all 0.4s cubic-bezier(0.6, -0.05, 0.01, 0.99); } @media (min-width: 768px) { .three .content__title { letter-spacing: -0.1rem; } .three .content__link:last-child { margin-left: 2rem; } .three .content__link--icon { max-width: 2.5rem; } .three .content__link--text { margin-left: 1rem; font-size: 16px; } } @media (min-width: 1450px) { .three .content__title { font-size: 62px; } .three .content__subtitle { font-size: 28px; } .three .content__link--text { font-size: 22px; } } ``` Once everything will be in place, we should have the result that looks like this: ![Markup ready](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7ahhp06nbjzklvpwyep.gif) As we can see, the object is centered and it would fit a lot better on the right so that it won't intersect with the text on the left. In order to move it, we need to adjust the cameraX inside the animate function: ```js const cameraX = cursor.x; //Before const cameraX = cursor.x -1; //After ``` Since we wanted to move the object on the right, we have subtracted the 1 to the camera, so that it will always have an offset of 1. ![Camera fixed and ready](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2yvvpm6kz23nk1ldnbvt.gif) --- ##Adding sequenced entrances with GSAP We are at the very end, and as ending we want to animate with [GSAP](https://greensock.com/gsap/) the entrance of the elements in the page. In order to animate our floating object, *we need to change how the canvas is attached to the body*. At the moment the canvas is attached automatically to the body by ThreeJS but we need to animate the canvas element on load so we need to already have it on the page at load time. Inside the *index.html*, adjacent to the `<section class="content">` inserted in the last paragraph, we need to insert the canvas manually and give it an id or a classname: ```html <canvas id="world"></canvas> ``` At this point we can declare the variables for each element we want to animate: ```js const canvas = document.querySelector("#world"); const title = document.querySelector(".content__title"); const subtitle = document.querySelector(".content__subtitle"); const buttons = document.querySelectorAll(".content__link"); ``` We take the canvas variable and we pass it as a parameter to the renderer, like this: ```js const renderer = new THREE.WebGLRenderer({ canvas: canvas }); ``` > This will tell the renderer that the canvas to attach is the one passed to the canvas parameter, so the one with the id "world". Now that the renderer knows what it has to display, we can remove this line: ```js document.body.appendChild(renderer.domElement); ``` Then, we need to pass two parameters to the **material** in order to let it be able to be transparent: - *transparent: true* - *opacity: 0* and we set them inside the material declaration ```js const material = new THREE.MeshMatcapMaterial({ matcap: matcapTexture, transparent: true, opacity: 0 }); ``` Now we need to install GSAP and with NPM we can type the following command: > npm install gsap Once installed, we can import it on top of our *script.js* file: ```js import { gsap } from "gsap"; ``` and we can declare a classic timeline like this one: ```js const tl = gsap.timeline({paused: true, delay: 0.8, easing: "Back.out(2)"}); tl.from(title, {opacity: 0, y: 20}) .from(subtitle, {opacity: 0, y: 20}, "-=.3") .from(buttons, {stagger: {each: 0.2, from: "start"}, opacity: 0, y: 20}, "-=.3" ) .to(material, {opacity: 1}, "-=.2"); ``` As a very last step, we call the timeline play trigger after the animate function. ```js tl.play(); ``` ![Final Result](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3ffd3muo9fqoxg3h0hdk.gif) Mission accomplished! Congratulations! 🥳 🎉 👏 --- ##Final Recap I leave down here the full final *script.js* code block so you can have a better look at it: ```js // script.js import * as THREE from "three"; import { gsap } from "gsap"; const canvas = document.querySelector("#world"); const title = document.querySelector(".content__title"); const subtitle = document.querySelector(".content__subtitle"); const buttons = document.querySelectorAll(".content__link"); const cursor = { x: 0, y: 0 }; const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight); camera.position.z = 3; scene.add(camera); const textureLoader = new THREE.TextureLoader(); const matcapTexture = textureLoader.load("https://bruno-simon.com/prismic/matcaps/3.png"); const geometry = new THREE.TorusKnotGeometry(0.5, 0.2, 200, 30); const material = new THREE.MeshMatcapMaterial({ matcap: matcapTexture, transparent: true, opacity: 0 }); const mesh = new THREE.Mesh(geometry, material); scene.add(mesh); const renderer = new THREE.WebGLRenderer({ canvas: canvas }); renderer.setSize(window.innerWidth, window.innerHeight); window.addEventListener('resize', () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }) window.addEventListener('mousemove', (_e) => { cursor.x = _e.clientX / window.innerWidth - 0.5; cursor.y = _e.clientY / window.innerHeight - 0.5; }); const tl = gsap.timeline({ paused: true, delay: 0.8, easing: "Back.out(2)" }); tl.from(title, {opacity: 0, y: 20}) .from(subtitle, {opacity: 0, y: 20}, "-=.3") .from(buttons, {stagger: {each: 0.2, from: "start"}, opacity: 0, y: 20}, "-=.3") .to(material, { opacity: 1 }, "-=.2"); const animate = function () { window.requestAnimationFrame(animate); mesh.rotation.x += 0.01; mesh.rotation.y += 0.01; const cameraX = cursor.x -1; const cameraY = - cursor.y; camera.position.x += (cameraX - camera.position.x) / 10; camera.position.y += (cameraY - camera.position.y) / 10; renderer.render( scene, camera ); }; animate(); tl.play(); ``` --- ##Conclusion I really hope that this mini-series has helped you and as many people as possible and maybe inspired as Bruno Simon did with me when I saw [the interview](https://twitter.com/prismicio/status/1454078632884846600) for the first time. Please let me know if you appreciated the article and the whole mini-series. You can follow me on [Twitter](https://twitter.com/Th3Wall25), [GitHub](https://github.com/Th3Wall) & [Hashnode](https://hashnode.com/@th3wall). Thanks for reading! Th3Wall
th3wall
913,473
The Real Job: Managing Uncertainty and The Unknown
There are an endless amount of things to learn as a software developer. It can be difficult to know...
0
2021-11-30T18:43:02
https://dev.to/jobber/the-real-job-managing-uncertainty-and-the-unknown-18c8
productivity, career, discuss, motivation
There are an endless amount of _things_ to learn as a software developer. It can be difficult to know what to focus on to ensure you advance in your career. Learning to manage uncertainty and the unknown is one of the most important skills to master. Experienced developers quickly (and effectively) identify, reduce, and plan for uncertainty. **What does managing uncertainty look like?** Early on in a developer’s career the amount of what is not known can be overwhelming. To combat that feeling one can become eager to learn as much as possible as fast as possible. This will lead to burn out and can even cause stagnation. Instead start by identifying the specific uncertainty that needs addressing. Let’s use a made up example: Christine is a junior developer who is two months into her first software development role at Company ABC. She is uncertain about many things, including how to use her new tools, the processes that Company ABC has for releasing features, and just general best practices. Christine lists out everything she doesn't know and selects the top 3. Christine uses [Edmond Lau’s](https://www.linkedin.com/in/effectiveengineer) definition of leverage to decide what is most important (to learn more check out his book [The Effective Engineer](https://www.effectiveengineer.com/book)). There will be a long-lasting impact on Christine’s team if she can resolve or reduce these 3 uncertainties: - How can I better use my integrated development environment (IDE) to read and write code faster? - How can I write better tests to ensure quality code coverage? - How can I understand a new area of the code base to prepare for upcoming work? Next she refines this list to be more specific: - How can I better use my IDE to read and write code faster? - What are the quick keys to search and find code in my IDE? - What are the code completion and templating tools in my IDE? - What add-ons or tooling can I add in my IDE to auto generate common code snippets? - How can I write better tests to ensure quality code coverage? - What resources can I use to practice working within our testing framework? - What is Company ABC’s testing strategy? - What golden examples do we have available to reference? - How can I understand a new area of the code base to prepare for upcoming work? - What current resources and subject matter experts are available? - What does the data structure look like and how is it displayed to our users? - What do the tests say about how this code should work? These will be easy to address! Christine can search existing developer blog posts and technical guides on the internet. She can also use company resources and ask her coworkers for support. She schedules 30 minutes everyday, for the next two weeks, to investigate these questions. She also uses that time to practice what she learns. Christine does a walk through of the new area of code with Jerry, who is very familiar with the code. She now understands at a high level how that code works. She is prepared for the upcoming work. It's now time to estimate and plan the next increment of work with her team. Christine shares what she understands of the work and what she knows she still needs to learn. She also shares her new reduced capacity and that she will be taking 30 minutes everyday to learn and improve. The team strategizes about how to tackle that upcoming work. They decide a senior developer will pair with Christine. This plan will ensure that the work gets done on time. It also ensures she has immediate support in understanding the remaining code uncertainty. **How do experienced developers manage uncertainty?** The uncertainty grows as software developers progress in their career. The resources available to reduce that uncertainty shrink. And the type of uncertainty changes. Let's fast forward 10 years and Christine is now a senior developer tackling new problems. She is ready for the unknown. She is currently investigating how to integrate SMS into Company ABC’s mobile app. She suspects that delivering this project will require significant effort. To prepare for this project Christine starts to list out everything she doesn’t know. There are many techniques to identify and prioritize project uncertainty. One great way is story and assumption mapping explained by [Teresa Torres](https://www.linkedin.com/in/teresatorres) in her book [Continuous Discovery Habits](https://www.producttalk.org/2021/05/continuous-discovery-habits/). Christine generates her list by considering her past projects. The “surprises'' in other large projects were great learning opportunities. Checkout how [Jobber](https://getjobber.com/) learns from “surprises'' in [this article about Post Mortems](https://www.linkedin.com/pulse/incident-post-mortems-jobber-jesse-van-herk?trk=public_post-content_share-article). Christine also asks her Designer, her Product Manager and subject matter experts at Company ABC to refine and add to this list. SMS in the mobile app project: - How can we immediately show new SMS in the UI when user is looking at the app? Does our existing infrastructure enable this? - How can we send a push notification to our users when they receive a new SMS? - How can/should we track usage of SMS in the app? - How can we … Next Christine works with her team to identify the riskiest uncertainty in the list. These are questions that, if answered "no" or "not possible", would stop the project. They are often about the feasibility of a solution. By answering these questions up front the team won’t waste time on an impossible project. Christine schedules time for her team to answer these specific questions. The answers look promising so she then organizes a mini-hackathon. This is a time-boxed event for her team to build a working prototype as fast as possible. Christine and her team complete this work with a better understanding of the code. They also reduced some secondary uncertainties, including the decision on whether to use a library or build a UI to display SMS. And lastly, they add new uncertainties they discovered to the list. Christine can use what she now knows (and what she now knows she doesn't know) to better estimate and plan work. Her team estimates the work considering time to develop, resources and the remaining uncertainty. She assigns higher estimates to the parts of work with higher uncertainty. Next she provides a realistic project timeline to her stakeholders. The SMS in the mobile app project will take 3 to 4 months considering existing commitments. It's unrealistic to reduce all uncertainty up front. Christine plans to tackle the parts of the project with the highest uncertainty first. Christine and her team can inform their stakeholders about new discoveries as early as possible. Then together they can decide to adjust the project timelines or pivot to a different project. **Why is this important? ** Identifying, reducing, and planning for uncertainty allows companies to better compare projects. Companies can identify the higher leverage projects to work on now. Managing uncertainty well also allows teams to build and maintain trust with stakeholders. Christine has successfully delivered on her last two projects. Her stakeholders at Company ABC are confident she will meet her commitment with this new project. They can appropriately plan their own work around the 3 to 4 month timeline. To be successful like Christine, start accepting and welcoming the unknown. It’s in this uncertain space where important growth opportunities live.  **_How well do you manage the unknown?_** ## About Jobber We are hiring for remote positions across Canada at all software engineering levels!  Our awesome Jobber technology teams span across Payments, Infrastructure, AI/ML, Business Workflows & Communications. We work on cutting edge & modern tech stacks using React, React Native, Ruby on Rails, & GraphQL.  If you want to be a part of a collaborative work culture, help small home service businesses scale and create a positive impact on our communities, then visit our [careers site](https://getjobber.com/about/careers?utm_source=devto&utm_medium=social&utm_campaign=eng_blog) to learn more!
kkimble006
926,228
CSS can help improve your HTML⁉ - Ep 2: buttons and links.
Part 2 of using CSS to make our HTML better! In this second part of this series we will be exploring...
15,938
2021-12-15T13:07:06
https://dev.to/grahamthedev/css-can-help-improve-your-html-ep-2-buttons-and-links-21m9
html, css, a11y, tutorial
Part 2 of using CSS to make our HTML better! In this second part of this series we will be exploring how we can use CSS to ensure (and enforce) that we are using `<button>` and `<a>` elements correctly...you would be surprised how many developers get this wrong! If you missed part one you may need to have a quick read of that so you get the key concepts as I won't be repeating them in detail here: {% post https://dev.to/inhuofficial/using-css-to-prevent-html-errors-ep-1-alt-attributes-11o8 %} All caught up? Great! Before we start part 2, it is worth mentioning (reiterating) that this concept relies on two style sheets. One for production (and development) and one for development **only** (the one containing error messages). In the fiddles I have indicated which styles you would use in your **production** stylesheet and which to use in your **development** stylesheet! Right, with that reminder out of the way, let's begin! ## A button is a button! I know I keep saying it and I sound like a broken record but, a button is a button! {% post https://dev.to/inhuofficial/they-just-won-t-learn-a-button-is-a-lt-button-gt-accessibility-rants-k1b %} See, I told you I keep saying it! But what if we could guide our developers towards this logical conclusion using CSS? Well first thing is first, we can make it so our `.btn` class **only** works on a `<button>`. ``` css button.btn{} ``` Try and use the `.btn` class on anything else and it just won't work! but we can do better than that! What if we can also give our team a little bit of a warning to let them know they have used the wrong element? ``` css .btn:not(button){/* wrong element error highlighting */} ``` ### Meaningful warning and error messages Now while adding outlines to stuff that is wrong is great, it isn't very informative. Luckily we can fix that also! By using `:after` we can insert an error message So we end up with a selector to add an outline and another selector to add a warning that is the same but using the `:after` pseudo selector. By utilising the `content` property we can add a custom error message! ``` css .btn:not(button) /* outlines */ .btn:not(button):after /* error message */ ``` ### Example for buttons In this example we have a real button and a fake button made with a `<div>`. Notice how the real button works and the fake button has no styling as well as an error message! {% codepen https://codepen.io/inhuofficial/pen/BawWjKg default-tab=result, html, css %} ### Taking it one step further! I would argue that for most sites we can actually go one step further and completely do away with the `.btn` class on our buttons! This helps with consistency, looks neater and enforces our policy of `<button>`s for buttons! At this point we no longer even need an error check as we can only get styling on a `<button>`! We can do this by using the element as the selector `button{}`! ``` css button{ padding: 0.75rem; background-color: #333; color: #fff; margin: 2rem 0; border: 0; border-radius: 0.3rem; width: 100%; } ``` However this may have one unintended consequence... ### That's great, but we often style anchors like buttons! And that is a valid point and nowadays, you are right! However we can recycle our selector from the first part so we can have a `.btn` class **only** on anchors (`<a>`)! ``` css button, a.btn{/* our styles for buttons! */} ``` This does mean we have to reintroduce our error checks though, but this time to ensure that we only use the `.btn` class on an anchor! This raises an interesting question, do we want an error to show if we have a `.btn` class on a `<button>`? If we **do** then our error selector just needs a subtle change ``` css .btn:not(a){} .btn:not(a):after{} ``` This will add our error messages to `<button class="btn"`, which might be confusing. As it won't do any harm having the `.btn` class on a `<button>` (as we have no valid selector for it anyway) I would think it better to not show error messages in this instance. Yet again the power of CSS makes this relatively simple, we can add multiple items within our `:not` selector! ``` css .btn:not(a,button){} .btn:not(a,button):after{} ``` This is saying:- - select all items with the `.btn` class - that are not (`:not()`) - an anchor (`a`) - OR a button `,button` (comma seperated). ### Example including anchors Bringing everything together we end up with the following: {% codepen https://codepen.io/inhuofficial/pen/VwMperq default-tab=result, html, css %} Looks great, but we can go **even** further! ### But we only want valid anchors Now that we have allowed the `.btn` class to be added to anchors we have opened up another problem! The dreaded `<a href="#"` or `<a href="javascript: void()`! This anti-pattern has not been needed since HTML5 (you did read my rant on buttons I linked earlier didn't you?). So how can we fix this one? Well in part 1 we used attribute selectors `[attr]` and once again they can come to our rescue! As this is a site wide error (it should never be used!) we can ignore the `.btn` selector and just focus on anchors! The first one is easier to solve, we select any anchors with a `href="#"` (and while we are at it an empty `href` or missing `href` too!) ``` css a:not([href]), /* A missing href attribute! */ a[href=""], /* an empty (or null) href */ a[href="#"] /* the anti pattern! */ ``` That covers most of them, we just need to highlight the JavaScript anti-pattern! Yet again we covered this in part 1, we can use the "begins with" notation: ``` css a[href^="javascript:" i] ``` Remember the "i" at the end to make it case insensitive. We used the "begins with" `^=` syntax for this example as it doesn't have to be `javascript: void()`, this way we can capture all JavaScript `href`s no matter what function they call! ### Example for valid anchors! Utilising the same system of using `:after` we can add messages to our anchors as well! {% codepen https://codepen.io/inhuofficial/pen/wvrJMQM default-tab=result, html, css %} **Note:** We can make this much better by having separate message depending on whether the problem is a missing `href`, bad `href` or the use of JavaScript. I haven't done that in the example but you would do it as follows: ``` css a:not([href]):after{content: "missing href attr"} a[href="#"]:after{content: "anti-pattern on href detected"} a[href=""]:after{content: "empty or null href"} a[href^="javascript:" i]:after{content: "using javascript in href anti-pattern detected"} ``` ### Additional things to mention As pointed out by @ashleyjsheridan it is perfectly valid to have an anchor without a `href`. As such where I marked anchors with missing or empty `href` attributes as errors this was a mistake on my part. Instead these should be downgraded to "warnings" just to pick up on mistakes. Additionally this then means that if you use `<a name="sectionName">` for whatever reason it will only be a warning (although this is quite a dated way to do things as you can just give an element an `id` attribute and link to that instead). Overall it has no bearing though as the **development** style sheet will not impact production, might just be a little annoying though if you do edge case stuff like dynamically adding a `href` to an existing anchor. Additionally they mention: > Might also be worth considering the 3 <input> button types: button, submit, and reset. This is an excellent point, so to add those you would update the selector to target: ``` css button, a.btn, input[type="button"], input[type="submit"], input[type="reset"]{ /* can use the same default styling and overwrite with additional styles to differentiate as needed */ } ``` If you need to use those. ## Conclusion A lot of what we learned in part 1 has carried over to part 2. It is just that our selectors have become a little more complex. But hopefully you can see how this allows us to enforce business style guides once again (having or not requiring a `.btn` class on `<button>` elements for example). In the next part we are going to focus on document structure best practices and introduce some WAI-ARIA attributes and some tips and tricks with those! ## Thanks for Reading! Thanks for reading, I hope you enjoyed it! In fact to show my appreciation please do have a virtual ❤ and 🦄 to show how much it means to me! If you enjoyed this and want something just a *little* (OK a **lot** longer I have written) why not read my monster accessibility tips article: {% post https://dev.to/inhuofficial/101-digital-accessibility-tips-and-tricks-4728 %} Have a great week!
grahamthedev
926,305
Kotlin Coroutines 101
What is a coroutine? To put it simply, a coroutine is a way creating a suspendable code that can...
0
2021-12-14T15:26:16
https://dev.to/jimmymcbride/kotlin-coroutines-101-3adj
kotlin, android, mobile
What is a coroutine? To put it simply, a coroutine is a way creating a suspendable code that can run concurrently with code running on other threads. But what does that mean? Let's take a deeper look and see what coroutines have to offer us, what they are not, and where/when we would want to use them in the scope of an android project. First, let's define a couple things so that we're all on the same page. > **Thread** - A thread is a [sequential line of execution] in a program. The Java Virtual Machine > allows an application to have multiple threads of execution running concurrently. > [Source](https://developer.android.com/reference/java/lang/Thread) > **Concurrency** - The coordination and management of independent lines of execution. These > executions can be truly parallel or simply be managed by interleaving. They can communicate via > shared memory or message passing. > [Source](https://cs.lmu.edu/~ray/notes/introconcurrency/) > **Multithreading** - Execution of a program with multiple threads. > [Source](https://cs.lmu.edu/~ray/notes/introconcurrency/) > **Main-safe** - We consider a function main-safe when it doesn't block UI updates on the main thread. > [Source](https://developer.android.com/kotlin/coroutines#use-coroutines-for-main-safety) > **Suspend Function** - A function that could be started, paused, and resume. > [Source](https://www.geeksforgeeks.org/suspend-function-in-kotlin-coroutines/) ## Coroutine Scopes In the context of Android, we have 3 possible scopes for coroutines, each with their own specific behavior. That is global, lifecycle and viewmodel. ### Global Scope A coroutine launched in the global scope will live as long as the application. That makes it the least desirable scope in which to launch most coroutines. Launching a coroutine in the global routine, you can expect the following behavior: - If a coroutine finishes before the application is shut down, the coroutine will be destroyed and not live for the remainder of the applications life. (This is good.) - A coroutine launched in the global scope will continue to run through all lifecycle and activity changes. This means activity/fragment lifecycle changes will not cancel the coroutine. This isn't always desirable behavior for our app. Example: A coroutine that adds 1 to a counter every second will continue to count as the user rotates the screen and navigates through activities and fragments. While there may be use cases for using global scope, this shouldn't be your default choice and should only be used when necessary. You can gain access to using the global scope coroutine context with the following dependency in your modules build gradle: ```groovy implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2' ``` ### Lifecycle Scope A coroutine in the lifecycle scope, is bound to the lifecycle of the activity. So say we have a coroutine function that adds 1 to a counter every second. This counter will be reset if the user rotates the screen and onDestroy gets called. This coroutine will also be canceled when navigate to a new activity. We can gain access to the lifecycle scope in our projects by adding the following dependency: ```groovy implementation 'androidx.activity:activity-ktx:1.4.0' ``` ### ViewModel Scope When we use fragments, compose and in single activity apps having our coroutines last for the entire life of the activity becomes undesirable, for the same reason global scope is undesirable. In that case we can use the viewmodel scope. The viewmodel scope is effective because now our coroutines will only last as long as our viewmodel is alive. This means we can set up viewmodel's for each fragment or composable function that we want to limit our coroutines too. So if our composable functions and fragments that our viewmodel's are attached to die, so will our coroutines. If we want to use viewmodel scoped coroutines in our project, we can add the following dependency: ```groovy implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.0' ``` ## Practical Examples So now that we understand a little more about what's involved with coroutines and the various scopes in which we can run them in, let's play around with them a little so we can get a practical understanding of the can work in our application. For this post, I'm going to use lifecycleScope in the main activity of a new project, since we won't be using any viewmodel's today. Let's start with a simple example: ```kotlin class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) Log.d( TAG, "Pre lifecycleScope - onCreate, running on thread: ${ Thread.currentThread().name }" ) lifecycleScope.launch { Log.d(TAG, "LifecycleScope, running on thread: ${Thread.currentThread().name}") } Log.d( TAG, "Post lifecycleScope - onCreate running on thread: ${ Thread.currentThread().name }" ) } companion object { const val TAG = "KotlinCoroutines" } } ``` If we run our app, we'll see that our logs print out ``` Pre lifecycleScope - onCreate, running on thread: main LifecycleScope, running on thread: main Post lifecycleScope - onCreate running on thread: main ``` This is to be expected. Our code has run synchronously. But coroutines shine in areas where code takes some time to run. We can easily make our lifecycleScope.launch take more time by simply adding a delay, which is a suspended function and can only be called from a coroutine context or another suspended function. So now our lifecycleScope.launch should look something like this: ```kotlin lifecycleScope.launch { delay(3000L) Log.d(TAG, "LifecycleScope, running on thread: ${Thread.currentThread().name}") } ``` Now when we run our logs we will see: ``` Pre lifecycleScope - onCreate, running on thread: main Post lifecycleScope - onCreate running on thread: main ``` And three seconds later we will see `LifecycleScope, running on thread: main` pop up in our logs. What this means is that even through our lifecycle scope is running on the main thread, it did not block the main thread at all. So our code here can be considered main-safe. To further illustrate main-safety let's update the UI after the lifecycle scope block and see if the UI does indeed update before our delayed lifecycle scope is done running. (I have given the default textview in my activity_main.xml file an id of `tv_dummy`.) ```kotlin val dummyTextView = findViewById<TextView>(R.id.tv_dummy) Log.d( TAG, "Pre lifecycleScope - onCreate, running on thread: ${ Thread.currentThread() .name }" ) lifecycleScope.launch { delay(3000L) Log.d(TAG, "LifecycleScope, running on thread: ${Thread.currentThread().name}") } dummyTextView.text = "Hello, from after lifecycle scope!" ``` When we run this code, we will see that our UI immediately has the new text displayed in the textview, so our code is main-safe. But what if we want to make this code not main-safe? We can use something called run blocking. Run blocking gives us a coroutine scope that blocks the main thread until the code has been completed. So if we change our lifecycleScope.launch to a runBlocking scope: ```kotlin val dummyTextView = findViewById<TextView>(R.id.tv_dummy) Log.d( TAG, "Pre lifecycleScope - onCreate, running on thread: ${ Thread.currentThread() .name }" ) runBlocking { delay(3000L) Log.d(TAG, "LifecycleScope, running on thread: ${Thread.currentThread().name}") } dummyTextView.text = "Hello, from after lifecycle scope!" ``` We will observe that the UI is blank for 3 seconds before displaying the UI. That is because our runBlocking scope has stopped the UI from updating for 3 seconds until it lets our onCreate lifecycle finish. Our code is no longer main safe. ### Running Multiple Coroutines and Suspended Functions To explore a little further, let's see what happens when we try to launch more than one suspended function and coroutine at once. Let's start with just a suspended function first. ```kotlin suspend fun greet() { delay(3000L) Log.d(TAG, "Greetings from thread: ${Thread.currentThread().name}") } ``` Now we call this function from inside our lifecycle scope twice and see what happens. ```kotlin Log.d( TAG, "Pre lifecycleScope - onCreate, running on thread: ${ Thread.currentThread() .name }" ) lifecycleScope.launch { greet() greet() } Log.d( TAG, "Post lifecycleScope - onCreate running on thread: ${ Thread.currentThread() .name }" ) ``` Running this code logs `Pre lifecycleScope - onCreate, running on thread: main` and `Post lifecycleScope - onCreate running on thread: main` immediately when the application gets launched. Then, after 3 seconds `Greetings from thread: main` gets ran, followed by `Greetings from thread: main` again after another subsequent 3 seconds. This seems to make sense. Lifecycle scope is running both functions is sequence, each taking 3 seconds, making the full lifecycle scope launch take a total of 6 seconds to complete. But what happens if we add a lifecycle scope for the main thread inside the suspended function? Something like this: ```kotlin suspend fun greet() { lifecycleScope.launch { delay(3000L) Log.d(TAG, "Greetings from thread: ${Thread.currentThread().name}") } } ``` If we do this and run our code we will see our pre and post lifecycleScope logs logging right away when we start the app. However, 3 seconds later both greet functions will print at the same time, from the main thread. This is because even though they are running on the same main thread, the functions are able to be suspended an ran concurrently alongside each other since they have they are launched in their own lifecycle scope. This is pretty nifty. So, for example if we had 5 network requests that we wanted to run at the same time, we could launch them each in their own lifecycle scope to have them all fire off at approximately the same time without slowing anything down. Even so, we still don't want to clog up our main thread with a huge amount of long running and heavy computational tasks, because that could still slow down and clog up the main thread. Which leads us to our next topic, dispatchers. ## Dispatchers To divide up the workload, we can pass the context of the thread we want our code to run on with the use of dispatchers. There are 4 types of dispatchers that we can pass as context for our coroutine launch scopes. - Main: Used for UI operations and quick work such as calling suspend functions. - IO: Great for running network, database or disc operations. Think Input/Output. - Default: Best used for CPU-intensive work, like sorting or parsing giant lists of data. - Unconfined: This dispatcher isn't confined to any thread. Instead it executes the coroutine in the current scopes context and let's the coroutine resume in whatever thread that is used by it's suspended function and does not dictate which thread it needs to run on. When creating our coroutine scope launch, we can specify which thread we want it to launch, as well as using `withContext` to switch contexts of the thread your running code on in a current coroutine scope. Let's check out some examples below to see how this works. ```kotlin Log.d( TAG, "Pre lifecycleScope - onCreate, running on thread: ${ Thread.currentThread() .name }" ) lifecycleScope.launch(Dispatchers.Main) { Log.d( TAG, "LifecycleScope, context MAIN - running on thread: ${ Thread.currentThread() .name }" ) withContext(Dispatchers.IO) { Log.d( TAG, "LifecycleScope, context IO - running on thread: ${ Thread.currentThread() .name }" ) } } Log.d( TAG, "Post lifecycleScope - onCreate running on thread: ${ Thread.currentThread() .name }" ) ``` Will result in the following logs: ``` Pre lifecycleScope - onCreate, running on thread: main Post lifecycleScope - onCreate running on thread: main LifecycleScope, context MAIN - running on thread: main LifecycleScope, context IO - running on thread: DefaultDispatcher-worker-2 ``` So we can see here that we choose `Dispatchers.Main` in our lifecycle scope, everything is the same, but once we switch the context to IO we can see our code running on a separate thread. ## Recapping So today we've learned about: - Key definitions to understand coroutines. - Different coroutine scopes in Android. - Practical examples about the behavior of coroutines. - Coroutine dispatchers and running code on different threads. There is obviously a lot more to learn about coroutines, from jobs to async await and edge case behavior, but we can learn more about that in a later post. What areas of coroutines would you like to explore together next? Leave a comment below with your thoughts, constructive feedback, or any corrections to explanations/examples. Thanks for reading, happy coding!
jimmymcbride
926,347
How to create an awesome Github README
Versão em PT-BR aqui. Introduction Github is the most popular service used by...
0
2021-12-14T16:30:12
https://dev.to/akadot_/how-to-create-a-awesome-github-readme-4mb4
github, readme, markdown
> Versão em PT-BR [aqui.](https://dev.to/akadot_/como-criar-um-readme-para-o-seu-perfil-do-github-404n) ## Introduction **Github** is the most popular service used by developers in the world, or following the company slogan _"Where the world builds software"_. But, in addition to all the features, you can also, Github can be considered a **developer's social network** and just like all networks, its interessting you have a good profile in your main page. So, you can create a _"profile readme"_, a file with the same name that your **@**, it's fully custom and you can use **Markdown** and **HTML** to do this. Today I'll show you hot to write a cool personal readme file for your profile, with a lot of integrations and features, like [this](https://github.com/akadot/akadot). _OBS.: There is a lot of ways to do this, I'll just explain some of them today, but I'll let some usefull links to others options._ ## Let's Start To active this resource, you just need to create a repository with the same name of your **@** and create a READE.md file inside: ![My Repo Readme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/za6s11voi3z426jkacn8.png) ![My Repo Readme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3356pcooemkm0bkwri21.png) Now, you can open the file to start to put your readme code. If you never worked with Markdown files, you can follow this [guide here](https://docs.pipz.com/central-de-ajuda/learning-center/guia-basico-de-markdown#open). There are a lot of models to your README, I'll let some examples bellow to get you inspired: [Awesome GitHub Profile README](https://github.com/abhisheknaiidu/awesome-github-profile-readme) [Awesome GitHub Profile README Template Collection](https://github.com/durgeshsamariya/awesome-github-profile-readme-templates) ### Badges You can add **Badges** in your profile to represent your social medias, your technologies of interest, your tools, etc. The best website to get or generate a custom badge is [Shields.io](https://shields.io/). Also, there are two others very cool repositories with a copy and paste system, to you get your badges: [Markdown Badges](https://github.com/Ileriayo/markdown-badges) by [Ileriayo Adebiyi](https://github.com/Ileriayo) [Badges](https://github.com/aleen42/badges) by [Aleen](https://github.com/aleen42) You can also add your tecnologies as a simple image, following this repo: [Tech-Icons](https://github.com/Workshape/tech-icons) by [Workshape.io](https://github.com/Workshape) All of the ways will generate a line of code that you can copy and paste in your README. ### Stats Another cool feature to you add on your profile, is your **statistics** (numbers of commits, techs more used, pull requests, etc). Just like the badges, you just need to put a line of code inside your file, following the repository tutorial: [GitHub Readme Stats](https://github.com/anuraghazra/github-readme-stats) by [Anurag Hazra](https://github.com/anuraghazra) [Waka Readme Stats](https://github.com/anmol098/waka-readme-stats) by [Anmol Pratap Singh](https://github.com/anmol098) - **It is necessary to create an account** ### Integrations In addition to "decorations" and styles, you can also integrate other services in your profile, I'll leave the most common and popular ones below: **Discord** - [Discord Banner](https://github.com/dgibbs64/discord-banners) - you will need to access your discord profile, activate developer mode, and redeem your API Key to make this integration. **Spotify** - [Spotify Github Profile](https://github.com/kittinan/spotify-github-profile) - just click the Connect with Spotify button and enable the integration. **DEV.to** - [Latest Post](https://github.com/gautamkrishnar/blog-post-workflow) ### Images You can add images and animations on your profile too, this can be do using the native Markdown resource (just create a folder to upload the images and reference them). But there are some cool alternatives too: [Readme Typing SVG](https://github.com/DenverCoder1/readme-typing-svg) [README Header Image Generator](https://github.com/khalby786/REHeader) Ok, now you can create an awesome Github Readem Profile, please share the link in comments if you want. I hope you enjoyed it, see you. ✌️
akadot_
926,554
Application error An error occurred in the application and your page could not be served. in heroku
...
0
2021-12-14T18:35:25
https://dev.to/com_ashwin/application-error-an-error-occurred-in-the-application-and-your-page-could-not-be-served-in-heroku-2idh
django, heroku, python, html
{% stackoverflow 70323095 %}
com_ashwin
926,579
Car booking ( React-Redux)
Last week I found an old repository from a university project on GitHub, and I decided to give this...
0
2021-12-14T19:31:44
https://dev.to/aom19/new-project-3afh
webdev, react, career, design
Last week I found an old repository from a university project on GitHub, and I decided to give this 'little boy ' a new aspect. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b84c04aou490yq2xtds1.png) ## I started by adding: Home page: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lvj3i76bs3ykf454xiyn.png) Contact page: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2s158awf7k1czi7eoht2.png) About page: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6icppwwdl71llbyt8u73.png) manage state with Redux: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bil9ydhvnci71iswwg4q.png) For more check : old project: https://github.com/aom19/ProjectBD new one: https://github.com/aom19/rentCar Next step: Remove Redux and manage state with Apollo Client 🤛 🤓
aom19
926,711
Connecting High School Students to Internships - Interniac
Given how competitive University admissions are and how often the average University student changes...
0
2021-12-14T22:20:43
https://dev.to/christianstefaniw/connecting-high-school-students-to-internships-interniac-1m1g
django, webdev, python, opensource
Given how competitive University admissions are and how often the average University student changes majors due to career confusion, getting a high school internship is more valuable than ever before. However, pre-university work experience is difficult to come by and oftentimes opportunities are given to students who have strong networks (either through a parent or their school). Today, there is no platform through which high school students all over the country can find an internship on their own. We aim to build a platform that supports high schoolers attending public schools and empowers businesses in hiring bright students. Interniac fills the gap in our education system by simplifying the process for employers to start internship programs and source candidates who are eager to gain valuable out-of-the-classroom work experience. Our mission is to bring you opportunities, whether that be an internship or a chance to speak to professionals in the field you are interested in. We strive to help you build your future. Join our platform to learn more about what opportunities Interniac can offer you! Please check out this OPENSOURCE project here and don’t forget to leave a star! https://www.github.com/interniac/Interniac-website
christianstefaniw
926,728
Read Lock vs Write Lock
A lock is a synchronization primitive which limits access to a shared resource among multiple...
0
2021-12-14T22:42:17
https://dev.to/wasinaseer/read-lock-vs-write-lock-5181
lock, multithreading, concurrency
A lock is a synchronization primitive which limits access to a shared resource among multiple threads. We don’t need locks when only one thread is running or there is no shared resource because lock is always acquired on a shared resource. Let’s look at what locks can be acquired. ## Read Lock Multiple threads can acquire read lock at the same time. However, while holding the lock, they can only read the data. Also, no other thread can update the data while the read lock is acquired. In other words, during the period of holding the read lock on data, it’s guaranteed that the data haven’t been changed by any thread. ## Write Lock Write lock can be acquired by only one thread at a time. During the lock holding period, the thread can read or write data. If a write lock has been acquired, no other threads can read the data or acquire a read lock on the data. In short, during the period of holding the write lock on data, it’s guaranteed that the data haven’t been read or changed by any thread. Write lock is more strict than the read lock and ensures better synchronization. In a multithreaded application, we usually go for the read lock if we’re only reading data and taking decisions based on the read data. That’s why we need to ensure that whatever we have read for taking the decisions must be true until the processing has been done and a response has been sent to the client.
wasinaseer
926,767
AR Engine and Scene Kit Deliver Virtual Try-On of Glasses
Background​ The ubiquity of the Internet and smart devices has made e-commerce the...
0
2021-12-15T02:13:34
https://dev.to/hmscore/ar-engine-and-scene-kit-deliver-virtual-try-on-of-glasses-2man
##Background​ The ubiquity of the Internet and smart devices has made e-commerce the preferred choice for countless consumers. However, many longtime users have grown wary of the stagnant shopping model, and thus enhancing user experience is critical to stimulating further growth in e-commerce and attracting a broader user base. HMS Core offers intelligent graphics processing capabilities to identify a user's facial and physical features, which when combined with a new display paradigm, enables users to try on products virtually through their mobile phones, for a groundbreaking digital shopping experience. ##Scenarios​ AR Engine and Scene Kit allow users to virtually try on products found on shopping apps and shopping list sharing apps, which in turn will lead to greater customer satisfaction and fewer returns and replacements. ##Effects​ A user opens an shopping app, then the user taps a product's picture to view the 3D model of the product, which they can rotate, enlarge, and shrink for interactive viewing. ![Image description](https://forum.xda-developers.com/attachments/1-gif.5479105/) ##Getting Started​ **Configuring the Maven Repository Address for the HMS Core SDK** Open the project-level build.gradle file in your Android Studio project. Go to buildscript > repositories and allprojects > repositories to configure the Maven repository address for the HMS Core SDK. ``` buildscript { repositories{ ... maven {url 'http://developer.huawei.com/repo/'} } } allprojects { repositories { ... maven { url 'http://developer.huawei.com/repo/'} } } ``` **Adding Build Dependencies for the HMS Core SDK** Open the app-level build.gradle file of your project. Add build dependencies in the dependencies block and use the Full-SDK of Scene Kit and AR Engine SDK. ``` dependencies { .... implementation 'com.huawei.scenekit:full-sdk:5.0.2.302' implementation 'com.huawei.hms:arenginesdk:2.13.0.4' } ``` For details about the preceding steps, please refer to the development guide for [Scene Kit](https://developer.huawei.com/consumer/en/doc/development/graphics-Guides/integrating-sdk-0000001063754635) on HUAWEI Developers. **Adding Permissions in the AndroidManifest.xml File** Open the AndroidManifest.xml file in main directory and add the permission to use the camera above the <application line. ``` <!--Camera permission--> <uses-permission android:name="android.permission.CAMERA" /> ``` ##Development Procedure​ **Configuring MainActivity** Add two buttons to the layout configuration file of **MainActivity** . Set the background of the onBtnShowProduct button to the preview image of the product and add the text **Try it on** ! to the onBtnTryProductOn button to guide the user to the feature. ``` <Button android:layout_width="260dp" android:layout_height="160dp" android:background="@drawable/sunglasses" android:onClick="onBtnShowProduct" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Try it on!" android:textAllCaps="false" android:textSize="24sp" android:onClick="onBtnTryProductOn" /> ``` If the user taps the onBtnShowProduct button, the 3D model of the product will be loaded. After tapping the onBtnTryProductOn button, the user will enter the AR fitting screen. **Configuring the 3D Model Display for a Product​** 1.Create a SceneSampleView inherited from SceneView. ``` public class SceneSampleView extends SceneView { public SceneSampleView(Context context) { super(context); } public SceneSampleView(Context context, AttributeSet attributeSet) { super(context, attributeSet); } } ``` Override the surfaceCreated method to create and initialize SceneView. Then call loadScene to load the materials, which should be in the glTF or GLB format, to have them rendered and displayed. Call **loadSkyBox** to load skybox materials, **loadSpecularEnvTexture** to load specular maps, and loadDiffuseEnvTexture to load diffuse maps. These files should be in the DDS (cubemap) format. All loaded materials are stored in the **src > main > assets > SceneView** folder. ``` @Override public void surfaceCreated(SurfaceHolder holder) { super.surfaceCreated(holder); // Load the materials to be rendered. loadScene("SceneView/sunglasses.glb"); // Call loadSkyBox to load skybox texture materials. loadSkyBox("SceneView/skyboxTexture.dds"); // Call loadSpecularEnvTexture to load specular texture materials. loadSpecularEnvTexture("SceneView/specularEnvTexture.dds"); // Call loadDiffuseEnvTexture to load diffuse texture materials. loadDiffuseEnvTexture("SceneView/diffuseEnvTexture.dds"); } ``` 2.Create a SceneViewActivity inherited from **Activity** . Call setContentView using the **onCreate** method, and then pass SceneSampleView that you have created using the XML tag in the layout file to **setContentView** . ``` public class SceneViewActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sample); } } ``` ``` <com.huawei.scene.demo.sceneview.SceneSampleView android:layout_width="match_parent" android:layout_height="match_parent"/> ``` 3. Create an **onBtnShowProduct** in MainActivity. When the user taps the onBtnShowProduct button, **SceneViewActivity ** is called to load, render, and finally display the 3D model of the product. ``` public void onBtnShowProduct(View view) { startActivity(new Intent(this, SceneViewActivity.class)); } ``` **Configuring AR Fitting for a Product** Product virtual try-on is easily accessible, thanks to the facial recognition, graphics rendering, and AR display capabilities offered by HMS Core. 1. Create a** FaceViewActivity** inherited from **Activity**, and create the corresponding layout file. Create **face_view** in the layout file to display the try-on effect. ``` <com.huawei.hms.scene.sdk.FaceView android:id="@+id/face_view" android:layout_width="match_parent" android:layout_height="match_parent" app:sdk_type="AR_ENGINE"></com.huawei.hms.scene.sdk.FaceView> ``` Create a switch. When the user taps it, they can check the difference between the appearances with and without the virtual glasses. ``` <Switch android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/switch_view" android:layout_alignParentTop="true" android:layout_marginTop="15dp" android:layout_alignParentEnd="true" android:layout_marginEnd ="15dp" android:text="Try it on" android:theme="@style/AppTheme" tools:ignore="RelativeOverlap" /> ``` 2. Override the **onCreate** method in **FaceViewActivity** to obtain FaceView. ``` public class FaceViewActivity extends Activity { private FaceView mFaceView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_face_view); mFaceView = findViewById(R.id.face_view); } } ``` 3. Create a listener method for the switch. When the switch is enabled, the loadAsset method is called to load the 3D model of the product. Set the position for facial recognition in **LandmarkType** . ``` mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mFaceView.clearResource(); if (isChecked) { // Load materials. int index = mFaceView.loadAsset("FaceView/sunglasses.glb", LandmarkType.TIP_OF_NOSE); } } }); ``` Use **setInitialPose** to adjust the size and position of the model. Create the **position, rotation**, and **scale** arrays and pass values to them. ``` final float[] position = { 0.0f, 0.0f, -0.15f }; final float[] rotation = { 0.0f, 0.0f, 0.0f, 0.0f }; final float[] scale = { 2.0f, 2.0f, 0.3f }; ``` Put the following code below the **loadAsset** line: ``` mFaceView.setInitialPose(index, position, scale, rotation); ``` 4. Create an onBtnTryProductOn in MainActivity. When the user taps the **onBtnTryProductOn** button, the FaceViewActivity is called, enabling the user to view the try-on effect. ``` public void onBtnTryProductOn(View view) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( this, new String[]{ Manifest.permission.CAMERA }, FACE_VIEW_REQUEST_CODE); } else { startActivity(new Intent(this, FaceViewActivity.class)); } } ``` ## References​ For more details, you can go to: AR Engine [official website](https://developer.huawei.com/consumer/en/hms/huawei-3d-modeling/?ha_source=hms1); Scene Kit [official website](https://developer.huawei.com/consumer/en/hms/huawei-scenekit/?ha_source=hms1) [Reddit](https://www.reddit.com/r/HMSCore/) to join our developer discussion [GitHub](https://github.com/HMS-Core/hms-AREngine-demo) to download sample codes [Stack Overflow](https://stackoverflow.com/questions/tagged/huawei-mobile-services?tab=Votes) to solve any integration problems
jacksssson
926,869
Self-Taught Developer Journal, Day 18: TOP Landing Page Cont.: Beginning the Third Section
Today... Thinking Through The Odin Project Landing Page cont. I noticed some of the...
16,004
2021-12-15T04:17:10
https://dev.to/jennifertieu/self-taught-developer-journal-day-18-top-landing-page-cont-beginning-the-third-section-1aan
webdev, beginners, codenewbie, devjournal
Today... ## Thinking Through The Odin Project Landing Page cont. ![The Odin Project Project Landing Page Full Design Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qcwlb2cle80pmz7kpksx.png) I noticed some of the elements of second section were overlapping the elements of the third section. Immediately, I knew it was because I was using my laptop instead of my usual monitors. To fix this, I removed height:30vh and changed it to adding a margin-bottom at 10%. Now, the space between the second and third section should always be separated by the margin. I thought this bug was a good way to learn (and reminder to myself) to not only pay attention to the appearance, but also how the elements of the HTML documents are relative to each other. ![Second Section Overlap](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/av8heq41qg616i3jcf7l.png) Next, I selected the quote-section and set the background color to gray. I replaced the lorem ipsum text with the quote from the Odin Project example and set the quote text style. ![Third Section Quote](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wa5jefqajtf7ht9nyghl.png) I'm going to end it here today to try and catch up on some sleep. To be continued. ## Resources [The Odin Project Landing Page Project](https://www.theodinproject.com/paths/foundations/courses/foundations/lessons/landing-page) Day 17: https://dev.to/jennifer_tieu/self-taught-developer-journal-day-17-top-landing-page-cont-completing-the-second-section-5h0p Please refer to [Starting My Self-Taught Developer Journey]( https://dev.to/jennifer_tieu/starting-my-self-taught-developer-journey-2dga) for context.
jennifertieu
926,909
Create a simple web app with Python and flask in 10 minutes
Hello, world! Today, I would be creating a simple python web application with Flask, a microframework...
0
2021-12-15T07:11:30
https://dev.to/arjunpraveen2008/create-a-simple-web-app-with-python-and-flask-in-5-minutes-22kd
python, webdev, flask, programming
Hello, world! Today, I would be creating a simple python web application with Flask, a microframework for creating full-fledged web applications. I will be covering this topic with Flask since it is an intermediate + beginner tutorial, where anyone with no prior experience can follow along. > ## Before we move on... >This tutorial assumes that you have Python installed in your Mac or PC (*required*) and that you have done [object-oriented programming](https://www.w3schools.com/python/python_classes.asp) in Python before. These prerequisites (except the former one) are _recommended but not required_. ## What is Flask? 1. Flask is a micro web framework written in Python. 2. It is classified as a microframework because it does not require particular tools or libraries. 3. It has no database abstraction layer, form validation, or any other components where pre-existing third-party libraries provide common functions. (Source: [wikipedia](https://en.wikipedia.org/wiki/Flask_(web_framework))) ![Flask logo banner](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wlssytoezalpr9q7f5k2.png) --- ## Installation It is always recommended to create a new directory as your project folder, and that you have activated a [virtual environment](https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/) (optional). > **Via Pip** - `pip install Flask` (See [this](https://pypi.org/project/Flask/) for specifications.) > **Via Conda** - `conda install -c anaconda flask` (See [this](https://anaconda.org/anaconda/flask) for specifications.) To check whether Flask has been successfully installed on your Mac or PC, type in `flask --version`. If getting an error, try using `python -m flask --version` or `python3 -m flask --version`. If none of the above commands work for you, you can directly run your app instead of running it from the terminal or command prompt (more on that later). Hmm...Seems like a handful of configurations, but these are only necessary for the first time when you install flask. (Not meant for people using [virtual environment](https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/)). ![Installation of Flask](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/up845oz1x8n0fz57n0xd.png) ## Our first Flask app Now, it's time to create our flask app; create a new file in the project directory and name it "app.py". This file contains the back-end code for our application. As a starter template, type in this code: ```python # app.py from flask import Flask app = Flask(__name__) @app.route('/') def index(): return "Hello, world!" # Omittable if __name__ == "__main__": app.run(debug=True) ``` ## Code lines explained (for newbies) `from flask import Flask` - seems a bit strange that you have to import Flask, again from flask? What is happening here is that you are importing a class named **"Flask"** (capitalized) from the actual module that we installed before, named **flask**. `app = Flask(__name__)` - Here, we are instantiating the Flask class and declaring it in a variable named "app"; this app variable is the main structure of our app that can handle routes, run the app, debug it, etc. The extra parameter that we give to the Flask class (_____name_____) just checks whether we are in an application package, or just an individual module. (Learn more [here](https://blog.miguelgrinberg.com/post/why-do-we-pass-name-to-the-flask-class)). ` @app.route('/') ` - Now, this is a Python [decorator](https://www.geeksforgeeks.org/decorators-in-python/). Here, we are defining a route (If you are already familiar with web programming and have used any web frameworks for this purpose, you might be familiar with routes as well). A route is a simple way of telling the server to create a specific path in the app, so that the users will be able to visit it via a web browser. For the purpose of demonstration, consider these routes as a pathway where users can walk through. A web app can contain multiple routes, and each route is prefixed with a forward slash "/". If you visit a URL, most of the times the default route will be "/" (For example, " dev.to/", " google.com/"). Other examples include: - /search - /login - /signup - /posts/abcd (This is a nested route, having a route inside another route) - /greet?name=John+Smith (A route with a URL parameter "name" and its value set to "John Smith") `def index(): return "Hello, world!"` - This line of code defines a function named **index** and the above decorator installs this function to the app instance of Flask class, then this function returns "Hello, world!" which would be displayed in the user's browser as an HttpResponse. Next lines of code can be omitted if the `flask --version` commands worked in your terminal window. These lines just run the app, only if the user is actually running the "app.py" file and not when importing the file from somewhere else. ## Running the app To run our app, just type in `flask run` to run it via the terminal window or command prompt (in Windows), or just run the python file to run it directly (`python app.py`). **Hurray!** Our app has been run, now you can visit [localhost:5000](localhost:5000) in your favorite browser to see our app up and running! > Note: Try changing the value of "Hello, world!" in the 8th line to see the result being reflected on the browser. ## Some HTML, perhaps? Ok, now it's time to write some HTML and make our app look a bit nicer. Our app only returns "Hello, world!" since, which no one would like to stay with. You can also add inline HTML to the string provided (For example, `return "<h1>Hello!</h1>"`), but that isn't the way to do it. The following steps show you how to add an html file to the server and display it to the user to make it an actual web app. Create a new folder named _templates_ in the project directory; inside of it, create a new file named "index.html". Then, inside "index.html": ```html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>Hello, world!</title> </head> <body> <h1>Hello, world</h1> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> </body> </html> ``` >Note: I've added additional Bootstrap CDN to style our web app. Now, in our Python code, change the `from flask import Flask` to something like: ```python from flask import Flask, render_template ``` This is done to make sure that we import a function named 'render_template' which returns an **HTML template** as an HttpResponse. Then, change the `return "Hello, world!"` to something like: ```python return render_template('index.html') ``` The above is self-explanatory. It just returns _index.html_ whenever someone visits the "/" route. >Note: if you are using the command `flask run`, you may have to stop the server (<kbd>Ctr + C</kbd>) and rerun it to see the changes. ## Challenge: More routes Now, our app is just serving one route, but we can add more routes to make it more sophisticated: ```python # app.py from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/greet') def greet(): return render_template('greet.html') # Omittable if __name__ == "__main__": app.run(debug=True) ``` This creates another route named "greet", and returns another HTML file "greet.html". Try creating the "greet.html" file in the templates folder and visiting [localhost:5000/greet](localhost:5000/greet) to see the newly created file! ## Serving static? CSS, JS and Assets (like images, video clips, SVG, etc.) files never change dynamically - so these can be called as static files. Create a new folder in the project directory named "static", and inside of it, you can place all your static files. One more tweak in the "app.py" file, and you are ready to go. ```python from flask import Flask, render_template, url_for ``` When linking static files, consider adding this way: ```html <link rel="stylesheet" href="{{url_for('static', filename='style.css')}}"> ... <script src="{{url_for('static', filename='script.js')}}"></script> ``` `{{}}` are Jinja syntaxes. Now, Jinja is a templating language used by Flask to serve dynamic pages. ## Dynamic pages? Pages that can change its content dynamically according to the data entered by the user are called dynamic pages. These can be easily created by passing in the values (to be dynamically displayed) in the `render_template` function, like: ```python return render_template('index.html', name="Brian") ``` This can be called from the "index.html" like: ```html <h1>Hello, {{name}}!</h1> ``` ## Conclusion Congrats, you've created and run your first Flask app! > If you are having any queries or suggestions related to this topic, feel free to mention it in the comments below, and I will try my best to reply for the same! Flask is an amazing platform to get started with web programming. Possibilities are endless with Flask, and you can do a lot more than the details listed in this article. There are a lot of tutorials on the internet that can provide you with the finest materials for creating more advanced projects, and I too soon will be posting a tutorial for creating advanced apps in Flask; this was just a beginning. I will also post an article on how you can host your web app on Heroku for free. Till then, bye 🖐!
arjunpraveen2008
927,014
Password Generator - PHP
Let's start. We want to create a strong password and control its size. Let's see the next code. I...
0
2021-12-15T08:25:48
https://dev.to/morcosgad/password-generator-php-238h
php, laravel, programming, beginners
Let's start. We want to create a strong password and control its size. Let's see the next code. I hope it helps you and use it in your projects ```php $lowercase = range('a','z'); $uppercase = range('A','Z'); $digits = range(0,9); $special = ['!','@','#','$','%','^','&','*']; $ch = array_merge($lowercase, $uppercase, $digits, $special); $length = 8; $password = array(); for($i = 0; $i <= $length; $i++){ $int = rand(0, count($ch) - 1); array_push($password, $ch[$int]); } echo implode("",$password); ``` I hope you enjoyed the code Source :- https://www.youtube.com/watch?v=Cv3MmZpxQvM
morcosgad
927,057
Blazingly fast Preview Environments for NextJS, NodeJS, and MongoDB on AWS
Introduction Have you ever dreamed of deploying your applications on the cloud without any...
0
2021-12-15T10:00:59
https://dev.to/pjeziorowski/blazingly-fast-preview-environments-for-nextjs-nodejs-and-mongodb-on-aws-o1k
webdev, node, mongodb, react
## Introduction Have you ever dreamed of deploying your applications on the cloud without any hassle? Imagine a platform where all you need to do is to sign in with your AWS credentials, and automagically the platform does all the hard work of configuration of the cloud for you, and, on top of that, provides some extra features that do not exist out of the box anywhere else. Qovery is this platform - not only does it allow you to deploy your infrastructure and applications on your own cloud account, but also provides extra cool features, one of which we will see in this article. *Don't take our words for granted - 14000 developers from more than 100 countries use Qovery to deploy their apps on AWS.* ### Preview Environments Imagine working on a new feature. You're dealing with a full-stack application - you have a frontend, backend, and a database. You introduce a change to your backend app - how do you test all of it? It would be great if there was a service that could deploy everything for you so you can test your changes quickly and in separation with all the components... Qovery Preview Environments are designed to help you with exactly this. It not only deploys the app you changed but all other related applications and databases as well in the cloud so that you can test your new features and collaborate with reviewers of your code. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dvhsaudl4xqvxuw3rmnn.png) Preview environments feature is available on other platforms as well. Vercel and Netlify allows you to test your changes before merging code into production. It’s perfect for single frontend applications, but the concept of Preview Environments on Qovery goes far beyond this. Qovery is able not only to create a preview environment for your frontend, but also for the backend and databases - the whole stack is supported. Running a set of backend microservices? No worries, Qovery got you covered. All services will be replicated in the new environment. ### Preview environments benefits - **Time-saving** - You don't have to set up a fresh environment to test changes in isolation - Qovery does it all for you - **Productivity** - Faster changes, quicker review, better feedback loop - the productivity and quality of your application increases dramatically - **Better tests** - It's best to test apps in isolation, but it's almost impossible with a complicated stack if you have to prepare the testing environment manually - Qovery does it all "automagically" for you - **Independence** - Each environment is completely separate, meaning more people can work flawlessly on the project, testing the changes they introduce in parallel, not blocking each other - **Deliver quickly** - Faster feedback loop, independent developers, fewer bugs, meaning the product is delivered more quickly - **Reduce friction** - Waiting for others to test your changes is frustrating - with preview envs everyone has his own testing environment ## Demo ### AWS Infrastructure Before we start with the deployments, we need to have our AWS infrastructure ready and deployed. It can be done as simply as by providing credentials to your cloud account, you can see how to configure the credentials in this article - [https://hub.qovery.com/docs/using-qovery/configuration/cloud-service-provider/amazon-web-services/](https://hub.qovery.com/docs/using-qovery/configuration/cloud-service-provider/amazon-web-services/) ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/04ilry028dda5tk13pu3.png) The initial setup takes about 15 min, and your cluster is ready to host your applications. ### Full Stack Application In this example, we will use a Next.js frontend, Node.js backend, and MongoDB as a database. The app will display an image gallery with images fetched from the backend. Preview Environments feature will help us introduce a new change in the backend - moving away from a hardcoded POC list of images to a list fetched from our database. ### Frontend Our simple image gallery will look like this ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3k56v3eqfatdm7zkim24.png) To generate the application, we used `npx create-next-app@latest`, but the source code can be found here - [https://github.com/pjeziorowski/gallery-demo/tree/master/frontend](https://github.com/pjeziorowski/gallery-demo/tree/master/frontend) The main changes introduced to the generated application scaffolding are: - Adding a `Dockerfile` ```docker FROM node:alpine RUN mkdir -p /usr/src WORKDIR /usr/src COPY . /usr/src RUN npm install RUN npm run build EXPOSE 3000 CMD npm run start ``` - Adding a query to our backend (which we will be built soon in the next steps) that fetches a list of images to display in our gallery ```jsx function useImages() { return useQuery("images", async () => { const { data } = await axios.get( `${apiRoot}/api/v1/images` ); return data; }); } ``` - Plus, we adjusted the HTML and styling for the demo purpose of showing a list of images ### Backend Our backend is the main star of the demo. In its first version, the backend is displaying a hardcoded list of images. In the next step, we will gradually expand its capabilities. It will connect to a database and fetch the list from MongoDB instead. To make sure the changes are correct, we will use `Preview Environment` feature before merging the pull request to our production environment The backend was generated using Express `npx express-generator --no-view`, and the source code can be found here - [https://github.com/pjeziorowski/gallery-demo/tree/master/backend](https://github.com/pjeziorowski/gallery-demo/tree/master/frontend) Changes that we introduced to the generated app scaffolding are the following: - Adding a Dockerfile ```docker FROM node:16 WORKDIR /usr/src/app COPY package*.json ./ RUN npm install COPY . . EXPOSE 8080 CMD [ "node", "src/index.js" ] ``` - Creating a `/api/v1/images` endpoint that returns a hardcoded array of images ```jsx router.get('/images', (req, res) => { res.json([ { title: 'IMG_4985.HEIC', size: '3.9 MB', source: 'https://images.unsplash.com/photo-1582053433976-25c00369fc93?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=512&q=80', } }); }); ``` In the next step we will improve the function to use a Mongo database instead. ### Deployment After creating a new project, let's now set up our `production` environment. First, let's deploy our frontend. Click `Add my first application`, select a correct repository, `Docker` as build mode and expose port `3000`. The application root path is `/frontend`. Next step: add a `MongoDB` database - it will be used by our backend later on. You can do so by clicking on `Add` button in Qovery Console in Environment. Now let's deploy our backend. Click `Add` → `Application`, pick up `/backend` as application root path, `8080` port, and `Docker` build mode. For the future connection to DB, let's add an alias named `DATABASE_URL` that points to our Mongo database internal URL in our backend `Environment Variable` settings: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hjh1gf92i7feako2fpig.png) Additionally, let's create an alias called `API_ROOT` in our frontend application that points to our backend external URL: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vuf8ugubrao052hz48nq.png) This is it! Now we can deploy our production environment. After a few minutes, navigate to the frontend app, click on `Open` - you should be redirected to the image gallery ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3uyy1wn6aao02wx6wevn.png) ### Enable Preview Environments The next step to see the preview environment feature in action is to enable it for our backend application. To do so, navigate to `Environment` → `Settings` → `Preview Env` and tick it for the backend app ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aalevwhxkrxm8th41f28.png) Great! The feature is enabled. To see it in action, let's edit our code in the backend app so that the list of images is fetched from the database instead. ### Testing Preview Environments Let's make a small update of our backend - let's connect to MongoDB and fetch images from there. Here are changes to the function we could introduce to make it happen: ```jsx const databaseUrl = process.env.DATABASE_URL || 'mongodb://localhost:27017/test'; const imageSchema = new mongoose.Schema({ title: String, size: String, source: String }); mongoose.connect(databaseUrl); router.get('/', (req, res) => { imageSchema.find().then((data) => { res.json( data ) }); }); ``` Let's now create a new branch in our repository and create a pull request to our production (master branch) environment. Preview Environments feature will spin up a new environment for us so that we can safely test changes we just introduced! ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a8z9a6unj4zgjgj9atbe.png) Now, when we display environments in our project, we will see that a new environment for the pull request is being deployed: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kdg8dtj44r9vk0do92cv.png) with all the resources we need! A database, backend, frontend - we can now test our changes in complete separation from the production without any manual setting up work: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pteka2uluhf2pgy9rxf8.png) ### Preview Environment Explained The Preview Environment feature can be enabled or disabled per app. It creates a complete copy of your environment so that you can test new changes from pull requests in separation. It deploys your databases, backend, and frontend applications to a completely new environment once a pull request is opened. If you update your pull request, all new changes are also reflected in the new environment so that you can test them or fix problems during the review. What is great is that Qovery takes care of managing all environment variables for you as well, creates new aliases just as you had in your prod environment, so that everything is really tested separately and it all happens automagically. After the pull request is merged, Qovery automatically cleans up the preview environment to save your money. ### Testing Preview Environments PT II After a few minutes, your preview environment should be up and running. You can now navigate to the frontend app and click `Open` - in the image gallery, you will see an empty list because we don't yet have any images in the database. You can add a few images manually by connecting to your mongo instance via CLI. The credentials can be found in the database overview: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nqfhonsonx6yipnzfhfl.png) After connecting, let's add images by executing the following: ```jsx db.createCollection("images") db.images.insert([ { title: 'IMG_4985.HEIC', size: '3.9 MB', source: 'https://images.unsplash.com/photo-1582053433976-25c00369fc93?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=512&q=80', }, { title: 'IMG_4985.HEIC', size: '3.9 MB', source: 'https://images.unsplash.com/photo-1582053433976-25c00369fc93?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=512&q=80', }, { title: 'IMG_4985.HEIC', size: '3.9 MB', source: 'https://images.unsplash.com/photo-1582053433976-25c00369fc93?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=512&q=80', } ]) ``` Now, after opening the frontend app in our preview environment, we will see all the images we put in the database! It looks like the feature is working well, so let's merge the PR: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xubg6kpwcx9qnal66g9z.png) What now happens is automatically after the PR merge, the preview environment is automatically cleaned up: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mcqtug1mnj4ck8ztba4.png) Great job! Thanks to Qovery Preview Environments, we managed to develop a new feature in a complete separation from our production, we tested it in a real environment deployed in the cloud, and we didn't have to spend any time preparing our environment for tests at all. ### Conclusion In the article, we quickly went through the process of creating a full-stack application with frontend, backend, and database. We enabled the Preview Environment feature to develop new features more quickly. We learned what the benefits of Preview Environments are, how to use them, and how to integrate them to day to day development workflow.
pjeziorowski
927,087
🔥Awesome Personal Portfolio Page
Manilla Manilla for modern trend, Personal Portfolio Landing Page. It is 100%...
0
2021-12-15T10:51:15
https://dev.to/devtips3/awesome-personal-portfolio-page-hp2
javascript, css, html, webdev
# Manilla Manilla for modern trend, Personal Portfolio Landing Page. It is 100% responsive. <p align="center"> <kbd> <img src="https://i.ibb.co/2hfGQfs/manilla-bg.png"></img> </kbd> </p> ### To view a portolio, **[click here](https://github.com/saidMounaim/manilla)**.
devtips3
927,257
DinoLab: adapting an interactive learning platform for a global audience
Uchi.ru has launched gamified online courses for children in Brazil, the USA, Canada, China, South...
0
2021-12-15T13:34:11
https://evrone.com/dinolab
microservices, ruby, react, webdev
Uchi.ru has launched gamified online courses for children in Brazil, the USA, Canada, China, South Africa, and other countries around the world. In early November 2020, a service for teaching mathematics and programming, DinoLab, was launched in India. The client approached Evrone for development, as we already had experience with gamified online platform development. At the beginning of October 2020, we completed the new online platform for interactive education, DinoLab, and at the beginning of 2021, [switched to a systematic product development role.](https://evrone.com/dinolab)
evrone
927,267
Host a Gatsby website on Firebase
What is Gatsby ? Gatsby is a static site generator that uses React and GraphQL. Very...
0
2021-12-15T14:54:11
https://dev.to/lachouri/host-a-gatsby-website-on-firebase-50ng
gatsby, firebase, tutorial, javascript
## What is Gatsby ? Gatsby is a static site generator that uses React and GraphQL. Very useful to create blogs (just like mine !), it allows you to create Single page apps very easily. Write your pages in JSX, or even better, with TSX, and write your content in Markdown, Gatsby will generate HTML and build a fast and secure website. But Gatsby can also be used to create dynamic sites like e-commerce. ## And what is Firebase ? Firebase is a platform from Google that offers a range of tools to "build, improve and grow your app", from database to auth, hosting or file storage. Combining Firebase and Gatsby is a great **free** solution to host your very own blog. So I'm going to show you how to host a Gatsby project on Firebase. ## Creating a Gatsby project Install the Gatsby client by running the following command : ```bash // NPM npm install gatsby-cli // Yarn yarn add gatsby-cli ``` Run the command `gatsby new` to initialize your project. Enter the project name and where you want to create it. Gatsby offers to add a CMS, styling libraries and plugins. Select what you wish to install, select Done and press Enter. (Installing Markdown is pretty handy if you wish to create a blog) Wait until the project is created. You can start the project with `yarn start` or `npm start`. ## Hosting on Firebase ### Creating the project on Firebase First you need to create a project on the Firebase website. Go to [https://firebase.google.com/](https://firebase.google.com/) and click on **Get Started**. 1. Proceed to click on **Create a project**. 2. Enter a project name and check yes if you wish to add analytics to your project. 3. Wait for the project to be created. Go to the 🌍**Hosting** tab on the sidebar and click on **Start**. ### Logging in Firebase will ask you to install a client with the following command : ```bash // NPM npm install -g firebase-tools // Yarn yarn add firebase-tools ``` You will then need to log into your Google Account, in order to do that, use the command `firebase login`. Then a window will pop up to select your google account. Authorize Firebase and a success message should appear. ### Initializing the project You can now use the `firebase init` command. Firebase will then ask you which feature you want to add to your project. Here we will add **Hosting**, so select Hosting and press enter. Then you can either use an existing project, create a new project or add Firebase to a Google Cloud Plateform project. Here we will use an existing project and select our previously created project. Enter which directory will be the public directory, if you want to configure it as a single-page app (yes as well in our case). You can add an automatic build and deploys to Github, but we will not talk about that in this article. Two files will be created : - `firebase.json` holds rules of hosting - `.firebaserc` tells which firebase project you are using. ### Deployment You can now launch `firebase deploy` and your site will be hosted ! Go back to the Hosting page and you will discover a place to add a domain name and a history of deployments. ![Firebase deploy](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v43pr23wg8pf7hjycc0w.png) You can click on the address that looks like this : _**https://test-59961.web.app/**_ and your website will appear ! --- Originally posted on my [blog](https://blog.ludivineachouri.com/). Check out my [instagram ](https://www.instagram.com/la.dev/)account to learn more about web development.
lachouri
927,313
Why I added text to my 'pure icon' site after eight years
Since 2013, I was using a website design with no visible words—icons only; it was an obsession with...
0
2021-12-15T15:21:53
https://dev.to/rosano/why-i-added-text-to-my-pure-icon-site-after-eight-years-10cl
design, a11y, discuss, ux
Since 2013, I was using a [website design with no visible words](https://web.archive.org/web/20211024165114/https://rosano.ca/)—icons only; it was an obsession with [The icon is a promise](https://rosano.hmm.garden/01et68bmqf38n795hrda63vcdp) and the perspective of words being 'limited' in expressing things. Eventually I added text available only to [screenreaders](https://en.wikipedia.org/wiki/Screen_reader), and thought it was interesting to have a context where visually impaired persons (VIPs) would be able to 'see more' than sighted people. I digged the pure visual aesthetic and the designed seemed like it would last forever (just keep adding icons to the list). I also avoided explaining 'me' because I thought that 'what I do should explain me', and seeked to make everythig 'about the projects'. So for almost a decade, I have been 'explaining' myself to the online world with a list of icons, and a small amount of project-specific text essentially _invisible_ to most people. After contemplating this recently, I began to notice issues. When imagining what it's like for someone arriving there, I feel it would be overwhelming to click on anything: a giant list of icons, each one descending into a rabbit hole of who knows what, not one seeming to offer a sense of the landscape or horizon—how does one decide where to start? I suspect that the poor sense of 'what to click on next' might cause me to lose many people who arrive there and feel lost. It would be selfish to expect people to essentially gamble with their attention and click many links at random in order to understand the larger picture—if they aren't able to understand, the medium of communication has failed. Worse, I realized recently that although it was possible to hover on icons to see the name and description of each icon, this was not possible on mobile devices. I sometimes thought I was raising awareness about the needs of VIPs, but in retrospect it was kind of a jerk move to make it harder for most people on purpose… So it's time to try something different. It should be simple to get an overview of what's going on: perhaps better to present with more information. Comparing [current and previous layouts](https://rosano.hmm.garden/01fpxpv5ybqs9pdvvcqcch4jj8): text is now visible everywhere without any special interaction or hardware and there is a small blurb about me which links to an [about page](https://rosano.ca/about) for a more textual overview. I think both frame everything in a way that's more accessible for everyone, making it simpler to understand what on earth I'm doing with my life. I feel happy with the result: I still dig the aesthetic and actually find it more friendly. Looking forward to see how this next phase of the design goes, and how much time passes until the next change. * * * As a bonus, check out the [pre-2013 layout on Wayback Machine](https://web.archive.org/web/20120814083036/http://rosano.ca/). --- Follow my journey on [Twitter](https://twitter.com/rosano) (or via the [mailing list](https://rosano.ca/list)) --- (Image by [Uriel Soberanes](https://unsplash.com/photos/RWCF3DxX-28).)
rosano
927,336
CRUD with Redis OM .NET - C# Advent
Tis the season of C# Advent again and for my topic, I'm going to talk about a library I recently...
0
2021-12-16T11:26:37
https://dev.to/slorello/crud-with-redis-om-net-c-advent-4gif
redis, database, csharp, dotnet
Tis the season of [C# Advent](https://www.csadvent.christmas/) again and for my topic, I'm going to talk about a library I recently wrote, [Redis OM](https://github.com/redis/redis-om-dotnet). Big thanks to all the contributors of C# advent and to [Matthew Groves](https://twitter.com/mgroves) and [Calvin Allen](https://twitter.com/_CalvinAllen) for organizing it this year. if you haven't yet, make sure you check out all the great content the community has put out this year. Redis is a NoSQL database that's loved for its simplicity and speed. Those two virtues make it the [most loved database](https://insights.stackoverflow.com/survey/2021#technology-most-loved-dreaded-and-wanted) by developers. But there's a problem inherent in Redis if you want to store more complicated objects. Redis is a key-value data structure store. This means that if you're going to perform CRUD(Create Read Update and Delete) operations on your data, and the only way you care to access the data is by your key, you'll have no problem. But what if we wanted to look up items by value? This is where things can get tricky in Redis, and that's also where the story of [Redis OM](https://github.com/redis/redis-om-dotnet) begins. Querying items by their values in Redis requires a fair amount of legwork on the developers' part to manually build and maintain secondary indexes for those objects. After that, you need to execute several commands to perform your query. With [Redis OM](https://github.com/redis/redis-om-dotnet) and [RedisJSON](https://oss.redis.com/redisjson/), you can build your model ahead of time and query them with a LINQ interface. ## Our Model We're going to use this `Customer` object as our model throughout our examples: ```csharp public class Customer { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public int Age { get; set; } } ``` We will assume that we want to search on any field in Customer. With that in mind, we'll go through what we would have to do in Redis OM and what we would have had to do in prior iterations of Redis for the basic operations of persistent storage - Create Read Update and Delete (CRUD). ## Setting up ### Start up Redis First, we'll set up our environment. Then, for development purposes, we'll use Docker to run Redis: ```bash docker run -p 6379:6379 redislabs/redismod ``` ### Set up our project Next, we'll set up our project. Then, finally, we'll just run this all as a console app: ```bash dotnet new console -n RedisOmComparison ``` Cd into the `RedisOmComparison` directory, and run `dotnet add package Redis.OM` to install Redis OM. ### Initialize connection objects Now we'll initialize our two connection objects. The ConnectionMultiplexer for our standard redis Setup and the RedisConnectionProvider for the Redis OM setup. In program.cs run the following: ```csharp // Standard Redis var muxer = await ConnectionMultiplexer.ConnectAsync("localhost"); var db = muxer.GetDatabase(); // Redis OM var provider = new RedisConnectionProvider("redis://localhost:6379"); ``` ### Initialize Bob So we are consistent, we'll use the same customer object across both examples, Bob: ```csharp var bob = new Customer { Age = 35, Email = "foo@bar.com", FirstName = "Bob", LastName = "Smith" }; ``` ## Create indexed objects in Redis with Redis OM To create an object in Redis with Redis OM, we'll start with our initial model but add some attributes to it. First, we'll decorate the class itself with the `Document` Attribute, and then we'll decorate each of the properties with the `Indexed` attribute. After this is done, our Customer object should look like this: ```csharp [Document] public class Customer { [Indexed(Sortable = true)] public string FirstName { get; set; } [Indexed(Sortable = true)] public string LastName { get; set; } [Indexed(Sortable = true)] public string Email { get; set; } [Indexed(Sortable = true)] public int Age { get; set; } } ``` This should be stored in a new file - `Customer.cs` ### Create the index Now that you've declared the Customer with indexing in mind, you'll just create the index. This only has to be done once per index. In Program.cs add: ```csharp provider.Connection.CreateIndex(typeof(Customer)); ``` ### Add a customer All that's left to do is add a customer, create a `RedisCollection<Customer>`, and simply insert a new customer into Redis. ```csharp var customers = provider.RedisCollection<Customer>(); var customerId = await customers.InsertAsync(bob); ``` ## Create indexed objects in Redis without Redis OM Creating indexed objects without Redis OM will be a bit more complicated. We're going to have to go through three stages, which will need to run each time we add something. 1. Create a key name 2. Map the object to a hash and create the hash 3. Update the indexes associated with each item ### Key name We'll use `Customer:AGuid` as our key name to keep it simple. ```csharp var keyName = $"Customer:{Guid.NewGuid()}"; ``` ### Create the object's hash The natural data structure to use when storing indexable objects in Redis (without a module) is a Redis Hash. To store an object in a Redis hash, we'll need to break it down into a set of field-value pairs that we can send off to our Redis along with our Redis key. Once this is done, the object is actually stored in redis. You can do that by calling the `HashSetAsync` method on the `DB` object and passing in the properties/values of `Bob` as field value pairs: ```csharp await db.HashSetAsync(keyName, new HashEntry[] { new HashEntry(nameof(Customer.FirstName), bob.FirstName), new HashEntry(nameof(Customer.LastName), bob.LastName), new HashEntry(nameof(Customer.Email), bob.Email), new HashEntry(nameof(Customer.Age), bob.Age) }); ``` ### Set up the index Unlike Redis OM, the indexes are not set & forgotten in standard redis. Each indexed field needs to have its own separate index maintained. For this purpose, for each field, we'll keep different sorted sets. For each string field name, this will be a sorted set for each value, and forage will be a single sorted set. Mind you, later, when we update items in Redis, these will also need to be updated. To create the indexes, run the following code: ```csharp await db.SortedSetAddAsync($"Customer:FirstName:{bob.FirstName}", keyName, 0); await db.SortedSetAddAsync($"Customer:LastName:{bob.LastName}", keyName, 0); await db.SortedSetAddAsync($"Customer:Email:{bob.Email}", keyName, 0); await db.SortedSetAddAsync($"Customer:Age", keyName, bob.Age); ``` ## Comparison So after the preliminary steps to initialize the index for redis OM (decorating the class and calling `CreateIndex` once), creating a customer object is very straightforward: ```csharp var customerId = await customers.InsertAsync(bob); ``` Versus doing so without Redis OM: ```csharp var keyName = $"Customer:{Guid.NewGuid()}"; await db.HashSetAsync(keyName, new HashEntry[] { new HashEntry(nameof(Customer.FirstName), bob.FirstName), new HashEntry(nameof(Customer.LastName), bob.LastName), new HashEntry(nameof(Customer.Email), bob.Email), new HashEntry(nameof(Customer.Age), bob.Age) }); await db.SetAddAsync($"Customer:FirstName:{bob.FirstName}", keyName); await db.SetAddAsync($"Customer:LastName:{bob.LastName}", keyName); await db.SetAddAsync($"Customer:Email:{bob.Email}", keyName); await db.SortedSetAddAsync($"Customer:Age", keyName, bob.Age); ``` Naturally, the former is much more straightforward, and it only requires a single round trip to Redis to accomplish! ## Reading data out of Redis with an Id Now that we've inserted our data into Redis, how can we read it? Well, there are two dimensions to think about 1: How are you querying objects? 2: How are you marshaling your objects? There are two types of ways to query your objects 1: by key 2: by values. In the former case, querying is straightforward in both cases: ### With Redis OM To read an Item out of Redis with Redis OM, just use the generic `FindById` command: ```csharp var alsoBob = await customers.FindByIdAsync(customerId); ``` ### Without Redis OM Without Redis OM, you'll need to call `HGETALL` and then build a new instance of the object from the hash, which takes a bit more effort: ```csharp var bobHash = await db.HashGetAllAsync(keyName); var manuallyBuiltBob = new Customer { Age = (int)bobHash.FirstOrDefault(x=>x.Name == "Age").Value, FirstName = bobHash.FirstOrDefault(x=>x.Name == "FirstName").Value, LastName = bobHash.FirstOrDefault(x=>x.Name == "LastName").Value, Email = bobHash.FirstOrDefault(x=>x.Name == "Email").Value, }; ``` ## Reading data out of Redis by Value This is where things start to get interesting. Many database use cases require the ability to look items up by values. For Example, if we wanted to find all the customers named "Bob" in a traditional SQL database, we'd just run `SELECT * FROM Customers WHERE FirstName = 'Bob'`. However, by default, Redis lacks the concept of a table scan to look up records by a given value. That's why earlier, we constructed secondary indexes for both types. So now, let's look at querying items by their values. ### Query by FirstName Redis OM To query by the `FirstName` property in Redis OM, all you need is a simple LINQ statement: ```csharp var bobsRedisOm = customers.Where(x => x.FirstName == "Bob"); ``` Then when that collection enumerates, all of the Bobs currently in Redis will be populated as Customers. ### Querying by FirstName without Redis OM Querying by First Name without Redis OM is more complicated, as has been typical so far. This time, you need to read the Set containing all the Bobs, and then you need to query each of those Ids individually: ```csharp var bobIds = await db.SortedSetRangeByRankAsync($"Customer:FirstName:Bob"); var bobsWithoutOm = new List<Customer>(); foreach (var id in bobIds) { var hash = await db.HashGetAllAsync(id.ToString()); bobsWithoutOm.Add(new Customer { Age = (int)hash.FirstOrDefault(x=>x.Name == "Age").Value, FirstName = hash.FirstOrDefault(x=>x.Name == "FirstName").Value, LastName = hash.FirstOrDefault(x=>x.Name == "LastName").Value, Email = hash.FirstOrDefault(x=>x.Name == "Email").Value, }); } ``` ### Query by Age Redis OM To query by Age in Redis OM, we can use the typical operators we would use for numerics `>=,<=,>,<,==` ```csharp var under65RedisOm = customers.Where(x=>x.Age < 65); ``` ### Query by Age without Redis OM Querying by Age without Redis OM is similar to how querying strings would work. Except for this time, you would just send a range query to the sorted Set: ```csharp var under65IdsWithoutRedisOm = db.SortedSetRangeByScore($"Customer:Age", 0, 65); var under65WithoutRedisOm = new List<Customer>(); foreach (var id in under65IdsWithoutRedisOm) { var hash = await db.HashGetAllAsync(id.ToString()); under65WithoutRedisOm.Add(new Customer { Age = (int)hash.FirstOrDefault(x=>x.Name == "Age").Value, FirstName = hash.FirstOrDefault(x=>x.Name == "FirstName").Value, LastName = hash.FirstOrDefault(x=>x.Name == "LastName").Value, Email = hash.FirstOrDefault(x=>x.Name == "Email").Value, }); } ``` ## Updating objects in Redis The mechanics of updating objects in Redis is pretty straightforward. For a hash, you simply call `HSET` and pass in the key and the field/value pairs you'd like to update. However, when you're indexing items, you need to coordinate the indexes as well, at least when you're not using Redis OM: ### Updating an item in Redis with Redis OM To update an item in Redis using Redis OM, simply change an item in an enumerated collection and call `Save` on the collection: ```csharp foreach (var customer in customers) { customer.Age += 1; } await customers.SaveAsync(); ``` This will be the same regardless of what you update in the item. ### Updating an item in Redis without Redis OM To update an item in Redis without Redis OM, you'll need to first make the call to update the item, and then for each field, you update you need to adjust its index. So let's go ahead and see how we would update the Email and age attributes without Redis OM. #### Updating the data Updating the data is fairly straightforward - call `HashSet` on the key and each of the fields within it you want to update. ```csharp await db.HashSetAsync(keyName, new HashEntry[]{new ("Age", bob.Age + 1), new("Email", "bar@foo.com")}); ``` #### Updating the indexes With the data updated, we now have to go in and update the indexes as well. For our Email, this will involve deleting the record from the previous Email's Set and then adding it to the new Email's Set. For Age, this just means updating the members score in the sorted Set: ```csharp await db.SortedSetRemoveAsync($"Customer:Email:{bob.Email}", keyName); await db.SortedSetAddAsync($"Customer:Email:@bar@foo.com", keyName, 0); await db.SortedSetAddAsync($"Customer:Age", keyName, bob.Age + 1); ``` ## Deleting indexed items ### With Redis OM When deleting an indexed item in Redis with Redis OM, it's as easy as calling `Unlink` on the item's key: ```csharp provider.Connection.Unlink(customerId); ``` ### Without Redis OM Without Redis OM, you will, in addition to having to delete the key, have to go into all the sets for the accompanying indexed fields and remove the key from there too: ```csharp await db.KeyDeleteAsync(keyName); await db.SortedSetRemoveAsync($"Customer:Email:{bob.Email}", keyName); await db.SortedSetRemoveAsync($"Customer:FirstName:{bob.FirstName}", keyName); await db.SortedSetRemoveAsync($"Customer:LastName:{bob.LastName}", keyName); await db.SortedSetRemoveAsync($"Customer:Age", keyName); ``` ## Summing up As we've seen throughout this article, Redis OM is a real boon when you are performing all of the CRUD operations with Redis, as it vastly decreases the complexity of each type of operation. Not only that, but because you can complete everything in Redis OM with a single command, you remove any concerns of conflicting updates and any cross-shard complexity associated with updating stuff in Redis. ## Resources * There's a tutorial for Redis OM on [developer.redis.com](https://developer.redis.com/develop/dotnet/redis-om-dotnet/connecting-to-redis) * If you want to open an issue or PR for Redis OM - feel free to stop by in [GitHub](https://github.com/redis/redis-om-dotnet) * To learn more about Redis in general - check out [redis.io](http://redis.io/) * To learn more about RedisJSON - the module that powers the search features in Redis - checkout [redisjson.io](https://oss.redis.com/redisjson/)
slorello
927,751
Planning a feature enhancement.... continued
Building off last weeks blog, there are four things we want to implement: Continue to build off...
0
2021-12-16T01:43:42
https://dev.to/amasianalbandian/planning-a-feature-enhancement-continued-4j75
Building off last weeks blog, there are four things we want to implement: 1. Continue to build off the previously created UI for the advanced search. 2. I want to implement the search by date, once I have this down I should understand how to further leverage the implementation of Elasticsearch to implement more. 3. Let's try to implement search by Semester, or date range. 4. I explored some queries on the Elasticsearch container in docker, and realized we can pass more than just one parameter #### Knocking off #2 Last week, I was able to put up a [PR ](https://github.com/Seneca-CDOT/telescope/pull/2584) for the date search. What this accomplished was that we now had a way to search posts by date. Unfortunately, I quickly realized this is not the direction I wanted to head in for my solution, as it was not practical. Why would anyone want to search just by date? The point of an advanced search should be that you can search multiple fields and refine the search to that. So from that PR, I was able to get some feedback about the UI and enhancements to make for the users. Although this PR should not be merged in for the solution, it provided me more insight on how the search works. I was able to understand Elasticsearch a bit better. So from here, the implementation was not completely useless. What I needed to do now was implement the date search as a part of the fields for an advanced search. #### Back to our journey The Repository now contained the post/title search, author search, and the date search. Additionally, I thought, why search by date? Let's do date range. This way, if you want just one day, we can use this, but we can also expand it to be a range. So what we needed to do now was take all the data fields, and come up with a query for Elasticsearch. This was by far the most difficult part of the implementation. I would think of this as "diving into the unknown". I had no idea how difficult, something so flexible could be. The queries have absolutely no limits on Elasticsearch, you can try and do almost everything - which makes writing a query a little difficult when learning. #### Knocking off #3 and #4 together The original query was simple: ``` query: { query: { simple_query_string: { query: textToSearch, default_operator: 'and', fields: createFieldsFromFilter(filter), }, }, } ``` What I ended up with was this: ``` query: { query: { bool: { must: [ { match: { author: { query: authorText, zero_terms_query: 'all', }, }, }, { match: { text: { query: postText, zero_terms_query: 'all', }, }, }, { match: { title: { query: titleText, zero_terms_query: 'all', }, }, }, { range: { published: { gte: dateStart, lte: dateEnd, }, }, }, ], }, }, ``` So to start off with, we changed a few things. I used a bool query, which would allow us to search multiple fields for matches. What you need to do next is decide do we use `should` or `must`. Simply put `must` is like the AND operator, `should` is OR, and then there's one more `must_not` which is the NOR operator. This was helpful, because my brain operates better on logical terms than explanations. Problems? Yes!!! Now that we are using `must` we need to provide all the fields... So if a field was missing it would return 0 results. I thought this was not good - however, after some exploration `zero_terms_query: 'all'` covers scenarios where that term is not provided. This allowed us to bypass that. Lastly, we had to do our date implementation. For this one, had already seen the documentation for the ranges, and thought it wouldn't be too bad - and it wasn't. I only had some difficulty with where to place it. I believe I just stuck it in the wrong braces and took 4 minutes to figure that out. We want it so that it MUST be in that range also. I default set the dateStart and dateEnd in the query, so if it's not provided it will search from 2010-01-01 to date.now. #### Next Steps: So now that we have all the backend implementation, we can do the front end right? I was wrong. I didn't realize that we go through both Elasticsearch AND search, two containers on docker. I need to further explore how to implement this so that we can access both search types and not break either.
amasianalbandian
927,815
How to Install Kubernetes on Windows 10?
Kubernetes or K8s is an open-source platform to manage containerized workloads and applications....
0
2021-12-16T03:54:41
https://dev.to/nawazsiddiqui27/how-to-install-kubernetes-on-windows-10-4bep
kubernetes, devops, cloudnative, opensource
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xtepgg3wkusql7hwb09p.png) Kubernetes or K8s is an open-source platform to manage containerized workloads and applications. With containers, it's easy to manage, run or ship your application. Kubernetes helps to manage cloud resources and makes your cloud infrastructure more scalable by automating and deploying applications in no time. While installing Kubernetes for the first time, these are the steps I followed on my Windows 10 home. Let’s explore each of them: ## Setting up Hyper-V Hyper-V is window's own virtualization software same as Virtualbox. If you are using windows home, you need to install Hyper-V. Here is the article for that. After installing, follow these steps to enable Hyper-V on your local machine. 1. Open search bar and go to control panel 2. On the left side of the control panel, click on program and then on programs and features. 3. Turn on the Windows features on and off. 4. Check on the Hyper-V and Windows Hypervision Platform, click the OK button. 5. It may take a few minutes to install Hyper-V on the system, in some cases, your system will reboot itself a couple of times. 6. To verify the successful installation of Hyper-V on Windows, open windows Powershell, run it as an administrator, and paste the below command. Get-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bjrojkx1iowob16lk8ia.png) ## Installing Docker on Windows 10 You can install any alternatives of docker like Containerd, RunC, Podman, and many more to mention. Although I am installing Kubernetes for the first time in the system, I used the Docker desktop. Click here to go to the official website of docker and click on Get Docker Desktop. Follow the instructions while installing and you are ready to run Docker on your machine. ## Installing Kubernetes on Windows 10 Follow these steps to install Kubernetes on windows 10 seamlessly. 1. Open the Docker GUI tool and click on Settings. 2. On the left plane, click on Kubernetes and check on Enable Kubernetes Apply the changes, wait for 5 to 10 minutes, or until the installation complete popup message is shown up on the screen. To confirm the running of Kubernetes, hover your mouse pointer on the down left side of the Docker desktop plane, you will see “Kubernetes Running” message. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5vnqu7hg8il4syji06a3.jpg) ## Accessing Kubernetes UI Kubernetes UI is not installed by default. It’s a web-based interface and can be accessed via a web browser. Open the command prompt and paste the given script to deploy dashboard UI. kubectl apply -f https://raw.githubusercontent.com/Kubernetes/dashboard/v2.4.0/aio/deploy/recommended.yaml In my case, the command was showcasing some error with my Linux, so I reinstalled Ubuntu 20.04 LTS. If you don’t have any Linux distribution, install from the Microsoft store in case of any error. ## Accessing Kubernetes Dashboard You need to create a sample user to access the Kubernetes dashboard. Follow this article to create a sample user and generate token. To enable access to the dashboard, use the below command in the terminal kubectl proxy The dashboard will be available at http://localhost:8001/api/v1/namespaces/Kubernetes-dashboard/services/https:Kubernetes-dashboard:/proxy/ If everything is done right you will be able to get access to the dashboard. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6u70tjaetpesx7g21l2.png) These are the steps I followed to install Kubernetes on windows 10 home. I hope this article was helpful. If you still face any problems, comment down below, I will try to get back to you with the solution.
nawazsiddiqui27
927,872
Moxi Robot - The Future of Healthcare Industry
Secondary robots are the helpers. Hospitals run 24/7. There is no doubt that the nurses, ward boys,...
0
2021-12-16T06:15:03
https://dev.to/angelajonex/moxi-robot-the-future-of-healthcare-industry-34p8
ai, python, webdev, news
Secondary robots are the helpers. Hospitals run 24/7. There is no doubt that the nurses, ward boys, and other staff have too much to do. That is why secondary robots were invented. The robots such as the Moxi robot by Diligent Robotics help the hospital staff restock, bring the items, clean, and do other works. {% youtube vniKNpy5SFs %} This enables the human staff to spend more time with the patient to offer a friendly environment while leaving the never-ending work to the robots. Another excellent example of those secondary robots is the UV light disinfection robot. It is stated that the robot doesn’t leave the room until it is totally germs-free. You can book a demo of Moxi Robot directly on their website with [Catch coupon](https://www.revounts.com.au/catch-coupons-code). Source: [Hackernoon](https://hackernoon.com/ai-robotics-and-the-future-of-healthcare)
angelajonex
928,009
Mentorship in Tech: Useful Tips For Mentors and Mentees
Keeping your tech team up to speed on the latest innovations in technology and ensuring professional...
0
2021-12-16T09:04:00
https://blog.getace.io/,,,
career, beginners, management
Keeping your tech team up to speed on the latest innovations in technology and ensuring professional skill development can be overwhelming. Integrating mentorship into your team’s culture is a great way to foster both meaningful work relationships and professional development opportunities within your organization. In this blog post, you will find out what is mentorship and get tips for mentoring to significantly improve productivity of the whole tech team. Read: [Full guide on how to start a mentorship program at work](https://blog.getace.io/all-posts/ultimate-guide-on-how-to-start-a-mentorship-program-at-work) ## What is mentorship? Mentorship is a relationship between two people, in which a person with more experience, knowledge, and connections (a mentor) can transfer what they have learned to a less experienced specialist (a mentee) in a particular field. The activities of a mentor are aimed at maximizing the personal and professional potential of the mentee. However, it is important to note that mentoring is not focused on a person's problems, but is aimed at developing and teaching, so that a junior specialist can solve their problems and face challenges on their own. Ideal mentoring is a two-way road, where both the mentor and the mentee benefit. Although at first glance, it seems that the mentee gets the main benefit — this is only one side of the coin. By helping a junior employee become better, the mentor not only gains the satisfaction of helping and developing someone, but also achieves success in management and takes their career to the next level. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b1a1adroloykoa5z6kc0.png) _Benefits of a mentorship program_ ## Tips for mentees It's worth taking the time for software developers to find a good mentor, because it's one of the best ways to accelerate your professional growth. We will tell you more about what goals you should strive for with a mentor and how to find a suitable mentor for yourself in this section. ### Why do developers need a mentor? The skills of knowledge workers, especially software engineers, become obsolete very quickly, which is why developers need to constantly level-up and learn. An experienced mentor can help you with this. A good mentor will not only help you see growth points in your development, but also how to stay on top of the latest industry trends, join a community of like-minded people and build a development plan with appropriate learning activities. How does a software developer benefit from mentorship? Let's find out: * **Learn about best practices and tools.** Your mentor can teach you advanced programming techniques. Of course, it is useful to gain general knowledge about universal tools for a developer: programming languages, frameworks, etc. But it is especially helpful to learn how to tailor your programming skills to the needs of a particular team. * **Find a better solution to a challenging problem.** If you can't cope with a difficult task, the mentor can give a broader view of the problem and suggest a different angle or faster solutions. It is important to understand that, if the mentor solves the problem for you, this is the wrong way to go about it. It is better if the mentor can competently suggest which books, courses, and other resources can be studied on this topic. This will help you deal with difficult tasks on your own in the future. * **Identify areas of growth.** The mentor can honestly point out areas where you need to work on improving. It is absolutely normal that we do not notice our weaknesses, because it is human nature to avoid difficult tasks. And working on your weaknesses is one of the most difficult tasks that can stand in the way of achieving high results in your career. * **Career development advice.** A mentor can help you find the area of ​​development that suits you best and that you like. Help from a senior colleague will make your career path easier and help you avoid mistakes. Perhaps thanks to the timely advice of a mentor, you can create a career path and achieve your goals more quickly. * **Support during remote work.** How can you gain a rewarding experience when you work alone? A mentor will come to the rescue, immerse you in the culture of the company and help you build friendships with colleagues, from whom you can gain experience and with whom you will create successful projects. Remote work will not take you away from reality, if there is a specialist next to you, who is interested in integrating you into the development team. ### How to find a mentor Finding the right mentor is not an easy task. Firstly, he or she must be qualified in the area in which you want to develop; and secondly, you must have a match and the desire to trust your mentor. Here are the ways you can find a mentor: **Mentorship programs at the workplace** Often, employers organize mentoring programs, where more experienced developers train and mentor junior employees. It is a very good indicator if the company has such programs. This means that the company cares about the development of its employees. Developers should use this opportunity, if the company involves them in such an onboarding process. **Professional communities** There are many professional communities, in which developers share knowledge, experience, and information. You can become a member of such a [community](https://community.getace.io/), take an active part there, follow the specialists you are interested in and ask them for help. Many experienced developers, CTOs, or engineering managers are happy to share their experience and provide advice. **Mentorship platforms** There are also specialized resources, where mentors and mentees can meet. You can find a list of such databases in our [blog post](https://blog.getace.io/all-posts/mentorship-platforms). The easiest way to find the right mentor (and most effective!) within your team or on other platforms is to use [Ace AI](https://www.getace.io/). It analyzes the working activity of developers in Git, catches the skill gaps, and gives a recommendation on the most suitable mentor. See how [Ace AI](https://www.getace.io/) personalized recommendations work in practice: ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4fr6wiavfalrv89b4tbr.gif) _Personalized recommendations on mentors in [Ace AI](https://www.getace.io/)_ ### Signs that you and your mentor are a good match How do you know if your mentor is right for you? We advise you to pay attention to the following signs, which show that you and the mentor will work together well and your cooperation will, indeed, be beneficial for both parties. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/puwk8xgglysixe8l2b4e.png) _Signs of a good mentor_ * Relevant experience. If your mentor has gone through the same career points as you and has already achieved the goals you have in your mind - this person can help you avoid mistakes that he or she faced in the past. * Successful cases and completed challenges in relevant fields. Find out what achievements the mentor had when they started their career in development. If among them there are those that are relevant to your aspirations, the mentor will share their experience and help you achieve what you want faster. * Goal-oriented. A good mentor creates a growth plan, monitors your progress, and clearly tells you what you need to do to get to the next level. The stated goals at the start increase the chances of success at the end. * Available for regular meetings. Observe how responsive your mentor is and whether he or she responds in a timely manner to your problems. Also, in order to achieve the best results, it is important to meet regularly and summarize the outcomes of the iteration or task. Meetings, strategy sessions, and calls show the mentor's interest and involvement in your affairs. * A good listener. Assess the mentor as a person: is he/she listening to your ideas and professional difficulties? Does he/she give feedback? If yes, it will be easy for you to work together for a long time. * Shows interest in empowering others. The mentor should be interested in your growth and support your intention to take on more tasks or empower you to do so. For example, if at some point you want to not only write code, but also do testing or take on managerial tasks, a good mentor will do their best so that you feel supported in your development. * Open to flexible mentoring styles. There are a lot of approaches and different styles of mentoring, so the mentor should be ready to find what suits best for your work together and make sure everyone feels comfortable with it. * Ready to learn from a mentee. This is one of the most important points, because a person who is ready to admit that he/she does not know something and is ready to learn, can teach this skill to others. You will both feel satisfied if a mentorship session gives you both useful experience and new knowledge. ## Tips for mentors In this section, we will talk about why it is useful to become a mentor and give advice to those who want to mentor. ### What are the benefits of becoming a mentor? Ideal mentoring is a win-win story, where each side benefits from the interaction. Mentors also get benefits from conducting sessions with young professionals. This is new knowledge, and a new impetus in a career, and an opportunity to influence the future. Let's take a closer look. These are the benefits that mentors can get when they start working with mentees: - **Next step in their career** Often, developers who have taken a senior position or become team leads do not see a further career path for themselves. Becoming a mentor is one of the roads a developer can grow into. Mentoring can be perceived as the highest career point, because a person grows from a specialist into an expert and influencer in their field. - **Opportunity to make a contribution to the community** With their expertise, a mentor can influence the future of a field of activity that they are passionate about. It is an honor for every developer who truly loves what they do to oversee the transfer of best practices to future generations and to make sure the industry develops. - **New knowledge from young professionals** Although beginners do not have much experience in development, they have a lot of ideas and think broadly, while their everyday life is not busy with routine tasks. Plus, the mentor develops as a manager, planning and controlling tasks for a young specialist. ### How to become a great mentor To become a good mentor, you need to adhere to a certain ideology and order of actions in your work. Let's share a few behaviors, which mostly speak for themselves. #### Mentor tips **Tip #1**: The best mentor relationships eventually become two-way. Be ready to learn from your mentee. **Tip #2**: Listen. Put the focus on the other person, his/her needs and difficulties. **Tip #3**: Guide, don’t control. Mentees must make their own decisions, so direct and support, rather than dictating to them. **Tip #4**: Give specific, actionable advice. Don’t be vague. **Tip #5**: Be authentic; practice what you preach. Ask questions that encourage, inspire, and stimulate. **Tip #6**: Be direct and tell the truth, however hard. Your mentee expects you to be objective and constructive. _Read Ace’s [Ultimate Guide on How to Start a Mentorship Program at Work](https://blog.getace.io/all-posts/ultimate-guide-on-how-to-start-a-mentorship-program-at-work)_ ## Toolbox In order for the mentoring session to become not just a discussion of problems, but an opportunity to solve specific problems, you need to have at your disposal a set of tools that will help increase efficiency: **Skill matrices** These will help a mentor determine what skills are needed for a particular role and what needs to be improved for a person to fit that role. To simplify this process and choose relevant skills, use Ace AI [skills matrix templates](https://www.getace.io/templates#skill-matrices), or skill graphs, which are regularly updated for each tech role. **1-ON-1 MEETINGS TO GIVE REGULAR FEEDBACK** To keep the mentorship session structured and effective, the mentor should hold regular one-on-one meetings to monitor the progress of professional development and give feedback. [Ace AI](https://www.getace.io/) helps to automate this process and allows you to write AI feedback for specific skills and save time. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h8pom5137546nd2fzywl.gif) _Automatic feedback for skills in [Ace AI](https://www.getace.io/)_ Also, [Ace AI](https://www.getace.io/) builds automatic agenda for your 1-on-1 meeting to discuss growth plan progress based on developer updates from Git and growth plan initiatives. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1n5ju6gkojb4osntpnhy.gif) _Automatic agenda for 1-on-1 meeting in [Ace AI](https://www.getace.io/)_ **PDP** A good PDP, or a professional development plan, should include a combination of learning activities and working tasks on developing focus skills in order to successfully implement continuous learning in the workflow of a tech team and meet career goals faster. You can also automate the process of creating a personalized professional development plan with AI. [Ace AI](https://www.getace.io/) uses Git data to find skills gaps and creates a development goal with recommendations on mentors and learning materials based on these skill gaps. ## Key ideas - The cooperation between the mentor and the mentee is important for both parties. A young specialist develops the skills, and a mentor builds up expertise in management. - When choosing a mentor, it is important to find a person with whom the match will be successful. This can be determined by the existing skill gaps, the relevance of experience, goals, and similarities of interests. - The mentor should only direct and support mentees, rather than giving ready-made decisions. Learning to make decisions and move tasks forward is the main goal of mentoring. - To make mentorship sessions more effective, a mentor should use special tools like skill matrices, meeting templates, and AI-powered tools to automate mentorship and make it more effective.
extravertivecto
928,067
The Next Big Thing in Technology? The Metaverse
Metaverse is an expression invented by Neal Stephenson in a novel called ‘Snowcrash in the year 1992....
0
2021-12-16T10:48:31
https://dev.to/brisklogic/the-next-big-thing-in-technology-the-metaverse-1j4c
webdev, react, programming, devops
Metaverse is an expression invented by Neal Stephenson in a novel called ‘Snowcrash in the year 1992. It was mentioned as a reference for a simulated 3D environment made up of avatars that were based on humans. In the past few months, the creator of Facebook, Mark Zuckerberg has discussed the concept of a metaverse as well as the ambitious plans being debated for bringing a virtual universe to life that anyone can participate in. The metaverse is believed to be the next version of the Internet which is built on the technology that is already in use to integrate all 3D virtual worlds to create a single virtual universe.
brisklogic
928,105
My 1st WEB PAGE
https://codepen.io/Bhuvanesh_Dev/pen/MWEpLYO?editors=1000 Created a basic "My interests" web page...
0
2021-12-16T12:07:19
https://dev.to/bhuvanesh_dev1006/web-page-creation-3kep
https://codepen.io/Bhuvanesh_Dev/pen/MWEpLYO?editors=1000 Created a basic "My interests" web page using HTML and CSS by adding images and color modification using CSS with the help of CodePen platform. Suggestions are welcome! #beginner #open_source #html #css #Learn_in_Public
bhuvanesh_dev1006
928,109
8 reasons why you should consider learning python today!
Python is one of the most popular languages today. Chances are that you might've already heard about...
0
2021-12-16T12:24:46
https://pranshujha.hashnode.dev/8-reasons-why-you-should-consider-learning-python-today
python, beginners, programming
Python is one of the most popular languages today. Chances are that you might've already heard about it if you're a developer or starting as one. That said, it's one of the languages you should consider learning. Here are some reasons why - ## [1] High Demand & Popularity No doubt python is one of the most popular languages now. It has taken the number one slot on TIOBE's Index Rankings. So there's no doubt that developers love Python! ## [2] English like syntax And this is why developers love it so much! Python has probably the easiest to understand syntax among the popular programming languages. This makes python one of the top choices for beginner developers. Here's an example of a hello world program in Python and C++ for comparison. ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639653508718/Zo5escri3.png) ![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1639484847526/91jmkrGhE.png) ## [3] Machine Learning & AI ...are some of the top-grossing buzzwords currently and, will be so for a long time to come. Python is one of the popular choices for Machine Learning. Python also provides multiple modules for Machine Learning like Scikit-learn, Tensorflow, PyTorch, etc. ## [4] Web Development Although you'll need to know HTML, CSS, and a dash of JavaScript to make a delicious website, python can help you with its numerous web-development frameworks and libraries. A few popular examples are Django, Flask, Bottle, web2py, etc. Fun fact: Python powers popular websites like Spotify, Instagram, Dropbox, Reddit, etc. So I'd recommend you to at least give Python a try if you're into web development like me. ## [5] Game Development Python offers some of the easiest to use game development libraries, promoting rapid prototyping. Pygame, Arcade, Ursina are some of the popular game development libraries for python. ## [6] Automation & Scripting (This bit is also from personal experience) I've used python to automate everything from taking screenshots of my online classes to taking attendance of students. And I have to say...it's really nice to be able to shave some time off of tedious tasks. ## [7] Huge Community This means any bug you encounter has probably been encountered before and there probably exists a StackOverflow post about it as well. (It's kind of nice knowing that you won't keep banging your head over stupid bugs :p) ## [8] Tons of libraries and frameworks Python has numerous libraries for every purpose you might need it for. There are libraries for everything from game development to data science and, frameworks for everything from making websites to GUI applications, you name it! --- ## Conclusion To conclude simply, Python is a great choice for developers especially beginners. I urge you to give Python a chance, I'm sure you'll be enthralled by its magic ✨
pranshuj73
928,538
UX Case Study: Killer Kao
Live Demo GitHub Repo Initial Design I wanted to create a different take on the...
0
2021-12-16T19:29:32
https://dev.to/cat/ux-case-study-killer-kao-h98
ux, beginners
[Live Demo ](https://catcarbonell.github.io/killerkao/) [GitHub Repo](https://github.com/catcarbonell/killerkao) --- ## Initial Design I wanted to create a different take on the classic "Rock-Paper-Scissors" JavaScript project by using [Kaomojis](http://kaomoji.ru/en/) (the predecessor to our current, beloved emojis!) Here are some wireframes I initially created via Sketch: ![I designed different screens in accordance to the possibilities a user would take, for example, the user would choose the "strike" button and the little fighter would change from a static pose to a punch pose](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7ko7z1v0j91g3q4d787.png) (I was very much inspired by fighting games: Street Fighter, Tekken, King of Fighters, etc.) ## Feedback After I created the first iteration, I had friends and family test it out-- especially on mobile-- and was open to any and all feedback! This is from my older brother: ![Feedback from my older brother that pointed out the block button wasn't exactly working](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3thxejmifrozi4b7wx2h.png) One of my close friends' friend had feedback for me! ![My friend Patrick showed my game app to his friend and she had feedback for me. She suggested that I animate the kaomoji with CSS!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4eglr3nyynh6inphegwg.png) Even Shen ([Shen Comix](https://www.webtoons.com/en/challenge/shen-comix/list?title_no=129357&page=1)) took the time to try out my app! ![A friend pointing out that there is no punishment or feedback from when you spam the strike button.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b6a6pfwxgu0sfa218ljr.png) I was even sent screenshots of when the Kaomoji would break: ![The kaomoji were off-screen thus indicating that the battlefield wasn't adjusting to the viewport properly.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/esdevqonn8lmg286l84c.png) So I adjusted the Kaomoji structure accordingly, as well as came up with the logic to prevent block or strike "spamming" (hitting repeatedly with no consequences). ## Postmortem lessons This was definitely a fun project, not just created by me, but by those in my community. I think I should have opened up feedback to a wider set of people, especially those who are fighting game enthusiasts. If I had the time, I would have implemented the choice to play as either a human or bear and made the kaomoji SVGs instead of the traditional text-made artistry to make it more accessible. If I had the tech savvy, I would have made it a two-player game instead of one-player against a random number generator. --- Here are the links again if you want to try out this project! [Live Demo ](https://catcarbonell.github.io/killerkao/) [GitHub Repo](https://github.com/catcarbonell/killerkao) --- ## Thanks for reading! If you want to keep in touch, reach out to me via [Twitter](https://twitter.com/catcarbn)!
cat
928,125
All About Validators in Angular + Creating Custom Sync & Async Validators
Validators in angular are just simple functions that check our form values and return an error if...
0
2021-12-16T13:18:25
https://blog.sreyaj.dev/creating-custom-sync-and-async-validators-in-angular
angular, tutorial, webdev, typescript
Validators in angular are just simple functions that check our form values and return an error if some things are not the way its meant to be. Angular ships with a bunch of Validators out of the box. These can be used directly without the need for any configuration. ## Using validators in angular forms Validators can be set up in different ways to validate user inputs in form elements. Angular provides a lot of validators that are commonly needed for any form. If we special validation requirements or if we are dealing with custom components, the default validators might not just cut it. We can always create custom validators for these cases. ## In-built validators of angular Angular ships with different validators out of the box, both for use with Template forms as well as Reactive forms. - In-built Validator Directives. - A set of validator functions exported via the `Validators` class. Both the directives and `Validators` class use the same function under the hood. We can provide multiple validators for an element. What Angular does is stack up the validators in an array and call them one by one. ### Validator Directives Native HTML form has inbuilt validation attributes like `required`, `min`, `max`, etc. Angular has created directives to match each of these [native validation attributes](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Constraint_validation#validation-related_attributes). So when we place these attributes on an `input`, Angular can get access to the element and call a validation function whenever the value changes. Here's how you would use a validator directive: ```html <input type="email" required minlength [(ngModel)]="email"/> ``` The attributes `required` and `minlength` are selectors for the `RequiredValidator`( [ref](https://github.com/angular/angular/blob/0115e2b66493b06532f5399f3cad79e6149aed7f/packages/forms/src/directives/validators.ts#L347) ) and `MinLengthValidator` ( [ref](https://github.com/angular/angular/blob/0115e2b66493b06532f5399f3cad79e6149aed7f/packages/forms/src/directives/validators.ts#L550) ) directives respectively. These can be used with both **Template drive forms** and **Reactive Forms**. Here's how the `required `directive looks like: ```ts @Directive({ ... providers: [{ provide: NG_VALIDATORS, useExisting: forwardRef(() => RequiredValidator), multi: true }], ... }) export class RequiredValidator implements Validator { // ..... validate(control: AbstractControl): ValidationErrors|null { return this.required ? requiredValidator(control) : null; } // ..... } ``` Let's break down the code: 1. The class `RequiredValidator` implements an interface called `Validator`. 2. The `Validator` interface forces the class to implement a `validate()` method. 3. The method will be called for validation of the value. 4. The validation logic can be performed in the method and just have to return an object if there is an error or `null` if there is no error. 5. Now, we need to let Angular know about this custom validation that we've set up. 6. We use the `NG_VALIDATORS` Injection token for this. 7. We ask Angular to use our same `RequiredValidator` class by using the `useExisitng` property. So when the user places `required` on a form control, the `RequiredValidator` directive gets instantiated and the validator also gets attached to the element. Take a look into the [source code](https://github.com/angular/angular/blob/13.0.3/packages/forms/src/directives/validators.ts#L325-L386) for `Required Validator`( [ref](https://angular.io/api/forms/RequiredValidator) ). ### Validators class `Validators` class exposes a set of static methods that can be used when dealing with **Reactive Forms** like so: ```ts import { FormControl, Validators } from '@angular/forms'; export class AppComponent{ email = new FormControl('', [Validators.required, Validators.minLength(5)]); } ``` Here's the list of all the function inside the class: ```ts class Validators { static min(min: number): ValidatorFn static max(max: number): ValidatorFn static required(control: AbstractControl): ValidationErrors | null static requiredTrue(control: AbstractControl): ValidationErrors | null static email(control: AbstractControl): ValidationErrors | null static minLength(minLength: number): ValidatorFn static maxLength(maxLength: number): ValidatorFn static pattern(pattern: string | RegExp): ValidatorFn static nullValidator(control: AbstractControl): ValidationErrors | null static compose(validators: ValidatorFn[]): ValidatorFn | null static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null } ``` --- ## Custom Sync Validators We can also create custom validators in Angular which are tailored to our particular use case. You can't just always rely on the built-in capabilities of Angular. ![Custom Sync validators in Angular](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w0f4lbjmfm7xiu44tzmg.png) Validators are just functions of the below type: ```ts export interface ValidatorFn { (control: AbstractControl): ValidationErrors|null; } ``` Let's create a custom validator function that checks if a domain is secure (`https`) or not. ```ts export const ProtocolValidator: ValidatorFn = (control) => { const { value } = control; const isSecure = (value as string).startsWith("https://"); return isSecure ? null : { protocol: `Should be https URI` }; }; ``` #### Custom validator with parameters If we want our custom validator to be more configurable and re-use in multiple places, we can pass parameters to our validator function to create a validator based on the provided parameters. For example, if the Secure validator needs to validate Websocket URIs also, we can modify the `ProtocolValidator` to accommodate this change: ```ts export const ProtocolValidator = (protocol: string): ValidatorFn => (control) => { const { value } = control; const isSecure = (value as string).startsWith(protocol); return isSecure ? null : { protocol: `Should be ${protocol} URI` }; }; ``` ### Use custom validators in Reactive Forms We can directly use the function in the reactive forms like so: ```ts const urlControl = new FormControl('', [Validators.required, ProtocolValidator('https://')]); ``` and the template will be something like this: ```html <input type="text" [formControl]="urlControl" /> ``` ### Use custom validator in Template-driven Forms If we want to use these validators with Template-drive forms, we need to create a directive. ```ts @Directive({ selector: "[protocol]", providers: [{ provide: NG_VALIDATORS, useExisting: forwardRef(() => ProtocolValidatorDirective), multi: true }] }) export class ProtocolValidatorDirective implements Validator { @Input() protocol!: string; validate(control: AbstractControl): ValidationErrors|null { return ProtocolValidator(this.protocol)(control); } } ``` and we use it like this: ```html <input type="text" protocol="wss://" [(ngModel)]="url" /> ``` **Note**: For the directive selector, it's always a good idea to also look for whether there is a valid form connector added to the element: ```ts @Directive({ selector: '[protocol][formControlName],[protocol][formControl],[protocol][ngModel]' }) ``` What this translates to is that the element where our `protocol` directive is placed should also have either of these attributes: 1. formControlName 1. formControl 1. ngModel This makes sure that the directive is not activated on non-form elements and you won't get any unwanted errors. --- ## Custom async validators The process of creating async validators in angular is exactly the same, except this time we are doing our validation in an async way (by calling an API for example). ![Async validators in Angular](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hfwmzumz71pc4s5ti8gw.png) Here is the type of async validator function: ```ts interface AsyncValidatorFn { (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> } ``` The only thing that is different here is that the method now returns either an **Observable** or a **Promise**. Let's create an async validator by modifying the above validator that we wrote. Ideally, we will be using async validation for meaningful validations like: 1. Check username availability 2. Whether a user is blocked 3. If the user's phone number is part of a blocklist. Let's create an async validator to check if a username is available. We are gonna be creating 3 things: 1. **Username Service** - which makes the API call to see if the username is available 1. **Validator Service** - which contains the validation logic 1. **Validator Directive** - for using template-driven forms ### Username Service We'll mock the logic for this: ```ts @Injectable({ providedIn: "root" }) export class UsernameService { constructor(private http: HttpClient) {} isUsernameAvailable(username: string) { return this.http.get("https://jsonplaceholder.typicode.com/users").pipe( map((users: any[]) => users.map((user) => user?.username?.toLowerCase())), map( (existingUsernames: string[]) => !existingUsernames.includes(username) ), startWith(true), delay(1000) ); } } ``` ### Async Validator Service This is the main part of our validation process. ```ts @Injectable({ providedIn: "root" }) export class UsernameValidatorService implements Validator { constructor(private usernameService: UsernameService) {} validatorFunction: AsyncValidatorFn = (control) => control?.value !== "" ? this.usernameService .isUsernameAvailable(control.value) .pipe( map((isUsernameAvailable) => isUsernameAvailable ? null : { username: "Username not available" } ) ) : of(null); validate(control: AbstractControl) { return this.validatorFunction(control); } } ``` Why did we create a separate `validatorFunction()`? Why can't the logic be placed inside the `validate()` method itself? This is done so that, we can use the `validatorFunction()` when we are using Reactive Forms: ```ts export class AppComponent { constructor(private usernameValidator: UsernameValidatorService) {} username = new FormControl("", { asyncValidators: this.usernameValidator.validatorFunction }); } ``` Now to use the validator with **Template-driven** forms, we need to create a **Directive** to bind the validator to the element. ### Async Validator Directive ```ts @Directive({ selector: "[username][ngModel]", providers: [ { provide: NG_ASYNC_VALIDATORS, useExisting: UsernameValidatorService, multi: true } ] }) export class UsernameValidatorDirective {} ``` We provide `NG_ASYNC_VALIDATORS` instead of `NG_VALIDATORS` in this case. And since we already have the `UsernameValidatorService` (which implements the `Validator` interface). **Note:** `UsernameValidatorService` is `providedIn: 'root'`, which means the **Injector** has the service instance with it. So we just say use that same instance of `UsernameValidatorService` by using the `useExisitng` property. Angular takes care of subscriptions of these validators so we don't have to worry about cleaning the subscriptions later. ## Code and Demo {% codesandbox angular-async-validator-5idsm %} Code: https://codesandbox.io/s/angular-async-validator-5idsm **Note**: Open in a new window to see the demo properly. Make sure to not just use the code as-is. For the scope of this post, things are kept simple and straightforward. Take some time to see if you can improve something in the code before you use it. ## Connect with me - [Twitter](https://twitter.com/AdiSreyaj) - [Github](https://github.com/adisreyaj) - [Linkedin](https://www.linkedin.com/in/adithyasreyaj/) - [Cardify](https://cardify.adi.so) - Dynamic SVG Images for Github Readmes Do add your thoughts in the comments section. Stay Safe ❤️ [![Buy me a pizza](https://cdn.hashnode.com/res/hashnode/image/upload/v1639498527478/IA3aJ9R0J.png)](https://www.buymeacoffee.com/adisreyaj)
adisreyaj
928,295
Here are the top 25 DevOps Interview questions which is asked in DevOps interviews..
Operating system 1) What is the distinction among Linux and Unix ? 2) What’s a KVM ? 3) How might...
0
2021-12-16T14:24:59
https://dev.to/devopsacademy21/here-are-the-top-25-devops-interview-questions-which-is-asked-in-devops-interviews-3e81
devops, docker, kubernetes, tutorial
Operating system 1) What is the distinction among Linux and Unix ? 2) What’s a KVM ? 3) How might you ensure a help begins an OS of your decision ? 4) Here’s a terminal. What kind of Linux is running ? 5) Write an order to erase all unfilled record under a registry. 6) What is Active Directory ? How would you make a worker join an area ? Systems administration 1. What is the contrast among TCP and UDP ? 2. What is ICMP ? For what reason should you block it ? 3. What is IPv6 ? For what reason should we give it a second thought ? 4. In a professional workplace clients from London can ping a specific worker however clients from New York can’t, what steps will you take to investigate the issue ? 5. What steps are expected to change the host name on a Linux machine ? 6. Where is the host name document on a Windows worker ? 7. How is a host name settled on a Linux machine ? 8. What’s a SSL burrow ? 9. What’s a SDN ? Scripting (inquiries here change on rating and rely practically upon advising the individual to compose a short content) 1. What is your most loved scripting language ? Why ? 2. What are configuration designs ? 3. Portray a few contents you have composed/computerization you have done/programs you have composed. Legitimize your decision of scripting language and configuration designs. 4. Would you be able to port a similar content to another dialect ? On another OS ? 5. What amount of time would it require for you to get familiar with another dialect ? CI/CD Pipeline 1. How might you follow a twofold arrangement back to the source code ? How might you construction such a form ? 2. How would you oversee conditions ? 3. CI must be utilized to figure out arrange time blunders rapidly. Valid/False. Clarify. 4. How might you structure CD for an application that relies upon 3 other applications ? 5. How would you plan limit with regards to your CI/CD workers ? 6. All your fabricated doubles ought to be registered to your git/svn for snappy sending and posterity. Valid/False. Clarify. Thanks for going through the top 25 DevOps interview questions in 2021, we hope it served your purpose. That is everything we can consider at this moment. we will continue to refresh these as I consider more inquiries and subjects. To learn DevOps, Click https://devopsacademy.co/devops-training/
devopsacademy21
928,353
JavaScript Types
Hey All 👋 This is more of a notes rather than an article that I took while doing an course. In this...
0
2021-12-16T16:41:40
https://dev.to/thecoollearner/javascript-types-5b4k
javascript, webdev, beginners, programming
Hey All 👋 This is more of a notes rather than an article that I took while doing an course. In this article we will talk about JavaScript types and about typeof operator. --- **Based on the ES Specs the types are defined as -** _“An ECMAScript language type corresponds to values that are directly manipulated by an ECMAScript programmer using the ECMAScript language. ”_ So it pretty much explains itself that types have some kind of values that can be manipulated by us using javascript. **Let’s talk about the primitive types that we have -** ## Undefined It has only one value called **undefined**. Any variable which is not assigned a value has the value undefined. ## Null The Null type has exactly one value, called **null**. It represents an intentional **absence of object value**. ## Boolean This refers to two specific values - **true** & **false**. ## String The string type is generally used to represent the **textual data**. This is just the **double quotes** or **single quotes** string literal. ## Number The Number type is a double-precision 64-bit binary format IEEE 754 value (numbers between -(2^53 − 1) and 2^53 − 1). Also, it has three other values namely: **+Infinity**, **-Infinity**, and **NaN** ("Not a Number"). ## Object An Object is a **collection of properties**. Each property is either a **data property** or an **accessor property**. ## Symbol The Symbol type is the set of all non-String values that may be used as the key of an Object property. It is a unique and immutable primitive value. **Note -** Functions and arrays are treated as sub-type of Object type. **Note -** BigInt is now recognized as primitive type which is supported by most of the browsers. ```javascript typeof(23423432423423423424234n) // 'bigint' ``` Read more about BigInt - [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#bigint_type) --- ## typeof We can use **typeof** operator to check the type of the value stored in a variable. **Let’s see some examples -** ```javascript var a; typeof(a); // 'undefined' a = 5; typeof(a); // 'number' a = "Apple"; typeof(a); // 'string' a = true; typeof(a); // 'boolean' a = {}; typeof(a); // 'object' ``` Here, one thing to note is that it **returns the type in string**. So if you have a piece of code like this - ```javascript if(typeof(a) === Number){ ... } ``` It’s not gonna work as you intend to. The correct way to do this is by using **number as a string**. ```javascript if(typeof(a) === 'number'){ ... } ``` **Let’s have a look at some tricky ones -** ```javascript typeof(doesntExist); // 'undefined' var v = null; typeof(v); // 'object' v = function(){}; typeof(v); // 'function' v = [1,2,3] typeof(v); // 'object' ``` Here we can see that the type of a variable which is **not declared** yet or **doesn’t exist** is **‘undefined’**. Unlike typeof(undefined) which returns 'undefined', typeof(null) **returns 'object'** which is actually a **historical bug**. And now it can’t be fixed as a lot of legacy apps will break because of it. Though **function** is not a type but it’s typeof() **returns 'function'** but that’s not the case with an **array** as typeof([]) **returns ‘object’**. --- I'll be posting more of my notes on JS topics, So stay tuned :) [Say Hi 👋👋👋](www.twitter.com/thecoollearner)
thecoollearner
928,361
Is automated testing better than manual?
There is indeed a tendency to automate almost any process and QA in particular. Of course, automation...
0
2021-12-16T17:00:19
https://dev.to/okqa/is-automated-testing-better-than-manual-4nel
testing, qa, okqa
There is indeed a tendency to automate almost any process and QA in particular. Of course, automation makes manual testing more efficient, but it goes only for simple, repetitive tests. For complex test cases, short-term projects, human feedback on the application usability, manual testing is the best and the most profitable option. This type of testing allows to bring in a human perspective, costs less in set up terms, and is more flexible and adaptable to project changes. Facing manual vs. automated testing dilemma? Let's get in touch to discuss and set up the test process that’s just right for you!
okqa
928,388
Solidity for Swift developers: File Structure and Functions
Solidity is an object-oriented language to write smart contracts that can be deployed on the blockchain, for instance, Ethereum. The syntax is similar to Javascript, but on the other hand, semantics is closer to C++. We will dig into Solidity language structure and functions from a Swift developer's perspective.
0
2021-12-16T17:53:04
https://dev.to/fassko/solidity-for-swift-developers-file-structure-and-functions-3p0b
swift, solidity
--- title: Solidity for Swift developers: File Structure and Functions published: true description: Solidity is an object-oriented language to write smart contracts that can be deployed on the blockchain, for instance, Ethereum. The syntax is similar to Javascript, but on the other hand, semantics is closer to C++. We will dig into Solidity language structure and functions from a Swift developer's perspective. tags: swift, solidity //cover_image: https://direct_url_to_image.jpg --- Solidity is an object-oriented language to write smart contracts that can be deployed on the blockchain, for instance, Ethereum. The syntax is similar to Javascript, but on the other hand, semantics is closer to C++. We will dig into Solidity language structure and functions from a Swift developer's perspective. ## Pragma and file extension Before we jump into the Solidity language structure, we need to know what a `pragma` keyword is and what it means. Unlike the Objective-C `#pragma` and Swift `MARK`, the' pragma' keyword in Solidity describes what version of the compiler should use. Keep in mind that it instructs the compiler to check if the versions do match. It does not turn on or off any language features. For instance, if we would like to tell the Solidity compiler that we want to use the 0.8.x version, we can start the source file like this: ``` pragma solidity ^0.8.0; ``` We can also use greater or smaller operations to describe even the version interval, which could be handy. There are other ways to use the `pragma` keyword, but we won't look into that this time. Solidity source files are saved with the `.sol` extension. ![Solidity file](https://kristaps.me/assets/solidity-swift-developers-structure/solidity-file.png) ## Everything starts with a Contract Contracts in Solidity language are similar to classes in Swift. Contracts contain state variables, functions, function modifiers, events, errors, structs, and enums. This time we are only going to look into function structure. Like classes, we need to name it and open, and close with braces. ``` contract HelloSwiftFromSolidity { } ``` ## State Variables State variables are variables that are declared inside the `contract`. Be aware that this information is stored on the blockchain contract storage once you deploy it. We don't need to worry about getters and setters. Solidity compiler generates that for us. ``` contract HelloSwiftFromSolidity { string hello; } ``` You can notice now that each execution line should end with the semicolon `;`. That is not the case for the Swift language. ## Functions Functions can be declared inside and outside the `contract`, similar to Swift. They can execute a piece of code. ``` contract HelloSwiftFromSolidity { // visibility = public because access from outside string public hello = "Hello Swift"; // visibility = public because access from outside // view = just view the data function helloSwift() public view returns(string memory) { return hello; } } ``` It is going on a lot, so let's break it down. If we want to access the state variable from outside, we need to set the visibility type to `public` and do the same for the function. In our case, the function returns something, and we can mark it as `view`. It returns a string that is stored in the memory and removed after the execution is finished. The places, where the function variables and return data can be stored, are: * `memory` - the lifetime of the variable is limited to the function scope, it isn't saved anywhere; * `storage` - data is stored in the smart contract storage on the blockchain; * `calldata` - data is stored outside from where the function is being called, we will discuss more details and how to use it in the future. ### Function types Functions in Solidity can execute instructions, view data. It can be a `view` or `pure` when we view the data. The difference between these two is that pure functions don't modify nor read the state variables. ``` function helloWorld() public pure returns(string memory) { return "Hello World"; } ``` In the code above, we are not reading nor changing anything on the blockchain but just returning some data. ## TL;DR Solidity is a language to write the smart contracts that can be deployed on the blockchain. The most popular currently is Ethereum. From a Swift developer's perspective, language is quite similar syntax-wise but very different semantics-wise. First of all, every execution line should end with a semicolon. In Solidity equivalent to the Swift classes are contracts that can contain state variables, functions, and other structures. ## Links * [Layout of a Solidity Source File](https://docs.soliditylang.org/en/v0.8.10/layout-of-source-files.html) * [Structure of a Contract](https://docs.soliditylang.org/en/v0.8.10/structure-of-a-contract.html) * [Ethereum Developer Resources](https://ethereum.org/en/developers/)
fassko
928,552
Make Your Windows PC Greet You According to Current Time
As I have written the previous post on a very interesting topic that was about to Make your Computer...
0
2021-12-16T20:02:52
https://dev.to/ith/make-your-windows-pc-greet-you-according-to-current-time-4pmp
javascript, programming, beginners, productivity
![Make your PC Greet you](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r04r6hfhf54y78uo1zmf.jpg)As I have written the previous post on a very interesting topic that was about to Make your Computer Greet you but that was very first and basic Script to do that. Now it’s time to do something new, hilarious and awesome. So this script will make your computer greet you with the current time of your PC. Example: Good Morning user, the current time is 8:30 AM. Yes, you heard it Right this script will detect the Current time and Greet you Accordingly. Like an intelligent Programme. Good morning in the morning Before 12′ o Clock and after that Good Afternoon and Good Evening and Midnight. If you want a simple “Hello READERS! Welcome to indiantechhunter.in” greeting at the startup of your window PC then do check our old previous post on how to make your computer welcome you. <h3>1st Step To Make your PC greet you according to Time:</h3> Open any Text Editor that you are comfortable with or you like as I have told you that we are going to do some simple Copy+Paste and Change some text in it. So we simply Use Notepad that is already available on your PC. To open the notepad, You can press the Win Logo Button+R to open the RUN dialogue box and type ‘notepad’ in the search box and hit ENTER. OR Press on the Windows Home button and type notepad to search it. <h3>2nd Step to make your computer Greet you according to the current Time:</h3> Copy the Code given Below and Paste it in the Text Editor. You have to change some words or some of them should replace according to you. For example, let’s Suppose your name is Prashant/Priyanka, then You should replace the text ‘User’ with Prashant/Priyanka. in the following code. Copy this code And Paste it into the Text editor ``` Set Sapi = Wscript.CreateObject("SAPI.SpVoice") dim zira if hour(time) < 12 then Sapi.speak "Good Morning User" else if hour(time) > 12 then if hour(time) > 16 then Sapi.speak "Good evening User" else Sapi.speak "Good afternoon User" end if end if end if Sapi.speak "The current time is " if hour(time) > 12 then Sapi.speak hour(time)-12 else if hour(time) = 0 then Sapi.speak "12" else Sapi.speak hour(time) end if end if if minute(time) < 10 then Sapi.speak "o" if minute(time) < 1 then Sapi.speak "clock" else Sapi.speak minute(time) end if else Sapi.speak minute(time) end if if hour(time) > 12 then Sapi.speak "P.M." else if hour(time) = 0 then if minute(time) = 0 then Sapi.speak "Midnight" else Sapi.speak "A.M." end if else if hour(time) = 12 then if minute(time) = 0 then Sapi.speak "Noon" else Sapi.speak "P.M." end if else Sapi.speak "A.M." end if end if end if ``` Caution: Don’t Change anything other than USER. Replace User with your Good Name to call your name by Your Narrator. If you change any other part of the script/Code, then Script may break and may not Work. Do it at your own risk. <h3>3rd step to Save the Code/Script:</h3> This is the most important step and here you should be more Careful. Because we are not Going to save this file as (.TXT) or (.PDF) or (.DOCX) and anything like that. You must save this Script with [.vbs]. To save it press ctrl+s and you can rename it like [welcome.vbs] as we have shown you in the following picture. ![Saving welcome file](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ujz13dxk4hdpy30i0xgy.jpg) <h3>Step 4th the Final Most Important Step:</h3> Well! Will your computer started Greeting you? Are you Done? Not at all because you haven’t done the most important step. The final step is to move the created welcome.vbs file to the startup folder. For that, you just Press Windows Logo key+R to open the “Run” Dialogue box or just press the Window logo key and type Run which will search the Run box. Then in the open: box, type, “shell:startup” and hit Enter. Now it will open a new window in the File Explorer. Further, just Drag and drop the welcome.vbs in that folder which you were saved on your desktop. That’s it. Now, whenever you start your Windows device it will greet you. <h4>Ease for You as a Bonus</h4> Maybe you are reading it on your smartphone or for any reasons you may not be unable to copy-paste the script above. So here I have done half of your work, just download and paste the Welcome.vbs file to the location mentioned above. What you want in the next Post from my end? Feel free to suggest to me any tricks, tips or anything related to technology. Comment below the topic you want to be covered in this blog, I will definitely cover that topic. For Now, share this post with your Friends and Family if you think you have Learnt anything from this post. For contacting me you can reach me on <br><a href="https://www.youtube.com/channel/UCzWsfjkSaT1tp92xcVDNZCQ/about">Youtube,</a> <br><a href="https://www.quora.com/profile/Indian-Tech-Hunter-1">Quora,</a><br> <a href="https://www.instagram.com/indian_tech_hunter/?hl=en">Instagram,</a><br> <a href="https://twitter.com/indiantechunter">Twitter</a>.
ith
928,585
Render html tags based on condition in asp.net core
If you are using Razor in your applications based on ASP.NET CORE, sometimes you might want to check...
0
2021-12-17T09:57:18
https://dev.to/uthmanrahimi/render-html-tags-based-on-condition-in-aspnet-core-4chm
csharp, netcore, aspnetcore
If you are using Razor in your applications based on `ASP.NET CORE`, sometimes you might want to check something and according to that generate `HTML` tags and show them to clients. For example one of the common things is when we check to know if a user is logged-in or not, if User is not logged-In we would show the Login button otherwise show the `Sign-out` button. To accomplish this, we end up with a code like this: ``` if (User.Identity.IsAuthenticated) { <a href="/Account/Signout">SignOut</a> } else { <a href="/Account/SignIn">SignIn</a> } ``` This is fine and does what we want, but there is one more way that I think is much more cleaner and that is using `Tag Helper`. After implementing a custom Tag Helper, we can refactor our code and render HTML tags like below: ``` <a href="/Account/Signout" condition=="@User.Identity.IsAuthenticated">SignOut</a> ``` As you can see above, there is no `if` statement and just used `condition` in `HTML` tag and passed it a `boolean` value. Implementation of `Condition` tag helper is: ``` using Microsoft.AspNetCore.Razor.TagHelpers; namespace CustomTagHelpers.TagHelpers { [HtmlTargetElement(Attributes = nameof(Condition))] public class ConditionTagHelper : TagHelper { public bool Condition { get; set; } public override void Process(TagHelperContext context, TagHelperOutput output) { if (!Condition) { output.SuppressOutput(); } } } } ``` To make this `tag helpe` available throughout all `views`, add its `namespace` to `_ViewImports.cshtml` > Condition tag helper renders output when passed a true value.
uthmanrahimi
928,599
Generating PDFs in React with react-pdf
Written by Hussain Arif ✏️ Assume that you own a successful online business. In such a place, you...
0
2021-12-16T22:18:14
https://blog.logrocket.com/generating-pdfs-react/
react, webdev, tutorial, programming
**Written by [Hussain Arif](https://blog.logrocket.com/author/hussain-arif/)** ✏️ Assume that you own a successful online business. In such a place, you would need to generate invoices and email them to your customers. To create a receipt for each buyer, you would have to do the following: * Open your word processor and paste the user’s personal information * Write the user’s purchases in a table and calculate the total * Download this file and convert it to PDF format * Email this document to the user Sure, that might work. But consider this: what if you get hundreds of customers in a single day? This would waste a lot of time and energy since you’re doing the same process over and over again. So, how do we mitigate this problem? The best way to solve this issue is to automate this operation by using an API. This is where [react-pdf](https://react-pdf.org/) comes in. It is an open source, easy-to-use library that allows developers to generate PDF documents in a React environment. In this article, you will learn the basics of the [react-pdf](https://react-pdf.org/) library. We will cover the following concepts: * [Simple usage](#simple-usage) * [Fundamental components](#fundamental-components) * [Embedding links](#embedding-links) * [Displaying annotations](#displaying-annotations) * [Displaying graphics in a `Canvas`](#displaying-graphics-in-a-canvas) * [Displaying SVG images](#displaying-svg-images) * [Rendering JPG or PNG photos](#rendering-jpg-or-png-photos) * [Advanced concepts](#advanced-concepts) * [Using flex boxes](#using-flex-boxes) * [Page breaks](#page-breaks) * [Dynamic page content](#dynamic-page-content) ## Installation To install the react-pdf package, run the following terminal command: ```react npm i @react-pdf/renderer ``` ## Simple usage The following block of code renders a basic PDF document in the browser: ```react import { Document, Page, Text, View, StyleSheet, PDFViewer, } from "@react-pdf/renderer"; // Create styles const styles = StyleSheet.create({ page: { backgroundColor: "#d11fb6", color: "white", }, section: { margin: 10, padding: 10, }, viewer: { width: window.innerWidth, //the pdf viewer will take up all of the width and height height: window.innerHeight, }, }); // Create Document Component function BasicDocument() { return ( <PDFViewer style={styles.viewer}> {/* Start of the document*/} <Document> {/*render a single page*/} <Page size="A4" style={styles.page}> <View style={styles.section}> <Text>Hello</Text> </View> <View style={styles.section}> <Text>World</Text> </View> </Page> </Document> </PDFViewer> ); } export default BasicDocument; ``` A few inferences from this code: * The `StyleSheet` module allows developers to apply CSS code on their PDF documents. Here, we are telling React to change the background color and the font color of our pages * Furthermore, in the `viewer` object, we are using the `width` and `height` properties. As a result, this will tell react-pdf that we want the browser’s PDF viewer to take up all of the space on the page * As the name suggests, the `PDFViewer` component will render a PDF viewer on the browser Let’s test it out! As the next step, render the `BasicDocument` component to the DOM like so: ```react import BasicDocument from "./BasicDocument"; function App() { return ( <div className="App"> <BasicDocument /> </div> ); } export default App; ``` ![Rendering the BasicDocument Component to the DOM](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdfs-react-react-pdf.png) We can even reduce the viewer’s available space: ```react const styles = StyleSheet.create({ viewer: { width: window.innerWidth / 3, height: window.innerHeight / 2, }, //further code... }); ``` In this snippet, we restricted the viewport’s `width` and `height` properties. This will decrease their available size on the page. ![Decreasing the Viewport's Width and Height Properties](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdfs-react-react-pdf-2.png) ## Fundamental components ### Embedding links We can display anchor links using the [`L` component](https://react-pdf.org/components#link). This is handy for cases where you want to redirect the user to a website: ```react import { Link } from "@react-pdf/renderer"; <Text> <Link src="www.facebook.com">Go to Facebook</Link> </Text> ``` Here, we are assigning the `src` prop to Facebook’s website. When the user clicks on this piece of text, the app will redirect them to the page. ![App Redirecting Users to a Different Page](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdf-react-react-pdf-3.gif) ### Displaying annotations To attach annotations in your document, use the [`Note`](https://react-pdf.org/components#note) component. One critical use case for this element is when you need to display comments in a file: ```react import { Note } from "@react-pdf/renderer"; <Note>This will take the user to Facebook</Note> ``` ![Attaching Annotations Using the Note Component](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdf-react-react-pdf-4.gif) ### Displaying graphics in a `Canvas` The [`Canvas`](https://react-pdf.org/components#canvas) component lets users draw content on the page. This is suitable for displaying simple diagrams and logos in SVG format. This code snippet renders a triangle on the page: ```react import { Canvas } from "@react-pdf/renderer"; // Create styles const styles = StyleSheet.create({ canvas: { backgroundColor: "black", height: 500, width: 500, }, }); <Canvas style={styles.canvas} paint={ (painterObject) => painterObject .save() .moveTo(100, 100) //move to position 100,100 .lineTo(300, 100) //draw a line till 300, 100 .lineTo(300, 300) //draw another line till 300,300 .fill("red") //when the diagram is drawn, set the background color to pink } /> ``` In the above snippet, we used the `Canvas` component to display a diagram. The `paint` prop is a callback function. One of its parameters is a `painterObject` argument, which gives us access to drawing methods. ![Rendering a Triangle on the Page](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdf-react-react-pdf-5.png) ### Displaying SVG images react-pdf also bundles an [`SVG` component](https://react-pdf.org/svg) to render [SVG diagrams](https://blog.logrocket.com/how-to-use-svgs-in-react/). Just like `Canvas`, we can use this for rendering simple diagrams. This piece of code renders a line on the page: ```react import { Line, Svg } from "@react-pdf/renderer"; // Create styles const styles = StyleSheet.create({ line: { x1: "0", //starting coords are x1 and y1 y1: "0", x2: "200", //ending coords: y2: "200", strokeWidth: 2, stroke: "rgb(255,255,255)", //stroke color }, }); <Svg width={"50%"} height={"50%"} style={{ backgroundColor: "blue" }}> <Line style={styles.line} /> </Svg> ``` Here, we used [`Line`](https://react-pdf.org/svg#line) to render a line in the document. Notice that `Line` is a child of the `Svg` component. ![Rendering a Line in the Document](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdfs-react-react-pdf-6.png) We can also use the [`Polygon`](https://react-pdf.org/svg#polygon) component to render closed shapes like so: ```react <Svg width={"50%"} height={"50%"} style={{ backgroundColor: "blue" }}> <Polygon points="100,100 200,100 200,250 100,250" fill="white" //color of background stroke="black" //color of border strokeWidth={10} //border thickness /> </Svg> ``` The `points` prop accepts a dataset of coordinates. This will help the app render the graphic. ![Rendering Closed Shapes in the Document](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdfs-react-react-pdf-7.png) ### Rendering JPG or PNG photos The [`Image`](https://react-pdf.org/components#image) component gives us the ability to insert images over the network or on a local disk. This is great for displaying complex diagrams or screenshots. This block of code renders a 500 by 500 pixel image on the PDF: ```react import { Image } from "@react-pdf/renderer"; const styles = StyleSheet.create({ image: { width: 500, height: 500, }, }); <Image style={styles.image} src="https://image.shutterstock.com/image-photo/tiny-floating-house-on-lake-600w-1980476267.jpg" /> ``` The `src` prop contains the source URL of the image that we want to render. ![Rendering a Pixel Image on the PDF](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdfs-react-react-pdf-8.png) ## Advanced concepts ### Using Flex boxes Just like CSS, react-pdf lets developers use the `flex` property, which allows for responsive design. This is handy for cases where you want your documents to scale up or down depending on the device’s screen size: ```react // Create styles. Notice that we have specified a flex direction. const styles = StyleSheet.create({ page: { flexDirection: "column", }, }); <Page size="A4" style={styles.page}> <View style={{ backgroundColor: "black", flex: 1 }}></View> <View style={(styles.section, { backgroundColor: "pink", flex: 1 })}></View> </Page> ``` In this piece of code, we used the `flex` property on both of our `View` components. This means that half the page will have a background color of black and the other half will have a pink colored background. ![Using the Flex Property so the Background is Half Black and Half Pink](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdfs-react-react-pdf-9.png) ### Page breaks Page breaks are useful for ensuring that a certain element will always show up on the top of the page. We can enable page breaks via the `break` prop like so: ```react // Create styles const styles = StyleSheet.create({ text: { fontSize: 40, }, }); // Create Document Component <Page> <Text break style={styles.text}> First PDF break </Text> <Text break style={styles.text}> Second break </Text> </Page> ``` ![Enabling Page Breaks](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdfs-react-react-pdf-10.gif) ### Dynamic page content With react-pdf, we can render dynamic text using the `render` prop of the `Text` component like so: ```react <Document> <Page size="A4"> <Text style={styles.text} render={({ pageNumber, totalPages }) => `Page ${pageNumber} of ${totalPages}` } fixed /> </Page> <Page> <Text> Hello, second page!</Text> </Page> </Document> ``` Here, the `render` prop has two arguments: `pageNumber` (the current index of the page), and `totalPages` (the total number of pages that this document contains). We are displaying both of their values to the client. ![Displaying Both Page Number and Total Pages to the Client on the Document](https://blog.logrocket.com/wp-content/uploads/2021/12/generating-pdfs-react-react-pdf-11.png) _N.B., the_ `render` _function is executed twice for_ `<Text />` _elements: once for layout on the page wrapping process, and another one after it knows_ _how many pages the document will have._ _Therefore, use it in cases where app performance is not a problem._ We can also use the `render` prop on our `View` element: ```react <View render={({ pageNumber }) => ( //detect if user is NOT on an even page: pageNumber % 2 === 0 && ( <View style={{ background: 'red' }}> {/*If condition is fulfilled, display this component*/} <Text>I'm only visible in odd pages!</Text> </View> ) )} /> ``` ## Conclusion In this article, we covered the fundamentals of the react-pdf library. Not only is it secure and robust, but it is also lightweight, thus bringing performance to the table. Thank you so much for reading! Happy coding! --- ## Full visibility into production React apps Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, [try LogRocket](https://www2.logrocket.com/react-performance-monitoring). [![LogRocket Dashboard Free Trial Banner](https://blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png)](https://www2.logrocket.com/react-performance-monitoring) [LogRocket](https://www2.logrocket.com/react-performance-monitoring) is like a DVR for web apps, recording literally everything that happens on your React app. Instead of guessing why problems happen, you can aggregate and report on what state your application was in when an issue occurred. LogRocket also monitors your app's performance, reporting with metrics like client CPU load, client memory usage, and more. The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores. Modernize how you debug your React apps — [start monitoring for free](https://www2.logrocket.com/react-performance-monitoring)
mangelosanto
928,678
Testing redux in react native with testing library
This post is also available as a youtube video that can be checked out here: The video version...
0
2021-12-16T23:43:01
https://dev.to/gabrieleloy/testing-redux-in-react-native-with-testing-library-d4b
reactnative, react, redux, testing
This post is also available as a youtube video that can be checked out here: {% youtube Uh01lkHDaKw %} The video version covers the topic with more depth than this article, and I highly recommend you check it out ## Redux Redux is undeniably one of the most well known and widely used state management libraries available. There was a time it was nearly impossible to hear the keywords react or react native with an "and redux" append at the end. Today, even though redux is far from its monopoly days, it still is a super relevant tool, and a common doubt many people have is how to test redux applications. Many times, I've heard the question > "What changes when testing a react (native) + redux application ?" The answer to that is, **almost nothing**. In this tutorial, we'll be using [react native testing library](https://callstack.github.io/react-native-testing-library/) and the main philosophy of this library is focusing on testing how your application works, instead of its implementation. A major positive point of this testing strategy, is only caring about what's important, the software's functionality. So, if you restructure your entire codebase, but everything still works as before, your tests won't break. But, even though the tests themselves don't change, the way you render your tests must change to accommodate redux needs. Usually, when testing a component we only render it, like the following example ```javascript import { render } from '@testing-library/react-native'; import Component from 'component' describe('When testing a component', () => { it('Usually only render the component itself', () => { render(<Component />); }) }) ``` But, if you are familiar with redux, you know that every component which uses redux must be wrapped inside a provider with a valid store. If we try to render a component which relies on redux for its state management without the expected provider, we the following error will be thrown ``` could not find react-redux context value; please ensure the component is wrapped in a <Provider> ``` The way to solve this, is by simply wrapping your rendered component in a provider, like the following ```javascript import { render } from '@testing-library/react-native'; import Component from 'component' import { Provider } from 'react-redux'; import yourStore from './store'; describe('When testing a redux component', () => { it('Should be wrapped by a provider', () => { render( <Provider store={yourStore}> <Component /> </Provider> ); }) }) ``` But, doing this every time will pollute our code base, and there must be a better way to handle this rendering, don't you agree ? Thankfully for us, we can leverage the existence o [jest globals](https://jestjs.io/docs/api) If you are not familiar with jest globals, or jest itself, here goes a quick explanation: Jest - is a test runner shipped by default in react native projects globals - globals are globally available helper functions, usable in our test suite without the need to import them Although a jest global for rendering redux applications does not exist, we can easily create new globals with jest. So let's create a global called renderWithRedux, which will encapsulate this logic for us ## Creating globals To create a redux global, the first thing we'll need is editing our package JSON to expect a [setupFile](https://jestjs.io/pt-BR/docs/configuration#setupfiles-array) Search your the following line in your file ```json "jest": { "preset": "react-native" } ``` and edit it to look like this ```json "jest": { "preset": "react-native", "setupFiles": ["<rootDir>/setupTests.js"] } ``` Basically what we are doing here is telling our application to read a setup file which resides in our root directory, hence the rootDir tag, and is called setupTests.js But, this file does not exist yet, so, create it, and leave it blank for now. ## Creating our rendering function First start by creating a folder called helpers, and inside of it, create another folder, called testHelpers. Inside the testHelpers folder, create a file called renderWithRedux.js Inside that file, let's create our helper. it will look something like this ```javascript import { configureStore } from '@reduxjs/toolkit'; import reducers from '<pathToYourReducers>'; // this is not a real path import { Provider } from 'react-redux'; import { render } from '@testing-library/react-native'; export function renderWithRedux(renderedComponent){ const store = configureStore({ reducer: { ...reducers }, }); return render(<Provider store={store}>{renderedComponent}</Provider>) } ``` > In this example I use [redux toolkit](https://redux-toolkit.js.org/) to create my store, but you can use whichever method you like, as long as it generates a valid store at the end the renderWithRedux function expects renderedComponent and then renders it wrapped in a provider, so you won't have to manually do this every time at the end, the result of our render is returned a store is created every time to ensure a clean test state. This is important to ensure each test is running in isolation and hence when you add a new test, you don't risk breaking pre-existing tests, which was a possibility if we didn't take this measure. ## Exposing our function globally With our function created, all we have left to do before we're able to use this function in our codebase is make it globally available in our setup function. Open our prior created setupTests.js file, and populate it with the following code: ```javascript import { renderWithRedux } from "<pathToTestHelpers>/renderWithRedux"; //Not a real file global.renderWithRedux = renderWithRedux; ``` in the following piece of code: ```javascript global.renderWithRedux = renderWithRedux; ``` you are extending the global object, and adding a new property called renderWithRedux to it, with the value of our renderWithRedux function. From this point on we can use this function to render components which rely on redux, so, doing the following: ```javascript import ComponentWithReduxData from 'componentWithReduxData' describe('When rendering a component that uses redux data with the renderWithRedux global', () => { it('Should render correctly', () => { renderWithRedux(<ComponentWithReduxData />); }) }) ``` will be a valid operation, and should mitigate any error related to redux rendering in our application renderWithRedux returns the exactly same [query methods](https://callstack.github.io/react-native-testing-library/docs/api-queries) as testing library's render method There it is, now you can your redux functions using a global function instead of redux boilerplate
gabrieleloy
928,925
How to develop collaboratively and remotely with your team in 5 minutes
Recently my friend Wendy, a front-end engineer, was working on an open source project based on her...
0
2021-12-17T08:48:53
https://dev.to/trystancocolatte/how-to-develop-collaboratively-and-remotely-with-your-team-in-5-minutes-22n5
programming, opensource, devops, productivity
Recently my friend Wendy, a front-end engineer, was working on an open source project based on her own ideas. To help users learn more about the project and try it out, she planned to build a user manual website using the Nextjs front-end framework. When writing the document, she thought of me, her product manager friend, and hoped that I could help her develop the website together to provide better user experience. Wendy had taught me a lot about front-end technologies, so I said yes immediately. However, here came the problem, her website wasn't online yet. To preview the project in advance, I needed to install her project locally. This stumped me, as I had learned some front-end basics during my work, but it was still difficult for me to actually install the environment and start the project by myself. After I explained my concerns to Wendy, she came up to my computer. Five minutes later, she showed me a Welcome page. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/89cx49a6ixucyi5kf7m8.png) Surprised and Confused, I asked her: "What is it? How could a front-end project be installed in such a short time?" She said that the Welcome page was the running result of [TeamCode](https://www.teamcode.com/)'s [Pylon](https://www.teamcode.com/products/pylon), a development environment in the cloud and a live preview. Then Wendy showed me the process of project pull-up. Just filling in the Git address could automatically generate the development environment. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tfykwfzky8i06ifq1v9k.png) The project was created successfully. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9jeboqrm2743xaz4c7or.png) I could choose to open the project using cloud-IDE or a local IDE, and here we used the cloud-IDE,so that our subsequent collaborative development could be more convenient. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6czrtqov5rgko84u0xqz.png) She also showed me her development interface and demonstrated the project start-up process. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zw4s0mtj4ovqh35nw3ow.png) With just one click the development environment was generated and saved. In addition, it could automatically expand the capacity, and support the local IDE. Pylon allowed development in collaboration with team members and the remote synchronization of the coding process. ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wi9p34nnq308trgiehcl.png) I asked her was this VS Code? She said it was VS Code in the cloud, and the experience was the same as local. With the popularity of cloud computing, many software based on traditional desktop is migrating to the cloud, and cloud-based integrated development environment is emerging. Pylon is one of them, it's a lightweight remote collaborative development environment. Developers can edit and preview project changes online anytime, anywhere, without the traditional CI\CD path. TeamCode's Pylon tool is the perfect solution to the time-consuming and laborious pain points of development environment installation.
trystancocolatte
928,951
What Is Event-Driven Machine Learning?
Machine learning algorithms will build a model based on sample data to decide or predict without...
0
2021-12-17T09:34:43
https://rudderstack.com/guides/what-is-event-driven-machine-learning/
eventdriven, machinelearning, cdp, dataengineering
Machine learning algorithms will build a model based on sample data to decide or predict without being explicitly programmed. This sample is also known as training data, and it's the key to any precise analysis. The highly modern technology is mostly used in healthcare, where diagnostics are predicted for doctors' reviews. The sentiment analysis that tech giants are doing on social media is another interesting way to apply machine learning, fraud detection in the finance sector, and predicting customer churn in eCommerce. Buckle up, and let's dive deeper into the essence of machine learning, its overall impact on technology and businesses, and its core industry applications. Better Software With Machine Learning ------------------------------------- The possibility of machine learning has introduced new encouraging abilities in the software engineering world. All types of software applications are personal assistants trained to answer predetermined questions such as *Will these types of customers purchase that kind of products? *Earlier, the only way to build software was to code human-defined rules for a specific application whose purpose was to answer those particular questions. Back in those *ancient* times, the human operator had to tell the software how to calculate the probability of a specific customer purchasing a certain product! However, instead of giving the software a specific command on doing a certain calculation, we can now provide precedents from the past using machine learning. Now, the software can make thorough data analysis and come up with its own rules. This entire process is what we now call "learning." Data is the most crucial element in the process of machine learning. The overall data quality will decide the software-defined rules and their quality. If the required information is not met, the software will not find the correct answers. Answering the question about getting the most data is the key to leveraging the power of machine learning. Event-Driven Data Collection ---------------------------- The initial and essential step in any data science project is data collection. There are numerous ways when it comes to collecting data - from one or many sources. Sometimes it is hard to have direct entry to essential but sensitive information when working with enterprises. Many times, data scientists need to request data dumps. This implementation may prevent accidents, but it separates ongoing projects and enterprise reality. It averts teams from having real-time data access. It also requires activating various bureaucratic-based processes that will further cause additional work. This can be fixed with event-driven data collection. Data scientists can recreate brand new and real-time data by just listening to events emitted by the enterprise systems. Moreover, a data scientist can process the data with no risks of altering the enterprise data whatsoever. The enterprise system can also anonymize any kind of sensitive information or filter it. However, there is one requirement for the enterprise system: to adopt an event sourcing or event-driven. Event-Driven Data Exploration ----------------------------- Data scientists need to pre-process and filter the correct information to produce the most accurate answers. Data exploration is crucial to finding the correct combination of transformations to deliver the optimal data for the machine learning model. Thanks to a huge variety of data visualization tools, understanding data through visual representation helps us grasp its underlying connections. Remember, events are essentials to master data! The use of events will assist data scientists in putting all data into context. The reason for any data modification cannot be discovered if there are limits to the exploration process, which should be applied to the mutable data. The updated data cannot be explored without calculating the previous value. All supplementary information events will provide patterns, habits, and highlight behavior, among other things. More qualitative data can be achieved by increasing machine learning capabilities. The enhancement of these capabilities can be further achieved with the overall process of event-driven data exploration. Event-Driven Data Preparation ----------------------------- When a product is developed, data scientists don't design it for data machines but for humans. A machine cannot understand something like literature, but the human brain can process it as easily as focused reading. However, a human brain will have difficulty calculating massive matrix operations, while the machine will do it with ease. This tells us that machines cannot compute abstract data, but this field is humans' expertise. To optimize machine learning, scientists need to convert this human-centric data. Data preparation will pre-process, specialize, and clean data for each ML model. Since each model will be set to answer questions different from one another, the data coming from a single model won't fit another's requirements. The event-driven data technique can dramatically shorten the otherwise arduous task by incrementally producing specific data in a way that will process incoming events in continuity, making it a very valuable tool. Summary ------- While machine learning is nothing new, not all current companies have the potential to store exponential data volumes and use it adequately in equipping soon-to-be learning machines. In other words, not being able to enforce machine learning properly will prevent many, and especially smaller enterprises, from acquiring a favorable business outcome. In due time, and as technology continues to evolve, the models based on which machine learning now operates are expected to be facilitated and made available for all-size enterprises. The biggest hope researchers have in terms of sophistication of machine learning in the foreseeable future lies in making current models far more flexible and applicable. This will ultimately train respective machines to handle more than one task at a time - all by learning faster, smarter, and better. ### Sign Up For Free And Start Sending Data Test out our event stream, ELT, and reverse-ETL pipelines. Use our HTTP source to send data in less than 5 minutes, or install one of our 12 SDKs in your website or app.[Get Started](https://app.rudderstack.com/signup?type=freetrial)
teamrudderstack
929,024
What I Learn From Trying Selenium on VPS
Currently, I'm exploring various ideas for side projects. One of them needs some automated scraping...
0
2021-12-20T08:39:51
https://dev.to/adyaksa_w/what-i-learn-from-trying-selenium-on-vps-5a56
programming, python, webdev, cloud
Currently, I'm exploring various ideas for side projects. One of them needs some automated scraping that runs as a CRON job. Because I'm used to scrapping with Python using Selenium, I immediately choose them and connect them with Flask. There is 1 little problem: My previous scraping experience is only on a local machine. So I need to learn how to do scraping on the server and add a CRON job on top of that. Because it's quite a common use case, there should be many tutorials about it and make it easier when I need to troubleshoot, right? **Oh god, how wrong I was.** Okay, so before I started building this, I already researched a bit about 3 common libraries for scraping in Python with their advantage and disadvantage. To recap it a bit from what I learned: 1. **Selenium:** Can handle javascript-heavy websites, pass more scrapper detection than other alternatives, but so much slower than other libraries. 2. **BeautifulSoup + requests:** Simplest solution (I used requests on my previous project, so I only need to learn how to parse HTML using BeautifulSoup, which is quite easy too). 3. **Scrapy:** So much functionality and faster than Selenium, but quite inflexible than other solutions. Because some websites that I need to scrape have some scrapper detection and are quite javascript-heavy, I don't see the need to use another library. I also don't need to update this CRON job too often, so slow performance doesn't matter to me. In total, it took me 1 day to finish the prototype for this side project. I tested the scrapper locally and it works. It's slow, but expected. Satisfied with the result, I try to start the scraping on the VPS. It broke. Okay no worry, I can fix this. The error keeps changing, and it's getting more obscure. I spent a few days after that to debug it, and my final solution is "**Restart and hope for the best**". ![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/48vv98d42g6d8ys6xrt4.png) _By [Luca Bravo](https://unsplash.com/@lucabravo) from [Unsplash](https://unsplash.com/photos/XJXWbfSo2f0)_ There is so much hardship that comes with scraping on the VPS. First, VPS doesn't have GUI, so we need to configure the server or the Selenium so it can still run without GUI. I found 2 solutions regarding this, using [virtual display](https://stackoverflow.com/questions/6183276/how-do-i-run-selenium-in-xvfb) or running Selenium with a [headless](https://stackoverflow.com/questions/55544648/how-to-run-selenium-script-on-server)browser. I tried the virtual display approach, but the error that came up is still the same. When I changed to the headless solution, the error changes, so I choose this solution. Second, **the program frequently crashes**. To handle this, I used [WebDriverWait](https://selenium-python.readthedocs.io/waits.html) so the driver can wait until the browser finishes loading. I also added various try except in risky lines that have a high chance to create an error. Lastly, **the driver frequently disconnects**. This is the hardest problem for me. What I found out is that ChromeDriver is very unstable compared to GeckoDriver. It successfully reduces the disconnection, but still not zero. So I need to run the scrapper in batch and restart every time the driver disconnected. As a result, I changed my approach. I used the second scraping method (BeautifulSoup + requests) for website that can handle it. For the rest of the website, I used Selenium and wait patiently. From this project, I learned that scheduled scraping on VPS is hard and time-consuming. Moreover, the problem that I encountered doesn't include when the target website blocks your scraping attempt. To handle this, there is a need to configure my scrapper so it doesn't look like it came from a scraping program. But because I'm just doing this side project for fun, I just change a few basic configurations. If in the future I need to have another scraping on VPS, I probably will invest a bit on a few proxies to change the requester's IP or even use web scraping services such as [ScraperAPI](https://www.scraperapi.com/?fp_ref=adyaksaw). But if not really needed, I don't want to do scraping on VPS again. _If you're curious about the side project that I'm building, you can check it out on [this page](https://www.lnprice.com/). This is a simple price aggregation website for [light novels](https://en.wikipedia.org/wiki/Light_novel). I'm planning to release a weekly blog about something that I find interesting while working on my side projects, and this article is one of them._
adyaksa_w
929,050
I want to sell a html responsive theme
A post by Adeel-ui
0
2021-12-17T11:31:08
https://dev.to/adeelui/i-want-to-sell-a-html-responsive-theme-4m57
adeelui
929,085
Python programs to calculate perimetrs and areas of triangle, rectangle and circle.
Perimeters and areas of Triangle the mathematical equation to calculate the perimeter and...
0
2021-12-17T12:47:40
https://dev.to/checoslbches/python-programs-to-calculate-perimetrs-and-areas-of-triangle-rectangle-and-circle-5don
### Perimeters and areas of Triangle the mathematical equation to calculate the perimeter and area of a Triangle with height(h), length(l) and width(w) is : `p= h+l+w a=1/2(l*w) ` so with python it can be executed as ``` length=float(input("Enter length : ")) width =float(input("Enter width : ")) height=float(input("Enter height: ")) print("the perimetre of the triangle is : " +str(length+width+height)) print("the area of the triangle is : " +str(1/2*(length*width))) ``` and the output will be `` Enter length : 2 Enter width : 3 Enter height: 4 the perimeter of the triangle is : 9.0 the area of the triangle is : 3.0 `` ### Perimeters and areas of rectangle the mathematical equation to calculate the perimeter and area of a Rectangle with length(l) and width(w) is : p= 2l + 2w a= l*w **and the code will be** ``` length=float(input("Enter length : ")) width =float(input("Enter width : ")) print("the perimeter of the rectangle is : "+str(2*length+2*width)) print("the area of the rectangle is : "+str(length*width)) ``` and the output will be `` Enter length : 2 Enter width : 3 the perimeter of the rectangle is : 10.0 the area of the rectangle is: 6.0 `` ### Perimeters and areas of Circle the mathematical equation to calculate the perimeter and area of a Circle with radius(r) is : `p= 2*PI*r a=PI*r**2 ` so with python it can be executed as ``` from math import pi r=float(input("Enter radius : ")) print("the Perimetre of the circle with radius "+str(r)+" is : " +str(2*pi*r)) print("the area of the circle with radius "+str(r)+" is : " +str(pi*r**2)) ``` and the output will be `Enter radius : 3 the Perimeter of the circle with radius 3.0 is : 18.84955592153876 the area of the circle with radius 3.0 is : 28.274333882308138`
checoslbches
929,296
Log4j Vulnerability - Important Note to Performance Engineers
The Internet went crazy last week. If you are an avid user of Tech Twitter, you would have known...
0
2021-12-17T16:40:02
https://qainsights.com/log4j-vulnerability-important-note-to-performance-engineers
performance, webperf, tutorial, testing
<!-- wp:paragraph --> <p>The Internet went crazy last week. If you are an avid user of Tech Twitter, you would have known about the Log4j fiasco. Within a few hours, Log4j vulnerability made headlines on popular news outlets, Twitter, LinkedIn, major organizations' internal forums, Slack channels and more. This blog post is all about Log4j vulnerability for performance engineers about how to mitigate the attack.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2>What is Apache Log4j Vulnerability CVE-2021-44228?</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>I am not a security expert. But I closely follow the security news on Twitter and feeds. CVE-2021-44228 is about remote code execution via JNDI lookup. </p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Apache Log4j is a popular logging framework for Java applications, websites, enterprises, consumer apps and more. Developers log information about security and performance for debugging, audit, and analysis. </p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>By sending the JNDI with LDAP, it is possible to extract or operate the remote server or local machine, if the app is using Log4j 2.0-beta9 to 2.14.1. </p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>There are numerous articles, videos, repos are available to deep-dive into this CVE. </p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>This article targets performance engineers to help out with how to mitigate this vulnerability for the testing tools we are using. </p> <!-- /wp:paragraph --> <!-- wp:image {"align":"center","id":8945,"sizeSlug":"large","linkDestination":"media"} --> <div class="wp-block-image"><figure class="aligncenter size-large"><a href="https://qainsights.com/wp-content/uploads/2021/12/Log4j-Vulnerability-Important-Note-to-Performance-Engineers.jpeg"><img src="https://qainsights.com/wp-content/uploads/2021/12/Log4j-Vulnerability-Important-Note-to-Performance-Engineers-1024x1024.jpeg" alt="Log4j Vulnerability - Important Note to Performance Engineers" class="wp-image-8945"/></a><figcaption>Log4j Vulnerability - Important Note to Performance Engineers</figcaption></figure></div> <!-- /wp:image --> <!-- wp:heading --> <h2>Apache JMeter</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>The latest version of JMeter 5.4.1 uses Log4j 2.13.3 which is affected by CVE-2021-44228.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>There are a couple of options available to mitigate the risk. But it is recommended to follow the Apache Log4j guidelines which are mentioned <a href="https://logging.apache.org/log4j/2.x/security.html#CVE-2021-44228" target="_blank" rel="noreferrer noopener">here</a>.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>CVE-2021-44228 solves the problem partially. CVE-2021-45046 prevents attacks by mitigating attackers various patterns. </p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Log4j 2.16.0 fixes this issue by removing support for message lookup patterns and disabling JNDI functionality <strong>by default</strong>.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>My recommendation is to update the Log4j jars of JMeter to 2.16.0 completely.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Go to JMETER_HOME\lib, delete all the log4j* files. </p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Download the Log4j zip file from <a href="https://logging.apache.org/log4j/2.x/download.html" target="_blank" rel="noreferrer noopener">Log4j website</a>.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Extract it and copy the below files and paste it into JMETER_HOME\lib folder.</p> <!-- /wp:paragraph --> <!-- wp:code --> <pre class="wp-block-code"><code>log4j-1.2-api-2.16.0.jar log4j-api-2.16.0.jar log4j-core-2.16.0.jar log4j-slf4j-impl-2.16.0.jar</code></pre> <!-- /wp:code --> <!-- wp:paragraph --> <p>JMeter 5.4.2 will be released soon with the bumped up version of Log4j. I will update my post, once it is released.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>UPDATE: <a href="https://qainsights.com/whats-new-in-apache-jmeter-5-4-2/" target="_blank" rel="noreferrer noopener">JMeter 5.4.2 has been released</a>.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2>Tricentis NeoLoad</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Tricentis has released NeoLoad 8.0 with Log4j 2.15.0.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2>Grafana k6</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>Grafana's k6 <a href="https://k6.io/blog/k6-products-not-impacted-by-cve-2021-44228/" target="_blank" rel="noreferrer noopener">doesn't use Log4j</a>. You are good to go. </p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2>MicroFocus LoadRunner and Silk Performer</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>MicroFocus LoadRunner family is impacted by Log4j vulnerability. Please <a href="https://portal.microfocus.com/s/article/KM000003046?language=en_US" target="_blank" rel="noreferrer noopener">follow this link</a> to mitigate the risk.</p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Here is the bulletin link for <a href="https://microfocus.my.salesforce.com/sfc/p/#1t000000vhDP/a/8e000000c7fR/JrOxnycbJxIXDpzlzCCfBOy6pqqRcPD_cu.ySvH5Vc8" target="_blank" rel="noreferrer noopener">Silk Performer</a>.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2>Gatling</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p><a href="https://gatling.io/2021/12/log4shell-why-is-gatling-unaffected/" target="_blank" rel="noreferrer noopener">Gatling uses</a> logback logging library. If you are using Gatling, you are not affected.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2>RedLine 13</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>RedLine13 itself doesn't use Log4j framework. But once JMeter 5.4.2 is out, it will be available on the RedLine13 platform.</p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2>EggPlant Performance</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>If you are using <a href="https://blog.eggplantsoftware.com/apache-log4j-2-security-vulnerability" target="_blank" rel="noreferrer noopener">EggPlant Performance</a>, you are NOT affected by the Log4j vulnerability. </p> <!-- /wp:paragraph --> <!-- wp:heading --> <h2>Conclusion</h2> <!-- /wp:heading --> <!-- wp:paragraph --> <p>It is recommended to update the Log4j libraries with 2.16.0 ASAP. I will keep posting this blog post, if I get any new information. </p> <!-- /wp:paragraph --> <!-- wp:paragraph --> <p>Log4j developers have been working tirelessly to fix the issues for the past 1 week. A big salute to them from <a href="https://qainsights.com" target="_blank" rel="noreferrer noopener">QAInsights</a>.</p> <!-- /wp:paragraph -->
qainsights
929,528
Dec 24: Dev Holidays Guide ⛄️
Bah Humbug Tips are my own way of coping &amp; recovering from burnout &amp; holiday stress. ...
15,961
2021-12-24T18:33:02
https://dev.to/helengriffinjr/dec-24-dev-holidays-guide-ho2
stateofdevs, bahhumbugtip, mentalhealth, tips
Bah Humbug Tips are my own way of coping & recovering from burnout & holiday stress. ###🎄 Today's Bah Humbug Tip of the Day. {% twitter 1474415603649695745 %} ######🎁 Today's Options {% twitter 1474415608141795328 %} You can find more tips here & on [Twitter](https://twitter.com/stateofdevs). Let me know in the comments if any of these tips helps. > If you're struggling w/ burnout & open to sharing your story, please [take the State Of Devs survey](https://stateofdevs.com/helps/dev). 🗳 Thanks!
helengriffinjr
929,586
Apama Advent Calendar - 17 Dec 2021 - Enhancing Cloud Fieldbus using Apama
This is Day #17 of a short series of brief tips, tricks, hints and reminders of information relating...
0
2021-12-20T08:34:19
https://tech.forums.softwareag.com/t/apama-advent-calendar-17-dec-2021-enhancing-cloud-fieldbus-using-apama/253984
apama, iot, cumulocity, streaminganalytics
--- title: Apama Advent Calendar - 17 Dec 2021 - Enhancing Cloud Fieldbus using Apama published: true date: 2021-12-17 23:54:35 UTC tags: apama, iot, cumulocity, streaminganalytics canonical_url: https://tech.forums.softwareag.com/t/apama-advent-calendar-17-dec-2021-enhancing-cloud-fieldbus-using-apama/253984 --- _This is Day #17_ _of a short series of brief tips, tricks, hints and reminders of information relating to the Apama Streaming Analytics platform, both from Software AG as well as from the community._ Cumulocity IoT Cloud Fieldbus is the standard approach to connect Fieldbus devices (e.g. Modbus) to Cumulocity IoT in a consistent manner. Cloud Fieldbus only supports integer values to be read from registers. Some devices are reporting floating point numbers though (e.g. temperatures like 25.1 °C). There is no standardized way of doing this but typically IEEE-754 (Wikipedia) encoded floating point numbers are used. In today article, we will show you how to tackle the IEEE-754 decoding using Apama within Cumulocity IoT. So go check it out in the [Software AG Tech Community](https://tech.forums.softwareag.com/t/apama-advent-calendar-17-dec-2021-enhancing-cloud-fieldbus-using-apama/253984). _Note that some posts may be published a day or two early or late (e.g. Mon-Fri) so you may find you have bonus days with more than one post!_
techcomm_sag
929,681
Path aliases in Nextjs
Tired of writing such imports? import test from '../../../components/Test.tsx'; Enter...
0
2021-12-18T05:31:45
https://dev.to/avxkim/path-aliases-in-nextjs-4pio
react, nextjs, javascript
Tired of writing such imports? ```js import test from '../../../components/Test.tsx'; ``` If you're using a typescript, you can create a path alias instead: ```json { "compilerOptions": { "baseUrl": "src", "paths": { "@/*": ["./*"] } } } ``` Then you can import more conveniently: ```js import test from '@/components/Test.tsx'; ``` **Don't forget to restart your running task to affect changes.**
avxkim
929,761
Tracking in React Apps
Disclaimer The code might not be a best practice, because it's based on personal...
0
2021-12-25T11:30:38
https://dev.to/peterchu999/tracking-in-react-apps-584e
javascript, react, monitoring, todayilearned
## Disclaimer - The code might not be a best practice, because it's based on personal experience. - Example has been simplified, so we could focus on the tracking code and tools - This post will not discuss or used any 3rd party implementation of specific tracking platform (crashlytics, data dog, sentry, mixpanel, etc) - The 3rdParty Mocked code might be different from real 3rdParty API ## Notice if you are interested in the application code more than the tracking implementation. Leave reaction to this post, I'll consider making another post to explain it. ## Tracking Nowadays, tracking user experience is a must for most application, by collecting the tracked data from user we can develop, fixing or improve our feature (especially UX). Based on my experience tracking can be differ into 2 category : - `product / marketing`: this tracking goals is to keep track and evaluate marketing approaches (FB ads, google ads, instagram link, etc), and help product team to evaluate UX - `error`: this tracking purpose is to notify developer about the error that occur in production before customer making any complain. Let's see the implementation in react code ## Application and tracking statement To implements tracking we need to at least having an application. I have create a base project at: {% github https://github.com/peterchu999/react-tracking-impl no-readme %} **What is the app functionality ?** - a news curation app that use [newsapi](https://newsapi.org/) - there is 2 tab `Home` and `Top News` - Each tab have `refresh` news functionality - Each news card linked to respective article website ![News Apps](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fn5gcnjxpv7sprkfm29t.png) **What are we going to track ?** - track every click on `go to source` button, we want to evaluate whether user usually go to `tops news` tab or not, so the Data expected looks like : ``` { eventName: 'click_go_to_source', page: 'Home / TopNews' } ``` - track every click on `refresh feed` button, we want to evaluate whether user click `refresh feed` button or not so the data expected looks like : ``` { eventName: 'refresh_feed', page: 'Home / TopNews' } ``` - track error when `fetching data`, we want to track every error occur when fetching data. Data expect to looks like : ``` { eventName: 'error_fetch', page: 'Home / TopNews', errorReason: stringify error object } ``` ## Usual Tracking (Direct Approach) Basically it's just calling 3rd party sdk / api for event tracking or logging on every click handler or error catch In this code example we will use Mocked `DataDog` for our **error** tracking and `MixPanel` for our **click** tracking. The code implementation can be seen in [link](https://github.com/peterchu999/react-tracking-impl/tree/direct). ### Detail Code go through **Click Go To Source Track** every time the user click `go to source` this code will send over the data to mock `MixPanel`. ``` // ArticleCard.js ... // line 7 const handleClick = () => { const eventName = "click_go_to_source"; const unique_id = uuid(); MixPanel.track(eventName, unique_id, { page, }); ... }; .... ``` **Click Refresh Feed Track** every time the user click `refresh feed` this code will send over the data to mock `MixPanel`. ``` // Home.js or TopNews.js ... // line 26 const onRefreshClick = () => { const eventName = "refresh_feed"; const unique_id = uuid(); MixPanel.track(eventName, unique_id, { page, }); ... }; .... ``` **Fetch News error Track** every time our fetch to news from newsapi failed, this code will send over the `fetch_error` data to mock `DDlog`. ``` // Home.js or TopNews.js ... // line 15 onError: (err) => { const eventName = "error_fetch"; DDlog.error(eventName, { page, errorReason: JSON.stringify(err, null, 4), }); }, .... ``` It seems everything to work fine 🤔, yep that's what i thought, until some changes was needed because of new feature or 3rd Party tracking platform commercial issue / fees. Imagine that we already put 100+ tracker over 10 screens, then we need to : - change tracking platform, for example from `MixPanel` to `Heap`. we need to manually refactor all of our `MixPanel` tracking code 1-by-1 😵‍💫. - add additional tracking data since we have new login feature, now we want to track user data every too 🤯. Gratefully, i encounter this problem when my tracker was still less than 20 😮‍💨. But there is a question pop up on my mind, do i need to change the code one-by-one every time there is commercial issue or new feature that affect current tracking ? ## React Tracking That's what lead me to `react-tracking` by NYT, a React specific tracking library. it helps to : - Centralize our tracking logic, yet compartmentalize tracking concerns to individual components - Give tracking data a scope Let's see the code implementation [link](https://github.com/peterchu999/react-tracking-impl/tree/rtracking). We create `ReactTrackingInitializer` HOC (High Order Component) to be our parent / root tracking wrapper. ``` const ReactTrackingInitializer = ({ children }) => { const { Track } = useTracking( { // this is where the initialize data put trackVersion: "1.0.0", }, { dispatch: (trackedData) => { console.log("dispatchData", trackedData); } ); return <Track>{children}</Track>; }; ``` `useTracking` is a hooks version to implementing `react-tracking` which suitable for functional component, find out more on their docs if you still implementing class component. `useTracking` takes 2 params: 1. initial data, means this data available for the rest of the child component. 2. is the options which consist of `dispatch`,`dispatchOnMount`,`process`, and `fowardRef` more detail check [react-tracking](https://github.com/nytimes/react-tracking) `useTracking` will return object with 3 properties: 1. `trackEvent`: a function to send data to be process at `process`, then `dispatch`. 2. `getTrackingData`: a function that return current initial data in our tracker. 3. `Track`: a HOC that wrapped a child component to give scope to it's initial data, `process` and `dispatch` logic. which later can be triggered using `trackEvent` From the reference we can implements our 3rd Party logic at `dispatch` option. so it will looks like this : ``` ... dispatch: (trackedData) => { console.log("dispatchData", trackedData); const { eventName, ...restOfData } = trackedData.data; switch (trackedData.type) { case "product": const unique_id = uuid(); MixPanel.track(eventName, unique_id, restOfData); break; case "error": DDlog.error(eventName, restOfData); break; default: break; } }, ... ``` It looks a lot like `redux` reducers. Now you might ask there must be a dispatch mechanism to like redux, where is it ? checkout the code at `Home.js` line 25 - 33 ``` const { trackEvent, Track } = useTracking({ data: { page: "HOME" }, }); const onRefreshClick = () => { trackEvent({ type: "product", data: { eventName: "refresh_feed" } }); refetch(); }; ``` the `trackEvent` will send over the data below to our `dispatch` function. ``` { type: "product", data: { eventName: "refresh_feed", page: "HOME" } trackVersion: "1.0.0" } ``` Wait, Where did `trackVersion: "1.0.0"` and `page: "HOME"` came from 🙄 ? react tracking perform a merge operation on data we sent and initial data provided. in this case : - data we send : ``` { type: "product", data: { eventName: "refresh_feed" } } ``` - initial value on `Home.js` useTracking : ``` { data: { page: "HOME" } } ``` - initial value on `ReactTrackingInitializer` useTracking: ``` { trackVersion: "1.0.0" } ``` We already utilize `react-tracking` 🎉🎉🎉, Just Note that: - there must be at least 1 component that wrapping with `<Track></Track>` at root level (prefer to wrap <App/>) - Initial value only available to child component if we wrapped them with `<Track></Track>`. that why we wrapped `<ArticleCard>` in `Home.js` line 57 - 63, so it get the initial value from `Home.js` useTracking, otherwise it will only have initial value of `ReactTrackingInitializer.js`. Now back to the problem, let say we need to: 1. change MixPanel to Heap 2. add user data to every tracker, because we have new login feature just see the difference between branch `rtracking` and `rtracking-solution`. {% github https://github.com/peterchu999/react-tracking-impl/pull/1 %} and compare it to the difference between branch `direct` and direct-solution`. {% github https://github.com/peterchu999/react-tracking-impl/pull/2 %} It will more work to be done when using 3rdParty Sdk / API directly, Imagine we have 10+ MixPanel tracker, it will cost a lot of time. ## Conclusion React Tracking Help us to centralize the tracking logic so if there are any changes needed we can just refactor our dispatch function. Thanks for reading, leave any comment below 😊 ## Shout Out {% github https://github.com/nytimes/react-tracking no-readme %} {% medium https://open.nytimes.com/introducing-react-tracking-declarative-tracking-for-react-apps-2c76706bb79a %}
peterchu999
929,789
Dev.to looses 3000 views per month (at least)
My last post with a video got 120 readers. Six reactions and I got 108 followers. My plan was to...
0
2021-12-18T09:21:33
https://dev.to/tomaszs2/devto-looses-3000-views-per-month-at-least-4ie5
meta
My last post with a video got 120 readers. Six reactions and I got 108 followers. My plan was to publish one video per day. What gives at least 3000 views per month, 180 reactions and over 3000 followers. However, it won't happen. Why? I was told by the moderator of dev.to that video posts are not welcome on dev.to. And I should add texts and snippets (that are in the video...) also as text. I can not do it because it is additional work I rather spend on making videos. Moreover, video section of dev.to is not working and it is impossible to upload videos there. It is still in beta BTW. The result is that I can not publish my videos on dev.to. The question is what is the plan of dev.to? People clearly like videos here, what can be seen by statistics. But because of a ban on video posts and not working video section dev.to users loose access to something they like. Since that said, as a dev mentor with 16 years of experience in education I just can say sorry to everyone who is affected by this. I wished I'd be able to share knowledge with you here. Short videos are great in explaining things. You like it. But nor me, not you decide what we can do on dev.to....
tomaszs2
929,854
First Post by {{ @shriekdj }}
My First Post.
0
2021-12-18T11:21:00
https://codewithshriekdj.netlify.app/posts/my-first-post-8428b
firstpost, shriekdj
My First Post.
shriekdj