teleren/devto huggingface dataset:
How to persist data between requests for form validation in Magento 2
Published: 2023-01-02 11:16:59

The DataPersistorInterface is used to persist data temporarily for later use, such as during a redirect. 

It is often used in controllers to store form data in the session so that it can be used to pre-populate a form if there is an error in form submission.

```php
public function execute()
{
    $post = $this->getRequest()->getPostValue();
    $resultRedirect = $this->resultRedirectFactory->create();
    if ($post) {
        $model = $this->contactFactory->create($post);
        try {
            $this->contactRepository->save($model);
            $this->messageManager->addSuccessMessage(__('Your inquiry was submitted and will be responded to as soon as possible. Thank you for contacting us.'));
            $this->dataPersistor->clear('contact_us');
            return $resultRedirect->setPath('contact/index');
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
        } catch (\Exception $e) {
            $this->messageManager->addExceptionMessage($e, __('An error occurred while processing your form. Please try again later.'));
        }

        $this->dataPersistor->set('contact_us', $post);
        return $resultRedirect->setPath('contact/index');
    }
    return $resultRedirect->setPath('contact/index');
}
```

To use it simple include the `Magento\Framework\App\Request\DataPersistorInterface` in your `__construct()`

```php
use Magento\Framework\App\Request\DataPersistorInterface;

class YourClass {

  protected DataPersistorInterface $dataPersistor;

  public function __construct(
     DataPersistorInterface $dataPersistor
  ) {
      $this->dataPersistor = $dataPersistor;
  }
}
```
[Hands-on] How to create a bucket in S3
Tags: aws, s3, webdev, frontend
Published: 2023-01-02 11:14:25

## What is S3?
1 . S3 is a Simple Storage Service

2 . S3 is used to store the object (key/value) data

3 . S3 is a global service

4 . In S3, we create buckets. Buckets are like folders. They are regional

5 . Buckets contain the files.

6 . Buckets are key, and content is valuable in it

7 . One of the uses of the S3 is to hold static content such as images, HTML pages, CSS, and JavaScript.

8 . You can save from 0 to 5TB of data

9 . By default buckets are private and cannot be accessed outside.

10 . To make buckets public one needs to allow it by setting the policy.

