Developer

Developer

Learn JavaScript - Full Course for Beginners

JavaScript Tutorial for Beginners - Full Course in 12 Hours

Kickstart your Web Development career or take it to the next level with this JavaScript tutorial. This JavaScript course is perfect for Beginners as well as Intermediate Developers.

⏳Timestamps:
00:00:00 - Set up Your Environment as a JavaScript Developer
00:07:01 - JavaScript 101
00:22:39 - Build Your First App with JavaScript (Beginner Weather App)
00:40:44 - Build a Basic Tip Calculator App (For Beginners)
01:11:22 - What are Arrays in JavaScript? (Understanding Arrays | Arrays 101)
01:25:10 - What are Objects in JavaScript? (Understanding Objects | Objects 101)
01:45:04 - Understanding For Loops in JavaScript (Getting Started with Loops)
02:04:21 - Practice Arrays and Objects with these Exercises (For Beginners)
03:01:02 - Array Methods (mapping, filtering, reducing | Understanding Array Methods)
03:42:02 - Understanding the DOM (DOM Manipulation for Beginners)
04:22:31 - Build the Advanced Tip Calculator Project (For Beginners & Intermediate)
05:06:06 - Build a Rock Paper Scissors App (Part 1)
05:40:31 - Building the Rock Paper Scissors App with JavaScript (Portfolio Project!)
06:12:18 - What are APIs in JavaScript? (Understanding APIs)
06:33:51 - Build the Superhero App (For Beginners & Intermediate)
07:39:58 - Understanding Async Programming (Promises, Async, Await, Fetch, Then)
08:26:28 - Building the Weather App with JavaScript (Portfolio Project for Entry Level Developers)
08:54:59 - What are Classes in JavaScript? (Object Oriented Programming | OOP)
10:14:56 - Advanced Web Development (Loops, Listeners, Audio | For Beginners & Intermediate)
10:32:03 - Building the Fighting Game with JavaScript (Portfolio Project!)
11:49:52 - Building the Netflix Clone with JavaScript (Portfolio Project!)

#web3 #frontend #javascript #programming #developer #webdev #blockchain

Learn JavaScript - Full Course for Beginners

Tailwind CSS Tutorial | Responsive Designs with Tailwind CSS

Responsive Designs with Tailwind CSS

Tailwind Responsive Classes let us fine-tune how our sites look across mobile, tablet, and desktop devices. Tailwind gives us the sm: md: lg: xl: 2xl: prefixes so that we can add these classes to any of the Tailwind classes. If the prefix is applied, then Tailwind will only apply a class to that certain breakpoint.

CodePen: https://codepen.io/chris__sev/pres/eYdrBeJ 

0:00 Introduction
0:40 Tailwind Responsive Docs
2:12 Basic Example
4:04 Bigger Example
8:59 Responsive Everything


Responsive Design

Using responsive utility variants to build adaptive user interfaces.

Overview

Every utility class in Tailwind can be applied conditionally at different breakpoints, which makes it a piece of cake to build complex responsive interfaces without ever leaving your HTML.

There are five breakpoints by default, inspired by common device resolutions:

Breakpoint prefixMinimum widthCSS
sm640px@media (min-width: 640px) { ... }
md768px@media (min-width: 768px) { ... }
lg1024px@media (min-width: 1024px) { ... }
xl1280px@media (min-width: 1280px) { ... }
2xl1536px@media (min-width: 1536px) { ... }

To add a utility but only have it take effect at a certain breakpoint, all you need to do is prefix the utility with the breakpoint name, followed by the : character:

<!-- Width of 16 by default, 32 on medium screens, and 48 on large screens -->
<img class="w-16 md:w-32 lg:w-48" src="...">

This works for every utility class in the framework, which means you can change literally anything at a given breakpoint — even things like letter spacing or cursor styles.

Here’s a simple example of a marketing page component that uses a stacked layout on small screens, and a side-by-side layout on larger screens (resize your browser to see it in action):

<div class="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl">
  <div class="md:flex">
    <div class="md:shrink-0">
      <img class="h-48 w-full object-cover md:h-full md:w-48" src="/img/store.jpg" alt="Man looking at item at a store">
    </div>
    <div class="p-8">
      <div class="uppercase tracking-wide text-sm text-indigo-500 font-semibold">Case study</div>
      <a href="#" class="block mt-1 text-lg leading-tight font-medium text-black hover:underline">Finding customers for your new business</a>
      <p class="mt-2 text-slate-500">Getting a new business off the ground is a lot of hard work. Here are five ideas you can use to find your first customers.</p>
    </div>
  </div>
</div>

Here’s how the example above works:

  • By default, the outer div is display: block, but by adding the md:flex utility, it becomes display: flex on medium screens and larger.
  • When the parent is a flex container, we want to make sure the image never shrinks, so we’ve added md:shrink-0 to prevent shrinking on medium screens and larger. Technically we could have just used shrink-0 since it would do nothing on smaller screens, but since it only matters on md screens, it’s a good idea to make that clear in the class name.
  • On small screens the image is automatically full width by default. On medium screens and up, we’ve constrained the width to a fixed size and ensured the image is full height using md:h-full md:w-48.

We’ve only used one breakpoint in this example, but you could easily customize this component at other sizes using the sm, lg, xl, or 2xl responsive prefixes as well.

Mobile First

By default, Tailwind uses a mobile first breakpoint system, similar to what you might be used to in other frameworks like Bootstrap.

What this means is that unprefixed utilities (like uppercase) take effect on all screen sizes, while prefixed utilities (like md:uppercase) only take effect at the specified breakpoint and above.

Targeting mobile screens

Where this approach surprises people most often is that to style something for mobile, you need to use the unprefixed version of a utility, not the sm: prefixed version. Don’t think of sm: as meaning “on small screens”, think of it as “at the small breakpoint“.

Don't use sm: to target mobile devices

<!-- This will only center text on screens 640px and wider, not on small screens -->
<div class="sm:text-center"></div>

Use unprefixed utilities to target mobile, and override them at larger breakpoints

<!-- This will center text on mobile, and left align it on screens 640px and wider -->
<div class="text-center sm:text-left"></div>

For this reason, it’s often a good idea to implement the mobile layout for a design first, then layer on any changes that make sense for sm screens, followed by md screens, etc.

Targeting a single breakpoint

Tailwind’s breakpoints only include a min-width and don’t include a max-width, which means any utilities you add at a smaller breakpoint will also be applied at larger breakpoints.

If you’d like to apply a utility at one breakpoint only, the solution is to undo that utility at larger sizes by adding another utility that counteracts it.

Here is an example where the background color is red at the md breakpoint, but green at every other breakpoint:

<div class="bg-green-500 md:bg-red-500 lg:bg-green-500">
  <!-- ... -->
</div>

Notice that we did not have to specify a background color for the sm breakpoint or the xl breakpoint — you only need to specify when a utility should start taking effect, not when it should stop.

Customizing breakpoints

You can completely customize your breakpoints in your tailwind.config.js file:

module.exports = {
  theme: {
    screens: {
      'tablet': '640px',
      // => @media (min-width: 640px) { ... }

      'laptop': '1024px',
      // => @media (min-width: 1024px) { ... }

      'desktop': '1280px',
      // => @media (min-width: 1280px) { ... }
    },
  }
}

Building responsive websites with Tailwind CSS

Tailwind CSS is a CSS framework, like Bootstrap, Bulma, and Foundation. However, Tailwind does things in a less conventional way when compared to traditional CSS frameworks. Instead of providing CSS classes based on components or functional roles (e.g. .card or .row), Tailwind only provides utility classes, in which each class does only one specific thing a CSS attribute usually does, such as m-4 for margin: 1rem or mt-8 for margin-top: 2rem.

In Bootstrap, one can simply apply the provided .card CSS class to have a <div> styled like a card the Bootstrap way. In Tailwind, the styles have to be constructed with a string of different atomic classes. E.g. the equivalent of a Bootstrap’s .card would be something like relative flex flex-col break-words bg-white bg-clip-border min-w-0 rounded border. Verbose, yes, but this gives flexibility for the developers to define the appearance of a .card element themselves (e.g. there could be multiple variants of appearances of a .card) without having to worry about overriding inherited/​cascading CSS classes, which are typically the cause of many CSS bugs in production.

Atomic CSS

The first thing most notice when developing with Tailwind is how wordy CSS class lists can get. It feels almost like using the style="" attribute to write CSS. In the traditional approach to CSS, suppose there are two elements with identical margins:

.card {
  display: block;
  margin: 1rem;
}

.container {
  margin: 1rem;
}

Here, we can see that margin is declared twice. Those duplicates are going to be a few extra bytes in the final CSS payload.

With Tailwind, however, this is how the equivalent would be written:

<div class="block m-4">
</div>

<div class="m-4">
</div>

Here, both of the <div>s are reusing the same class m-4, which is provided out-of-the-box by Tailwind. This approach ensures that the project’s CSS does not grow, which is important for good user experience. Constructing the CSS of a page is a render-blocking task in a web page load. So, the bigger the CSS, the longer the wait time for a user to see something on the browser. Yes, the HTML payload will grow, but just by a little.

One of the differences between using Tailwind CSS classes and using style attribute is that the latter cannot be used to style pseudoclasses (e.g. :hover, :disabled). With CSS classes, that is achievable, but there are special prefixes that Tailwind provides for each of the variants to take effect.

For example:

<!-- margin: 1rem by default, margin: 2rem on hover -->
<div class="m-4 hover:m-8"></div> 

<!-- white background by default, light gray background when disabled -->
<input class="bg-white disabled:bg-gray-100"/> 

Keep in mind that not all variants/​pseudoclasses are supported by default, as this would make the development output of a Tailwind CSS file really big to cater all of the possible variants. To have them supported, it has to be configured inside the project’s tailwind.config.js:

// tailwind.config.js
module.exports = {
  variants: {
    extend: {
      backgroundColor: ['active'],
      // ...
      borderColor: ['focus-visible', 'first'],
      // ...
      textColor: ['visited'],
    }
  },
}

Or, if the project is on Tailwind CSS v2.1+, the developers can enable Just-in-Time mode, which grants access to all variants out-of-the-box while also being more functional in development mode.

Shaking off the unused CSS

By default, Tailwind will be loading the whole Tailwind CSS project files, with CSS declarations on almost every possible CSS rule. There are a lot in there that a developer might never use. To put that into context, there are 105 different values just for grid and flexbox gaps. Most projects aren’t likely to use them all, so Tailwind needs a way to remove the unused CSS when generating the final CSS build for production use.

This is where PurgeCSS comes in. PurgeCSS is a plugin that analyzes all CSS, HTML, and JavaScript files in the project and removes unused CSS declarations from the final build. This tool is available as a PostCSS, Webpack, Gulp, Grunt, or Gatsby plugin.

Because PurgeCSS analyzes the project’s source code to find exact matches of a given CSS style, a CSS class cannot be used through string concatenations or PurgeCSS will not be able to detect that the given Tailwind class is used.

// SomeComponent.jsx
const SomeComponent = (props) => {
  return (
    <div className={'text-' + props.color}>
      Some text
    </div>
  )
}

// <SomeComponent color='gray-400'/>
// In this case, `text-gray-400` will be removed by PurgeCSS in the final CSS 
// production build because it does not know that the component is using it.

DRYing it up

Suppose we have two cards on the page and we want their appearance to be consistent. In the traditional CSS approach, both these two cards will just have the .card CSS class, and the same styles would be applied to both of them. In Tailwind we can’t do that, however, and it doesn’t make sense to be repeating 7 or 8 or more different class names on both HTML elements on the page.

const AppButton = () => (
  <button className='py-2 px-4 font-semibold rounded-lg shadow-md'>
    I'm a button
  </button>
)

// Just use <AppButton> everywhere and their appearances will be consistent
// No need to repeat the CSS classes for all three components
render(
  <Form>
    <AppButton/>
    <AppButton/>
    <AppButton/> 
  </Form>
)

Therefore, Tailwind can be easier to implement in component-based frameworks, such as Vue or React. But even if you’re not using any of them and are just building a plain HTML file, Tailwind provides a way to compose these classes together by using @apply:

.button {
  @apply py-2 px-4 font-semibold rounded-lg shadow-md;
}

.button.success {
  @apply py-2 px-4 font-semibold rounded-lg shadow-md text-white bg-green-400;
}

Then, .button and .button.success classes will be available to us for reuse as in traditional CSS.

<!-- py-2 px-4 font-semibold rounded-lg shadow-md gets applied when using "button" -->
<button class="button">I'm a button</button>

<!-- py-2 px-4 font-semibold rounded-lg shadow-md text-white bg-green-400 gets applied -->
<button class="button success">I'm a green button</button>

Building a responsive page using Tailwind

Now let’s look at responsive design. Suppose we want to implement a page with a navigation bar, a sidebar, a content area, and a footer:

Layout with Tailwind CSS - desktop view

And the sidebar and content area should collapse into one column on mobile devices, like this:

Layout with Tailwind CSS - mobile view

First, let’s have the basic page layout:

<nav class="p-4 bg-gray-100">
  <ul class="flex gap-2 justify-end">
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</nav>
<div class="flex flex-col">
  <aside class="flex items-center justify-center p-4 bg-red-100">
    Sidebar
  </aside>
  <main class="min-h-screen p-4 bg-green-100">
    <p>
      Sit eos nam quam nemo qui. Quas recusandae praesentium ratione incidunt sunt commodi labore Nemo nemo error molestias saepe ducimus? Porro reprehenderit voluptatibus nihil voluptate quia. Voluptatibus autem maiores vero?
    </p>
    <p>
      Consectetur veniam voluptate esse amet debitis eius? Voluptatem officia quibusdam voluptates cum rerum Odio rem maiores laborum commodi cum. Nobis numquam quia nemo maiores repellendus error fuga Repellendus consequatur laudantium?
    </p>
    <p>
      Elit vitae sit reprehenderit sit laboriosam Ratione iusto numquam corrupti ullam libero! Nisi veritatis facere repudiandae eos perspiciatis recusandae veritatis. Cupiditate temporibus repellat tempore optio numquam id! Perferendis maxime unde
    </p>
    <p>
      Dolor autem dolore tempora atque provident. Maxime quos ipsum porro non suscipit. Consectetur et perspiciatis perspiciatis illum quos Ab nostrum unde facere nemo mollitia, saepe ab? Vitae tempore hic accusamus
    </p>
    <p>
      Elit labore odit error pariatur cupiditate Ex sequi accusantium maxime et vero Unde quo laboriosam illo ipsam modi eaque Delectus dolorem quas quidem reprehenderit fugiat! Exercitationem provident voluptatum perferendis ut.
    </p>
  </main>
