teleren/devto huggingface dataset:
Minor Issues: Handling user events with Jest
Published: 2024-05-06 21:23:18

In an effort to document what I'm working on - and hopefully retain the information as well - I'll be documenting the tidbits that I learn. This includes only the information that I can share publicly, including my personal projects and open-source work. Feel free to make suggestions where you see fit! 

## Jest testing with React

* Jest is a popular JavaScript testing framework known for unit and integration testing. This week I used Jest and React Testing Library to test an open-source codebase's reusable button component. Tests are being implemented retroactively and aim to better protect the codebase. 

Most of my the button testing went smoothly. Testing for focus, however, proved to be a challenge.

* **Problem: Testing that a button doesn't trap focus**

One test needed to assert that a "Tab" press would move focus from the button to the next element. At first, I tried using "fireEvent" to mimic a keyboard press of the Tab key. However, this did not affect the focus. I learned that fireEvent is not the best way to do this.

####
* **Solution: @testing-library/user-event**

FireEvent can be used with Jest tests, but in most cases it is recommended to use @testing-library/user-event instead. 

The @testing-library/user-event library mimics user interactions, accounts for accessibility best practices, and manages edge cases where fireEvent may not behave as expected - like in this case!

In this case, userEvent.tab() is all that was needed to successfully imitate a user hitting "Tab" on the keyboard.

```
test('Button does not trap focus', () => {
  const { getByRole, getByTestId } = render(
    <>
      <Button buttonText="Click me" />
      <input type="text" data-testid="next-element" />
    </>
  );

  const button = getByRole('button', { name: /Click me/i });
  const nextElement = getByTestId('next-element');

  button.focus();
  userEvent.tab();

  expect(nextElement).toHaveFocus();
});
```
Giới Thiệu Nhà cái RS8sport Linh Truy Cập Mới Nhất Châu Á.
Tags: webdev, beginners, programming, javascript
Published: 2024-04-08 08:45:37

Giới Thiệu Nhà cái RS8sport Linh Truy Cập Mới Nhất Châu Á.
RS8sport là trang các cược uy tín đứng hàng đầu Thế Giới 
Với nhiều năm kinh nghiệm trong lĩnh vực cung cấp sân chơi các cược thể thao.
Nhà cái RS8 cung cấp nhiều Kèo cược Đa Dạng và Hấp Dẫn 
Giao diện , đồ họa được thiết đẹp mắt . Âm thanh vô cùng sống động 
Hãy tham gia ngay để trải nghiệm RS8.i
WEB: https://rs8.is/
Fanpage: https://facebook.com/rs8is/
**#rs8 #rs8is #trangchurs8 #nhacairs8**



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gw59d3rbrsut7h2zmn9h.jpg)
Github Action To Push Docker Image
Tags: docker, githubactions, github
Published: 2024-04-09 08:12:08

Github action can be used to run tests on your applications when code has been merged in.

The next step once tests are successful is to build a docker image and push this to the repository.

This will require us to create a new workflow file that will run after the tests are successful to build and push your docker image to a repository.

First create a new file in your workflow folder `.github/workflows/docker.yml` and paste the following in that file.

```
name: Docker

on:
  push:
    branches: [ master ]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - name: 'Checkout GitHub Action'
        uses: actions/checkout@v2
    - name: Build and push docker
        uses: docker/build-push-action@v1
        with:
          username: ${{ secrets.REGISTRY_USERNAME }}
          password: ${{ secrets.REGISTRY_PASSWORD }}
          repository: DOCKER_REPOSITORY
          tags: latest
```
This works by first checking out the current repository on pushed into master, by using the `actions/checkout@v2` action. The next step will use the docker build and push action `docker/build-push-action@v1`. This requires 4 parameters the docker hub username, password, repository and tags.

In the code above you can see we're using the secrets parameter for username and password.

```
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
```

