teleren/devto huggingface dataset:
Fixing "Trying to import a file after Jest has been torn down"
Tags: testing, react, reactnative
Published: 2023-11-29 18:18:22

This is the story of how I solved `ReferenceError: You are trying to import a file after the Jest environment has been torn down.`

[Previously](https://dev.to/bytehala/pushing-anti-patterns-to-production-for-fun-and-profit-2nei), I wrote about how I pushed an anti-pattern to our main branch. I got a comment that it was just a quick fix and didn't solve the actual bug. Fair enough!

Before we get to the solution, I want to provide some context. We had a `react-native-modal` that had the following behavior:
`onClick -> showLoadingIndicator -> doSomething -> send analytics -> hideLoadingIndicator -> close modal`

The previous test looked like:
```typescript
fireEvent.press(modalButton);
await waitForElementToBeRemoved(() => loadingIndicator);
expect(analytics).toHaveBeenCalled();
```

The tests were passing, but was throwing an error:
```
ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

  at Object.get InteractionManager [as InteractionManager] (node_modules/react-native/index.js:158:12)
  at node_modules/react-native-modal/dist/modal.js:332:26
  at tryCallOne (node_modules/promise/lib/core.js:37:12)
  at node_modules/promise/lib/core.js:123:15
  at flush (node_modules/asap/raw.js:50:29)
```

Going to `react-native/index.js` line 158 told me I was importing Modal:

```typescript
  get Modal(): Modal {
    return require('./Libraries/Modal/Modal');
  },
```

Following the stacktrace up, and going to `modal.js` line 332 yielded:

```typescript
this.close();
```

Going to raw.js and looking at the `flush` code, it's documented as "The flush function processes all tasks that have been scheduled".

When we put that all together, what was effectively happening was my test was over and successful, Jest was torn down, but the call to `close()` had been queued previously and getting ran by `flush`. Since `close()` was a Modal reference, the error told me I was importing Modal after Jest has been torn down. It all makes sense, but to be honest it was a puzzle that needed to be pieced together.

The non-antipattern solution:

```typescript
fireEvent.press(modalButton);

await waitFor(() => 
  expect(modal.props).toHaveProperty("visible", false)
);

expect(analytics).toHaveBeenCalled();
```

So what did we learn here? Two things. First: If you have the time, dig deeper into the stack trace to really understand a crappy error message. Second: Be wrong on the internet. Be hacky. Someone will call you out, and you might learn a thing or two.
The Plan 0.4
Published: 2023-11-29 17:54:51

Release 0.4 is taking on the biggest problem, the biggest task, and the largest project we can for now. It's crazy to think that we are in the final legs of our term.

We have three things.

1. What I'll do
2. How I'll do it
3. The goals. 

## Let's start with the What
What I need to do is find a bug that I want to work with. I have no clue where to find it. so I placed in a few labels on github
```
archived:false is:open language:Python label:bug
```
pretty simple but straight forward I am always looking for python projects to work on, I had a few chances to take a look on some of the repositories I worked but it was not enough, well for me though. I sent a few comments on a few issues what I wanted to work on but there is really one issue I want to work on. Which was [funccol collectives rewrite in dynamo does not work w/ kwargs #114179](https://github.com/pytorch/pytorch/issues/114179#issuecomment-1826813865) which is an issue from pytorch. 

Just a quick rundown on the bug we need to fix a bug. So this code is working it's fine

```
dist.all_gather_into_tensor(
                output_tensor=flat_tensor, input_tensor=input_flat_tensor_shard, group=group
            )
```
BUT

When we start rewritting it with dynamoDB an start using kwargs or keyword arguments it's not working.

```
dist.all_gather_into_tensor(
                flat_tensor, input_flat_tensor_shard, group=group
            )
```
 

## Now the How
Let's discuss the how, I need to learn how dynamo rewriting works.they mentioned dynamically rewriting it with dynamo, which in all honestly I have no clue how dynamically re writing works so ill start there. I have nothing much to say here yet, just because the how is something I need to work on first.

they asked me to check out 
```
def _traceable_collective_remaps():
    # We can't rely on importing from distributed, since it's not always built
    if torch.distributed.is_available():
        from torch.distributed._functional_collectives import (
            traceable_collective_remaps,
        )

        return traceable_collective_remaps
    return {}
```

So that's what im doing here first.

## The goal
Well the goal is find a way to fix it and hopyfully merge it. It's not as easy as it sounds to be honest. I have to back track a bit and work my way up. I'm guessing I'm starting at -200 right now and not even at 0 just because I need to learn dynamo and being able to dynamically re write with it.

The goal hopefully I can submit a PR by next week but we will see.
For now let's get going and learn dynamo!

Hopefully I can give good update by next week.

okay See you!
Exploring Java Basics and Object-Oriented Programming
Published: 2023-11-29 17:10:22

Java is a widely used programming language known for its versatility and adaptability in building various software applications. In this blog post, we'll take a closer look at the basics of Java, including the Java Virtual Machine (JVM), types in Java, the differences between primitive and non-primitive types, and the fundamental principles of Object-Oriented Programming (OOP) along with its four main concepts.

Java Basics: JVM and Compilation Simplified
Java programs run on the Java Virtual Machine (JVM), acting like a middleman between the code and the computer. This allows Java code to run on different devices without modification. During development, Java code is converted into bytecode, a universal language for the JVM to understand and execute.

Understanding these basics helps make Java code more portable and efficient.

Java Types:
In Java, you must tell the computer what information your variables will hold before using them. There are two types: primitive (like numbers and true/false values) and non-primitive (like groups of information called objects). This typing system helps organize and manage data in your program.

Primitive vs. Non-Primitive Types: What's the Difference?
Primitive types hold basic values directly, while non-primitive types store references to more complex data structures. Understanding this difference is important for how your program uses memory and performs tasks.

Object-Oriented Programming (OOP) in Java
Java is what's called an "object-oriented" language. That means it's all about organizing code into "objects" that contain both data and instructions. These objects help make your code more organized and easier to reuse.

The Four Pillars of OOP Explained
Object-Oriented Programming in Java is based on four main ideas:

a. Inheritance: Let one class take on the characteristics of another. It's like passing down family traits in your code.

b. Encapsulation: Keeps your data and methods bundled together, preventing unwanted meddling and making your code more manageable.

c. Abstraction: Simplifies complex things by focusing on the important parts. It's like using a remote control without knowing all the inner workings of your TV.

d. Polymorphism: Allows different things to take on different forms. In Java, this means using one interface for different types of data, making your code more flexible.

Conclusion:

Getting the hang of Java is more than just typing code. It's about understanding how things work under the hood. Whether you're just starting with Java or want to deepen your skills, these basics and OOP principles are the building blocks for writing good, solid code. So, whether you're a beginner or a seasoned coder, remember that mastering Java is all about grasping these fundamental concepts for creating robust and efficient applications.
Switching gears to Unreal Engine
Tags: gamedev, beginners, discuss
Published: 2023-11-29 17:01:19

The first game I made was a "Choose-Your-Own-Adventure" Twine game that had the player choose options to advance the story and every once in a while play a mini-game or clue puzzle to progress. When making this game, I absolutely fell in love with the idea of making more games. I ended up learning Python as a foundation for learning programming language and made a basic terminal game as my final project for my course.

Then it came time to decide what game engine I wanted to learn. After considering between the two big names in the industry, Unity and Unreal Engine. I decided to go with Unity for a few reasons. A few of the games I have really enjoyed were made using Unity and also Unity was better equipped to use for 2D games whereas Unreal Engine was more known for 3D games. At that point in my game dev journey, I wasn't confident to be making 3D games and wanted to make pixel games like Stardew Valley.

I have made a few games as projects with Unity. Ultimately, I had to take a break from my game dev journey as work became overwhelming and I got accepted into graduate school. 

Then about two months ago, the whole drama with Unity happened. For anyone who doesn't know, here is a [video](https://youtu.be/jK7MU4a69fo?si=4lxxgsH3eLo8vHOE) that I watched that summarises everything pretty well.

Now, I believe that Unity's future is uncertain due to the company losing a lot of game developers' trust and respect. I decided yesterday that I would be moving on from Unity and learning a new game engine instead. I thought about learning Godot because there are some whispers that it might be the next big thing. But ultimately, I decided to go with Unreal Engine. I have become more comfortable with creating 3D objects and environments using Blender and thus, feel more confident in the idea of creating games with it.

It is still heartbreaking to accept that the time I put into learning Unity is put on a shelf. I know it will maybe help me in the future, but it is kind of like saying goodbye to an old relationship and starting a new one. It is bittersweet.

However, the roadmap to learning Unreal Engine feels clouded. I am not sure how this is going to go. But I will be keeping a log on here starting next week after my finals are over. I refuse to let my dream of making games die.

**What are your thoughts on the future of Unity? And what are your opinions on other game engines? Will there be a rise in Unreal Engine programmers? Or do you also believe Godot is going to make it big?**
#FIGMA Material Minimal Design System: Updated & Extended
Tags: webdev, tailwindcss, javascript, news
Published: 2023-11-29 17:00:00

What is Material Minimal Design System?

The base for the MDBootstrap and TW Elements libraries, an improved version of the classic Material Design. Material Minimal seeks a golden mean between the naturalness of the real world and the functionality necessary in the digital world. On the one hand, Material Minimal appreciates and uses the standard created by Google, and on the other hand improves it, giving it lightness, subtlety, and elegance.

Latest Updates & Improvements: 🧱Components. Over 4000 Variants now. 🔥🔥🔥

➕ Added some that were missing: Sidenav, Scrollspy, Button group, Lightbox, Placeholders, Popconfirm, Popovers, Charts, Charts advanced, Tables, Datatables, Datetimepicker, Carousel.

➕ Already existing Components have been enriched with new variants. For example: many new Cards, Navbars, Footers, and many others were created, mostly those that had such options in all our colour variants.

➕Where it was possible and necessary, mobile versions were added, e.g., Navbar, Footer, Header, in Tables and DataTables.

➕ More resolutions (desktop, MacBook, iPad horizontal, iPad vertical, iPhone). Improved the responsiveness of inputs, including the Label - they are now fully adapted to all resolutions, and can be used to create elegant forms (this improvement in responsiveness is an important topic, as users reported a problem).

➕Improved the responsiveness of many other Components.

➕The library also now features many new Icons (and variants) in the form of a Component ready to use in three different sizes: Including, byt not limited to, social media icons (Twitter updated to X).

➕Some Components have been animated, e.g., Carousel, Lightbox , Pills, Tabs, Accordion, Collapse, Dropdown (basic version), List group, Modal (one specific), Placeholder, Rating, Spinners, Tables (scroll horizontally on mobile). Basic Bar Chart also animates individual data now💪💪💪

Download 🆓 Figma files below & leave a ❤
[Material Minimal Design System on Figma](https://www.figma.com/community/file/1255241951305406231)
Automate Everything (you can)
Tags: productivity, opensource, learning, linux
Published: 2023-11-29 16:57:38

Do you have a gig where you do repetitive tasks.
I have.

It's a chore!
Automate yourself out of a job - I've been warned about this for well over a decade.

In a recent gig, they had several technical writers on staff who would copy defect information, insert the content by manual paste, save and do this again. The other end was the writer worked with SMEs to get the summary for the release notes. Since the writers were unfamiliar with reading logs, this took some communication to draft the content.

Seriously, the engineers would include logs, images, sometimes video and a summary. The draft is easy for a dev, not a journalist or English major. 

So, basically, I automated the grab and insertion process and drafted these one day when the team needed assistance. Warning: If you are productive, guess what - you are assigned more. Expect this. Set a good baseline of expectations based on bandwidth.

The problem was the company used a CCMS with DITA. This CCMS was completely unnecessary and restricted automation. 

Reroute around the problem. Insert local and One copy/paste. No reason for a CCMS at all. Have you heard of XSL? Perhaps SVN or git. 

When proprietary products - costing money restricts automation, it's time for a workflow improvement!

In one month, the main release notes writer did 2 release notes. I did 32 the first day and 42 the next.

Automagically!
CORS
Tags: rest, beginners, french, webdev
Published: 2023-11-29 16:33:20

Lorsque différents sites web interagissent entre eux, des questions de sécurité se posent. Comment un site peut-il savoir s'il doit faire confiance à un autre pour partager ses ressources ? Voici où entre en jeu **CORS**, ou *Cross-Origin Resource Sharing* .

## Comprendre CORS

CORS (Cross-Origin Resource Sharing) est un **mécanisme de sécurité** mis en place par les navigateurs pour contrôler les requêtes faites entre différentes origines (ou domaines). Une "origine" est composée du protocole (http, https), du nom de domaine et du port.

Lorsqu'un site web, comme `www.monsite.fr`, tente de charger des ressources depuis un autre domaine, comme `www.autresite.com` le navigateur vérifie si `www.autresite.com` autorise explicitement `www.monsite.fr` à accéder à ses ressources. Si cette autorisation est absente ou incorrecte, le navigateur bloque la requête pour des raisons de sécurité.

Mais comment faire si j'ai besoin d'accéder à une API sur un autre domaine quand je développe ? 

## Pour contourner ces blocages lors du développement

 - **Extensions de Navigateur** : Des outils comme "CORS Everywhere" ou des paramètres spécifiques permettent de désactiver temporairement la sécurité CORS sur le navigateur, pratique pour tester les requêtes entre domaines pendant le développement.

- **Serveur Proxy** : En utilisant un serveur intermédiaire (un proxy) côté serveur, les requêtes peuvent être redirigées. De cette façon, la requête provient du même domaine que le serveur, évitant ainsi les restrictions CORS.

Mais alors, je peux désactiver CORS sur mon site ? 🤔

## Quel est le rôle de CORS ?

Non, on ne doit pas autoriser tous les sites !

CORS joue un rôle crucial dans la **sécurisation** des échanges entre sites web, en abordant plusieurs problèmes de sécurité :

 - **Protection contre les Attaques CSRF** : CORS empêche les requêtes non autorisées depuis des sites tiers, ce qui réduit le risque de manipulation de session ou de vol de données.

- **Contrôle d'Accès aux Ressources** : CORS limite l'accès aux ressources d'un serveur à des domaines spécifiques autorisés, empêchant ainsi des sites malveillants d'accéder à des données sensibles d'un autre site sans autorisation.

- **Prévention des Fuites d'Informations** : CORS réduit les risques de fuite d'informations sensibles en bloquant les requêtes d'origines non autorisées qui pourraient récupérer des données confidentielles.

## Bien configurer les règles CORS

Pour définir des règles CORS, on peut utiliser l'annotation @CrossOrigin dans le contrôleur.

```javascript
// Exemple de requête GET
fetch('https://tonserveur.com/api/public', {
    method: 'GET',
    headers: {
        'Origin': 'https://www.monclient.com' // Origine autorisée pour cette requête
    }
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.error('Erreur :', error));
```

En résumé, CORS joue un rôle crucial dans la sécurisation des échanges entre différents sites web. Il est essentiel pour éviter les risques de sécurité sans bloquer complètement les interactions entre domaines. 🛡️
How I solved 100 problems on LeetCode and what I was doing wrong? 👨🏼‍💻
Tags: beginners, learning, leetcode, python
Published: 2023-11-29 16:27:29

LeetCode is a website with algorithmic problems similar to those in FAANG interviews and other IT companies. After solving over 100 problems in six months and discussing with others, I realized what I did wrong and right. Here's my experience to help you prepare more efficiently and quickly.

---

**Systematic Approach** ✅
Instead of randomly tackling problems, I purchased a preparation course and focused on solving problems by topic. I studied theory, reviewed solutions, and then attempted the problems. Investing $100 in the course was one of my best decisions.

**Avoiding Miracle Hopes** ❌
Realizing that prolonged contemplation didn't lead to solutions, I shifted to studying problem solutions first. Understanding algorithms and techniques from these solutions made it easier to solve similar problems in 5-20 minutes.

**Setting Clear Goals and Tracking Progress** ❌
Initially, I lacked a sense of progress. Keeping a journal with problem analyses, noting challenges, and maintaining statistics on tasks solved and course progress helped track growth and maintain motivation.

**Choosing the Wrong Programming Language** ❌
Using JavaScript/TypeScript, I faced challenges in writing solutions. I'm transitioning to Python, which simplifies problem-solving. Even my friend at Google in Germany recommended Python for its simplicity and built-in data structures.


![Python vs. JavaScript – and Python wins! 💪](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70r3vvpwvrvdlvlx1xw7.png)
_Python vs. JavaScript – and Python wins! 💪_

---


Share your LeetCode experience, mistakes, and successes in the comments! 👋
How to sequentially execute a procedure on concurrent requests
Tags: postgres
Published: 2023-11-29 16:25:01

We have a web application which is accessed by multiple users concurrently. PostgreSQL is the database for the application. 

The core functionality of app is to allocate tickets to the user who hits the "Fetch" button. All the business logics for the button click event are written inside the PostgreSQL Procedure. As said, users will hit the "Fetch" button concurrently.

Business requirement is, when the fetch button is clicked, all the requests to the procedure has to be executed sequentially(like FIFO). The next user's request should be processed only after the completion of previous request(Parallel execution should not be allowed). 

How to achieve this within PostgreSQL. 

I can install Postgres extensions if required.

Note: I have suggested my team to use message queuing applications to achieve this but they are not willing to rely on any external tools like RabbitMQ or any.
Nuxt Social Share module has many new features 🎉
Tags: nuxt, vue, javascript, frontend
Published: 2023-11-29 16:23:08

Since it first public release about a month ago, I continued to work on the Social Share module for Nuxt, fixing some problems and adding more features.


![Social Share buttons](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bk0ixfoekaw8ep8xms9k.png)

The latest release available right now is `v0.5.0` and features:

- two more networks (Reddit and Skype)
- more URL arguments (title, image, hashtags, etc.) for relevant social networks.
- components now have proper `aria` attributes for improved accessibility.
- in addition to the `<SocialShare>` component, the `useSocialShare` composable is exposed to the developer, providing more flexibility if needed.
- everything has been fully ported to Typescript.
- better modularization of code, helping both maintenance and contributions from other developers.
- some fixes to CSSs specificity, now the styles can be fully overridden.

All of these features and more are fully documented in the [repository's readme](https://github.com/stefanobartoletti/nuxt-social-share#readme)

You can install it and try it with:

```bash
# pnpm
pnpm add -D @stefanobartoletti/nuxt-social-share
# yarn
yarn add --dev @stefanobartoletti/nuxt-social-share
# npm
npm install --save-dev @stefanobartoletti/nuxt-social-share
```

Check it in its repository here: https://github.com/stefanobartoletti/nuxt-social-share
Navigating the Landscape of Tasks APIs and Integration Challenges
Tags: api, tasks, crm, programming
Published: 2023-11-29 16:21:07

The integration of Tasks APIs from diverse platforms – spanning project management systems, CRM platforms, and email providers – presents both immense opportunities and integration challenges for developers. My recent blog post talks about Tasks APIs offered by various platforms, delving into the benefits they offer for app developers and product teams while navigating the hurdles of integration.

Key Takeaways:

**Diverse Tasks APIs**: Explore the array of Tasks APIs across project management, CRM, and email provider platforms.

**Integration Benefits**: Discover the advantages of integrating Tasks APIs for product teams, including streamlined workflows, enhanced user experience, seamless collaboration, and data consolidation.

**Integration Challenges**: Understand the hurdles faced by developers, including compatibility issues, authentication and security, data synchronization, and user interface consistency.

**Overcoming Challenges**: Uncover strategies to maximize benefits and overcome integration challenges, such as thorough research and planning, adopting integration frameworks, prioritizing security measures, and continuous monitoring.

**Unified Tasks APIs**: Delve into the advantages of using a Unified Tasks API for developers and users, including simplified integration, consistent user experience, and task synchronization across platforms.

## Conclusion

The integration of Tasks APIs offers immense potential for app developers and product teams. By overcoming integration hurdles and harnessing the power of Unified Tasks APIs, developers can elevate app functionality, enhance user satisfaction, and drive productivity.

[Streamlining Task Management: Navigating the Landscape of Tasks APIs and Integration Challenges](https://www.aurinko.io/blog/tasks-api-integrations/)