[Video](https://cloudtips.dev/2023/01/01/13-project-host-a-static-website-on-s3/)

Happy Learning
Adicionando Boostrap 5 em um projeto Phoenix
Tags: tutorial, bootstrap, phoenix, elixir
Published: 2023-01-02 10:58:13

Olá, pessoas!

Normalmente quando se fala de aplicação phoenix, se fala também de tailwindcss, mas nem todo mundo tem familiaridade com o tailwindcss. Por outro lado, existem muitas aplicações web que usam o bootstrap. Então a ideia desse tutorial é demostrar como aplicar o bootstrap nas suas aplicações phoenix de maneira rápida.

Para utilizarmos o boostrap, faremos a utilização da lib [dart_sass](https://hexdocs.pm/dart_sass/DartSass.html) que é um instalador e "executor" para [sass](https://sass-lang.com/dart-sass).

Então vamos lá... No seu arquivo `mix.exs` na função privada `deps`, adicione a seguinte linha:
```elixir
{:dart_sass, "~> 0.5.1"}
```
No arquivo `config/config.exs` adicione o código para adicionar as configurações do dart_sass: 
```elixir
config :dart_sass,
  version: "1.43.1",
  default: [
    args: ~w(css/app.scss ../priv/static/assets/app.css),
    cd: Path.expand("../assets", __DIR__)
  ]
```
Na parte de watchers no arquivo `config/dev.exs` iremos adicionar o seguinte código para que nossa aplicação phoenix possa assistir os arquivos sass:
```elixir
sass: {
      DartSass,
      :install_and_run,
      [:default, ~w(--embed-source-map --source-map-urls=absolute --watch)]
    }
```
Também no arquivo `mix.exs` iremos alterar os aliases. Na parte chamada `assets.deploy` iremos adicionar o código `"sass default --no-source-map --style=compressed"` onde ficará semelhante ao código abaixo:
```elixir
"assets.deploy": ["esbuild default --minify", "sass default --no-source-map --style=compressed", "phx.digest"]
```
Para finalizar, faremos mais três alterações na pasta `assets`. A primeira é rodar o comando `npm install boostrap --prefix assets` pelo terminal na pasta do seu projeto e após isso, renomear o arquivo `assets/css/app.css` para `assets/css/app.scss` e apagar todo o conteúdo do arquivo e adicionar o código 
```css
@import "../node_modules/bootstrap/scss/bootstrap";
```
Por fim, iremos remover o código `import "../css/app.css"` do arquivo `assets/js/app.js` e adicionar o 
```js
import "bootstrap"
```
Agora você pode subir a aplicação e ver que toda a sua tela inicial foi alterada.
Python Dictionaries - Access, delete element…
Tags: webdev, python, programming, learning
Published: 2023-01-02 10:50:11

In the [last](https://dev.to/nitinreddy3/learn-python-9-yeah-dictionary-4lac) article we had seen how we can create a dictionary and access an element in it. Today we are going to deep dive into the main data structure in Python known as Dictionary.

## Accessing an element 💡

The element in the dictionary can be accessed through the square brackets nomenclature.
```
dict = {"name": "Nitin", "age": 34, "gender": "male"}

dict["name"]
Result -> Nitin
```

What if you are trying to access an element that is not in the dictionary?

```
dict = {"name": "Nitin", "age": 34, "gender": "male"}

dict["address"]
Result -> Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'address'
```
In the above example, the address is not in the dictionary because we are trying to access it from the square brackets.

But we can also leverage the `get` method to access the dictionary key
```
dict = {"name": "Nitin", "age": 34, "gender": "male"}
dict.get("name")
Result -> 'Nitin'
```



### Delete an element with `del` method 💡

```
dict = {"name": "Nitin", "age": 34, "gender": "male"}
del(dict["name"])
print(dict)
Result -> {"age": 34, "gender": "male"}
```

### Delete the dictionary 💡
```
dict = {"name": "Nitin", "age": 34, "gender": "male"}
del(dict)
print(dict)
Result -> <class 'dict'>
```
In order to delete the dictionary you just have to mention the dictionary variable name in the `del` method.

### Find the length 💡
Finding the length of the dictionary is quite simple.
```
dict = {"name": "Nitin", "age": 34, "gender": "male"}
len(dict)
Result -> 3
```

### Check if the key exists 💡

Not so difficult.
```
dict = {"name": "Nitin", "age": 34, "gender": "male"}
print("name" in dict)
Result -> True
```
The boolean would be returned when you try to check the key in the dictionary.



### Easy to understand? 💡

A dictionary contains

- unique keys
- key can have different types of values like `number`, `string`, `boolean` etc.
- we can access dictionary elements with multiple approaches

>This would look similar to an object in JavaScript


## Conclusion 📗

There are more posts on the way related to the tuples...So keep reading.

Thanks in advance for reading this article...🚀

*I am more than happy to connect with you on*

- [@twitter](https://twitter.com/_nitinreddy3)
- [@LinkedIn](https://www.linkedin.com/in/nitinreddy3/)

*You can also find me on*

- [@Github](https://github.com/nitinreddy3)
- [@DEV](https://dev.to/nitinreddy3)
- [@Medium](https://medium.com/@nitinreddy3)
Why Choose Full Stack Development For Your Business?
Tags: fullstack, businessapp, beginners, webdev
Published: 2023-01-02 10:47:40

Startups benefit from full-stack development because it makes it easier to create and maintain web and mobile applications quickly. These businesses employ full-stack developers to assist in the creation of brand-new applications. This type of development includes not only the front-end and back-end development of an application but also the integration of third-party components like payment gateways and analytics tools as well as the connection of databases and APIs with external services.

## Full stack Development is the new big thing!

Full-stack developers are in constant demand as new technologies enter the market, and this trend is expected to continue. Satisfy your curiosity about the [advantages of full-stack development](https://go.softwebsolutions.com/resources/complete-guide-full-stack-development.html) if you are intrigued by the prospects.

It is reasonable to say that full stack developers are extremely versatile because of their broad range of abilities to work with various technologies and build the best one. This is because full stack development eliminates some major underlying problems with web development, such as inefficiency, poor communication, technical issues, delivery backlogs, and many more.

When considering the big picture, full stack development is a uniquely suited method for tackling problems entirely rather than in pieces. Although the rise of full stack developers took some time, they are now essential for giving organizations the agility and skill sets they need.

﻿This approach allows developers to use their preferred tools and skillsets while still being able to leverage the benefits of other technologies. Full stack development can be applied across any industry, but is commonly seen in startups where the goal is to build something from scratch. This method of development helps startups get their product out of the door as soon as possible. They can work across many different platforms and languages.
OAuth 2.0 - Role-based Access Control
Published: 2023-01-02 10:33:17

Another way to control access is Role based, which enables "grouping" the privilege that makes management easier. 

For example, the real life scenario is like:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7hk6othlhm5qy2z5p0s0.png)

Again, 3-party play:

**Define user and roles in Auth Server**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6lw2t4srkg2grzsjna3k.png)

**Resource Server: Securing endpoints to a specific role**

```
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
		jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(new KeycloakRoleConverter());
	 
		http
			.authorizeRequests()
					.antMatchers(HttpMethod.GET, "/users/status/check")
					.hasRole("developer")
					
				.anyRequest().authenticated()
				.and()
			.oauth2ResourceServer()
			.jwt()
			.jwtAuthenticationConverter(jwtAuthenticationConverter);
	}
	
}
```

**Resource Server: Mapping the JWT role, into Autority class reckognised by Spring.**

In the code, we will need to convert the role into spring-authorities
Here is a trick on how to inspect the role from the token (https://jwt.io/)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3o86ht0blmfuyzi2624p.png)

```
public class KeycloakRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>> {

	@Override
	public Collection<GrantedAuthority> convert(Jwt jwt) {
        Map<String, Object> realmAccess = (Map<String, Object>) jwt.getClaims().get("realm_access");

        if (realmAccess == null || realmAccess.isEmpty()) {
            return new ArrayList<>();
        }

        Collection<GrantedAuthority> returnValue = ((List<String>) realmAccess.get("roles"))
                .stream().map(roleName -> "ROLE_" + roleName)  
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
 
        return returnValue;
	}

}
```

Spring framework has 2 methods to check:
1. `hasAuthority("ROLE_developer");` //you have to add the prefix ROLE_ by yourself.
2. `hasRole("developer");` // it is working the same as above, but without needing to add prefix ROLE_
C Vs C++
Tags: c, cpp, programming, beginners
Published: 2023-01-02 10:29:16

**C and C++** are both programming languages, but they were designed for different purposes and have some key differences. 
**Here are a few of the main differences between C and C++:**

**1)**C++ is an object-oriented programming (OOP) language, while C is a procedural language. This means that C++ provides support for classes, objects, and other OOP concepts, while C does not.

**2)**C++ includes features for exception handling, such as try-catch blocks, which are not present in C.

**3)**C++ allows function overloading, which means that multiple functions can have the same name as long as they have different argument lists. C does not support function overloading.

**4)**C++ has a **constexpr** keyword that allows you to define variables that are evaluated at compile-time, rather than at runtime. C does not have this feature.

**5)**C++ supports function templates, which allow developers to write generic functions that can work with a variety of data types. C does not have this feature.

**6)** C++ supports reference variables, which are an alternative to pointers that allow developers to more easily manipulate memory addresses. C does not have reference variables.

**7)** C++ has a more powerful type system than C, with features such as class inheritance and virtual functions.
C++ includes support for the standard template library (STL), a collection of pre-built data structures and algorithms that can be used in C++ programs. C does not have this feature.

**8)** C++ supports namespaces, which allow developers to group related code and avoid naming conflicts. C does not have this feature.