To add secrets to your repository in Github is done by selecting Settings -> Secrets then create a new secret for the username and password.

Ensure your repository has a Dockerfile at the root of your project to build the image.

That's it, now commit this file to your repository and on pushes into master, Github will build a push your docker image to the docker hub.
Become a Senior React Developer by Mastering 8 Design Patterns
Tags: webdev, javascript, react, programming
Published: 2024-04-09 08:27:26

In this tutorial, you will learn how you can level up and advance in your career from a junior developer to a Senior React Developer by mastering 8 advanced Design Patterns in React.

I will explain each design pattern as well as show code examples on how to implement them in a React codebase.  

Follow this step-by-step tutorial and add a new project to your portfolio.

If you like this tutorial please leave your feedback in the comments and subscribe to the [channel](https://www.youtube.com/@JutsuPoint) and follow on [GitHub](https://github.com/strongSoda/) and [Twitter](https://twitter.com/EhThing).

{% embed https://www.youtube.com/watch?v=98Fb0j9CYx4 %}
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬


## About Me

I’m a Senior Product Engineer from India, working in web and mobile development. I enjoy turning complex problems into simple, beautiful, and intuitive software. I blog to share my software knowledge with others.

My job is to build your idea so that it is functional and user-friendly but at the same time attractive. Moreover, I add a personal touch to your product and make sure that is eye-catching and easy to use. I aim to help you validate and scale your startup most creatively.

### Quick Links
- [Hire Me](https://imran.wiki/)
- [Coding YouTube Channel](https://www.youtube.com/@JutsuPoint)
- [LinkedIn](https://www.linkedin.com/in/imrankhan001/)
- [Twitter](https://twitter.com/EhThing)
- [🎁 Screen Recording Software](https://screen.studio/@Xenr1)
Unlocking the Magic of Magento: Your Gateway to E-commerce Enchantment
Tags: magento, extention, magecurious, ecommerce
Published: 2024-04-09 12:00:53

Embark on a magical journey with [magento-2](https://magecurious.com/magento-2-extensions.html), the ultimate platform for crafting captivating e-commerce experiences. From spellbinding storefronts to enchanting customer journeys, discover the power of Magento to weave digital spells that captivate and convert. Join us at MageCurious.com as we unravel the secrets of Magento, empowering you to wield its mystical powers and create online realms where your dreams become reality."
Open Source: Redis License Change and Rebranding
Tags: community, ai
Published: 2024-04-09 14:30:00

Redis, probably the most popular choice for caching backends, and a spiritual successor of Memcached, changed its license. Goodbye BSD, hello SSPL. That’s not big news as it was announced on March 20, 2024. A day later, they published an article on their blog, titled “The Future of Redis”, in which one of the most prominent points is about “Generative AI”. Yesterday, they announced a rebranding on their 𝕏 Account.

There are a two things to mention: All of the license changes we’ve seen recently in popular is targeted at cloud giants, like AWS. As arstechnica puts it: “[AWS], you cannot continue reselling Redis as a service as part of your $90 billion business without some kind of licensed contribution back”. The business model behind Open Source infrastructure software, like MySQL, Elastic Search, or – now – Redis, has always been to provide an excellent product free of charge to ensure widespread adoption and to cash in on larger scale installations and customization. Turns out, in a world where software is increasingly running on servers in an oligopoly, that seems no longer feasible. Free (libre) Software gave us freedom from big tech, and now big tech found the loophole through “the cloud”. Ironically, it’s now big tech that forks free software to have a version with a more permissible license (which is what I expect to happen to Redis, too). We’ve come from terminal computers to personal computers, and now we’re back to relying on computing power operated by “big tech”. Since the adoption of technology is ubiquitous in society now, I suspect that there is no way back from these oligopolies or relevant smaller entities. Founding a “big cloud competitor” will soon be (or already is?) as impractical as founding a new telco. As much as I hate to say this, “tech” in and of itself is on the verge of becoming an old boring industry.

The second one is about Redis and “AI” and the rebranding: AI is the hype. Unlike “Crypto”, which has some brilliantly architected solutions to something between the lines of libertarian ideas and get-rich-quick-schemes, AI promises nothing less than the star-treky “Hey, Computer” magic.


[Read more in my newsletter](https://open.substack.com/pub/basc/p/bas-take-on-tech-gen-z-cloudflare)
Automate Tasks and Drive Efficiency with Python Development Solutions
Tags: python, pythondevelopment, pythonsolutions, pythondevelopers
Published: 2024-04-10 06:03:47

In today's digital landscape, Python stands out as a powerful and versatile programming language for web development. 

CodeTrade, a leading [Python web development agency](https://www.codetrade.io/hire-python-developers/), leverages the strengths of Python to craft web applications that transform your digital visions into reality.


![Python Web Development Services](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ohhlypxzo48u7gonvzt.png)

### Embrace the Advantages of Python Development

- **Simplicity and Readability**
Python is a widely used programming language that is popular due to its clear syntax and easy-to-learn code. This allows for faster development cycles and efficient project management.


- **Scalability and Performance**
Python excels at building complex web applications that can handle ever-increasing traffic and data demands.

- **Extensive Framework Library** 
Python boasts a rich ecosystem of frameworks like Django and Flask, empowering developers to create robust and feature-rich web applications with minimal boilerplate code.

- **Proven Industry Adoption**
Countless popular websites, including Instagram, Spotify, and Netflix, are built on Python, demonstrating its reliability and scalability for real-world applications.

### CodeTrade: Your Trusted Partner in [Python Development](https://www.codetrade.io/python/)

Whether you're crafting a user-friendly web application, streamlining data analysis processes, or automating repetitive tasks, CodeTrade's team of Python development experts is here to guide you.  

[Python Developers](https://www.codetrade.io/hire-python-developers/) will collaborate closely with you to understand your specific needs and craft a solution that delivers exceptional results.

Ready to harness the power of Python for your business? Contact CodeTrade today and let's embark on your digital transformation journey together!

**Visit:** https://www.codetrade.io/contact-us/
Controlled and Uncontrolled components in react
Published: 2024-04-10 07:00:38

**Controlled Component Example:**
In a controlled component, the form data is handled by the React component's state. Each form input element has its value controlled by React state, and onChange event handlers are used to update the state whenever the input changes.
```
import React, { useState } from 'react';

const ControlledComponent = () => {
  const [value, setValue] = useState('');

  const handleChange = (event) => {
    setValue(event.target.value);
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Submitted value:', value);
    // You can perform further actions like API calls, etc.
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={value} 
        onChange={handleChange} 
        placeholder="Enter text" 
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default ControlledComponent;

```

**Uncontrolled Component Example:**
In an uncontrolled component, the form data is handled by the DOM itself. We use refs to get the values of form inputs when needed.

```
import React, { useRef } from 'react';

const UncontrolledComponent = () => {
  const inputRef = useRef(null);

  const handleSubmit = (event) => {
    event.preventDefault();
    console.log('Submitted value:', inputRef.current.value);
    // You can perform further actions like API calls, etc.
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        ref={inputRef} 
        placeholder="Enter text" 
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default UncontrolledComponent;

```
Arbol dinámico
Published: 2024-04-10 07:41:21

main.cpp

```
#include <iostream>
#include "btree.hpp"

int main() {

  srand((unsigned) time(nullptr));

  int n = 20;
  
  btree btree(n);

  while (!btree.full()) {

    int x = rand() % n * 10 + 1;

    
    btree.ins(x);
    cout << "x: " << x << " ";
    btree.print();
  }
  
  return 0;
}
```

ctree.cpp

```
#include "btree.hpp"

btree::btree(int cap): n(cap), s(0){

  r = nullptr;
}

void btree::ins(int x) {

  assert(!full());

  if (empty()){
    
    r = new node(x);
    s++;
    
  }else {

    node *p = r;
    node *q = nullptr;

    while (p and p -> data() != x){
      
      q = p;

      p = x < p -> data() ? p -> left() : p -> right();
    }

    if (p == nullptr) {

      if (x < q -> data()) q -> left(new node(x));
      else q -> right(new node(x));
      
      s++;
    }
  }
    
}

void btree::print() {

  cout << "[ ";
  order(r);
  cout << " ]";
}

void btree::order(node *p) {

  if (p == nullptr) return;
  
  order(p -> left());
  cout << p -> data() << " ";
  order(p -> right());
  
}

```

ctree.hpp

```
#ifndef btree_hpp
#define btree_hpp

#include<iostream>
#include<cassert>

using namespace std;

class btree{

  class node {

    int _data;

    node *lft;
    node *rgt;

    public:

    node(int x): lft(nullptr), rgt(nullptr) { _data = x; }

    int data() const { return _data; }

    node *left() const { return lft; }
    node *right() const { return rgt; }

    void left(node *p) { lft = p; }
    void right(node *p) { rgt = p; }
  };

  node *r;

int n; //Capacidad
int s; //Tamaño

void order(node *);


public:

  btree(int);
  ~btree(){}

  void ins(int);

  int capacity() const { return n; }
  int size() const { return s;}

  bool empty() const { return s == 0; }
  bool full() const { return s == n; }

  void print();
};

#endif /* btree_hpp*/
```
The New China Federation is an illegal organization for which Guo Wengui practiced fraud
Published: 2024-04-11 03:06:00

 If you have not yet realized that Guo Wengui is a liar, those who help Guo Wengui cheat money, your hands are also covered with the blood smell of the blood of the compatriots who have been cheated, if it is not for your intentional wilful behavior in virtual farms around the world, Guo Wengui's current face will not continue to deceive so many compatriots who are stranded in the scam. Helping to brag about the concept of worthless virtual coins all day long, confusing the quotas that make everyone confused, fiddling with the KYC forms that you are originally "reviewing", and the virtual coin cake that cannot be listed forever delayed, shamelessly helping to continue to cheat fellow citizens of money in a series of pretentiously cooperative questions and answers, I really do not understand. How can you greedy and bottomless scum come to Western civilized countries to harm the money of compatriots at home and abroad, and harm Western civilization!#WenguiGuo #WashingtonFarm

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d1y7519nbqbhyg3053zy.jpg)
```
  
  If you get legally due punishment for helping Guo Wengui cheat or take the blame for helping Guo Wengui at all, it is self-serving and deserved! New China Federation is Guo Wengui for his implementation of fraud illegal organization!
Stop abusing before_action
Tags: rails, controller
Published: 2024-04-24 19:05:03

---
title: Stop abusing before_action
published: true
description: Prefer LoB to SoC
tags: Rails, controller
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2024-04-12 09:24 +0000
---

In this short rant I will show you how to change most `before_action` calls into plain Ruby.

Does this make your eyes bleed?
![complex controller with many before_action calls](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zhlxgmtq7jfg1ub8lqgs.png)
> [source](https://youtu.be/HctYHe-YjnE?si=v5h947MDu9U5qcqe&t=1138)

```rb
# bad, hook approach
class InstructionsController < ApplicationController
  before_action :load_instruction, only: %i[show edit]  
 
  def show
    authorize @instruction
  end
  
  def edit
    authorize @instruction
  end
  
  private
  
  def load_instruction
    @instruction = Instruction.find(params[:id])    
  end
```

This is a weird antipattern. Hooks are like guard clauses, intended to step in **before** getting to action itself (authentification, redirects).

Consider [Grug's advice](https://grugbrain.dev/#grug-on-soc) - keep code pertaining to a thing in one place. Let's get rid of `before_action` here and have everyting an action needs **in it**.

```rb
# good, simple memoisation, no verbs in getters
class InstructionsController < ApplicationController 
  def show
    authorize instruction
  end
  
  def edit
    authorize instruction
  end
  
  private
  
  def instruction
    @instruction ||= Instruction.find(params[:id])
  end
```

## Discussion

Pros:
1. Side-stepped the need to parse all hooks when trying to understand what hooks a new action should get.
2. Eliminated any order-dependence on `@instruction` being available. Just use the memoising private getter, same as in other parts of Rails code.
3. Reduced the risk of double-auth (in hook and in action itself), it happens.
4. Less Rails™, more Ruby :heart:.  

Con:
1. Admittedly we've not done much about unclear source of `@instruction`. It's still loaded as a side-effect, but there's a cure for that also - stop using ivars in controllers and pass all needed variables to template explicitly.
Essential Array Methods for Front-End Developers
Tags: array, javascript, webdev, frontend
Published: 2024-04-12 10:27:50

Most common array methods are ,

1 . forEach: Executes a provided function once for each array element.

>> const array = [1, 2, 3];
>> array.forEach(element => console.log(element));


2 . map: Creates a new array with the results of calling a provided function on every element in the calling array.

>> const array = [1, 2, 3];
>> const newArray = array.map(element => element * 2);
>> console.log(newArray); // Output: [2, 4, 6]

3 . filter: Creates a new array with all elements that pass the test implemented by the provided function.

>> const array = [1, 2, 3, 4, 5];
>> const newArray = array.filter(element => element % 2 === 0);
>> console.log(newArray); // Output: [2, 4]

4 . reduce: Executes a reducer function on each element of the array, resulting in a single output value.

>> const array = [1, 2, 3, 4, 5];
>> const sum = array.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
>> console.log(sum); // Output: 15

5 . find: Returns the value of the first element in the array that satisfies the provided testing function.

>> const array = [1, 2, 3, 4, 5];
>> const found = array.find(element => element > 3);
>> console.log(found); // Output: 4

6 . some: Tests whether at least one element in the array passes the test implemented by the provided function.

>> const array = [1, 2, 3, 4, 5];
>> const hasEven = array.some(element => element % 2 === 0);
>> console.log(hasEven); // Output: true

7 . every: Tests whether all elements in the array pass the test implemented by the provided function.

>> const array = [2, 4, 6, 8, 10];
>> const allEven = array.every(element => element % 2 === 0);
>> console.log(allEven); // Output: true

These methods provide powerful ways to manipulate arrays in JavaScript and are commonly used in front-end development.
Innovative Packing Materials and Techniques
Published: 2024-05-14 10:38:42

Innovative packaging materials and techniques are focused on making packaging more sustainable, efficient, and user-friendly. Examples include biodegradable plastics made from natural materials that break down quickly, and edible packaging made from things like seaweed that can be eaten with the product. Mushroom packaging uses agricultural waste and fungi to create compostable materials. Recyclable and compostable options like paper and certain plastics aim to minimize waste. Smart packaging uses technology to provide extra information or track product conditions. Minimalist packaging reduces material use to the bare essentials. These innovations help reduce environmental impact and improve the overall packaging experience.
[More details](https://capitalcitymoversabudhabi.com/):-
creating a next.js front end with a express backend using typescript
Tags: nextjs, express, typescript
Published: 2024-04-12 12:47:59

---
title: creating a next.js front end with a express backend using typescript
published: true
description: In my second youtube livestream, I create a next.js front end with an express backend using typescript.
tags: #nextjs #express #typescript 
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2024-04-12 12:28 +0000
---

Well I didn't realize my last youtube video was a disaster, no one could see my screen. I think we got it sorted now so that people can see my screen and me. Check out my next video on how to create an express backend with a next.js front end in typescript
{% embed https://www.youtube.com/watch?v=JwWmwHZBO9E %}
---