teleren/devto huggingface dataset:
Fractals Using Pascal Triangle
Tags: java, pascal, fractals, programming
Published: 2024-03-10 15:30:48

**Pascal Fractals**
It is possible to recreate interesting fractals like infinite triangles inside smaller triangles, using Pascal triangle.

So, firstly, we have to understand what is Pascal's Triangle?
Well, it is just a triangle that consists of numbers:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
...
The first line is 1, and the second is 11,
then the first and the last elements are 1, 
and the others are just the sums of 2 elements that are near to each other.

Then, let's find out how to get Nth element of Pascal array that will be stored like: [1, 1, 1, 1, 2, 1, 1, 3, 3, 1, ...]
The array length is actually the Nth element of the geometric series: 1+2+3+...+n
We will use the formula Sn = an² + bn + c
S0 = 0 = a*(0)² + b*(0) + c => c = 0
S1 = 1 = a*(1)² + b*(1) + 0 => a + b = 1
S2 = 3 = a*(2)² + b*(2) + 0 => 4*a + 2*b = 3
If we solve the equation's system we get a = 0.5 = b
Thus, we get the formula:
Sn = 0.5*n² + 0.5*n = (n * (n + 1)) / 2

Then, even if we use `long` type it will return negative value at some point, so to avoid that when we use modulo (%) we can use the python implementation for the whole array:

```java
   public static void modPascalArray(long[] pascalArr, int mod)
    {
        int i = 0;

        for (i = 0; i < pascalArr.length; i++)
        {
            pascalArr[i] = (pascalArr[i] % mod + mod) % mod;
        }
    }
```
And then we can write simple graphics and get beautiful results for mod that is power of 2! :D

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


GitHub repository: https://github.com/Gavriel770U/Pascal
Como eu melhorei meus testes utilizando React Context
Tags: webdev, react, javascript, testing
Published: 2024-03-10 14:15:19

A Context é uma excelente forma de gerenciar estados em aplicações React e hoje em dia em muitos cenários dispensam o uso de bibliotecas adicionais para tal fim.

Uma das vantagens é a facilidade e simplicidade de testar os componentes que fazem uso de contextos com `react-testing-library`.

Veja como costumo fazer nos meus projetos:

```ts
export type User = {
  name: string;
};
```

```tsx
import { createContext } from 'react';
import { User } from './user';

export const UserContext = createContext<User>({} as User);
```

```tsx
import useSWR from 'swr';
import { User } from './user';
import { UserContext } from './user-context';

type Props = {
  children: React.ReactNode;
};

export function UserProvider({ children }: Props) {
  const { data, isLoading, error } = useSWR<User>('/api/user');

  if (error) {
    return <div>Erro ao carregar usuário</div>;
  }

  if (isLoading) {
    return <div>Carregando...</div>;
  }

  return (
    <UserContext.Provider value={data || ({} as User)}>
      {children}
    </UserContext.Provider>
  );
}
```

```tsx
import { useUser } from './useUser';

export function UserGreeter() {
  const user = useUser();

  if (user.name) {
    return <div>Olá, {user.name}!</div>;
  }

  return <div>Olá, visitante!</div>;
}
```

Vamos garantir no teste que a regra de saudação seja respeitada corretamente:

```tsx
import { render, screen } from '@testing-library/react';
import { UserGreeter } from './user-greeter';
import { UserProviderMock } from './user-provider-mock';

describe('UserGreeter', () => {
  it('should greet the user', () => {
    render(
      <UserProviderMock>
        <UserGreeter />
      </UserProviderMock>,
    );

    expect(screen.getByText('Olá, John Doe!')).toBeInTheDocument();
  });

  it('should greet the anonymous user', () => {
    render(
      <UserProviderMock value={{}}>
        <UserGreeter />
      </UserProviderMock>,
    );

    expect(screen.getByText('Olá, visitante!')).toBeInTheDocument();
  });
});
```

Observe que criei o `UserProviderMock` com valores padrão, para evitar repetições em todos os testes dos componentes que dependem do `User`:

```tsx
import { User } from './user';
import { UserContext } from './user-context';

type Props = {
  children: React.ReactNode;
  value?: Partial<User>;
};

export function UserProviderMock({ children, value }: Props) {
  return (
    <UserContext.Provider value={{ name: 'John Doe', ...value }}>
      {children}
    </UserContext.Provider>
  );
}
```