**9)** C++ has improved support for object-oriented programming, with features such as polymorphism and inheritance. C does not have these features.

**10)** C++ includes a number of additional operators and syntax elements that are not present in C, such as the "::"(scope resolution) operator for accessing a global variable when there is a local variable with same name.

**11)**C++ introduces the **new** and **delete** operators for allocating and deallocating memory dynamically. C does not have these operators and relies on manual memory management using functions such as **malloc()** and **free()**.


Despite these differences, C++ is based on C and many C programs can be easily adapted to C++ by adding object-oriented features. However, the reverse is not true: C++ code may not be compatible with C compilers and may require significant modification to work in a C environment.
Let's talk about generative AI!
Tags: programming, productivity, ai, machinelearning
Published: 2023-01-02 10:17:45


#AI will fundamentally change how businesses operate, innovate, and scale in the near future. 

We invite you to join us on Wednesday, together with Professor Eran Yahav, to discuss generative AI and its implications for software development👇
https://twitter.com/i/spaces/1yoKMZLRDveGQ?s=20


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oteqp7y2j1y4faxrne3o.png)
Creating a GitHub portfolio clone with ReactJs by implementing an API fetch
Published: 2023-01-02 10:11:16


React.js is a JavaScript library for building user interfaces that allows developers to create reusable UI components and efficiently update the view in response to data changes. It is often used for building single-page applications and mobile applications. 