</div>
<div class="p-4 bg-yellow-100">
  <h5 class="font-bold">Footer links</h5>
  <ul>
    <li>Home</li>
    <li>About</li>
    <li>Contact</li>
  </ul>
</div>

Tailwind official documentation recommends taking a mobile-first approach. Hence, all classes without any screen-size variants will be applied to all screen sizes. Tailwind then provides several screen-size variants such as sm, lg, xl, and 2xl that can be used to control the appearance on specific screen sizes range.

This is what we’re doing here. As you can see, we’re using flexbox layout to collapse all elements down to a single column.

Responsive variants

Now, let’s add Tailwind’s responsive variants so that the page is responsive to screen sizes. In our case, what we would want is to have aside and main placed side-by-side when there’s enough real estate on the screen. To achieve that, we would need to switch the flex-col class to flex-row on bigger screen sizes.

<div class="flex flex-col md:flex-row">
  <aside class="flex items-center justify-center p-4 bg-red-100 md:flex-none md:w-1/3 lg:w-1/4">
  <!-- sidebar -->
  </aside>
  <main class="min-h-screen p-4 bg-green-100">
  <!-- main content -->
  </main>
</div>

flex-col md:flex-row here does the trick for us. md variants, by default, kick in when the screen width is at a minimum of 768px. At that point, our flexbox will change from the column layout to the row layout, displaying our aside and main elements side-by-side in one row. To better distribute the width, we specify md:w-1/3 and lg:w-1/4 classes to the sidebar. w-1/3 and w-1/4 sets the width of the elements to one-third and one-fourth of the parent container respectively. The md and lg variants both control at what screen sizes should Tailwind apply which styles.

Conclusion

It can be a bit daunting to start, but once you get a handle on it, Tailwind CSS is a great option for rapidly building user interfaces with total control over the styles. Unlike other frameworks, Tailwind does not attempt to provide a default styling of any component, allowing every site that uses Tailwind to be truly unique from another.

These responsive variants can be applied to any other CSS class from Tailwind, providing a powerful way to build responsive user interfaces. The very thin abstraction over CSS provides developers with a greater flexibility and control over the design while being a good constraint to guide the development process.


Tailwind CSS: How to Create a Responsive Layout

This article is shows you how to create responsive and adaptive user interfaces in Tailwind CSS.

Overview

You can style responsive elements by using the following mobile-first breakpoint prefix system:

Breakpoint PrefixMinimum width
sm640px
md768px
lg1024px
xl1280px
2xl1536px
  

With a breakpoint prefix stays at the beginning, a utility will only make impact from a certain viewport size. For example: md:bg-red-500 only creates a red background when the viewport width is equal or greater than 768px.

When styling a component for mobile, you need to use the unprefixed version of a utility, not the sm prefix.

For more clarity, please see the complete example below.

Example

Preview

This example will create a typical web layout consisting of header, main content, sidebar, and footer. When the screen is small, the main content and sidebar will be in one column. When the screen is 768px or larger, they will be next to each other horizontally. In addition, the font size also changes at breakpoint 768px.

The Code

<body>
    <header class="bg-amber-400 p-5">
        <h1 class="text-2xl md:text-4xl">Header</h1>
    </header>

    <div class="bg-white my-5 w-full flex flex-col space-y-4 md:flex-row md:space-x-4 md:space-y-0">
        <main class="bg-sky-300 md:w-2/3 lg:w-3/4 px-5 py-40">
            <h1 class="text-2xl md:text-4xl">Main Content</h1>
        </main>
        <aside class="bg-green-300 md:w-1/3 lg:w-1/4 px-5 py-40">
            <h1 class="text-2xl md:text-4xl">Sidebar</h1>
        </aside>
    </div>

    <footer class="bg-slate-800 mt-auto p-5">
        <h1 class="text-2xl md:text-4xl text-white">Footer</h1>
    </footer>
</body>

Conclusion

You’ve learned how to build responsive user interfaces with the breakpoint system of Tailwind CSS and applied that knowledge in a practical example.

#tailwind #tailwindcss #programming #css #developer 

Tailwind CSS Tutorial | Responsive Designs with Tailwind CSS

Tailwind CSS Templates | 5 Free Update for Tailwind UI Customers

Beautiful UI components and templates by the creators of Tailwind CSS.

We just released our first set of official Tailwind CSS site templates! Beautifully designed, expertly crafted Next.js projects, built exactly the way we'd build them for production. And it's a free update for existing Tailwind UI customers:

  1. Salient
  2. Transmit
  3. Syntax
  4. Keynote
  5. Primer

 

Salient

Every SaaS marketing site uses the same formula — a hero, feature sections, some testimonials, you know the drill. But some are prettier than others.

What’s included

Salient is a beautiful landing page template for your next SaaS idea, built with Tailwind CSS and Next.js and designed and built by the Tailwind CSS team. It’s production-ready and easy to customize, making it the perfect starting point for your own project.

We’ve taken just as much care with the code as we have with the design, so it’s also an invaluable resource if you want to study how experts build a website with Tailwind CSS and React.

Built by experts — you can trust that all of the code is written following Tailwind CSS best practices, because it’s written by the same team who created and maintain the framework.

Easy to customize — everything is styled with utility classes, directly in the markup. No configuration variables or complex CSS to wrestle with, just open the markup in your editor and change whatever you want.

Built with Next.js — the template is a well-structured, thoughtfully componentized Next.js project, giving you a codebase that’s productive and enjoyable to work in.

Keyboard accessible — everything we build is keyboard accessible, and we carefully craft the markup to deliver the best screenreader experience we know how.

Production-ready — rigorously tested in the latest versions of all browsers to handle lots of edge-cases you might easily miss yourself.

Simple to deploy — production-ready and easily deployed anywhere that you can deploy a Next.js application, like Vercel or Netlify.

Screenshots

This is a detail imageThis is a detail imageThis is a detail imageThis is a detail image

Built for developers

Our templates are thoughtfully crafted with the latest and greatest versions of the tools we love so that they are easy to maintain, and fun to actually work on.

  • Next.js v12.1
  • Tailwind CSS v3.1
  • Headless UI v1.6
  • React v18

Transmit

You’ve ordered your SM7B, boom arm, and a bunch of acoustic foam. With this template, you can finally stop procrastinating and record your first episode.

What’s included

Transmit is a beautiful podcast template built with Tailwind CSS and Next.js, designed and built by the Tailwind CSS team. It’s production-ready and easy to customize, making it the perfect starting point for your own podcast site.

We’ve taken just as much care with the code as we have with the design, so it’s also an invaluable resource if you want to study how experts build a website with Tailwind CSS and React.

Built by experts — you can trust that all of the code is written following Tailwind CSS best practices, because it’s written by the same team who created and maintain the framework.

Easy to customize — everything is styled with utility classes, directly in the markup. No configuration variables or complex CSS to wrestle with, just open the markup in your editor and change whatever you want.

Built with Next.js — the template is a well-structured, thoughtfully componentized Next.js project, giving you a codebase that’s productive and enjoyable to work in.

Keyboard accessible — everything we build is keyboard accessible, and we carefully craft the markup to deliver the best screenreader experience we know how.

Production-ready — rigorously tested in the latest versions of all browsers to handle lots of edge-cases you might easily miss yourself.

Simple to deploy — production-ready and easily deployed anywhere that you can deploy a Next.js application, like Vercel or Netlify.

Screenshots

This is a detail imageThis is a detail imageThis is a detail imageThis is a detail image

Built for developers

Our templates are thoughtfully crafted with the latest and greatest versions of the tools we love so that they are easy to maintain, and fun to actually work on.

  • Next.js v12.1
  • Tailwind CSS v3.1
  • React v18

Syntax

Writing documentation is enough to make you rip your hair out without worrying about the design. Let us help you keep a few strands.

What’s included

Syntax is a beautiful documentation template built with Tailwind CSS and Next.js, designed and built by the Tailwind CSS team.

Powered by Markdoc, the new Markdown-based authoring framework from Stripe, it's now easier than ever to focus on writing great documentation, instead of the tooling around it.

It’s production-ready and easy to customize, making it the perfect starting point for your own documentation site.

We’ve taken just as much care with the code as we have with the design, so it’s also an invaluable resource if you want to study how experts build a website with Tailwind CSS and React.

Built by experts — you can trust that all of the code is written following Tailwind CSS best practices, because it’s written by the same team who created and maintain the framework.

Easy to customize — everything is styled with utility classes, directly in the markup. No configuration variables or complex CSS to wrestle with, just open the markup in your editor and change whatever you want.

Built with Next.js — the template is a well-structured, thoughtfully componentized Next.js project, giving you a codebase that’s productive and enjoyable to work in.

Keyboard accessible — everything we build is keyboard accessible, and we carefully craft the markup to deliver the best screenreader experience we know how.

Production-ready — rigorously tested in the latest versions of all browsers to handle lots of edge-cases you might easily miss yourself.

Simple to deploy — production-ready and easily deployed anywhere that you can deploy a Next.js application, like Vercel or Netlify.

Screenshots

This is a detail imageThis is a detail imageThis is a detail imageThis is a detail image

Built for developers

Our templates are thoughtfully crafted with the latest and greatest versions of the tools we love so that they are easy to maintain, and fun to actually work on.

  • Next.js v12.1
  • Tailwind CSS v3.1
  • Headless UI v1.6
  • React v18
  • Markdoc v0.1

Keynote

As if finding compelling speakers and a posh venue for your conference wasn’t hard enough, now you need a website too. Fret not, we’ve got you covered.

What’s included

Keynote is a beautiful conference template built with Tailwind CSS and Next.js, designed and built by the Tailwind CSS team. It’s production-ready and easy to customize, making it the perfect starting point for your own conference site.

We’ve taken just as much care with the code as we have with the design, so it’s also an invaluable resource if you want to study how experts build a website with Tailwind CSS and React.

Built by experts — you can trust that all of the code is written following Tailwind CSS best practices, because it’s written by the same team who created and maintain the framework.

Easy to customize — everything is styled with utility classes, directly in the markup. No configuration variables or complex CSS to wrestle with, just open the markup in your editor and change whatever you want.

Built with Next.js — the template is a well-structured, thoughtfully componentized Next.js project, giving you a codebase that’s productive and enjoyable to work in.

Keyboard accessible — everything we build is keyboard accessible, and we carefully craft the markup to deliver the best screenreader experience we know how.

Production-ready — rigorously tested in the latest versions of all browsers to handle lots of edge-cases you might easily miss yourself.

Simple to deploy — production-ready and easily deployed anywhere that you can deploy a Next.js application, like Vercel or Netlify.

Screenshots

This is a detail imageThis is a detail imageThis is a detail imageThis is a detail image

Built for developers

Our templates are thoughtfully crafted with the latest and greatest versions of the tools we love so that they are easy to maintain, and fun to actually work on.

  • Next.js v12.1
  • Tailwind CSS v3.1
  • Headless UI v1.6
  • React v18

Primer

We’ve actually published four info products ourselves and this landing page is honestly better than the sites we designed for all of those.

What’s included

Primer is a beautiful info product template built with Tailwind CSS and Next.js, designed and built by the Tailwind CSS team. It’s production-ready and easy to customize, making it the perfect starting point for your own info product site.

We’ve taken just as much care with the code as we have with the design, so it’s also an invaluable resource if you want to study how experts build a website with Tailwind CSS and React.

Built by experts — you can trust that all of the code is written following Tailwind CSS best practices, because it’s written by the same team who created and maintain the framework.

Easy to customize — everything is styled with utility classes, directly in the markup. No configuration variables or complex CSS to wrestle with, just open the markup in your editor and change whatever you want.

Built with Next.js — the template is a well-structured, thoughtfully componentized Next.js project, giving you a codebase that’s productive and enjoyable to work in.

Keyboard accessible — everything we build is keyboard accessible, and we carefully craft the markup to deliver the best screenreader experience we know how.

Production-ready — rigorously tested in the latest versions of all browsers to handle lots of edge-cases you might easily miss yourself.

Simple to deploy — production-ready and easily deployed anywhere that you can deploy a Next.js application, like Vercel or Netlify.

Screenshots

This is a detail imageThis is a detail imageThis is a detail imageThis is a detail image

Built for developers

Our templates are thoughtfully crafted with the latest and greatest versions of the tools we love so that they are easy to maintain, and fun to actually work on.

  • Next.js v12.1
  • Tailwind CSS v3.1
  • Headless UI v1.6
  • React v18

Original article source at https://tailwindui.com

#tailwind #tailwindcss #react #next #webdev #programming #developer 

Tailwind CSS Templates | 5 Free Update for Tailwind UI Customers
Anil  Sakhiya

Anil Sakhiya

1655107844

Everything You Need to Know About Full Stack Developer

What is a Full Stack Developer? Back End + Front End = Full Stack Engineer

In this tutorial, I will explain what Full Stack Development is, what skills you need to become a Full Stack Developer, salary expectations, and tips for landing a job.
 

If you are new to the tech industry, you might have heard of the term Full Stack. But what does that mean exactly?

What is Full Stack Development?

A full stack developer is someone who works with both the front end and back end of a web application. The front end is responsible for the visual look and feel of the website, while back end is responsible for the behind the scenes logic and infrastructure of the site.

Let's take a closer look at the terms front end and back end.

Front end Development (Client side)

Everything on a web page from the logo, to the search bar, buttons, overall layout and how the user interacts with the page was created by a front end developer. Front end developers are in charge of the look and feel of the website.

Front end developers also have to make sure the website looks good on all devices (phones, tablets, and computer screens). This is called Responsive Web Design.

Back end Development (Server side)

Back end development refers to the part of the application that the user does not see. Back end developers focus on the logic of the site, creating servers, and working with databases and API's (Application Programming Interfaces).

For example, the content and layout for a form would be created on the client side, but when the users submits their information it gets processed on the server side (back end).

Example of a Real World Full Stack Application

To get a better understanding of what a full stack application looks like, let's examine the freeCodeCamp website.

Screen-Shot-2021-08-30-at-3.54.01-AM

Everything you see on the page would be considered front end. All of the buttons, text, colors, and layout are the job of the front end developer.