Você ainda acha necessário o uso de bibliotecas de gerenciamento de estado? Por favor, deixe sua opinião nos comentários.
Mastering 3D Experiences with JavaScript and Wix: A Step-by-Step Guide
Tags: webdev, javascript, beginners, programming
Published: 2024-03-10 13:56:13


### Setting Up the Environment

In my last post, we explored making unique and stunning websites using 3D Gaussian splatting. Today, we dive deeper, showing you how to augment your Gaussian splat with JavaScript for mind-blowing 3D web experiences.

### Getting Started with Package Downloads

Before we jump into coding, let's set the stage. Our focus in this session will be on using the Luma web library. For this demonstration, I'm using Wix, but feel free to adapt the process to your preferred setup.

### Creating a Workspace in Wix

We start by navigating to Wix.com, creating a new site, and opting for a blank canvas. Turning on the developer mode, we then proceed to embed a custom element. After adjusting the custom element to fill the screen area, we specify the source for our code, either through hosting or creating a new Velo file.

### Importing Necessary Packages

To harness the full potential of our 3D setup, we install the Luma web package and Three.js from NPM through the Wix interface. These packages form the backbone of our 3D web experience.

### Diving into Custom Element Coding

With our packages installed, we dive into coding the custom element. This involves setting up the renderer, camera, and scene with Three.js, crucial components for rendering 3D graphics on the web.

{% embed https://youtu.be/JpDTuFTEsx0 %}

### Exploring Wix IDE and VS Code Integration

One neat feature is the ability to integrate the Wix IDE with VS Code. This synchronization allows for a more streamlined coding experience, especially helpful when dealing with complex 3D rendering code.





### Connecting to GitHub and Finalizing the Project

The project is then connected to GitHub for version control and collaborative development. This step involves installing the Velo application and setting up a new repository for our project.

During the setup, I switched to a local IDE for better integration with tools like GitHub Copilot, which aids in writing more efficient and error-free code.

### Implementing Advanced Visuals with LumaSplatsThree

The heart of our session lies in integrating LumaSplats3 for dynamic, interactive 3D visuals. The renderer is appended to our custom element, and with a few lines of code, our Gaussian splat comes to life, responsive to user interactions.

### Wrapping Up: Previewing and Publishing

Finally, we preview our project locally and then publish it to Wix. The result is a live, interactive 3D scene, accessible to anyone visiting the site.

And that's a wrap for this session! We've successfully integrated a Gaussian splat into our website using JavaScript and the Luma web library. In the next videos, I'll take you through adding those extra touches that elevate your 3D web experience. Stay tuned!
Exploring AWS Day by Day - Learn AWS in simple way
Tags: cloud, cloudcomputing, aws, learning
Published: 2024-03-10 13:33:50

Exploring AWS !!

Hello Connections, I shall be trying to help people out who want to learn AWS by sharing at least one service or article based on AWS per day. I have made some notes during my AWS learning journey which are in easy and understandable language, trying to share them with you guys.

Day 1:

Introduction to Cloud Computing

Cloud Computing - is when you use a computer/server which is provided to you by someone else. This server has to be accessed over internet by using a web based tool for personal or business server.

Virtualization - creation of a virtual version of something, such as OS, server, storage device or network resource. Virtualized compute environment over internet is cloud.
Cloud Computing = Virtualization + Internet

Advantages:

No Capital Expenditures or upfront cost
Highly available solution
Pay-as-you-go
Security
Getting a server is easy
Flexibility & Error shield

Advantages over on premises - controls servers as per traffic, as servers can be fluctuated.

Cloud Service and Deployment Models -

Clou9d Service Models:
IaaS (Infrastructure as a Service) - AWS, RackSpace, Azure
PaaS (Platform as a Service) - AWS Elastic Beanstalk, Heroku
Saas (Software as a Service) - Google drive, Google docs, MS Office

Infrastructure + Platform + Coding = Product --> Users

Cloud Deployment Models:

Public Cloud (AWS, Azure, Google Platform, IBM)
Private Cloud (HPE, VmWare, RedHat, OpenStalk)
Hybrid Cloud (AWS Outposts, Azure VMware Solution, Google Anthos, Nutanix Cloud Infrastructure)

Cloud Services Providers - delivers services & solutions based on cloud computing - Amazon Web Services (AWS), Microsoft Azure, Google Cloud

Amazon Web Services (AWS) - Biggest cloud service provider with 33 Availability zones spread across 17 regions. Netflix, Reddit, Inc., NSA use AWS to host their applications.
Microsoft Azure - Second biggest market, used by BMW Group, Samsung Electronics, PwC
Google Cloud - Third, mainly provide SaaS, used by LinkedIn, Facebook, PayPal.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5s6v22micy5kd2y8q6jr.png)
Javascript classes explanation in a simple way
Tags: javascript, class, beginners, es6
Published: 2024-03-10 13:25:30