In this article, you will understand the step by step approach to build a project with reactjs and use necessary tools such as useEffect to carry out some functionality eg fetching of data from API.

**Prerequisites**
Before proceeding with the various types of concepts given in this article, we assume that the readers have the basic knowledge in HTML, CSS. In addition to this, it will be very helpful, if the readers have a sound knowledge in JavaScript.


1. **Set up your React project:** You will need to create a new React project using a tool such as _create-react-app_.Open your Terminal and run _npx create-react-app <app-name>_  and after installation run cd <app-name> to enter into the app folder.
2. **Set up a list of repositories page:** On this page, you will need to make a request to the GitHub API to retrieve a list of your repositories. You can use the useEffect hook  to make a request to the GitHub API. You will also need to implement pagination for the repo list by dividing the list of repositories into pages and allowing the user to navigate between them.![three useEffect hook scenario](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0zps04z2sq15zdyxomg.jpeg)
3. **Set up a single repository page:** You will need to create a new page that displays data for a single repository that the user clicks on from the list of repositories. You can use nested routes to achieve this. To display data for a specific repository, you will need to make a request to the GitHub API using the repository's ID or name.
4. **Implement proper SEO:** To ensure that your pages are properly optimized for search engines, you will need to include relevant metadata such as titles and descriptions and use proper headings and formatting.
5. **Implement a 404 page:** A 404 page is a page that is displayed when a user navigates to a URL that does not exist. You will need to create a 404 page and configure your application to display it when a user navigates to a non-existent URL.
6. **Ensure good UI and design:** Good UI and design is important for creating a pleasant user experience. You will need to use appropriate layout, typography, and visual design elements to make your application visually appealing and easy to use.
What are your 2023 tech goals and do you want accountability?
Tags: discuss, codenewbie, ai, webdev
Published: 2023-01-02 10:11:00

---
title: What are your 2023 tech goals and do you want accountability? 
published: true
description: 
tags: discuss, CodeNewbie, ai, webdev 
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dhbcpr384yfrtg2halz.png
# Use a ratio of 100:42 for best results.
published_at: 2023-01-02 10:11 +0000
---