When it comes to things like user credentials, that is all maintained by the back end. All of the login processes and user information are examples of back end development at work.

Screen-Shot-2021-08-30-at-4.04.57-AM

If you are curious and want to take a peek at the code, you can find it on the freeCodeCamp open source page.

Skills You Need as a Full Stack Web Developer

Let's take a look at the technologies and tools you will need to learn to become a full stack developer.

HTML

HTML stands for HyperText Markup Language. HTML displays the content on the page like buttons, links, headings, paragraphs, and lists.

To learn the basics of HTML, freeCodeCamp has a HTML Crash Course for Beginners - Website Tutorial.

CSS

CSS stands for Cascading Style Sheets. CSS is responsible for the style of your web page including colors, layouts, and animations.

freeCodeCamp's Responsive Web Design Course will teach you the basics of CSS, responsive design, and accessibility. Responsive design is essential in creating websites that look good on all devices.

Accessibility is the practice of making sure that everyone can easily use your web sites. You do not want to create web sites that cannot be used by those who use assistive technologies like screen readers.

JavaScript

You use JavaScript with HTML and CSS to create dynamic and interactive web pages and mobile applications. Examples of JavaScript include animations, count down clocks, drop down mobile menus, and showing/hiding information when a user clicks on an element on the page.

To start learning JavaScript, you can take freeCodeCamp's JavaScript Algorithms and Data Structures course. From there, you can start building projects from my 40 JavaScript Projects for Beginners article.

CSS Frameworks, Libraries, and Preprocessors

These tools were created to help speed up the development process. Instead of writing all custom CSS, you can use a framework's catalog of CSS classes in your web pages.

There is no need to learn them all, but here is a list of a few options:

CSS preprocessors like Sass and Less allow you to add logic and functionality to your CSS. These tools make your CSS clean and easy to work with.

JavaScript libraries and frameworks

These frameworks and libraries allow you to save time and do more with less code.

Here are some popular options:

It is not necessary to learn them all. You should just research which technology is used in your area and start learning that one well.

Here are some suggested learning resources.

Databases

It is important for a full stack developer to know how to work with databases. A database in a web application is a place to store and organize your project's data.

There are many types of databases to learn but here are some popular options.

Back end languages

Languages you can use for back end development include Java, Python, Node, and PHP. It is not necessary to learn all of these languages, but instead focus on one to get started.

Here are some suggested learning resources.

There are also many tech stacks for both front end and backend development. Here are a few popular ones.

There are more backend languages to choose from but I would suggest researching the languages used most in your area.

Testing and Debugging skills

As you are developing your application, there will be errors in your code that need fixing. Debugging is the act of identifying those errors ("bugs") and fixing them.

Testing is another important skill to learn. Writing tests for your code is a way to ensure that your code is doing what it is supposed to do.

For a more in depth explanation on the different types of testing, I would suggest reading this article.

Version control

Version control is a way to track and manage changes to the project's code. Git is a popular software that you can use to track your code.

If you mess up a lot of things in your code, you can use Git to go back to a previous version of your code instead of manually rewriting everything.

Learning Git also allows you to collaborate with others on a team and make changes to the same code base from different locations.

I would suggest starting to learn Git and using a service like GitHub to host your personal projects.

Problem Solving

The most important skill for any developer is knowing how to problem solve. Companies and clients are looking for you to provide solutions.

It is important to learn how to tackle a problem, break it down into smaller manageable pieces, and troubleshoot the issue in these web applications.

Should I Pursue Full Stack Development?

If you are just starting out and are not sure if full stack is for you, then don't stress about that this early in your learning.

I would suggest focusing on learning the three core languages of the web which are HTML, CSS and JavaScript. As you progress in your journey, then you can decide which path is appropriate for you.

How Much Does a Full Stack Developer Make?

The salary range for full stack jobs will differ depending on where you are located in the world. I would suggest using sites like Glassdoor,  Indeed, and ZipRecruiter to look up salaries in your area.

Here are example salaries for the United States. This data was provided by ZipRecruiter and displays the national average.

Let's first look at a junior full stack developer salary. Junior developers are those who have been working in the industry for two years or less.

Screen-Shot-2021-08-30-at-3.26.16-AM

Next, let's take a look at mid level full stack salaries. These developers have been working between 2-4 years roughly.

Screen-Shot-2021-08-30-at-3.29.42-AM

Lastly, let's take a look at senior full stack salaries. These developers have been working in the industry for a few years now and often serve as a mentor for junior and mid level developers.

Screen-Shot-2021-08-30-at-3.32.16-AM

How Can You Get a Job as a Full Stack Developer?

Once you have learned the technical aspects of full stack development, you have to focus on putting together your job application materials. There are many incredible resources that can help you learn how to get a full stack job.

I hope you enjoyed this article and best of luck on your path to becoming a full stack developer.

Original article source at https://www.freecodecamp.org

#javascript #php #python #react #html #css #vue #sql #mysql #programming #developer 

Everything You Need to Know About Full Stack Developer

Pros Y Contras De Los Principales Lenguajes De Desarrollo Web

Elegir el lenguaje correcto para el desarrollo web puede ser difícil.

Si eres nuevo en la codificación, elegir el lenguaje de programación correcto puede ser difícil. Existen numerosas soluciones disponibles, así como fantásticos recursos educativos disponibles en línea.

¿Qué idioma deberías estudiar para convertirte en desarrollador web?

Mientras tenga una visión clara de lo que quiere hacer con el código en el futuro, estará en muy buena forma. Puede limitar sus opciones sabiendo qué idiomas se usan más comúnmente en la industria en la que desea trabajar.

Empecemos. Veremos algunos lenguajes de desarrollo web populares que puede aprender.

JavaScript

JavaScript es un lenguaje indispensable para aplicaciones web y desarrollo de sitios web. De hecho, JavaScript fue el lenguaje de programación más utilizado en la encuesta Stack Overflow 2019.

Los pros de Javascript:

  • Desarrollo rápido
  • Ejecución del lado del cliente
  • Interactividad de la interfaz de usuario
  • Hacer objeto XMLHttpRequest()
  • Interactividad de la interfaz de usuario

# Los contras de Javascript:

  • Un poco de ejecución lenta
  • Código siempre visible
  • Detener procesamiento

Pitón

Python es uno de los lenguajes de programación más utilizados en la actualidad. Es fácil de usar, rápido de aprender y adaptable a una variedad de proyectos. Python es un poderoso lenguaje de programación que se puede usar para el análisis de datos, el aprendizaje automático, el desarrollo web y el desarrollo de juegos.

Los pros de Python:

  • Fácil de usar y agradable de aprender
  • Soporta múltiples plataformas y sistemas
  • Da lugar a un desarrollo rápido al usar menos código
  • Código abierto con una gran comunidad
  • Tiene todas las bibliotecas que puedas imaginar.
  • Permite escalar incluso las aplicaciones más complicadas con facilidad

# Los contras de Python:

  • Python no es nativo del entorno móvil
  • No podemos usar Python para construir un juego 3D con muchos gráficos
  • No se recomienda Python para tareas que requieren mucha memoria
  • Python no es una buena opción para el trabajo multiprocesador/multinúcleo

Java

Java es un lenguaje de programación que se utiliza en una variedad de tareas, incluido el desarrollo web. Las aplicaciones móviles de Android también se pueden hacer con Java.

Java es otro lenguaje de programación popular entre los estudiantes universitarios. Java (o Python) es un lenguaje de programación ampliamente utilizado en informática y desarrollo de software.

Los pros de Java:

  • Un buen comienzo para estudiar para pensar como un desarrollador
  • Un lenguaje de alto nivel con una curva de aprendizaje suave y sintaxis simple
  • Estabilidad y una gran comunidad.
  • El estándar para la informática empresarial
  • subprocesos múltiples
  • Gestión automática de memoria
  • Independencia de la plataforma (escribir una vez y ejecutar en cualquier lugar)
  • Escasez de riesgos de seguridad

# Los contras de Java:

  • Mucho vocabulario nuevo para aprender
  • Bajo rendimiento
  • Código detallado y complejo

# rubí

También está Ruby, un lenguaje de programación de propósito general similar a Python. El ejemplo más conocido de Ruby on Rails es un famoso marco de desarrollo web llamado Ruby on Rails.

Ruby es fácil de aprender, rápido de dominar y divertido de usar. Ruby te da la libertad de ser creativo mientras escribes programas. Ruby puede proporcionar múltiples soluciones a un problema.

Los pros de RoR:

  1. Un gran número de bibliotecas y herramientas útiles.
  2. Una gran comunidad que apoya a los programadores.
  3. Eficiencia de tiempo
  4. Fuerte apego a las normas

# Los contras de RoR:

  • tiempo de actuación
  • Escasez de flexibilidad
  • precio del error

PHP

Aproximadamente el 80% de todos los sitios web están construidos con PHP. Debido a su creciente popularidad, PHP se ha convertido en una herramienta popular para los desarrolladores web autónomos.

A pesar de su uso actual, PHP puede ser un desafío para administrar y solucionar problemas. Es por esta razón que los desarrolladores a menudo tienen diferentes puntos de vista sobre el tema. En el año 2021, PHP será uno de los lenguajes de programación menos populares entre los desarrolladores.

Los pros de PHP:

  • Fuente abierta
  • Muy popular para aplicaciones web.
  • Completamente compatible multiplataforma
  • Altamente escalable
  • Enorme comunidad de soporte para programadores.
  • Incrustado fácilmente en HTML

# Los contras de PHP:

  • Los estudiantes deben tener un conocimiento básico de HTML
  • Funciona un poco más lento que otros lenguajes de programación.
  • No ajustado para aplicaciones de escritorio
  • La facilidad de personalización hace que sea más difícil detectar errores y más propenso a errores

Vamos

Desde 2007, Google ha estado desarrollando Go, comúnmente conocido como Golang, un lenguaje informático. Go fue creado para simplificar la creación de software confiable, simple y eficiente.

Go es un lenguaje de programación comparable a C, pero con tipado estructural, recolección de elementos no utilizados, seguridad de la memoria y concurrencia en el enfoque CSP.

Google, Facebook, Twitter, Youtube, Apple, Dropbox, The Economist, BBC, The New York Times, IBM, Docker son algunos de los sitios web que utilizan Golang.

Los pros de ir:

  • Go es un código abierto por naturaleza.
  • Ir tiene velocidad rápida.
  • Go tiene buenas credenciales.
  • Go mantiene alejados a los insectos.
  • Go tiene un recolector de basura.
  • Ir es concurrente.
  • Go es multiplataforma.

Los contras de ir:

  • Go carece de módulos de terceros.
  • Go es menos flexible.
  • Go no tiene genéricos.
  • Go difiere mucho de los lenguajes basados ​​en C.

Este blog debería haberle brindado información fundamental y conocimientos sobre la lista de lenguajes de desarrollo web.

Para ser un buen desarrollador web en cualquiera de estos idiomas, primero debe comprender correctamente el idioma y luego adquirir las habilidades necesarias en él. Además, debe obtener algo de experiencia en idiomas para poder avanzar en su trabajo.

Esta historia se publicó originalmente en https://hackernoon.com/discover-the-pros-and-cons-of-the-top-web-development-languages

#developer #language #go #javascript 

Pros Y Contras De Los Principales Lenguajes De Desarrollo Web
伊藤  直子

伊藤 直子

1654860553

トップWeb開発言語の長所と短所

Web開発に適切な言語を選択するのは難しい場合があります。

コーディングに不慣れな場合、正しいプログラミング言語を選択するのは難しい場合があります。利用可能なソリューションは数多くあり、オンラインで利用できる素晴らしい教育リソースもあります。

Web開発者になるには、どの言語を勉強する必要がありますか?

将来コードで何をしたいのかについて明確なビジョンを持っている限り、あなたはかなり良い状態にあります。働きたい業界で最も一般的に使用されている言語を知ることで、選択肢を制限することができます。

始めましょう。私たちはあなたが学ぶことができるいくつかの人気のあるウェブ開発言語を見ていきます。

JavaScript

JavaScriptは、WebアプリやWebサイト開発に欠かせない言語です。実際、JavaScriptはStack Overflow2019Surveyで最も使用されたプログラミング言語でした。

Javascriptの長所:

  • 急速な発展
  • クライアント側の実行
  • ユーザーインターフェイスの双方向性
  • XMLHttpRequest()オブジェクトを作成する
  • ユーザーインターフェイスの双方向性

#Javascriptの短所:

  • 実行が少し遅い
  • コードは常に表示されます
  • レンダリングを停止します

Python

Pythonは、今日最も広く使用されているプログラミング言語の1つです。使い方は簡単で、習得が早く、さまざまなプロジェクトに適応できます。Pythonは、データ分析、機械学習、Web開発、およびゲーム開発に使用できる強力なプログラミング言語です。

Pythonの長所:

  • 使いやすく、楽しく学ぶことができます
  • 複数のプラットフォームとシステムをサポート
  • より少ないコードを使用することにより、迅速な開発を実現します
  • 巨大なコミュニティを持つオープンソース
  • あなたが想像できるすべてのライブラリがあります
  • 最も複雑なアプリケーションでも簡単に拡張できます

#Pythonの短所:

  • Pythonはモバイル環境にネイティブではありません
  • Pythonを使用して高グラフィック3Dゲームを構築することはできません
  • Pythonは、メモリを大量に消費するタスクにはお勧めしません
  • Pythonは、マルチプロセッサ/マルチコアの作業には適していません

Java

Javaは、Web開発を含むさまざまなタスクで使用されるプログラミング言語です。AndroidモバイルアプリはJavaで作成することもできます。

Javaは、大学生の間で人気のあるもう1つのプログラミング言語です。Java(またはPython)は、コンピューターサイエンスおよびソフトウェア開発で広く使用されているプログラミング言語です。

Javaの長所:

  • 開発者のように考えることを勉強するための良いスタート
  • 穏やかな学習曲線と単純な構文を備えた高級言語
  • 安定性と巨大なコミュニティ
  • エンタープライズコンピューティングの標準
  • マルチスレッド
  • 自動メモリ管理
  • プラットフォームに依存しない(Write Once Run Anywhere)
  • セキュリティリスクの不足

#Javaの短所:

  • 学ぶべきたくさんの新しい語彙
  • 業績不振
  • 冗長で複雑なコード

#Ruby _

Pythonに似た汎用プログラミング言語であるRubyもあります。Ruby on Railsの最もよく知られている例は、RubyonRailsと呼ばれる有名なWeb開発フレームワークです。

