teleren/devto huggingface dataset:
Code Smell 241- Referential Transparency Violation
Tags: webdev, beginners, programming, tutorial
Published: 2024-02-17 01:25:00

*Pure functions produce the same output for the same input and have no side effects*

> TL;DR: Your functions should be replaceable by the computation result.

# Problems

- Readability

- Principle of least astonishment violation

- Testability

- [Coupling](https://dev.to/mcsee/coupling-the-one-and-only-software-design-problem-2pd7)

# Solutions

1. Avoid side effects and erratic behavior
 
# Context

Breaking referential transparency occurs when the code introduces side effects or relies on a mutable state.

This violates the principle that an expression or function can be replaced with its value without changing the program's behavior.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/8d91de12e8bce988a1ef8a16b858bcd4)
```python
# Global mutable variable
counter = 0

# Function with side effect
def increment_counter():
    global counter
    counter += 1
    return counter

# Function with implicit dependency and non-deterministic
def get_random_number():
    import random
    return random.randint(1, 100)

# Function with non-deterministic behavior
def get_current_time():
    import time
    return time.time()
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/e396dd603b41cc11865ad780ca6ffed6)
```python
import random
import time

# Function without side effects
def increment_counter(counter):
    return counter + 1

# Function without side effects (but not deterministic)
def get_random_number():
    return random.randint(1, 100)

# Function without side effects (can also be injected)
def get_current_time(timesource):
    return timesource.time()
```

# Detection

[X] Semi-Automatic 

Many linters warn you when you violate referential transparency

# Tags

- Coupling

# Level

[x] Intermediate

# AI Assistants

Most AI assistants will avoid violating referential transparency.

# Conclusion

Functional programming is known for its ability to enable concise, expressive, and maintainable code, as well as facilitating parallel and concurrent programming due to its emphasis on immutable data and pure functions. 

There are many concepts to borrow from it.

# Relations

{% post https://dev.to/mcsee/code-smell-209-side-effects-13l8 %}

# More Info

{% post https://dev.to/mcsee/coupling-the-one-and-only-software-design-problem-2pd7 %}

# Disclaimer

Code Smells are my [opinion](https://dev.to/mcsee/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned-1n3a).

# Credits

Photo by [Wilhelm Gunkel](https://unsplash.com/@wilhelmgunkel) on [Unsplash](https://unsplash.com/photos/white-and-black-diamond-shape-illustration-3VQ4AfOKCVc)
    
* * *

> Referential transparency is a very desirable property: it implies that functions consistently yield the same results given the same input, irrespective of where and when they are invoked.

_Edward Garson_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Curso inteligencia artificial IA University
Tags: chatgpt, ia, tecnologia, business
Published: 2024-02-17 01:17:35

[](https://ia.university/) En MDALatam, nuestro curso de vanguardia en IA 🚀 ofrece una oportunidad sin igual para sumergirte en el mundo de la inteligencia artificial, combinando teoría con aplicaciones prácticas en el mundo real. Diseñado tanto para principiantes como para profesionales, este curso te empodera para dominar los fundamentos de la IA 🧠, aprender sobre algoritmos de aprendizaje automático y aplicar la IA en estrategias de marketing digital para revolucionar negocios 💼. Ya sea que busques mejorar tu carrera, impulsar la transformación digital o innovar dentro de tu industria, nuestras sesiones lideradas por expertos, proyectos prácticos y un entorno de aprendizaje colaborativo brindan todas las herramientas que necesitas para el éxito. Únete a nosotros en MDALatam para desbloquear el potencial completo de la IA y convertirte en líder del futuro digital 🌟.
Things I Learned using Phoenix LiveView in 2024 (Part 2)
Published: 2024-02-17 01:05:03

### The beauty of `assign_async/3` and `async_result/1`

```elixir
# LiveView 
def handle_params(params, _uri, socket) do
    {:noreply, 
         socket
         # ... more assigns here
         |> assign_async_coffees()}
end

# ... more code here

defp assign_async_coffee(socket) do
    assign_async(socket, :coffees, fn -> 
        {:ok, %{coffees: Coffee.load_more_coffees}}
    end)
end
```

* [https://hexdocs.pm/phoenix\_live\_view/Phoenix.LiveView.html#module-async-operations](https://hexdocs.pm/phoenix_live_view/Phoenix.LiveView.html#module-async-operations)
    
    > It allows the user to get a working UI quickly while the system fetches some data in the background or talks to an external service, without blocking the render or event handling
    
* What I liked about the beauty of using `assign_async/3` is that everything is asynchronous. I get the chance to process data without blocking the render or event handling
    
* I also have the change to handle different states like the `loading`, `failures` and the `successful result`
    
    > You also want to catch any errors or exits and translate it to a meaningful update in the UI rather than crashing the user experience.
    
* And just in case there will any exit errors, I will be able to handle that in the liveview.
    

### The built-in component

```elixir
# LiveView heex file
<.async_result :let={coffees} assign={@coffees}>
    <:loading>Preparing what are the best coffees for you...</:loading>
    <:failed :let={_failure}>Please be patient, something came up...</:failed>
    <div :for={coffee <- coffees}>
        Here is your coffee <%= coffee %>
    </div>
</.async_result>
```

* `assign_async/3` has a partner that I could say a `built-in` partner wherein you can use it to render the different states that you want to show to your users.
    
* You can even customize the `loading` and `failed` component slots to have an even more beautiful UI.
    

Users can choose nicely from the list of coffees from your application if you seamlessly implemented this kind of approach.

> But I wonder does this one have any drawbacks?

That's another thing to find out.

> Happy coding
Introduction to the Python Random Library
Tags: python, beginners, programming
Published: 2024-02-17 00:44:38

# Introduction

Python has a built-in `random` library that provides various functions for performing stochastic operations. In this chapter, we'll explore some of the most commonly used functions in the `random` library, including generating random numbers, making random choices, and shuffling sequences.

# Generating Random Numbers

Several functions are available to generate `random` numbers, including `random`, `uniform`, `randint`, and `randrange`. Here's an example of using these functions to generate random numbers representing the roll of a die and the toss of a coin:

```{python}
import random

# Generate a random integer between two values
min_die = 1
max_die = 6
die_roll = random.randint(a=min_die, b=max_die)
print(f"Die roll: {die_roll}")
```

```
Output:
Die roll: 4
```

```{python}
# Generate a random choice from a sequence
coin_toss = random.choice(seq=["heads", "tails"])
print(f"Coin toss: {coin_toss}")
```

```
Output:
Coin toss: tails
```

# Making Random Choices

The `choice` and `choices` functions are available to make random selections from a sequence. Here's an example of using these functions to randomly select a card from a deck of cards:

```{python}
import random

cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]