We love a good New Year’s goal, and we’re setting some of our own, including starting a [learning cohort for freeCodeCamp’s Machine Learning with Python](https://docs.google.com/forms/d/1Ut4PKAv5cdYbaf6wPWlb3wx_1l9sV8-C7TlTHxcxjOk) in January. What goals are you setting? Do you want accountability?
Find the Linux man page you need with ManRepository
Tags: linux, command, ubuntu, beginners
Published: 2023-01-02 10:03:02

If you're a Linux user, you know the value of the man pages – detailed documentation on the commands, functions, and libraries available on your system. But finding the information you need can sometimes be a challenge.

![ManRepository website show nano command man page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mvbjiigj6v5dtajszlau.png)

ManRepository.com is a website that provides easy access to the Linux man pages. With its user-friendly interface, you can easily search and browse the documentation to find the information you need. The site is also mobile-friendly, so you can access the man pages from your smartphone or tablet while on the go.

In addition to the man pages themselves, [https://manrepository.com/](https://manrepository.com/) offers helpful resources such as a glossary of common Linux terms and a list of popular commands. These additional resources can be especially useful for new Linux users, helping them get up to speed more quickly.


![Linux image cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k7vh70rfw1axvhsod0pm.jpeg)

Whether you're a beginner or an experienced Linux user, ManRepository is a valuable resource that you'll want to bookmark and refer to regularly. So if you're looking for comprehensive documentation on the commands, functions, and libraries available on your Linux system, be sure to check out [https://manrepository.com/](https://manrepository.com/) today.
Get movie information
Tags: webdev, javascript, beginners, tutorial
Published: 2023-01-02 09:59:54

Yesterday I talked about my plan to better my knowledge of the JavaScript language. Today I continue this mission with a new challenge.



```js
/*
- create a movie object that takes in five arguments
- arguments: title, director, genre, release year and rating
- make a function that logs an overview of the movie:
'Movie', a 'genre' film released in 'year', was directed by 'director' and recieved a score 'score'.
*/
```
<br/>
This challenge looks similar to the book keeping challenge. I also solved it similarely, so if you want to have another example of a similar challenge you can find it [here.](https://dev.to/zuzexx/1-js-challenge-book-keeping-3kp3)

## Create a movie class
First I created a movie object. This can be done using functions or classes. Since I work mostly with functions I decided to focus on working with classes for this challenge.
<br/>
```js
class Movie {
  constructor(title, director, genre, releaseYear, rating) {
    this.title = title;
    this.director = director;
    this.genre = genre;
    this.releaseYear = releaseYear;
    this.rating = rating;
  }
}
```
<br/>
I also created a few movie objects, so that I can test the function.
<br/>
```js
const firstMovie = new Movie(
  "The best movie ever written",
  "mr. Moviemaker",
  "Comedy",
  "1984",
  "1.5/10"
);
const secondMovie = new Movie(
  "I, the movie",
  "mrs. MovieLover666",
  "Horror",
  "2020",
  "7.5/10"
);
const thirdMovie = new Movie(
  "The mountain movie",
  "MovieChild",
  "Thriller",
  "2012",
  "8.0/10"
);
```
<br/>

## Create an overview function

All I need this function to do is, return a string containing all of the elements of the movie. This string can be then console loged at the end of the app.
<br/>
```js
Movie.prototype.movieOverview = function () {
  return `${this.title}, a ${this.genre} film released in ${this.releaseYear}, was directed by ${this.director} and recieved a score ${this.rating}.`;
};
```
<br/>
I tried out the `movieOverview()` function by using it on the three movies I defined at the beginning. Based on the results I got in the console it looks like the function works as intended.
<br/>
```js
console.log(firstMovie.movieOverview());
console.log(secondMovie.movieOverview());
console.log(thirdMovie.movieOverview());

/* Result:
The best movie ever written, a Comedy film released in 1984, was directed by mr. Moviemaker and recieved a score 1.5 / 10.
I, the movie, a Horror film released in 2020, was directed by mrs. MovieLover666 and recieved a score 7.5 / 10.
The mountain movie, a Thriller film released in 2012, was directed by MovieChild and recieved a score 8.0 / 10.
*/

```
<br/>

### Conclusion

This concludes my second challenge. It is quite similar to the previous one, that had to do with book keeping. I think it is good to rehearse what you already know. I also must say that writing it all up in a post like this helps me a lot with understanding and remembering what I am/was doing. I will continuoue to write about the challenges and other things as much as possible.