Rubyは簡単に手に入れることができ、すぐに習得でき、楽しく使用できます。Rubyを使用すると、プログラムを作成する際に独創性を発揮する自由が得られます。Rubyは、問題に対して複数の解決策を提供できます。

RoRの長所:

  1. 多数の便利なライブラリとツール
  2. プログラマーをサポートする巨大なコミュニティ
  3. 時間効率
  4. 基準への強い順守

#RoRの短所:

  • 演奏時間
  • 柔軟性の不足
  • 間違いの代償

PHP

すべてのWebサイトの約80%がPHPで構築されています。その人気の高まりにより、PHPはフリーランスのWeb開発者に人気のあるツールになりました。

現在の使用にもかかわらず、PHPは管理とトラブルシューティングが難しい場合があります。このため、開発者はこのテーマに関して異なる視点を持っていることがよくあります。2021年には、PHPは開発者の間で最も人気のないプログラミング言語の1つになります。

PHPの長所:

  • オープンソース
  • Webアプリケーションで非常に人気があります
  • 完全に互換性のあるクロスプラットフォーム
  • 高度にスケーラブル
  • プログラマーサポートの巨大なコミュニティ
  • HTMLに簡単に埋め込む

#PHPの短所:

  • 学習者はHTMLの基本的な知識を持っている必要があります
  • 他のプログラミング言語よりも実行速度が少し遅い
  • デスクトップアプリケーション用に調整されていません
  • カスタマイズが簡単なため、エラーの検出が難しくなり、エラーが発生しやすくなります

行け

2007年以来、Googleはコンピュータ言語であるGolangとして一般に知られているGoを開発してきました。Goは、信頼性が高く、シンプルで効率的なソフトウェアを簡単に作成できるようにするために作成されました。

GoはCに匹敵するプログラミング言語ですが、構造型付け、ガベージコレクション、メモリの安全性、およびCSPアプローチでの並行性を備えています。

Google、Facebook、Twitter、Youtube、Apple、Dropbox、The Economist、BBC、The New York Times、IBM、Dockerは、Golangを使用するWebサイトの一部です。

Goの長所:

  • Goは本質的にオープンソースです。
  • Goの速度は速いです。
  • Goには優れた資格があります。
  • Goはバグを遠ざけます。
  • Goにはガベージコレクターがあります。
  • Goは並行です。
  • Goはクロスプラットフォームです。

囲碁の短所:

  • Goには3パーティモジュールがありません。
  • Goは柔軟性が低くなります。
  • Goにはジェネリックはありません。
  • GoはCベースの言語とは大きく異なります。

このブログは、Web開発言語リストに関するいくつかの基本的な情報と洞察を提供するはずです。

これらの言語のいずれかで優れたWeb開発者になるには、まずその言語を正しく理解してから、その言語で必要なスキルを習得する必要があります。さらに、仕事を進めるためには、ある程度の語学経験を積む必要があります。

このストーリーは、もともとhttps://hackernoon.com/discover-the-pros-and-cons-of-the-top-web-development-languagesで公開されました

#developer #language #go #javascript 

トップWeb開発言語の長所と短所
Brooke  Giles

Brooke Giles

1654763270

A 'textarea' with Code Automatically Highlighted via Highlight.js

highlighted-code

A textarea builtin extend to automatically provide code highlights based on one of the languages available via highlight.js.

Live demo

<!doctype html>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
textarea[is="highlighted-code"] { padding: 8px; }
</style>
<script type="module">
(async ({chrome, netscape}) => {

  // add Safari polyfill if needed
  if (!chrome && !netscape)
    await import('https://unpkg.com/@ungap/custom-elements');

  const {default: HighlightedCode} =
    await import('https://unpkg.com/highlighted-code');

  // bootstrap a theme through one of these names
  // https://github.com/highlightjs/highlight.js/tree/main/src/styles
  HighlightedCode.useTheme('github-dark');
})(self);
</script>
<textarea is="highlighted-code"
          cols="80" rows="12"
          language="javascript" tab-size="2" auto-height>
(async ({chrome, netscape}) => {

  // add Safari polyfill if needed
  if (!chrome && !netscape)
    await import('https://unpkg.com/@ungap/custom-elements');

  const {default: HighlightedCode} = await import('https://unpkg.com/highlighted-code');

  // bootstrap a theme through one of these names
  // https://github.com/highlightjs/highlight.js/tree/main/src/styles
  HighlightedCode.useTheme('github-dark');
})(self);
</textarea>

API

The component is literally a textarea so everything that works or applies for this kind of element works and applies for this custom element too.