Classes were added to Javascript in ECMAScript 2015 (ES6). They are not typical classes like in other object-oriented languages ie. Java.

![Class in Javascript is syntactic sugar](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oou81d84v5mx87ojfxmt.png)


The class in JS is helpful, facilitating syntactic sugar. It is nothing more than a regular function that receives an argument, and then this argument is assigned to the object THIS.
In the case when a class has a method, this method is assigned to the prototype of this object.

![Class equivalent in Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bh6zrf0zbsuf8jmqwud1.png)
Simplifying Big Data Analytics with AWS Serverless EMR
Tags: aws, bigdata, datascience, tutorial
Published: 2024-03-10 13:12:04

In the realm of big data analytics, managing clusters and servers can be a daunting task. Enter AWS Serverless EMR, a paradigm shift in the way data analysts and engineers approach big data workloads. This serverless option within Amazon EMR is transforming the analytics landscape by offering a hands-off experience that doesn't compromise on power or flexibility.

## What is AWS Serverless EMR?

AWS Serverless EMR is a deployment option within Amazon EMR that provides a serverless runtime environment for running analytics applications using popular open-source frameworks like [Apache Spark](https://spark.apache.org/) and [Apache Hive](https://hive.apache.org/). It's designed to simplify operations by eliminating the need to configure, optimize, secure, or operate clusters to run applications.

## The Benefits of Going Serverless

- **Ease of Use**: Select your desired open-source framework, and AWS Serverless EMR takes care of provisioning and managing the underlying compute and memory resources.
- **Scalability**: Automatically scales resources to meet the demands of your data volumes and processing requirements, ensuring that you only pay for what you use.
- **Cost Optimization**: With automatic scaling, AWS Serverless EMR minimizes concerns about over- or under-provisioning, leading to straightforward cost controls.

## AWS Serverless EMR in Action

Imagine a world where your big data analytics can run at any scale, adjusting seamlessly as workload demands change. With AWS Serverless EMR, this is not just possible; it's the new standard.

### Interactive Data Analysis

For use cases requiring quick responses, such as interactive data analysis, AWS Serverless EMR allows you to pre-initialize resources, ensuring that your applications respond within seconds.

### Development and Testing

Need to spin up a development and test environment? AWS Serverless EMR enables you to do so quickly and easily, with the added benefit of automatic scaling to accommodate unpredictable usage patterns.

## The Future of Big Data with AWS Serverless EMR

AWS Serverless EMR is not just a tool; it's a vision for the future of big data analytics. It represents a commitment to making powerful analytics more accessible and manageable, without the overhead of traditional cluster management.

## Conclusion

AWS Serverless EMR is redefining the big data analytics space by providing a serverless environment that's easy to use, scalable, and cost-effective. It's an invitation to embrace a future where big data analytics is more about insights and innovation and less about infrastructure management.
HOW TO SAFELY RECOVER SCAM BITCOIN : DIGITAL WEB RECOVERY
Tags: recovery, bitcoin, cryptocurrency
Published: 2024-03-10 12:55:52

Thanks to Digital Web Recovery, my challenging times have come to an end. In mid-January 2024, I ventured into cryptocurrency trading after being introduced by "Miss Elizabeth," whom I believed to be a legitimate finance manager. She showcased a LinkedIn profile with over 5000+ connections and an Instagram account with 500k+ followers, instilling trust in the company. Two weeks into our discussions, she persuaded me to set up a Metamask wallet and fund it with $39k USDT, emphasizing the use of USDT to prevent fund depreciation in my investment portfolio. Believing every word she said, I invested, and she explained that the $39k was just the beginning, advocating for larger trades. Despite my suggestion to wait for the first trade's completion, she insisted on taking on more significant trades in pairs, promising higher profits. Before the larger trade, I emphasized that these were my retirement funds, expecting returns upon completion. However, things didn't go as planned. The agreed-upon 4-week trading period passed, and no funds appeared in my wallet linked to the trading website. Upon bringing this to Elizabeth’s attention, she advised filing a complaint with Care support, revealing that my account had gone negative with imposed fees of over $90k in taxes and charges. Refusing to pay, I sought help from Digital Web Recovery after learning about their ability to TRACK & RECOVER lost investments. Contacting Digital Web Recovery and providing them with transaction details, they initiated a 5-day recovery process, fulfilling their promise as my funds returned to my wallet. If you're struggling to find a trustworthy hacker, look no further; your solution is here. Reach out to the team of experts in Digital Web Recovery with the information below, they are the best in the world in terms of crypto tracing and recovery. Website https://digitalwebrecovery.com
Email; digitalwebrecovery@mail-me.com 
Telegram user; @digitalwebrecovery
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x7b6qnwqamjgzov3auuo.jpg)
AI Comic Factory
Published: 2024-03-10 12:48:48