# Make a random choice from a sequence
card = random.choice(seq=cards)
print(f"Randomly selected card: {card}")
```

```
Output:
Randomly selected card: 7
```

```{python}
# Make multiple random choices from a sequence
num_choices = 5
cards = random.choices(population=cards, k=num_choices)
print(f"Randomly selected cards: {cards}")
```

```
Output:
Randomly selected cards: ['Queen', '3', 'King', '9', '8']
```

# Shuffling Sequences

The `shuffle` function is available to shuffle a sequence in place randomly. Here's an example of using the `shuffle` function to randomly shuffle a list of cards:

```{python}
import random

cards = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]

# Shuffle a sequence in place
random.shuffle(x=cards)
print(f"Shuffled cards: {cards}")
```

```
Output:
Shuffled cards: ['3', 'Queen', '8', '2', 'King', 'Jack', 'Ace', '9', '6', '7', '10', '5', '4']
```

# Conclusion

Whether you're simulating a game of chance or generating random data for a machine-learning model, the `random` library is an essential tool for any Python programmer.
Exploring the Document Object Model (DOM) in JavaScript
Tags: dom, webdev, javascript, beginners
Published: 2024-02-17 00:28:47

## Introduction

The Document Object Model (DOM) is a programming interface for HTML, XML, and SVG documents, which allows them to be accessed and manipulated by JavaScript. It represents the structure of a document as a tree-like data structure, with each node containing various properties and methods that can be used to manipulate the document. In this article, we will explore the advantages, disadvantages, and features of the DOM in JavaScript.

## Advantages

1. **Cross-browser compatibility:** The DOM is supported by all modern browsers, making it a reliable and widely used method for manipulating web pages.
2. **Dynamically update web content:** With the DOM, developers can easily change the content and style of a web page in real-time, without reloading the entire page.
3. **Easy to learn and use:** The DOM provides a simple and intuitive way to interact with web pages, making it easy for beginners to get started with JavaScript.

## Disadvantages

1. **Performance issues:** Manipulating the DOM can be slow, especially when dealing with large and complex documents, as changes to the document structure can cause the browser to re-render the page.
2. **Security concerns:** As the DOM allows for dynamic changes to a web page, it can also be vulnerable to cross-site scripting (XSS) attacks if proper precautions are not taken.

## Features

1. **Tree structure:** The DOM represents a document as a tree, with each element, attribute, and text node being a part of the overall structure.
2. **Methods and properties:** The DOM provides a wide range of methods and properties that can be used to access and modify a document's nodes, elements, and attributes.
3. **Event handling:** The DOM supports event handling, allowing developers to create interactive web pages that respond to user actions.

### Example of DOM Manipulation

```javascript
// Accessing an element by ID
const element = document.getElementById('myElement');
// Changing the content of the element
element.textContent = 'New content';
// Adding a class to the element
element.classList.add('new-class');
```

This example demonstrates basic DOM manipulation techniques, such as accessing an element, changing its content, and adding a class to it.

## Conclusion

The Document Object Model in JavaScript is a powerful and widely used tool for dynamic web development. While it has its limitations, the benefits of using the DOM far outweigh the drawbacks. With its intuitive interface and robust features, the DOM continues to be an essential part of modern web development. With practice and a good understanding of the DOM, developers can create dynamic and interactive web pages that enhance the user experience.
Frontend Developer Roadmap
Tags: webdev, javascript, beginners, career
Published: 2024-02-17 00:23:16

Step by step guide to becoming a frontend developer.

### Beginner

If you are familiar with the items listed in this chapter, you will be able to understand what other frontend engineers are talking about.

- Foundational concepts
  - HTML
  - CSS
  - JavaScript
- Getting Help
  - ChatGPT
  - Google
- Command-line interface
  - ls, cd, grep, rm, man...
- Version control
  - Git
- HTTP request
  - Fetch API
- Data structures
  - Data types
  - TypeScript
- Frontend frameworks
  - React
  - Vue.js
- Package Managers
  - npm
- CSS frameworks
  - Tailwind CSS
- Build and deploy
  - Domain names
  - DNS
  - Vite
  - Github Actions
  - AWS s3
  - AWS cloudfront
  - AWS route53
- Testing
  - Jest

### Intermediate

The following topics are not mandatory. Learn according to project needs.

- Web APIs
  - Canvas
  - SVG
  - MediaDevices
- Authentication
  - Sign in with Google
  - JWT
- Accept payments
  - Stripe
  - PayPal
- Frontend frameworks
  - Astro
- Package Managers
  - pnpm
- Linter
  - ESLint
  - Lint staged
  - Husky
- Data visualization
  - [Chart.js](https://www.chartjs.org/)

### Source
https://arnosolo.github.io/learn-web-development/article-2-frontend-developer-roadmap.html
A versatile React component based on the yFiles library
Tags: chart
Published: 2024-02-18 16:35:53

---
title: A versatile React component based on the yFiles library
published: true
date: 2024-02-17 00:14:00 UTC
tags: Chart
canonical_url: https://reactjsexample.com/a-versatile-react-component-based-on-the-yfiles-library/
---

## yFiles React Organization Chart Component
 ![A versatile React component based on the yFiles library](https://reactjsexample.com/content/images/2024/02/Code_2024-02_21-09-02.jpg)

![A versatile React component based on the yFiles library](https://reactjsexample.com/content/images/2024/02/react-orgchart-component.gif)

Introducing the yFiles React Organization Chart Component, an advanced React component built upon the robust yFiles library. This versatile tool empowers developers to effortlessly integrate organization charts into their React applications.

[View Demo](https://docs.yworks.com/react-yfiles-orgchart)[View Github](https://github.com/yWorks/react-yfiles-orgchart)

With its powerful features and seamless integration capabilities, the yFiles React Organization Chart Component offers a flexible solution for visualizing hierarchical structures with ease.
Another way to create test module configuration
Tags: drupal, php, phpunit
Published: 2024-02-23 15:59:46

---
title: Another way to create test module configuration
published: true
date: 2024-02-17 00:00:00 UTC
tags: [drupal, php, phpunit]
canonical_url: https://www.oliverdavies.uk/archive/2024/02/17/another-way-to-create-test-module-configuration
---

In one of the lessons in my [free automated testing in Drupal email course](https://www.oliverdavies.uk/atdc), I explain how I create configuration that I need within my tests, such as adding a custom field:

> But how do you know what to name the configuration files and what content to put in them?
> 
> Rather than trying to write them by hand, I create the configuration I need, such as fields, within a Drupal site and then export and edit the files I need.

As well as creating the fields in the Drupal UI, I was also using it to export the configuration files I needed:

> Once Drupal is installed and the configuration has been created, you can go to - /admin/config/development/configuration/single/export and select the configuration type and name.
> 
> The filename is shown at the bottom of the page, and you can copy the content into files within your module.

## There's another way

After reading that lesson, somene replied and reminded me that there's a `--destination` option you can use with the `drush config:export` command.

Instead of exporting to the standard configuration directory, I can do it to a temporary directory:

```
run drush cex --destination /app/.ignored/config