The only extras attributes this component offer are:

  • language, reflected as area.language to define which kind of language should be highlighted. See the list of supported languages here (see those that don't require extra packages).
  • tab-size, reflected as area.tabSize, to determine the amount of virtual spaces covered by tabs. Because we live in a Mobile world, the default is 2.
  • auto-height, reflected as area.autoHeight, to render the textarea as if it was a regular element. See the test page as example, or set autoHeight = true in the live demo and see the area growing while typing.

The exported HighlightedCode default class exposes these public methods/accessors:

  • HighlightedCode.useTheme(name:string) to bootstrap any valid CSS theme by name. This can also be a fully qualified URL to avoid CDN when desired.
  • HighlightedCode.insertText(text:string) to programmatically insert some text where the selection is.
  • HighlightedCode.library:hljs a getter to retrieve the imported hljs library, usable to register missing PLs or do something else.

Exports

The main export uses all default languages included in highlight.js, but there are other variants:

  • highlighted-code/web, which includes only Markdown, JS, TS, JSON, CSS, and HTML or XML
  • highlighted-code/sql, which includes only SQL

These variants are much lighter than default module.

F.A.Q.

How to disable editing?

You can either textarea.disabled = true or:

<textarea is="highlighted-code" language="css" disabled>
textarea[is="highlighted-code"]::before {
  content: "it's that simple!";
}
</textarea>

How to disable spellcheck?

You can either textarea.spellcheck = false or:

<textarea is="highlighted-code" language="css" spellcheck="false">
textarea[is="highlighted-code"]::before {
  content: "it's that simple!";
}
</textarea>

How to set cols or rows?

<textarea is="highlighted-code" language="css" cols="40" rows="12">
textarea[is="highlighted-code"]::before {
  content: "it's that simple!";
}
</textarea>

How to set a placeholder?

<textarea is="highlighted-code" language="css"
          placeholder="write css..."></textarea>

How to ...?

Look, this is a custom element builtin extend.

If you know how and when to use a textarea, you're 90% done with this module.

Now you need just the is attribute with value highlighted-code, a language attribute with a supported language from highlight.js library, optionally a tab-size attribute to have tabs wider than 2, and a theme, where default would work too, as long as HighlightedCode.useTheme('default') is invoked.

Download Details: 
Author: WebReflection
Source Code: https://github.com/WebReflection/highlighted-code 
License: ISC license
#programming #developer 

A 'textarea' with Code Automatically Highlighted via Highlight.js
Alex Rock

Alex Rock

1654496231

Understanding the Crypto Fundraising Models

What is an Initial Coin Offering (ICO)?

In the crypto world, an Initial Coin Offering (ICO) is equivalent to an Initial Public Offering (IPO) (IPO). The term "Initial Coin Offering" refers to a fundraising model that aids in the capitalization of the cryptocurrency industry. An ICO can be launched by a company or a new coin to raise funds. Interested investors can participate in the initial coin offering in exchange for a new crypto token issued by the company.

The process begins with a new or established company looking to raise capital for growth. It is a fundraising event for a new cryptocurrency asset, company, or venture.

What is an Initial DEX Offering (IDO)?

A crypto token offering that runs on a Decentralized Exchange is an Initial Decentralized Exchange (DEX) Offering. Liquidity pools (LP) play an essential role by providing liquidity after the sale. The initial DEX offering during a token generation event allows users to lock their funds in exchange for new tokens, providing a cost-effective and more accessible way for projects to distribute tokens.

Initial DEX offerings are similar to ICOs and IEOs in that they seek to raise funds and bootstrap a project. Unlike ICOs and IEOs, where tokens are sold before listing, IDOs are immediately listed on a decentralized exchange.

What is an Initial Exchange Offering (IEO)?

An Initial Exchange Offering (IEO) is a type of crowdfunding managed by an exchange platform. Unlike an ICO, where the project team is in charge of fundraising, an Initial Exchange Offering is made through an exchange platform. Users can directly purchase tokens in IEO using funds from their exchange wallet.

IEO is a simple fundraising model in which users only need an exchange platform account with some funds to participate. Where the exchange is staking its reputation for a project on its platform, IEOs provide a high level of trust and transparency.

What is an Initial Farming Offering (IFO)?

Initial Farming Offering (IFO) is a fundraising model that assists newly launched Defi projects in raising capital through participation in pre-sales events. The Initial Funding Offering (IFO) is the successor to the Initial Coin Offering (ICO), which depicts a crowdsourcing method used by crypto projects to raise capital in the early stages.

Investors can raise the capital needed for the available projects by participating in DEX's re-sales event. IFOs, which serve to raise funds for crypto projects, are both similar and distinct from IEOs and ICOs.

What is an Initial Liquidity Offering (ILO)?

An Initial Liquidity Offering (ILO) is a fundraising model in which a new token is offered to buyers who agree to contribute to a liquidity pool. Because the token is attracting new buyers, the Automated Market Maker (AMM) can function. It allows multiple projects and startups to raise funds by selling tokens on Defi-based DEX platforms instead of conducting an ICO.

ILOs are simple to carry out on Defi-based DEX platforms because they have many investors who may be interested in purchasing the crypto tokens immediately for a higher price. These DEXs use the AMM mechanism, which manages liquidity pools through highly skilled liquidity providers.

What is an Initial NFT Offering (INO)?

NFTs have played various roles in reaching out to the target audience and generating interest in new tokens or any business. NFT can be used as a marketing tool to attract customers by providing them with some benefit that benefits the NFT holder. At such times, the initial offering of NFT is the opportunity for the customer to acquire the NFT and use the utility for a specific project.

This INO (Initial NFT Offering) can be used as a marketing strategy or fundraising model. The main thing is to look at the number of people interested in the use case and the project's popularity. Sometimes a free NFT offering will include a few tasks to complete that will help spread the project to more people.

Please contact Suffescom Solutions, an IDO Development Company, if you want to develop any fundraising models.

#news  #suffescom  #hit  #hindustantimes  #idodevelopmentcompany  #media  #blockchain  #developer  #crypto  #dapp  #defi  #metaverse  #web3  #web3  #cryptowallet  #crypto  #wallet  
 

Michael Elliot

1654240328

Top 5 DEX Development Companies

Since the idea of Initial Dex Offerings (IDO) came up in the late 2010s, these have been a part of many crypto projects that are slowly becoming successful. Launchpads have helped bring new businesses into the crypto space by putting them in front of a larger group of investors. Also, the current crypto climate looks like it will bring a lot more wealth in the future as new uses are found. So, a business based on an IDO launchpad could be the best way for an entrepreneur to get started if they want to take advantage of the crypto world's potential by helping new projects. Even though a lot of companies say they are experts at making IDO launchpads, only a few of them really are, which can be seen by the wide range of clients they have worked with. In this blog, we'll look at the top five companies that build IDO launchpads.

1. Suffescom Solution: Suffescom Solutions has been since 2011 before the first popular non-fungible tokens (NFTs) went public. And The firm has started pioneering the development of various blockchain-based applications with a global presence with dedicated developers on various technologies. Also many time awarded by the national media groups such as Hindustan Times in India. The Suffescom Solutions Pvt. Ltd. was awarded by Shri Som Parkash (Honorable Union Minister of State for Commerce & Industry) at “Business & Entrepreneurs - Felicitation Ceremony 2022“ organized by leading print media Hindustan Times. According to some reports, the company’s on-demand IDO crypto Launchpad Development services have been one of their warm products. The experienced blockchain developers in the firm have the capability to develop IDO launchpad platforms from scratch and ready-made white label cryptocurrency exchange development solutions. Since the firm has a customer-centric stand, your requirements will be fulfilled without fail, and its services come at affordable prices. The firm also offers excellent services related to the development of crypto exchanges, NFT applications, DeFi applications, and more.

  • Hourly Rate: $25 — $49 / hr
  • Employees: 249–499
  • Year of Foundation: 2011
  • Location: United States of America, India, Australia, Dubai

2. Best Web3 Development: Best Web3 Development Firm is a top-notch web3 platform development firm in USA with advanced and latest technology. It has highly experienced 200+ blockchain developers understand your dream and turn it into reality. It is working in the technology since 2010 when blockchain and crypto booming at wide range and It came with a unique ideas regarding new internet era. Best Web3.0 Development company is ready to shape a revolutionary platform. It has plethora of solutions regarding web3.0 developers and consulting team to launch AR, VR and extended reality platform. Following are the services:

Whitepaper Drafting

Website Design

Token Creation

Marketing

Bounty Management

Listing services

Coin Boosting

Product Development

3. RisingMax Consultant

RisingMax is the next name in the top companies for cryptocurrency wallet development solutions. The organization is led by top leaders and managers who never compromise with the quality of the services. The company earned its reputation and clients’ trust by delivering cutting-edge blockchain solutions. The team members have hands on the latest technologies like cloud, chatbot, IoT, AI, machine learning, etc.

RisingMax has served clients from more than 15+ countries with an innovative and agile approach. This company’s methodology has helped many businesses to grow exponentially in no time. The blockchain developers from RisingMax strive to unlock the opportunity for their clients in the blockchain journey. RisingMax is the one-stop destination for businesses looking for crypto development services.

  • Hourly Rate: $25 — $49 / hr
  • Employees: 180
  • Year of Foundation: 2011
  • Location: NYC, Bangalore, Sydney

4. Blockchain Web Devs

Antiersolutions stands on the top of the list of crypto development companies due to its high-tech development solutions. The company is known for its excellence in delivering feasible, cost-effective, and on-time services. By adopting the latest technologies and frameworks, the antiersolution provides a high user experience that helps the businesses retain the customers and generate huge revenue.

Through the agile approach, the company comes up with creative solutions for the emerging problems related to blockchain business issues. Antiersolutions has rich expertise in blockchain development, on-demand app solutions, Machine learning, AI, cryptocurrency, etc. With the experience gained over the years, the company can tackle complex challenges while caring for clients’ requirements.

  • Hourly Rate: $25 / hr
  • Employees: 49–199
  • Year of Foundation: 2015
  • Location: NYC, Dubai, Singapore

5. Idealogic

Idealogic refers to a full-cycle software advancement company located at Kyiv, Ukraine, with significant QA assurance, custom software development, product design expertise, and post-release support under Logistics, Fintech, Retail, plus Business Intelligence domains. They focus on business with entrepreneurs and startup founders keen on improving their ideas transparently and flexibly with a cost-effective budget.

They do worry about every project and consider all as their own. Initially, you might think of it as marketing material; however, you will understand its approach right after sending your message. They take minutes to respond to an answer rather than hours, plus you will continually believe that they are there for you.

  • Hourly Rate: $25 — $49/hr
  • Employees: 10–49
  • Year of Foundation: 2016
  • Location: Ukraine, United States

#news #suffescom #HIT #hindustantimes #media #blockchain #developer #crypto #app 

Top 5 DEX Development Companies
Jacob Banks

Jacob Banks

1654229337

MERN Stack Tutorial | Become an Expert MERN Stack Developer

MERN Stack Tutorial for Beginners | MERN Stack (MongoDB, Express, React, Node.js)

This video is based on MERN Stack Developer Full Course. MERN Stack Developer tutorial will help you learn the latest technical advancements in MERN Stack and guide you with the fundamentals based on current IT standards. This tutorial will help you with critical skills, tips, and tips to become an expert MERN Stack Developer.


How to Use MERN Stack: A Complete Guide

This tutorial will show you how to build a full-stack MERN application—in this case, an employee database—with the most current tools available. Before you begin, make sure that you are familiar with Node.js and React.js basics and have Node and Create React App installed. You will also need access to the MongoDB Atlas database for this tutorial. The full code is available on this GitHub repo.

What is the MERN Stack?

The MERN stack is a web development framework made up of the stack of MongoDB, Express.js, React.js, and Nodejs. It is one of the several variants of the MEAN stack. MERN stack visualized When you use the MERN stack, you work with React to implement the presentation layer, Express and Node to make up the middle or application layer, and MongoDB to create the database layer.

In this MERN stack tutorial, we will utilize these four technologies to develop a basic application that is able to record the information of employees and then display it using a React.

How to Get Started with the MERN Stack

To get started, you will need to do the following:

Install Node
To install Node, go to https://nodejs.org/en/ and download either the LTS version or the current version.

Have or Install a Code Editor
You can use any code editor of your choice for this tutorial. However, for the sake of demonstration, we will be using VS Code editor with the plugin prettier and vscode icons.

Setting Up the Project

(Feel free to code along or to download the full code from this GitHub repo.)

MERN lets us create full-stack solutions. So, to leverage its full potential, we will be creating a MERN stack project. For this project, we will create both a back end and a front end. The front end will be implemented with React and the back end will be implemented with MongoDB, Node, and Express. We will call the front end client and the back end server.

Let’s start by creating an empty directory: mern. This folder will hold all our files after we create a new project. Then we will create a React app—client—in it.

mkdir mern
cd mern
npx create-react-app client

Then, we create a folder for the back end and name it server.

mkdir server

We will jump into the server folder that we created previously and create the server. Then, we will initialize package.json using npm init.

cd server
npm init -y

We will also install the dependencies.

npm install mongodb express cors dotenv

The command above uses a couple of keywords:

  • mongodb command installs MongoDB database driver that allows your Node.js applications to connect to the database and work with data.
  • express installs the web framework for Node.js. (It will make our life easier.)
  • cors installs a Node.js package that allows cross origin resource sharing.
  • dotenv installs the module that loads environment variables from a .env file into process.env file. This lets you separate configuration files from the code.

We can check out installed dependencies using the package.json file. It should list the packages along with their versions.

After we have ensured that dependencies were installed successfully, we create a file called server.js with the following code.:

mern/server/server.js

const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config({ path: "./config.env" });
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
app.use(require("./routes/record"));
// get driver connection
const dbo = require("./db/conn");
 
app.listen(port, () => {
  // perform a database connection when server starts
  dbo.connectToServer(function (err) {
    if (err) console.error(err);
 
  });
  console.log(`Server is running on port: ${port}`);
});

Here, we are requiring express and cors to be used. const port process.env.port will access the port variable from the config.env we required.

Connecting to MongoDB Atlas

It’s time to connect our server to the database. We will use MongoDB Atlas as the database. MongoDB Atlas is a cloud-based database service that provides robust data security and reliability. MongoDB Atlas provides a free tier cluster that never expires and lets you access a subset of Atlas features and functionality.

Follow the Get Started with Atlas guide to create an account, deploy your first cluster, and locate your cluster’s connection string.

Now that you have the connection string, go back to the ‘server’ directory and create a ‘config.env’ file. There, assign the connection string to a new ATLAS_URI variable. Once done, your file should look similar to the one below. Replace <username> and the <password> with your database username and password.

mern/server/config.env

ATLAS_URI=mongodb+srv://<username>:<password>@sandbox.jadwj.mongodb.net/employees?retryWrites=true&w=majority
PORT=5000

Create a folder under the server directory—db—and inside it, a file—conn.js. There we can add the following code to connect to our database.

mern/server/db/conn.js

const { MongoClient } = require("mongodb");
const Db = process.env.ATLAS_URI;
const client = new MongoClient(Db, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
 
var _db;
 
module.exports = {
  connectToServer: function (callback) {
    client.connect(function (err, db) {
      // Verify we got a good "db" object
      if (db)
      {
        _db = db.db("employees");
        console.log("Successfully connected to MongoDB."); 
      }
      return callback(err);
         });
  },
 
  getDb: function () {
    return _db;
  },
};

Server API Endpoints

Database done. Server done. Now it's time for the Server API endpoint. Let's start by creating a routes folder and adding record.js in it. Navigate back to your “server” directory and create the new directory and file:

cd ../server
mkdir routes
touch routes/record.js

The routes/record.js file will also have the following lines of code in it.

mern/server/routes/record.js

const express = require("express");
 
// recordRoutes is an instance of the express router.
// We use it to define our routes.
// The router will be added as a middleware and will take control of requests starting with path /record.
const recordRoutes = express.Router();
 
// This will help us connect to the database
const dbo = require("../db/conn");
 
// This help convert the id from string to ObjectId for the _id.
const ObjectId = require("mongodb").ObjectId;
 
 
// This section will help you get a list of all the records.
recordRoutes.route("/record").get(function (req, res) {
 let db_connect = dbo.getDb("employees");
 db_connect
   .collection("records")
   .find({})
   .toArray(function (err, result) {
     if (err) throw err;
     res.json(result);
   });
});
 
// This section will help you get a single record by id
recordRoutes.route("/record/:id").get(function (req, res) {
 let db_connect = dbo.getDb();
 let myquery = { _id: ObjectId( req.params.id )};
 db_connect
     .collection("records")
     .findOne(myquery, function (err, result) {
       if (err) throw err;
       res.json(result);
     });
});
 
// This section will help you create a new record.
recordRoutes.route("/record/add").post(function (req, response) {
 let db_connect = dbo.getDb();
 let myobj = {
   name: req.body.name,
   position: req.body.position,
   level: req.body.level,
 };
 db_connect.collection("records").insertOne(myobj, function (err, res) {
   if (err) throw err;
   response.json(res);
 });
});
 
// This section will help you update a record by id.
recordRoutes.route("/update/:id").post(function (req, response) {
 let db_connect = dbo.getDb(); 
 let myquery = { _id: ObjectId( req.params.id )}; 
 let newvalues = {   
   $set: {     
     name: req.body.name,    
     position: req.body.position,     
     level: req.body.level,   
   }, 
  }
});
 
// This section will help you delete a record
recordRoutes.route("/:id").delete((req, response) => {
 let db_connect = dbo.getDb();
 let myquery = { _id: ObjectId( req.params.id )};
 db_connect.collection("records").deleteOne(myquery, function (err, obj) {
   if (err) throw err;
   console.log("1 document deleted");
   response.json(obj);
 });
});
 
module.exports = recordRoutes;

If you run the application at this point, you will get the following message in your terminal as the connection establishes.

> node server.js

Server is running on port: 5000
Successfully connected to MongoDB.

That’s it for the back end. Now, we will start working on the front end.

Setting Up the React Application

As we have already set up our React application using the create-react-app command, we can navigate to the client folder and check our React application code. Navigate to client folder

Let’s flesh out the application, but before we do, we need to install two additional dependencies that will be used in our project. Open a new terminal emulator, navigate to the “client” directory, and install bootstrap and react-router-dom.

npm install bootstrap react-router-dom

bootstrap lets you quickly deploy a template and components for your new web application without having to do everything from scratch. And, the react-router-dom installs React router components for web applications. Make sure your server application is still running!

Setting Up the React Router

Let's start by emptying the src folder and adding two new files in it: index.js and App.js.

rm src/**/*
touch src/index.js src/App.js

Inside src/index.js, we add the following code:

mern/client/src/index.js

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById("root")
);

We have used BrowserRouter to keep our UI in sync with the URL. BrowserRouter helps with seamless transitions while switching between components. Basically, it will only reload/refresh the component that needs to be changed instead of refreshing/reloading the entire page. Though BrowserRouter is not a necessity, it is a must if you want your app to be responsive.

Creating Components

After adding the code to index.js files, we will create a components folder inside src. For each component we create, we will add a new .js file inside the components folder. In this case, we will add create.js, edit.js, navbar.js, and recordList.js.

mkdir src/components
(cd src/components &&
touch create.js edit.js navbar.js recordList.js)

A snapshot of each file would look like the following.

create.js

The following code will serve as a creating component for our records. Using this component, users can create a new record. This component will submit a create command to our server.

mern/client/src/components/create.js

import React, { useState } from "react";
import { useNavigate } from "react-router";
 
export default function Create() {
 const [form, setForm] = useState({
   name: "",
   position: "",
   level: "",
 });
 const navigate = useNavigate();
 
 // These methods will update the state properties.
 function updateForm(value) {
   return setForm((prev) => {
     return { ...prev, ...value };
   });
 }
 
 // This function will handle the submission.
 async function onSubmit(e) {
   e.preventDefault();
 
   // When a post request is sent to the create url, we'll add a new record to the database.
   const newPerson = { ...form };
 
   await fetch("http://localhost:5000/record/add", {
     method: "POST",
     headers: {
       "Content-Type": "application/json",
     },
     body: JSON.stringify(newPerson),
   })
   .catch(error => {
     window.alert(error);
     return;
   });
 
   setForm({ name: "", position: "", level: "" });
   navigate("/");
 }
 
 // This following section will display the form that takes the input from the user.
 return (
   <div>
     <h3>Create New Record</h3>
     <form onSubmit={onSubmit}>
       <div className="form-group">
         <label htmlFor="name">Name</label>
         <input
           type="text"
           className="form-control"
           id="name"
           value={form.name}
           onChange={(e) => updateForm({ name: e.target.value })}
         />
       </div>
       <div className="form-group">
         <label htmlFor="position">Position</label>
         <input
           type="text"
           className="form-control"
           id="position"
           value={form.position}
           onChange={(e) => updateForm({ position: e.target.value })}
         />
       </div>
       <div className="form-group">
         <div className="form-check form-check-inline">
           <input
             className="form-check-input"
             type="radio"
             name="positionOptions"
             id="positionIntern"
             value="Intern"
             checked={form.level === "Intern"}
             onChange={(e) => updateForm({ level: e.target.value })}
           />
           <label htmlFor="positionIntern" className="form-check-label">Intern</label>
         </div>
         <div className="form-check form-check-inline">
           <input
             className="form-check-input"
             type="radio"
             name="positionOptions"
             id="positionJunior"
             value="Junior"
             checked={form.level === "Junior"}
             onChange={(e) => updateForm({ level: e.target.value })}
           />
           <label htmlFor="positionJunior" className="form-check-label">Junior</label>
         </div>
         <div className="form-check form-check-inline">
           <input
             className="form-check-input"
             type="radio"
             name="positionOptions"
             id="positionSenior"
             value="Senior"
             checked={form.level === "Senior"}
             onChange={(e) => updateForm({ level: e.target.value })}
           />
           <label htmlFor="positionSenior" className="form-check-label">Senior</label>
         </div>
       </div>
       <div className="form-group">
         <input
           type="submit"
           value="Create person"
           className="btn btn-primary"
         />
       </div>
     </form>
   </div>
 );
}

edit.js

The following code will serve as an editing component for our records. It will use a similar layout to the create component and will eventually submit an update command to our server.

mern/client/src/components/edit.js

import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router";
 
export default function Edit() {
 const [form, setForm] = useState({
   name: "",
   position: "",
   level: "",
   records: [],
 });
 const params = useParams();
 const navigate = useNavigate();
 
 useEffect(() => {
   async function fetchData() {
     const id = params.id.toString();
     const response = await fetch(`http://localhost:5000/record/${params.id.toString()}`);
 
     if (!response.ok) {
       const message = `An error has occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }
 
     const record = await response.json();
     if (!record) {
       window.alert(`Record with id ${id} not found`);
       navigate("/");
       return;
     }
 
     setForm(record);
   }
 
   fetchData();
 
   return;
 }, [params.id, navigate]);
 
 // These methods will update the state properties.
 function updateForm(value) {
   return setForm((prev) => {
     return { ...prev, ...value };
   });
 }
 
 async function onSubmit(e) {
   e.preventDefault();
   const editedPerson = {
     name: form.name,
     position: form.position,
     level: form.level,
   };
 
   // This will send a post request to update the data in the database.
   await fetch(`http://localhost:5000/update/${params.id}`, {
     method: "POST",
     body: JSON.stringify(editedPerson),
     headers: {
       'Content-Type': 'application/json'
     },
   });
 
   navigate("/");
 }
 
 // This following section will display the form that takes input from the user to update the data.
 return (
   <div>
     <h3>Update Record</h3>
     <form onSubmit={onSubmit}>
       <div className="form-group">
         <label htmlFor="name">Name: </label>
         <input
           type="text"
           className="form-control"
           id="name"
           value={form.name}
           onChange={(e) => updateForm({ name: e.target.value })}
         />
       </div>
       <div className="form-group">
         <label htmlFor="position">Position: </label>
         <input
           type="text"
           className="form-control"
           id="position"
           value={form.position}
           onChange={(e) => updateForm({ position: e.target.value })}
         />
       </div>
       <div className="form-group">
         <div className="form-check form-check-inline">
           <input
             className="form-check-input"
             type="radio"
             name="positionOptions"
             id="positionIntern"
             value="Intern"
             checked={form.level === "Intern"}
             onChange={(e) => updateForm({ level: e.target.value })}
           />
           <label htmlFor="positionIntern" className="form-check-label">Intern</label>
         </div>
         <div className="form-check form-check-inline">
           <input
             className="form-check-input"
             type="radio"
             name="positionOptions"
             id="positionJunior"
             value="Junior"
             checked={form.level === "Junior"}
             onChange={(e) => updateForm({ level: e.target.value })}
           />
           <label htmlFor="positionJunior" className="form-check-label">Junior</label>
         </div>
         <div className="form-check form-check-inline">
           <input
             className="form-check-input"
             type="radio"
             name="positionOptions"
             id="positionSenior"
             value="Senior"
             checked={form.level === "Senior"}
             onChange={(e) => updateForm({ level: e.target.value })}
           />
           <label htmlFor="positionSenior" className="form-check-label">Senior</label>
       </div>
       </div>
       <br />
 
       <div className="form-group">
         <input
           type="submit"
           value="Update Record"
           className="btn btn-primary"
         />
       </div>
     </form>
   </div>
 );
}

recordList.js

The following code will serve as a viewing component for our records. It will fetch all the records in our database through a GET method.

mern/client/src/components/recordList.js

import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
 
const Record = (props) => (
 <tr>
   <td>{props.record.name}</td>
   <td>{props.record.position}</td>
   <td>{props.record.level}</td>
   <td>
     <Link className="btn btn-link" to={`/edit/${props.record._id}`}>Edit</Link> |
     <button className="btn btn-link"
       onClick={() => {
         props.deleteRecord(props.record._id);
       }}
     >
       Delete
     </button>
   </td>
 </tr>
);
 
export default function RecordList() {
 const [records, setRecords] = useState([]);
 
 // This method fetches the records from the database.
 useEffect(() => {
   async function getRecords() {
     const response = await fetch(`http://localhost:5000/record/`);
 
     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }
 
     const records = await response.json();
     setRecords(records);
   }
 
   getRecords();
 
   return;
 }, [records.length]);
 
 // This method will delete a record
 async function deleteRecord(id) {
   await fetch(`http://localhost:5000/${id}`, {
     method: "DELETE"
   });
 
   const newRecords = records.filter((el) => el._id !== id);
   setRecords(newRecords);
 }
 
 // This method will map out the records on the table
 function recordList() {
   return records.map((record) => {
     return (
       <Record
         record={record}
         deleteRecord={() => deleteRecord(record._id)}
         key={record._id}
       />
     );
   });
 }
 
 // This following section will display the table with the records of individuals.
 return (
   <div>
     <h3>Record List</h3>
     <table className="table table-striped" style={{ marginTop: 20 }}>
       <thead>
         <tr>
           <th>Name</th>
           <th>Position</th>
           <th>Level</th>
           <th>Action</th>
         </tr>
       </thead>
       <tbody>{recordList()}</tbody>
     </table>
   </div>
 );
}

navbar.js

In the navbar.js component, we will create a navigation bar that will link us to the required components using the following code.

mern/client/src/components/navbar.js

import React from "react";
 
// We import bootstrap to make our application look better.
import "bootstrap/dist/css/bootstrap.css";
 
// We import NavLink to utilize the react router.
import { NavLink } from "react-router-dom";
 
// Here, we display our Navbar
export default function Navbar() {
 return (
   <div>
     <nav className="navbar navbar-expand-lg navbar-light bg-light">
       <NavLink className="navbar-brand" to="/">
       <img style={{"width" : 25 + '%'}} src="https://d3cy9zhslanhfa.cloudfront.net/media/3800C044-6298-4575-A05D5C6B7623EE37/4B45D0EC-3482-4759-82DA37D8EA07D229/webimage-8A27671A-8A53-45DC-89D7BF8537F15A0D.png"></img>
       </NavLink>
       <button
         className="navbar-toggler"
         type="button"
         data-toggle="collapse"
         data-target="#navbarSupportedContent"
         aria-controls="navbarSupportedContent"
         aria-expanded="false"
         aria-label="Toggle navigation"
       >
         <span className="navbar-toggler-icon"></span>
       </button>
 
       <div className="collapse navbar-collapse" id="navbarSupportedContent">
         <ul className="navbar-nav ml-auto">
           <li className="nav-item">
             <NavLink className="nav-link" to="/create">
               Create Record
             </NavLink>
           </li>
         </ul>
       </div>
     </nav>
   </div>
 );
}

Now, we add the following to the src/App.js file we created earlier.

mern/client/src/App.js

import React from "react";
 
// We use Route in order to define the different routes of our application
import { Route, Routes } from "react-router-dom";
 
// We import all the components we need in our app
import Navbar from "./components/navbar";
import RecordList from "./components/recordList";
import Edit from "./components/edit";
import Create from "./components/create";
 
const App = () => {
 return (
   <div>
     <Navbar />
     <Routes>
       <Route exact path="/" element={<RecordList />} />
       <Route path="/edit/:id" element={<Edit />} />
       <Route path="/create" element={<Create />} />
     </Routes>
   </div>
 );
};
 
export default App;

Connecting the Front End to the Back End

We have completed creating components. We also connected our React app to the back end using fetch. fetch provides cleaner and easier ways to handle http requests. fetch is used in create.js, edit.js, and recordList.js as they handle http requests. In create.js, we appended the following code to the onSubmit(e) block. When a POST request is sent to the create URL, fetch will add a new record to the database.

// This function will handle the submission.
 async function onSubmit(e) {
   e.preventDefault();
 
   // When a post request is sent to the create url, we'll add a new record to the database.
   const newPerson = { ...form };
 
   await fetch("http://localhost:5000/record/add", {
     method: "POST",
     headers: {
       "Content-Type": "application/json",
     },
     body: JSON.stringify(newPerson),
   })
   .catch(error => {
     window.alert(error);
     return;
   });
 
   setForm({ name: "", position: "", level: "" });
   navigate("/");
 }

Similarly, in edit.js, we appended the following code to the onSubmit(e) block.

async function onSubmit(e) {
   e.preventDefault();
   const editedPerson = {
     name: form.name,
     position: form.position,
     level: form.level,
   };
 
   // This will send a post request to update the data in the database.
   await fetch(`http://localhost:5000/update/${params.id}`, {
     method: "POST",
     body: JSON.stringify(editedPerson),
     headers: {
       'Content-Type': 'application/json'
     },
   });
 
   navigate("/");
 }

We also placed the following block of code to edit.js beneath the constructor block.

useEffect(() => {
   async function fetchData() {
     const id = params.id.toString();
     const response = await fetch(`http://localhost:5000/record/${params.id.toString()}`);
 
     if (!response.ok) {
       const message = `An error has occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }
 
     const record = await response.json();
     if (!record) {
       window.alert(`Record with id ${id} not found`);
       navigate("/");
       return;
     }
 
     setForm(record);
   }
 
   fetchData();
 
   return;
 }, [params.id, navigate]);

Lastly, we have recordList.js. recordList.js fetches the records from the database, so we will be using fetch's get method to retrieve records from the database. To achieve this, we added the following lines of code above the recordList() function in recordList.js.

useEffect(() => {
   async function getRecords() {
     const response = await fetch(`http://localhost:5000/record/`);
 
     if (!response.ok) {
       const message = `An error occurred: ${response.statusText}`;
       window.alert(message);
       return;
     }
 
     const records = await response.json();
     setRecords(records);
   }
 
   getRecords();
 
   return;
 }, [records.length]);
 
 // This method will delete a record
 async function deleteRecord(id) {
   await fetch(`http://localhost:5000/${id}`, {
     method: "DELETE"
   });
 
   const newRecords = records.filter((el) => el._id !== id);
   setRecords(newRecords);
 }

After closing everything, to start the app, follow these steps.

  • Ensure that the server app is still running. If it’s not, start by executing the following command in the server/ directory:
node server.js
  • Go back to the client directory and run the command:
npm start

This is what the landing page of the record component will look like after we added two records for “Richard” and “Billy” via the “Create Record” button.

Sample record landing page

This is what the screen that lets you add an employee will look like. Sample create new record page

Congratulations on building your first MERN application. For more ideas and advanced concepts, visit our Developer Hub or follow this MERN workshop to take a basic MERN To-Do app through to a fully managed, auto-scaling application.

#mern #mongodb #express #react #node #programming #developer 

MERN Stack Tutorial | Become an Expert MERN Stack Developer
Web  Dev

Web Dev

1654226908

HTML Form Element | How Does an HTML Form Work?

HTML Form – Input Type and Submit Button Example

Forms are one of the most important parts of the web. Without them, there wouldn't be an easy way to collect data, search for resources, or sign up to receive valuable information.

You can embed forms on websites with the HTML form element. Inside the form element, several inputs are nested. These inputs are also known as form controls.

In this tutorial, we will explore the HTML form element, the various input types it takes, and how to create a submit button with which data is submitted.

By the end, you will know how forms work and you'll be able to make them with confidence.

Basic HTML Form Syntax

<form action="mywebsite.com" method="POST">
    <!--Input of any type and textareas goes in here-->
</form>

HTML Form Input Types

You use the <input> tag to create various form controls in HTML. It is an inline element and takes attributes such as type, name, minlength, maxlength, placeholder, and so on. Each of these has specific values they take.

The placeholder attribute is important as it helps the user understand the purpose of the input field before they type anything in.

There are 20 different input types, and we will look at them one by one.

Type Text

This type of input takes a value of “text”, so it creates a single line of text input.

<input type="text" placeholder="Enter name" />

An input with the type of text looks like the screenshot below:
textInput

Type Password

As the name implies, an input with a type of password creates a password. It is automatically invisible to the user, unless it is manipulated by JavaScript.

<input type="password" placeholder="Enter your password" />

passwordInput

Type Email

Any input with the type of email defines a field for entering an email address.

<input type="email" placeholder="Enter your email" />

typeEmail

Type Number

This type of input lets the user insert numbers only.

<input type="number" placeholder="Enter a number" />

numberInput

Type Radio

Sometimes, users will need to pick one out of numerous options. An input field with its type attributes set to “radio” lets you do this.

 <input type="radio" />

typeRadio

Type Checkbox

So, with an input type of radio, users will be allowed to pick one out of numerous options. What if you want them to pick as many options as possible? That’s what an input with a type attribute set to checkbox does.

<input type="checkbox" />

typeCheckbox

Type Submit

You use this type to add a submit button to forms. When a user clicks it, it automatically submits the form. It takes a value attribute, which defines the text that appears inside the button.

<input type="submit" value="Enter to Win" />

typeSubmit

Type Button

An input with a type set to button creates a button, which can be manipulated by JavaScript's onClick event listener type. It creates a button just like an input type of submit, but with the exception that the value is empty by default, so it has to be specified.

<input type="button" value="Submit" />

typeButton

Type File

This defines a field for file submission. When a user clicks it, they are prompted to insert the desired file type, which might be an image, PDF, document file, and so on.

<input type="file" />

The result of an input type of file looks like this:

fileInput

Type Color

This is a fancy input type introduced by HTML5. With it, the user can submit their favourite color for example. Black (#000000) is the default value, but can be overridden by setting the value to a desired color.

Many developers have used it as a trick to get to select different color shades available in RGB, HSL and alphanumeric formats.

<input type="color" />

This is the result of an input type of color:

colorInput

Type Search

Input with the type of search defines a text field just like an input type of text. But this time it has the sole purpose of searching for info. It is different from type text in that, a cancel button appears once the user starts typing.

<input type="search" />

typeSearch

Type URL

When the type attribute of an input tag is set to URL, it displays a field where users can enter a URL.

<input type="url" />

typeURL

Type Tel

An input type of tel lets you collect telephone numbers from users.

<input type="tel" />

typeTel

Type Date

You might have registered on a website where you requested the date of a certain event. The site probably used an input with the type value set to date to acheive this.

<input type="date" />

This is what an input with type date looks like:

dateInput

Type Datetime-local

This works like the input type date, but it also lets the user pick a date with a particular time.

<input type="datetime-local" />

datelocalInput

Type Week

The input type of week lets a user select a specific week.

<input type="week" />

weekInput

Type Month

The input with the type of month populates months for the user to pick from when clicked.

<input type="month" />

monthInput

Textarea

There are times when a user will need to fill in multiple lines of text which wouldn't be suitable in an input type of text (as it specifies a one-line text field).

textarea lets the user do this as it defines multiple lines of text input. It takes its own attributes such as cols – for the number of columns, and rows for the number of rows.

<textarea cols="50" rows="20"></textarea>

textarea

Multiple Select Box

This is like a radio button and checkbox in one package. It is embedded in the page with two elements – a select element and an option, which is always nested inside select.

By default, the user can only pick one of the options. But with multiple attributes, you can let the user select more than one of the options.

<select>
      <option value="HTML">Select a Language</option>
      <option value="HTML">HTML</option>
      <option value="CSS">CSS</option>
      <option value="JavaScript">JavaScript</option>
      <option value="React">React</option>
</select>

selectDemo

How to Label HTML Inputs

Assigning labels to form controls is important. When they're properly connected to the input field through their for attribute and the input’s id attribute, it's easier for the user to use as they can just click the label itself to access the input.

<label for="name">Name</label>
<input type="text" id="name" /> <br />
<label for="check">Agree with terms</label>
<input type="checkbox" id="check" />

labelDemo

How HTML Forms Work

When a user fills in a form and submits it with the submit button, the data in the form controls are sent to the server through GET or POST HTTP request methods.

So how is the server indicated? The form element takes an action attribute, which must have its value specified to the URL of the server. It also takes a method attribute, where the HTTP method it uses to convey the values to the server is specified.

This method could be GET or POST. With the GET method, the values entered by the user are visible in the URL when the data is submitted. But with POST, the values are sent in HTTP headers, so those values are not visible in the URL.

If a method attribute is not used in the form, it is automatically assumed that the user wants to use the GET method, because it’s the default.

So when should you use the GET or POST method? Use the GET method for submitting non-sensitive data or retrieving data from a server (for example, during searches). Use the POST request when submitting files or sensitive data.

Mini Project: Build a Basic Contact Form

Let’s take what we’ve learned about forms and use it to make a simple contact form. I will also introduce a few new concepts as we go to round it all out.

Here's the HTML:

<form action=example-server.com">
      <fieldset>
        <legend>Contact me</legend>
        <div class="form-control">
          <label for="name">Name</label>
          <input type="name" id="name" placeholder="Enter your name" required />
        </div>

        <div class="form-control">
          <label for="email">Email</label>
          <input
            type="email"
            id="email"
            placeholder="Enter your email"
            required
          />
        </div>

        <div class="form-control">
          <label for="message">Message</label>
          <textarea
            id="message"
            cols="30"
            rows="10"
            placeholder="Enter your message"
            required
          ></textarea>
        </div>
        <input type="submit" value="Send" class="submit-btn" />
      </fieldset>
</form>

What’s going on in this HTML code?

First, a form element is wrapping every other element. It has an action set to “example-server.com”, a dummy server where the form data will be received.

After the form element, every other element is also surrounded by a fieldset element with a legend tag right under it.

We use the fieldset element to group related inputs together, and the legend tag contains a caption conveying what the form is about.

The inputs name, email, and textarea are all in a div with a class of form-control. So they behave like a block element, in order to make styling easier with CSS.

They are also validated with the required attribute, so the form fails to submit when those fields are empty or when the user fails to type in the values in the appropriate format.

After all that, we'll have the result in the screenshot below:
unstyledForm

How ugly is that? We need to apply some styling!

Here's the CSS:

body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100vh;
    font-family: cursive;
  }

 input,
    textarea {
    width: 100%;
    padding: 5px;
    outline: none;
  }

  label {
    line-height: 1.9rem;
  }

  input[type="submit"] {
   transform: translate(2.2%);
   padding: 3px;
   margin-top: 0.6rem;
   font-family: cursive;
   font-weight: bold;
  }

 fieldset {
   padding: 20px 40px;
 }

What’s the CSS code doing here?

We center everything in the body horizontally with Flexbox, and vertically with a 100% viewport height. We used a font-family of cursive.

We gave the inputs and textarea a width of 100% so they go all the way across. The labels got a minimal line-height of 1.9rem (30.4px), so they don’t stay too close to their respective inputs.

We specifically styled the button (input type button) with the transform property to push it to the center as it was off center a bit. We gave it a padding of 3px for more spacing around it. We then selected a cursive font-family for it with a weight of bold.

Because the button was too close to the textarea, we set a margin-top of 0.6rem to push it down a little bit.

We gave our fieldset element a padding of 20px at the top and bottom, with 40px at the left and right to push apart the border it creates around the form elements it is wrapped in.

At the end of it all, we have the beautiful form below:
styledForm

Conclusion

I hope this tutorial has helped you understand how forms work. Now you should have the knowledge you need to integrate forms into your websites so you can start collecting data.

Thank you for reading, and keep coding.

Original article source at https://www.freecodecamp.org

#html #html5 #programming #developer #webdev 

HTML Form Element | How Does an HTML Form Work?

The Beginner’s Guide to CSS Shorthand

This short article covers the various bits of CSS shorthand you'll encounter in your day to day work. 

What is CSS shorthand?

CSS shorthand is a group of CSS properties that allow values of multiple properties to be set simultaneously. These values are separated by spaces. For example, the border property is shorthand for the border-width, border-style, and border-color properties. So in CSS, border: 5px solid red; would specify a border that’s five px wide, solid, and red.

In addition to the CSS border property, the margin, padding, background, font, animation, transition, and flex properties all have a shorthand.

Border

border allows you to set border width, style and, color all in one single property. So for example:

border: 1px solid black;

is equivalent to the following three rules:

border-width: 1px;
border-style: solid;
border-color: black;

You can also break these down further into even more specific rules, for a single border of the element it is applied to, like so:

border-left: 1px solid black;
border-right: 1px solid black;
border-top: 1px solid black;
border-bottom: 1px solid black;

or even:

border-left-width: 2px;
border-left-style: solid;
border-left-color: black;

You will very rarely want to go this granular; you will probably use simply border or border-left/-right/-top/-bottom in most cases. The more granular options will likely be used only if you want to override an earlier border declaration.

Margin, padding, outline

Shorthand for margin, padding, and outline all works in the same way. Consider the following margin rule:

div.foo {
  margin-top: 1em;
  margin-right: 1.5em;
  margin-bottom: 2em;
  margin-left: 2.5em;
}

Such a rule could also be written as:

div.foo {
  margin: 1em 1.5em 2em 2.5em;
}

These types of property can take less than four values too, as follows:

  1. Same value applied to all four sides — margin: 2px;
  2. First value applied to the top and bottom, second to the left and right — margin: 2px 5px;.
  3. First and third values applied to the top and bottom respectively, second value applied to the left and right — margin: 2px 5px 1px;.

Font

You can specify the font size, weight, style, family, and line height using one line of shorthand. Consider the following CSS:

font-weight: bold;
font-style: italic;
font-variant: small-caps;
font-size: 1.5em;
line-height: 200%;
font-family: Georgia, "Times New Roman", serif;

You could specify all of this using the following line:

font: bold italic small-caps 1.5em/200% Georgia, "Times New Roman", serif;

Note that it doesn’t really matter about the order of many of these, although you should make sure that font-size/line-height and font-family come in the positions shown above; in addition, font-size and font-family should be specified. If not, this shorthand may not work in some browsers.

Note also that if font-weight, font-style or font-variant are not specified, their values default to normal.

Background

In CSS 2, you can specify background color, background image, image repeat and image position with one line of CSS. Take the following:

background-color: #000;
background-image: url(image.gif);
background-repeat: no-repeat;
background-position: top left;
background-attachment: fixed;

This can all be represented using the following shorthand:

background: #000 url(image.gif) no-repeat top left fixed;

Note that if any of the values are left out, the following defaults are assumed:

background-color: transparent;
background-image: none;
background-repeat: repeat;
background-position: top left;
background-attachment: scroll;

Enhancements in CSS3

CSS3 introduces three new properties: background-size, background-origin, and background-clip. You can include them in the background shorthand like so:

background: #000 url(image.gif); no-repeat top left / 50% 20% border-box content-box;

Notice the slash between top left and 50% 20%; it separates the values for background-position and background-size since these two properties share some value units (lengths and percentage); without it we cannot distinguish which values are for which.

So if you want to include the background-size value in the shorthand syntax, you need to:

  • Explicitly include background-position values even if these are the same as the defaults (see above).
  • Write background-position values before background-size values.
  • Put a slash in between these two pairs of values.

Similarly, background-origin and background-clip share the same keyword as their values. These two also needs to be written in order: background-origin coming in first, and background-clip second.

If you only specify one box value (border-box, padding-box, or content-box), then the value applies to background-origin and background-clip.

Note: CSS3 gradients are a special, advanced value of background-image — aside from the syntactical difference, gradient values appear in exactly the same place in the shorthand as other background-image values, and work in the same way. For more on CSS3 gradients, you can read CSS3 linear gradients and CSS3 radial gradients over at dev.opera.com.

List

You can specify the list bullet type, position, and image on a single line. Take the following CSS:

list-style-type: circle;
list-style-position: inside;
list-style-image: url(bullet.gif);

This is the equivalent of:

list-style: circle inside url(bullet.gif);

Note that if any of the values are left out, the following defaults are assumed:

list-style-type: circle;
list-style-position: outside;
list-style-image: none;

Color

When specifying hexadecimal color values, you can use shorthand if both hex values are the same for each color channel. For example, #000 is equivalent to the longhand #000000. Let’s look at a more complicated example too: #6c9 is the same as #66cc99.

#css #programming #developer 

The Beginner’s Guide to CSS Shorthand
Ruthie  Blanda

Ruthie Blanda

1654059600

How to Become A Senior Developer FAST?

In this video we learn how to become a senior developer QUICKLY? Are there any "shortcuts" to seniority level? Let me give you a few tips and thoughts.

#developer 

How to Become A Senior Developer FAST?

Learn Python Programming from Scratch | Python from Zero to Hero

Python: Zero to Hero in 3 Hours

In this course you will learn about Python from scratch. In this course you will learn about Python basics, Python functions, Variables and much more!

Timestamps:
0:00:00 Introduction
0:10:53 Math Operations
0:17:51 Variables
0:20:26 Booleans / Conditions
0:27:55 If Statements
0:31:10 Introduction to Lists
0:33:24 For Loops
0:41:35 While Loops
0:47:30 If / Elif / Else
0:56:40 Functions
1:11:15 Is
1:27:13 Cool Function Tricks
1:34:27 File Reading / Writing
1:42:33 Objects and Classes
1:56:00 Comments / Docstrings
2:03:55 Lists in Detail
2:08:58 Dictionaries
2:17:02 Strings in Detail
2:27:47 Tuples
2:30:35 Sets
2:34:33 Errors / Try / Except
2:38:35 User Input
2:41:18 List Comprehension
2:49:13 ASCII / Ord / Chr
2:53:50 Modules / Pip / Packages
2:57:52 Python Scripts / Files
3:04:11 Local Python
3:07:38 Conclusion

Notebook available here: https://colab.research.google.com/drive/1YNJx2CMObRQqQvkDDMxIEISZfGs7npwU?usp=sharing 


Learning Python: From Zero to Hero

First of all, what is Python? According to its creator, Guido van Rossum, Python is a:

“high-level programming language, and its core design philosophy is all about code readability and a syntax which allows programmers to express concepts in a few lines of code.”

For me, the first reason to learn Python was that it is, in fact, a beautiful programming language. It was really natural to code in it and express my thoughts.

Another reason was that we can use coding in Python in multiple ways: data science, web development, and machine learning all shine here. Quora, Pinterest and Spotify all use Python for their backend web development. So let’s learn a bit about it.

The Basics

1. Variables

You can think about variables as words that store a value. Simple as that.

In Python, it is really easy to define a variable and set a value to it. Imagine you want to store number 1 in a variable called “one.” Let’s do it:

one = 1

How simple was that? You just assigned the value 1 to the variable “one.”

two = 2
some_number = 10000

And you can assign any other value to whatever other variables you want. As you see in the table above, the variable “two” stores the integer 2, and “some_number” stores 10,000.

Besides integers, we can also use booleans (True / False), strings, float, and so many other data types.

# booleans
true_boolean = True
false_boolean = False

# string
my_name = "Leandro Tk"

# float
book_price = 15.80

2. Control Flow: conditional statements

If” uses an expression to evaluate whether a statement is True or False. If it is True, it executes what is inside the “if” statement. For example:

if True:
  print("Hello Python If")

if 2 > 1:
  print("2 is greater than 1")

2 is greater than 1, so the “print” code is executed.

The “else” statement will be executed if the “if” expression is false.

if 1 > 2:
  print("1 is greater than 2")
else:
  print("1 is not greater than 2")

1 is not greater than 2, so the code inside the “else” statement will be executed.

You can also use an “elif” statement:

if 1 > 2:
  print("1 is greater than 2")
elif 2 > 1:
  print("1 is not greater than 2")
else:
  print("1 is equal to 2")

3. Looping / Iterator

In Python, we can iterate in different forms. I’ll talk about two: while and for.

While Looping: while the statement is True, the code inside the block will be executed. So, this code will print the number from 1 to 10.

num = 1

while num <= 10:
    print(num)
    num += 1

The while loop needs a “loop condition.” If it stays True, it continues iterating. In this example, when num is 11 the loop condition equals False.

Another basic bit of code to better understand it:

loop_condition = True

while loop_condition:
    print("Loop Condition keeps: %s" %(loop_condition))
    loop_condition = False

The loop condition is True so it keeps iterating — until we set it to False.

For Looping: you apply the variable “num” to the block, and the “for” statement will iterate it for you. This code will print the same as while code: from 1 to 10.

for i in range(1, 11):
  print(i)

See? It is so simple. The range starts with 1 and goes until the 11th element (10 is the 10th element).

List: Collection | Array | Data Structure

Imagine you want to store the integer 1 in a variable. But maybe now you want to store 2. And 3, 4, 5 …

Do I have another way to store all the integers that I want, but not in millions of variables? You guessed it — there is indeed another way to store them.

List is a collection that can be used to store a list of values (like these integers that you want). So let’s use it:

my_integers = [1, 2, 3, 4, 5]

It is really simple. We created an array and stored it on my_integer.

But maybe you are asking: “How can I get a value from this array?”

Great question. List has a concept called index. The first element gets the index 0 (zero). The second gets 1, and so on. You get the idea.

To make it clearer, we can represent the array and each element with its index. I can draw it:

1*ReMk6NgghLII20vPD6uNEA

Using the Python syntax, it’s also simple to understand:

my_integers = [5, 7, 1, 3, 4]
print(my_integers[0]) # 5
print(my_integers[1]) # 7
print(my_integers[4]) # 4

Imagine that you don’t want to store integers. You just want to store strings, like a list of your relatives’ names. Mine would look something like this:

relatives_names = [
  "Toshiaki",
  "Juliana",
  "Yuji",
  "Bruno",
  "Kaio"
]

print(relatives_names[4]) # Kaio

It works the same way as integers. Nice.

We just learned how Lists indices work. But I still need to show you how we can add an element to the List data structure (an item to a list).

The most common method to add a new value to a List is append. Let’s see how it works:

bookshelf = []
bookshelf.append("The Effective Engineer")
bookshelf.append("The 4 Hour Work Week")
print(bookshelf[0]) # The Effective Engineer
print(bookshelf[1]) # The 4 Hour Work Week

append is super simple. You just need to apply the element (eg. “The Effective Engineer”) as the append parameter.

Well, enough about Lists. Let’s talk about another data structure.

Dictionary: Key-Value Data Structure

Now we know that Lists are indexed with integer numbers. But what if we don’t want to use integer numbers as indices? Some data structures that we can use are numeric, string, or other types of indices.

Let’s learn about the Dictionary data structure. Dictionary is a collection of key-value pairs. Here’s what it looks like:

dictionary_example = {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}

The key is the index pointing to the value. How do we access the Dictionary value? You guessed it — using the key. Let’s try it:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian"
}

print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro
print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk
print("And by the way I'm %s" %(dictionary_tk["nationality"])) # And by the way I'm Brazilian

I created a Dictionary about me. My name, nickname, and nationality. Those attributes are the Dictionary keys.

As we learned how to access the List using index, we also use indices (keys in the Dictionary context) to access the value stored in the Dictionary.

In the example, I printed a phrase about me using all the values stored in the Dictionary. Pretty simple, right?

Another cool thing about Dictionary is that we can use anything as the value. In the Dictionary I created, I want to add the key “age” and my real integer age in it:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian",
  "age": 24
}