Unleash your storytelling prowess and artistic flair with AI Comic Factory, the ultimate tool for creating captivating comics and graphic novels. Powered by cutting-edge AI technology, AI Comic Factory revolutionizes the comic creation process, making it accessible to everyone, regardless of their traditional drawing skills.

With AI Comic Factory, you can effortlessly bring your ideas to life and create visually stunning comics. Dive into a world of creativity as you design unique characters with expressive faces, dynamic poses, and intricate details using our extensive library of customizable assets. Whether you're an experienced artist or a novice, AI Comic Factory provides intuitive tools that empower you to craft captivating panels and pages.

An exceptional feature of AI Comic Factory is its AI-powered dialogue generation. Choose from a diverse range of pre-written dialogues or let the AI generate original dialogues tailored to the context of your story. This not only saves time but also adds an extra layer of authenticity and creativity to your characters' conversations.

[AI Comic Factory](https://aicomicfactory.org/) also offers a vast collection of AI-generated backgrounds and visual effects to enhance the atmosphere of your comics. From bustling cityscapes to breathtaking landscapes, you can transport your readers to immersive and visually stunning worlds with ease.

Whether you're a passionate comic artist, a writer, or simply someone with a story to tell, AI Comic Factory empowers you to unleash your imagination and create compelling comics that leave a lasting impact. Explore the endless possibilities of AI-assisted comic creation and watch as your stories come alive with vibrant visuals and engaging narratives.
PWC 259 Something I think's worthwhile if a parser makes you smile
Tags: perl, perlweeklychallenge, pwc
Published: 2024-03-10 12:41:26

Short on time this week, so just a skeleton of a post about [Perl Weekly Challenge 259](https://theweeklychallenge.org/blog/perl-weekly-challenge-259)

Task 1 is a variation on Fizz Buzz.  Count days, but skip over weekends and holidays. Use the `DateTime` module to snarf up date strings (I love the smell of ISO8601 in the morning) and  ignore pesky thoughts about leap years and daylight saving time. Play the Bee Gees [Holiday](https://www.youtube.com/watch?v=KDJ5qqiQDto) on repeat.

Task 2 is a parsing problem. We could go all computer-science on it and write some kind of lexical tokenizer and grammar with a recursive descent parser. Or we could go hack-orific with regular expressions and obscure Perl features. I think you know where I'm going with this. You'll need this [note on the flip-flop operator](https://www.effectiveperlprogramming.com/2010/11/make-exclusive-flip-flop-operators/).

The solutions are on [Github](https://github.com/boblied/perlweeklychallenge-club/tree/w259/challenge-259/bob-lied/perl).
Unveiling Amazon Bedrock: The Bedrock of Generative AI Applications
Published: 2024-03-10 12:21:47

In the ever-evolving landscape of artificial intelligence, Amazon Bedrock emerges as a beacon of innovation, offering a seamless path to building and scaling generative AI applications. This fully managed service is not just a tool; it's a game-changer for developers and businesses alike, eager to harness the power of generative AI.

## What is Amazon Bedrock?

Amazon Bedrock is a revolutionary service provided by AWS that simplifies the creation and expansion of generative AI applications. It provides access to a selection of high-performing foundation models from leading AI companies through a single API¹. But what sets Amazon Bedrock apart is its commitment to security, privacy, and responsible AI, ensuring that your applications are not only powerful but also safe and ethical.

## The Core Features of Amazon Bedrock

- **Diverse Model Selection**: Choose from a variety of foundation models tailored to your specific needs.
- **Customization at Your Fingertips**: Fine-tune and use Retrieval Augmented Generation (RAG) to tailor models to your data.
- **Serverless Convenience**: Focus on innovation without the hassle of managing infrastructure.
- **Commitment to Security**: Build with confidence, knowing that your applications are protected.

## How Amazon Bedrock is Shaping the Future

The implications of Amazon Bedrock are vast. It's not just about the technology; it's about the doors it opens. From small startups to large enterprises, Amazon Bedrock democratizes access to advanced AI, enabling a new era of creativity and problem-solving.

### The Serverless Advantage

With Amazon Bedrock, the complexities of infrastructure management are a thing of the past. The serverless experience means you can dive straight into building and deploying your AI applications, scaling effortlessly with demand.

### A New Dawn for Developers

Amazon Bedrock empowers developers to experiment, innovate, and deploy generative AI applications with unprecedented ease. Whether it's fine-tuning models or integrating AI capabilities into existing applications, Amazon Bedrock is the partner every developer dreams of.

### The Ethical Dimension

In a world where AI ethics are increasingly scrutinized, Amazon Bedrock stands out for its commitment to responsible AI. It's not just about what AI can do; it's about doing it right, with a focus on security and privacy that sets a new standard for the industry.

## Conclusion

Amazon Bedrock is more than just a service; it's a vision for the future of generative AI. It's a foundation upon which countless applications will be built, shaping a world where AI is not only powerful but also responsible and accessible to all.

As we stand on the brink of this new frontier, Amazon Bedrock invites us to step forward into a world where our creative and technological aspirations know no bounds. It's time to build, scale, and innovate. Welcome to the bedrock of generative AI! For more info please check the official documentation [HERE](https://docs.aws.amazon.com/bedrock/)!.
Pull-to-Refresh in SwiftUI
Tags: swiftui
Published: 2024-04-11 08:28:41

---
title: Pull-to-Refresh in SwiftUI
published: true
date: 2024-03-10 12:19:59 UTC
tags: SwiftUI
canonical_url: https://wesleydegroot.nl/blog/Pull-to-Refresh-in-SwiftUI
---

Pull-to-refresh is a common UI pattern in iOS apps.  
It allows users to refresh the content of a view by pulling down on it.  
In this post, we will learn how to implement pull-to-refresh in SwiftUI, using the `refreshable` modifier.

## What is `Pull-to-refresh`?

Pull-to-refresh is a common UI pattern in iOS apps that allows users to refresh the content of a view by pulling down on it.

## Use Case: Pull to refresh

Let’s start with a simple example where you have a List displaying items.  
It should also provide a pull-to-refresh gesture to update the list of items.

```swift
import SwiftUI

struct ContentView: View {
    @State private var items = [String](repeating: "Item", count: 10)

    var body: some View {
        List {
            ForEach(items, id: \.self) { item in
                Text(item)
            }
        }
        .refreshable {
            items = [String](repeating: "Refreshed items", count: 10)
        }
    }
}
```

[Download the sample code for Swift Playgrounds](https://wesleydegroot.nl/resources/pull-to-refresh.swiftpm.zip)

In the example above, we attach the refreshable view modifier to the List view, configuring the pull-to-refresh gesture.

## Wrap up

SwiftUI's `refreshable` modifier makes it easy to add pull-to-refresh to your app.

## Conclusion

In this post, we learned how to implement pull-to-refresh in SwiftUI, using the `refreshable` modifier.

Resources:

- [Apple Developer Documentation](https://developer.apple.com/documentation/swiftui/view/refreshable)