```

Everyhing in a `.ignored` direcotry is automatically ignored by Git, and to get the files I need, I can use Linux's `find` command to find any files that contain the field name and copy them into my test module directory:

```
find .ignored/config \
  -type f \
  -name \*drupal_project\* \
  -exec cp -r {} web/modules/custom/foo/modules/foo_test/config/install \;

```

I still need to edit the files to remove the `uuid` and `_core` values, but this approach means less clicking in the Drupal UI which makes me more productive.

I used this approach when [writing my SaaS code yesterday](https://www.oliverdavies.uk/archive/2024/02/16/keep-logic-within-tests-for-as-long-as-you-can) and it worked well.

P.S. Do you need immediate access to an expert Drupal Developer? [With my Drupal development subscription](https://www.oliverdavies.uk/subscription), make unlimited requests for a fixed monthly price in less time than posting to a job board!
Understanding useEffect in React: Managing Side Effects
Published: 2024-02-16 23:51:25

**What's a Side-Effect? 🤔**
In programming, side-effects are operations that affect the outside world, such as API calls, DOM manipulation with setTimeout or intervals, and accessing or modifying global objects like document or window. Incorporating these directly into our React components can lead to inefficient re-renders, affecting the performance of our application.

**Enter useEffect ✨**
To address this issue, React introduced the useEffect hook. This hook enables us to perform side-effects in a controlled manner, executing them after the component has rendered. This helps avoid unnecessary re-renders, ensuring smooth performance for our React applications.

**How to Use It:**

useEffect(() => {
  // Your side-effect code here
}, []); // The second argument is an optional dependency array


What you put inside the dependency array determines when the effect should re-run. Understanding the dependency array is crucial for effectively managing side-effects.

- An empty dependency array ([]) indicates that the effect runs only once after the initial render. This is useful for effects such as data fetching, setting up subscriptions, or manual DOM manipulation that only need to occur once.
- A populated dependency array ([dep1, dep2, ...]) means the effect will re-run whenever any of the listed dependencies change. This is ideal for effects that need to update in response to changes in state or props.
- If no dependency array is provided, the effect will run after every render. This approach is rarely used as it can lead to performance issues, but it's necessary when an effect needs to adjust to every change.

The beauty of useEffect is that it doesn't return anything (undefined), focusing solely on side-effect management.
What The Hell is "Monkey Patching"? + 11 Software Development Terms ⚡️🙌
Tags: beginners, discuss, watercooler, codenewbie
Published: 2024-02-16 23:30:00

## 👇 Believe It Or Not!

This list will prove to be helpful despite of whether you're new to the developer community or an experienced developer like me.

As I explored the domain of programming I came across a vocabulary filled with intriguing terms. 

So, this article sheds light on some of the humorous expressions that frequently are used in conversations, within the software development community.

Here are some amusing terms that you might come across as a software engineer! 😄

***

### 🐒 Monkey Patching

It refers to modifications done during runtime. It is a temporary fix rather than a long-term solution.

### #! Shebang

You might already know this term in spoken language but in computing it refers to the character sequence at the beginning of a script.

### 🗑 Garbage Collection

It refers to cleaning up memory by removing unused data.

### 📊 Patch

A patch is a collection of changes applied to software.

### ⭐️ Yoda Conditions

Conditions where the LHS and RHS of an expression are reversed, eg, 5 == count

### 🔨 Brute Force

It refers to naive algorithms/solutions to a problem that are not optimized.

### 🎩 Magic Number

It is an arbitrary numerical value that appears in code without any explained context or meaning.

### 🍝 Spaghetti Code

Commonly used to refer to code that is hard to understand or maintain.

### 👃 Code Smell

A code smell is an indication that there is a problem in the fundamental design of the code.

### 🐤 Rubber Duck Debugging

It is the action of explaining a code problem in natural language to a rubber duck with the hope of identifying the issue while you explain it.

### 🔥 Hotfix

A hotfix is a small and quick software update to resolve a bug.

### 🛠 Yak Shaving

It refers to a situation when to achieve a goal, you must perform a series of seemingly unrelated tasks.

***

## 🌟 Wrapping Up

In summary, these unique expressions provide a peek, into the ever-growing software development culture, where innovation and troubleshooting intersect.

So when faced with a "Yak Shaving" situation, in the future approach it with a mindset and a sprinkle of humour 🙃!

Also, drop a software dev term that is ridiculous that it exists in the comments!

The best comments will be featured in my upcoming post relating to the same topic in the first week of March.

I hope you liked the article! ❤️

Connect with me: [linktree](https://linktr.ee/arjuncodess)

Happy Coding! 🚀
Thanks for 15555! 🤗
Playwright if locator is visible
Published: 2024-02-16 23:21:00

I have a project that sometimes will throw an error when try to delete an object.
I would like to catch that error and click on the OK button to close it.

Here is what works for me.

```
    const element = page.getByRole("button", { name: "OK" });
    if (await element.isVisible()) {
     await element.click();
    }
```