print("My name is %s" %(dictionary_tk["name"])) # My name is Leandro
print("But you can call me %s" %(dictionary_tk["nickname"])) # But you can call me Tk
print("And by the way I'm %i and %s" %(dictionary_tk["age"], dictionary_tk["nationality"])) # And by the way I'm Brazilian

Here we have a key (age) value (24) pair using string as the key and integer as the value.

As we did with Lists, let’s learn how to add elements to a Dictionary. The key pointing to a value is a big part of what Dictionary is. This is also true when we are talking about adding elements to it:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian"
}

dictionary_tk['age'] = 24

print(dictionary_tk) # {'nationality': 'Brazilian', 'age': 24, 'nickname': 'Tk', 'name': 'Leandro'}

We just need to assign a value to a Dictionary key. Nothing complicated here, right?

Iteration: Looping Through Data Structures

As we learned in the Python Basics, the List iteration is very simple. We Python developers commonly use For looping. Let’s do it:

bookshelf = [
  "The Effective Engineer",
  "The 4-hour Workweek",
  "Zero to One",
  "Lean Startup",
  "Hooked"
]

for book in bookshelf:
    print(book)

So for each book in the bookshelf, we (can do everything with it) print it. Pretty simple and intuitive. That’s Python.

For a hash data structure, we can also use the for loop, but we apply the key :

dictionary = { "some_key": "some_value" }

for key in dictionary:
    print("%s --> %s" %(key, dictionary[key]))
    
# some_key --> some_value

This is an example how to use it. For each key in the dictionary , we print the key and its corresponding value.

Another way to do it is to use the iteritems method.

dictionary = { "some_key": "some_value" }

for key, value in dictionary.items():
    print("%s --> %s" %(key, value))

# some_key --> some_value

We did name the two parameters as key and value, but it is not necessary. We can name them anything. Let’s see it:

dictionary_tk = {
  "name": "Leandro",
  "nickname": "Tk",
  "nationality": "Brazilian",
  "age": 24
}

for attribute, value in dictionary_tk.items():
    print("My %s is %s" %(attribute, value))
    
# My name is Leandro
# My nickname is Tk
# My nationality is Brazilian
# My age is 24

We can see we used attribute as a parameter for the Dictionary key, and it works properly. Great!

Classes & Objects

A little bit of theory:

Objects are a representation of real world objects like cars, dogs, or bikes. The objects share two main characteristics: data and behavior.

Cars have data, like number of wheels, number of doors, and seating capacity They also exhibit behavior: they can accelerate, stop, show how much fuel is left, and so many other things.

We identify data as attributes and behavior as methods in object-oriented programming. Again:

Data → Attributes and Behavior → Methods

And a Class is the blueprint from which individual objects are created. In the real world, we often find many objects with the same type. Like cars. All the same make and model (and all have an engine, wheels, doors, and so on). Each car was built from the same set of blueprints and has the same components.

Python Object-Oriented Programming mode: ON

Python, as an Object-Oriented programming language, has these concepts: class and object.

A class is a blueprint, a model for its objects.

So again, a class it is just a model, or a way to define attributes and behavior (as we talked about in the theory section). As an example, a vehicle class has its own attributes that define what objects are vehicles. The number of wheels, type of tank, seating capacity, and maximum velocity are all attributes of a vehicle.

With this in mind, let’s look at Python syntax for classes:

class Vehicle:
    pass

We define classes with a class statement — and that’s it. Easy, isn’t it?

Objects are instances of a class. We create an instance by naming the class.

car = Vehicle()
print(car) # <__main__.Vehicle instance at 0x7fb1de6c2638>

Here car is an object (or instance) of the class Vehicle.

Remember that our vehicle class has four attributes: number of wheels, type of tank, seating capacity, and maximum velocity. We set all these attributes when creating a vehicle object. So here, we define our class to receive data when it initiates it:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

We use the init method. We call it a constructor method. So when we create the vehicle object, we can define these attributes. Imagine that we love the Tesla Model S, and we want to create this kind of object. It has four wheels, runs on electric energy, has space for five seats, and the maximum velocity is 250km/hour (155 mph). Let’s create this object:

tesla_model_s = Vehicle(4, 'electric', 5, 250)

Four wheels + electric “tank type” + five seats + 250km/hour maximum speed.

All attributes are set. But how can we access these attributes’ values? We send a message to the object asking about them. We call it a method. It’s the object’s behavior. Let’s implement it:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    def number_of_wheels(self):
        return self.number_of_wheels

    def set_number_of_wheels(self, number):
        self.number_of_wheels = number

This is an implementation of two methods: number_of_wheels and set_number_of_wheels. We call it getter & setter. Because the first gets the attribute value, and the second sets a new value for the attribute.

In Python, we can do that using @property (decorators) to define getters and setters. Let’s see it with code:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity
    
    @property
    def number_of_wheels(self):
        return self.__number_of_wheels
    
    @number_of_wheels.setter
    def number_of_wheels(self, number):
        self.__number_of_wheels = number

And we can use these methods as attributes:

tesla_model_s = Vehicle(4, 'electric', 5, 250)
print(tesla_model_s.number_of_wheels) # 4
tesla_model_s.number_of_wheels = 2 # setting number of wheels to 2
print(tesla_model_s.number_of_wheels) # 2

This is slightly different than defining methods. The methods work as attributes. For example, when we set the new number of wheels, we don’t apply two as a parameter, but set the value 2 to number_of_wheels. This is one way to write pythonic getter and setter code.

But we can also use methods for other things, like the “make_noise” method. Let’s see it:

class Vehicle:
    def __init__(self, number_of_wheels, type_of_tank, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.type_of_tank = type_of_tank
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

    def make_noise(self):
        print('VRUUUUUUUM')

When we call this method, it just returns a string VRRRRUUUUM.

tesla_model_s = Vehicle(4, 'electric', 5, 250)
tesla_model_s.make_noise() # VRUUUUUUUM

Encapsulation: Hiding Information

Encapsulation is a mechanism that restricts direct access to objects’ data and methods. But at the same time, it facilitates operation on that data (objects’ methods).

“Encapsulation can be used to hide data members and members function. Under this definition, encapsulation means that the internal representation of an object is generally hidden from view outside of the object’s definition.” — Wikipedia

All internal representation of an object is hidden from the outside. Only the object can interact with its internal data.

First, we need to understand how public and non-public instance variables and methods work.

Public Instance Variables

For a Python class, we can initialize a public instance variable within our constructor method. Let’s see this:

Within the constructor method:

class Person:
    def __init__(self, first_name):
        self.first_name = first_name

Here we apply the first_name value as an argument to the public instance variable.

tk = Person('TK')
print(tk.first_name) # => TK

Within the class:

class Person:
    first_name = 'TK'

Here, we do not need to apply the first_name as an argument, and all instance objects will have a class attribute initialized with TK.

tk = Person()
print(tk.first_name) # => TK

Cool. We have now learned that we can use public instance variables and class attributes. Another interesting thing about the public part is that we can manage the variable value. What do I mean by that? Our object can manage its variable value: Get and Set variable values.

Keeping the Person class in mind, we want to set another value to its first_name variable:

tk = Person('TK')
tk.first_name = 'Kaio'
print(tk.first_name) # => Kaio

There we go. We just set another value (kaio) to the first_name instance variable and it updated the value. Simple as that. Since it’s a public variable, we can do that.

Non-public Instance Variable

We don’t use the term “private” here, since no attribute is really private in Python (without a generally unnecessary amount of work). — PEP 8

As the public instance variable , we can define the non-public instance variable both within the constructor method or within the class. The syntax difference is: for non-public instance variables , use an underscore (_) before the variable name.

“‘Private’ instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member)” — Python Software Foundation

Here’s an example:

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email

Did you see the email variable? This is how we define a non-public variable :

tk = Person('TK', 'tk@mail.com')
print(tk._email) # tk@mail.com

We can access and update it. Non-public variables are just a convention and should be treated as a non-public part of the API.

So we use a method that allows us to do it inside our class definition. Let’s implement two methods (email and update_email) to understand it:

class Person:
    def __init__(self, first_name, email):
        self.first_name = first_name
        self._email = email

    def update_email(self, new_email):
        self._email = new_email

    def email(self):
        return self._email

Now we can update and access non-public variables using those methods. Let’s see:

tk = Person('TK', 'tk@mail.com')
print(tk.email()) # => tk@mail.com
# tk._email = 'new_tk@mail.com' -- treat as a non-public part of the class API
print(tk.email()) # => tk@mail.com
tk.update_email('new_tk@mail.com')
print(tk.email()) # => new_tk@mail.com
  1. We initiated a new object with first_name TK and email tk@mail.com
  2. Printed the email by accessing the non-public variable with a method
  3. Tried to set a new email out of our class
  4. We need to treat non-public variable as non-public part of the API
  5. Updated the non-public variable with our instance method
  6. Success! We can update it inside our class with the helper method

Public Method

With public methods, we can also use them out of our class:

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def show_age(self):
        return self._age

Let’s test it:

tk = Person('TK', 25)
print(tk.show_age()) # => 25

Great — we can use it without any problem.

Non-public Method

But with non-public methods we aren’t able to do it. Let’s implement the same Person class, but now with a show_age non-public method using an underscore (_).

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def _show_age(self):
        return self._age

And now, we’ll try to call this non-public method with our object:

tk = Person('TK', 25)
print(tk._show_age()) # => 25

We can access and update it. Non-public methods are just a convention and should be treated as a non-public part of the API.

Here’s an example for how we can use it:

class Person:
    def __init__(self, first_name, age):
        self.first_name = first_name
        self._age = age

    def show_age(self):
        return self._get_age()

    def _get_age(self):
        return self._age

tk = Person('TK', 25)
print(tk.show_age()) # => 25

Here we have a _get_age non-public method and a show_age public method. The show_age can be used by our object (out of our class) and the _get_age only used inside our class definition (inside show_age method). But again: as a matter of convention.

Encapsulation Summary

With encapsulation we can ensure that the internal representation of the object is hidden from the outside.

Inheritance: behaviors and characteristics

Certain objects have some things in common: their behavior and characteristics.

For example, I inherited some characteristics and behaviors from my father. I inherited his eyes and hair as characteristics, and his impatience and introversion as behaviors.

In object-oriented programming, classes can inherit common characteristics (data) and behavior (methods) from another class.

Let’s see another example and implement it in Python.

Imagine a car. Number of wheels, seating capacity and maximum velocity are all attributes of a car. We can say that an ElectricCar class inherits these same attributes from the regular Car class.

class Car:
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        self.number_of_wheels = number_of_wheels
        self.seating_capacity = seating_capacity
        self.maximum_velocity = maximum_velocity

Our Car class implemented:

my_car = Car(4, 5, 250)
print(my_car.number_of_wheels)
print(my_car.seating_capacity)
print(my_car.maximum_velocity)

Once initiated, we can use all instance variables created. Nice.

In Python, we apply a parent class to the child class as a parameter. An ElectricCar class can inherit from our Car class.

class ElectricCar(Car):
    def __init__(self, number_of_wheels, seating_capacity, maximum_velocity):
        Car.__init__(self, number_of_wheels, seating_capacity, maximum_velocity)

Simple as that. We don’t need to implement any other method, because this class already has it (inherited from Car class). Let’s prove it:

my_electric_car = ElectricCar(4, 5, 250)
print(my_electric_car.number_of_wheels) # => 4
print(my_electric_car.seating_capacity) # => 5
print(my_electric_car.maximum_velocity) # => 250

Beautiful.

That’s it!

We learned a lot of things about Python basics:

  • How Python variables work
  • How Python conditional statements work
  • How Python looping (while & for) works
  • How to use Lists: Collection | Array
  • Dictionary Key-Value Collection
  • How we can iterate through these data structures
  • Objects and Classes
  • Attributes as objects’ data
  • Methods as objects’ behavior
  • Using Python getters and setters & property decorator
  • Encapsulation: hiding information
  • Inheritance: behaviors and characteristics

Congrats! You completed this dense piece of content about Python.

Original article source at https://www.freecodecamp.org

#python #programming #developer 

Learn Python Programming from Scratch | Python from Zero to Hero
Billy Chandler

Billy Chandler

1653709378

Electron 19.0.0 has been released

Electron 19.0.0 has been released! It includes upgrades to Chromium 102, V8 10.2, and Node.js 16.14.2. Read below for more details!

The Electron team is excited to announce the release of Electron 19.0.0! You can install it with npm via npm install electron@latest or download it from our releases website. Continue reading for details about this release and please share any feedback you have!

Notable Changes

Electron Release Cadence Change

The project is returning to its earlier policy of supporting the latest three major versions. See our versioning document for more detailed information about Electron versioning and support. This had temporarily been four major versions to help users adjust to the new release cadence that began in Electron 15. You can read the full details here.

Stack Changes

Breaking & API Changes

Below are breaking changes introduced in Electron 19. More information about these and future changes can be found on the Planned Breaking Changes page.

Unsupported on Linux: .skipTaskbar

The BrowserWindow constructor option skipTaskbar is no longer supported on Linux. Changed in #33226

Removed WebPreferences.preloadURL

The semi-documented preloadURL property has been removed from WebPreferences. #33228. WebPreferences.preload should be used instead.

End of Support for 15.x.y and 16.x.y

Electron 14.x.y and 15.x.y have both reached end-of-support. This returns Electron to its existing policy of supporting the latest three major versions. Developers and applications are encouraged to upgrade to a newer version of Electron.

E15 (Sep'21)E16 (Nov'21)E17 (Feb'22)E18 (Mar'22)E19 (May'22)
15.x.y16.x.y17.x.y18.x.y19.x.y
14.x.y15.x.y16.x.y17.x.y18.x.y
13.x.y14.x.y15.x.y16.x.y17.x.y
12.x.y13.x.y14.x.y15.x.y--

What's Next

In the short term, you can expect the team to continue to focus on keeping up with the development of the major components that make up Electron, including Chromium, Node, and V8. Although we are careful not to make promises about release dates, our plan is to release new major versions of Electron with new versions of those components approximately every 2 months.

You can find Electron's public timeline here.

More information about future changes can be found on the Planned Breaking Changes page.

Original article source at https://www.electronjs.org

#electron #electronjs #programming #developer 

Electron 19.0.0 has been released