teleren/devto huggingface dataset:
Bucles de JavaScript
Tags: javascript, webdev, programming, beginners
Published: 2024-06-04 13:55:43

Últimamente he estado trabajando en una aplicación que solo cuenta con **front-end**, ya que el cliente nos proporciona en **back-end**.
 
Debido a que muchos de los datos no se nos dan de la manera exacta que necesita el front, he tenido que procesar los datos para poder mostrarlos como se requería. 

Mientras pensaba en cómo hacer ésta tarea se me pasó una duda por la cabeza:

## Cual es el bucle más eficiente en JavaScript?

Ésta pregunta tiene diferentes respuestas según lo que estemos buscando.

Seguramente lo primero que se nos viene a la cabeza es lo siguiente:


```javascript
 const arr = [...];
 let i = 0;
 while(arr.length > i){
     const element = arr[i];
     i++;
 }
```
El típico bucle **while** de toda la vida, el cual no termina hasta que la condición especificado al inicio sea cumplida. Éste bucle se usa principalmente en ocasiones en las que no se sabe de antemano la cantidad de iteraciones que se llevarán a cabo.

La principal desventaja es que es difícil de interpretar al echar un primer vistazo, y ciertamente es más lento a la hora de recorrer una array.


```javascript
 const arr = [...];
 for(let i = 0; i < arr.length; i++){
         const element = arr[i];
 }
```

El bucle **for** es otro método muy utilizado a la hora de recorrer una array. Éste funciona de una manera similar al **while**, ya que creamos una variable, en cada iteración comprobamos una condición y finalmente pasamos a la siguiente iteración. 

La ventaja que tiene éste bucle en comparación al **while**, es que es más sencillo de interpretar.

El **for** es una buena opción a la hora de recorrer un array, mientras que el **while** no es muy eficiente, pero mi principal problema era que la aplicación debía ser lo más rápida posible. 

Entonces se me ocurrió la siguiente idea:
```javascript
 const new_array = array_imgs.map((imgs)=>{
     for (let i = 0; i < imgs.length; i++) {
         const element = imgs[i];
         if (element.id == item.id) {
             return expedient.image = element.imagen;
         }             
     }
     return item.img = null;
})
```
Debido a que estaba tratando con imagenes, las cuales son pesadas y costosas de procesar, necesitaba que el bucle hiciera las mínimas iteraciones posibles. 

Se me ocurrió recorrer el array con la función map(). La cual según estuve investigando, es la manera más rápida de recorrer un array (aparte de la función forEach() del propio array), además me permitía modificar crear un array nuevo con los datos nuevos y hacer las mínimas iteraciones. 

Fué la manera más eficiente que se me pasó por la cabeza. Tras probar varios métodos, puedo decir que es el mejor que he probado.

## Solución de chat-gpt

También se me ocurrió preguntar a chat-gpt la solución a mi problema y me ha presentado lo siguiente:


```javascript
 array_imgs.forEach((imgs) => {
    const element = imgs.find(element => element.id === item.id);
    if (element) {
        expedient.image = element.imagen;
    } else {
        item.img = null;
    }
});

```

Se te ocurre alguna idea mejor? Déjamelo en los comentarios!!
Buy PVA Google Voice Accounts
Tags: gmail, communication, email, googlevoice
Published: 2024-06-04 13:54:51

Hello friends. In this blog post I want to share some piece of information and this informations are going to help you in [buying Google Voice accounts](https://pvamails.com/pva-google-voice-accounts-pva-mails-copy/) and [Gmail accounts.](https://pvamails.com/old-accounts/)

If you have any type of question related to Google voice then visit this website ([PVAMails](pvamails.com)) or you if you want to contact us then contact us through our email. rsbukhari2@gmail.com

As we all know that Gmail is one of the best source for communication. Gmail is a service that is provided by Google and has millions of users in the world.

However, if you're looking to buy Google voice accounts then PVAMails can be a perfect choice for you. 

At PVAMails. We offer high quality Google Voice Accounts at a affordable prices. Moreover, we offer numerous packages of voice accounts. So you can choose the one that suits you well.

**What PVAMails Offers**

- Fully Verified Accounts

- Unique IP Created

- 2 days warranty

- Recovery Email Added

- Instant Delivery

**What is Google Voice Accounts and What are the Benefits of Buying Google Voice Accounts?**

Google Voice is a telephony service that provides users with a unique phone number, enabling them to make and receive calls, send text messages, and manage voicemail. Integrated seamlessly with Gmail, Google Voice offers a unified communication platform that simplifies and streamlines interactions.

Additionally, there are many key benefits of Google Voice Accounts. Like it supports multi-device access which enables you to use it on your phone, computer and tablet. Another key feature, you can port your existing number to their service. It means you can continue with your current number all the features that it offers. 

Moreover, it is also cost effective and also offers user-friendly interface. 

Thanks for reading the article. 

For more info, please visit the given site below.
Desarrollo de Software: Mantén la Motivación y Estudia de Manera Inteligente
Published: 2024-06-04 13:52:50



En el emocionante camino del desarrollo de software, la motivación y la eficiencia en el estudio son clave para el éxito. Descubre estrategias efectivas para mantener el impulso y optimizar tu aprendizaje en este viaje digital.

1. **Establece Metas Claras:** Define metas específicas y alcanzables. Establecer hitos claros te dará dirección y un sentido tangible de logro a medida que avanzas en tu aprendizaje.

2. **Diversifica tus Fuentes de Aprendizaje:** Explora una variedad de recursos: libros, tutoriales en línea, proyectos prácticos. Mantente al día con las últimas tendencias y tecnologías para enriquecer tu conocimiento.

3. **Planifica Descansos y Recompensas:** Rompe el estudio en bloques con pausas cortas. Premia tu esfuerzo con pequeñas recompensas para mantener la motivación y reducir la fatiga.

4. **Practica a Través de Proyectos Reales:** Aplica lo que aprendes en proyectos prácticos. Construir aplicaciones reales no solo refuerza tus habilidades, sino que también hace que el aprendizaje sea más emocionante y significativo.

5. **Aprende de la Comunidad:** Únete a comunidades en línea y participa en foros. Compartir experiencias y aprender de otros puede inspirarte y proporcionarte soluciones a desafíos comunes.

6. **Optimiza tu Entorno de Estudio:** Crea un espacio de estudio cómodo y libre de distracciones. La organización y la tranquilidad contribuyen a un ambiente propicio para el aprendizaje.

7. **Utiliza Herramientas de Gestión del Tiempo:** Emplea técnicas como la Técnica Pomodoro para gestionar el tiempo efectivamente. Establecer intervalos de trabajo y descanso maximiza la concentración y la productividad.

8. **Celebra Pequeños Logros:** Reconoce y celebra cada hito alcanzado. Esto refuerza la sensación de progreso y mantiene la motivación a largo plazo.

9. **Actualiza tus Conocimientos Constantemente:** El desarrollo de software evoluciona rápidamente. Programa momentos regulares para actualizar tus habilidades y mantenerte al tanto de las últimas tendencias.

10. **Cuida de tu Bienestar:** No subestimes la importancia del descanso, la alimentación y el ejercicio. Un cuerpo y mente saludables son fundamentales para el aprendizaje sostenible.

Mantén viva la pasión por el desarrollo de software mediante un enfoque inteligente y motivado. ¡Con estas estrategias, estarás listo para enfrentar cualquier desafío y alcanzar tus metas de manera efectiva en el vasto mundo del desarrollo tecnológico! 🚀📚
Tips and Tricks for Visual Studio Code
Tags: vscode, softwaredevelopment, beginners
Published: 2024-06-04 13:52:33


Terminal info:
-Our standard bash prompt environment for entering commands like rake grade or bin/server
-Pry for interacting with a database (we could also run rails console for that)
-Irb for typing in pure Ruby code

Commands:
   -Reopen a pane
        -Left
            Mac OS: ⌘ + B
            Windows: Ctrl + B
        -Bottom
            Mac OS: ⌘ + J
            Windows: Ctrl + J

   -Clear Terminal
        Mac OS: ⌘ + K
        Windows: Ctrl + K

   -Interrupt command
        Mac OS: ⌘ + C
        Windows: Ctrl + C

   -Quick Open file
        Mac OS: ⌘ + P
        Windows: Ctrl + P

   -Command Palette
        Mac OS: ⌘ + Shift + P
        Windows: Ctrl + Shift + P

   -Jump to end of line
        Mac OS: ⌘ + E
        Windows: Ctrl + E

   -Exit
        Mac OS: Q
        Windows: Q

   -Toggle Code
        Mac OS: ⌘ + /
        Windows: Ctrl + /

   -Find Next Selection
        Mac OS: Command + D
        Windows: Ctrl + D    

   -Move line
        Mac OS: Option + ⬇
        Windows: Alt + ⬇

   -Duplicate line
        Mac OS: Shift + Option + ⬇
        Windows: Shift + Alt + ⬇

Other:
    -rails console = opens an interactive Ruby environment with your Rails application's context-loaded
    -reload! = reload the application's code without exiting the console
How do I start to incorporate AI into my business?
Tags: ai, softwaredevelopment, aiempowerment
Published: 2024-06-04 20:03:07

---
title: How do I start to incorporate AI into my business?
published: true
date: 2024-06-04 13:51:58 UTC
tags: ArtificialIntelligence,SoftwareDevelopment,AI,AIEmpowerment
canonical_url: https://blog.jonathanflower.com/artificial-intelligence/how-do-i-start-to-incorporate-ai-into-my-business/
---

## 1. Spend at least 10 minutes playing with ChatGPT

1. Start chatting without needing to signup: [https://chat.openai.com/](https://chat.openai.com/)
2. Type whatever comes to mind. A few ideas to get the conversation started:
  - What were the last few things you Googled? Try typing those into ChatGPT.
  - What is a topic you are curious about? Ask ChatGPT to tell you about it.
  - Try to stump it by asking a hard question in your field of expertise.
3. There are a ton of AI tools out there. I suggest starting with ChatGPT because it is free and the best for many things.

## 2. Is it magic or an idiot?

1. This is largely dependent on the questions you asked and how you phrased them. The question is what types of questions can it answer, and how do I ask my questions in a way that helps it respond well?
2. The simplest advice is to imagine ChatGPT is a high school intern who has memorized the internet. Technically I don’t agree with personifying ChatGPT, but I have not found a better way to guide people with a simple concept. Let’s imagine giving a high school intern very brief instructions. Who knows what you are going to get from them! If you take the time to explain the goal, steps, any other relevant details or expectations, then you will be surprised if you don’t receive back something you can use or at least provide feedback on so that they can improve.

## 3. Practical uses

1. Now that you have some basic concepts, it is time to explore how it might be able to speed or enhance your work. You are on your way to becoming AI empowered.
2. We started this post with a question: “How do I start to incorporate AI into my business?” This is a perfect question to ask ChatGPT.

```
   I am in the [insert your industry] industry and my role is a [insert your role]. How do I start to incorporate AI in my business?
```

## 4. Ask ChatGPT to give you a lot of ideas for prompts:

```
   I am a [insert your profession]. Give me 50 ChatGPT prompts that can help me be more productive in my job.
```

## Privacy

As you start to use ChatGPT, you should be cautious about uploading documents or entering text with sensitive information. Do not enter anything sensitive. The free version of ChatGPT will use this information to train their models. Here is a guide on how to protect your private information: [How to Protect Your Data with ChatGPT | Jonathan Flower posted on the topic | LinkedIn](https://www.linkedin.com/posts/jonathan-flower_ai-chatgpt-codingtools-activity-7201957443331919876-6-0m?utm_source=share&utm_medium=member_desktop)
k8s Executor 적용기(1)
Tags: airflow, datapipeline, k8s
Published: 2024-06-04 13:49:55

## 1. 발단

airflow에 대해 잘 모르던 시기에 사정상 내가 구축하지 않은 시스템을 유지보수할 일이 생겼다. 

airflow를 좀 아는 팀원이랑 같이 가서 살펴보니 celery executor를 사용하는 전통적인(?) airflow 구조였음.

![celery architecture](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zf43cunpmyx5r8ekkty5.png) 

scheduler가 job을 배치하고, worker가 가져가서 수행한다는 전형적인 구조인데,
시스템에 문제가 생긴 이유는 RabbitMQ의 네트워크 문제.

실제로는 scheduler, worker, webserver가 동일망이었으니, 그림은 이렇게 됨.

![celery fault](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nqsvjpa1tgivs25wzmw1.png)

airflow 또한 systemctl로 올라가 있었는데, systemctl retry가 안돼서인지 뭔지 worker가 모두 죽어버린 상황.

담당자는 이 사실을 모른 채로 꽤 많은 시간이 지났고...뭐 어쨌거나 근본적인 원인분석이 됐으니 차후에 다시 기동하는 등의 사건 등이 있었으나 중요한 건 이 다음에 든 의문이었다.

**왜 굳이 이렇게 구성해야 하는가?** 하는 의문....
<br>
<br>

## 2. 고민
사실 내가 airflow에 대해 무지한 면이 많았으므로 애초에 왜 메시지큐를 사용해야 했는가 하는 의문부터 출발한 것인데, 

celery 기반의 airflow scheduler는 task를 job으로 만들어서 MQ에다 하나씩 던져준다.

![scheduler](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yxhws1qq8fki8jbdvwnd.png)

이렇게 구성하면 장점은

1) 많은 수의 job을 병렬 처리할 수 있다.
2) 전체적인 작업 capacity가 늘어난다.
3) worker가 분산처리되므로 자원분배 측면에서 리소스를 잘 활용할 수 있다.


단점은

1) 관리포인트가 늘어난다.
2) 유지보수에서 봐야 되는 것들이 더 늘어난다. (남의 시스템이라 더 모르겠더라.. )
3) worker, scheduler, webserver 등을 다 따로 체크해야 한다.
(솔직히 관리포인트 말고는 별 차이는 없지만, 다른 아키텍쳐를 써보고 싶은 마음이 컸다. 이거 대부분 k8s 쓰면 해결은 됨.)
<br>
<br>

## 3. 해답

- 팀원한테 좀 징징대봤다.
- 아 우리 어차피 pipeline도 얼마없는데 관리도 힘든 MQ 꼭 써야돼요?
  ( 나는 MQ에 대한 슬픈 사건이 꽤 많다... )
- 이거 안쓰고 localexecutor 같은건 문제가 있겠죠? 이건 안되겠고.


이러한 질문에 팀원이 대답해줬다.

**어 그거 라인인가 어딘가에서 k8s executor라고 쓰던데요.**


찾아보니
1) worker=pod이라서 MQ 없어도 되고
2) k8s 환경에서 선형적으로 작업량 늘어나도 분산처리 쉽고
3) image로 소스 처리하니까 CI/CD 쓸수있어요.

대략 이런 구조가 된다.
![k8s executor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7nee2jc4tcwr9tejedqj.png)

scheduler는 task를 job으로 만들고, 해당 job 하나하나는 해당하는 소스(이미지)를 불러와서 pod으로 기동된다.

우리는 하버를 쓰기때문에 배포할 수도 있고, 나중에는 확장해서 CI/CD까지 노려볼 수 있었다. 내가 그렇게 하고 싶어하던 전체 자동화!

**안 할 이유가 없다**

라고 생각했고, 안이한 생각이었음을 뒤늦게 깨닫게 된다....
How to Deploy Flutter Apps to the Google Play Store and App Store
Tags: webdev, flutterapps, deploy, development
Published: 2024-06-04 13:48:50

Today, we embark on an adventure – a journey to launch your captivating [Flutter app onto the vast landscapes of the Google Play Store and App Store](https://www.devitpl.com/application-development/how-to-deploy-flutter-apps-to-the-google-play-store-and-app-store/).

This comprehensive guide will be your trusty compass, guiding you through the essential steps of deploying your app on both prominent platforms. Whether you’re a seasoned developer or a curious newcomer, this guide is here to demystify the process and ensure a smooth [application deployment](https://www.devitpl.com/application-development/) for your creation.
Power BI Dashboard: Ultimate Tool for Dynamic Data Visualization and Storytelling
Tags: powerbi, dashboard, bi, microsoft
Published: 2024-06-04 13:45:11

Are you ready to unleash the [power of data storytelling with Power BI](https://www.devitpl.com/microsoft-power-platform/power-bi-dashboard-ultimate-tool-for-dynamic-data-visualization-and-storytelling/)? Take the first step today and embark on a journey of data discovery. Explore the vast potential of Power BI and watch your data transform from a silent collection of numbers into a chorus of insights that drive success!
Another Framework What's So Special About It ?
Tags: webdev, javascript, ui, library
Published: 2024-06-04 13:32:04

I've been dreaming of a ui library that lets me use declarative javascript.

Okay, but what do i mean cause every framework/library calls itself declarative.

I mean by this !
`ui.addButton(parent, text, width, height, options)`

And not jsx or a compiled framework. The mission is to keep the core library code under a 1000 lines of code.

---

innerscope's mission is to provide a set of core functions that can be extended to build custom components or port a whole design system to it.

Another design decision is we use a classes, its just to reduce js common pitfalls.

All you have to do is and the typical `index.html` file
And a companion `App.js` file.

_check the github page about this and its set-up_

How it works is I use a concept of layouts, layouts are div's but with special styles like `flex-start` and `flex-end`.

A layout is called like :

`ui.createLayout(layoutType, options)`

There are 4 types of layouts :

- Linear
- Absolute
- Card
- Frame

And don't forget to add it to your page via, `ui.addLayout()` function.

---

Writing Components & Sharing Them

Firstly i decided to create a class `ElementComposer` this class allows you to create components using this similar syntax and will inherit methods like ( setMargins / setPosition / show & hide ).

You can extend these methods by adding your own, but check the syntax rules.

When adding your components, you can load your additional scripts and css via the `ui.loadScript()` and `ui.loadCSS()`.

Writing components is done in js, so that means you use the 
`document.createElement()` api.
And finally add it to the composer div.

---

And you can write your ui in javascript, on top of that you can use this in production.
I've published it on npmjs.com and add as a script tag at unpkg.com.

[https://github.com/oarabiledev/innerscope](Here is my framework (✿◡‿◡))

Thank You For The Interest ❣️❣️❣️❣️
User Authorization with Postgres Row Level Security Policy
Tags: postgres, sql, database, security
Published: 2024-06-04 13:31:02

Supabase has a [storage gateway](https://github.com/supabase/storage) that uses [RLS](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) for authorization.

It requires a JWT that provides the role information to perform the SQL, here is an example of the JWT payload:

```json
{
  "sub": "authenticated",
  "iat": 1516239022,
  "role": "f918ffd9-a611-4b2a-b4bb-df8f25d7569f"
}
```

The storage bucket table is:

```
                        Table "storage.buckets"
   Column   |           Type           | Collation | Nullable | Default 
------------+--------------------------+-----------+----------+---------
 id         | text                     |           | not null | 
 name       | text                     |           | not null | 
 owner      | uuid                     |           |          | 
 created_at | timestamp with time zone |           |          | now()
 updated_at | timestamp with time zone |           |          | now()
```

You only need to set up the correct RLS policy in the database. Here is an example:

```sql
-- generate a UUID as the role name since it needs to match the owner type
SELECT gen_random_uuid(); -- f918ffd9-a611-4b2a-b4bb-df8f25d7569f

CREATE ROLE "f918ffd9-a611-4b2a-b4bb-df8f25d7569f";
GRANT all ON schema storage TO "f918ffd9-a611-4b2a-b4bb-df8f25d7569f";
GRANT all on buckets TO "f918ffd9-a611-4b2a-b4bb-df8f25d7569f";
-- generate another role
CREATE ROLE "11b795e0-a566-491b-9ee7-62c025175dd8";
GRANT all ON schema storage TO "11b795e0-a566-491b-9ee7-62c025175dd8";
GRANT all on buckets TO "11b795e0-a566-491b-9ee7-62c025175dd8";

CREATE OR REPLACE FUNCTION user_record_count(uuid) RETURNS integer AS $$
DECLARE
    count integer;
BEGIN
    SELECT COUNT(*) INTO count
    FROM buckets
    WHERE owner = $1;
    
    RETURN count;
END;
$$ LANGUAGE plpgsql;

CREATE POLICY limit_user_crud ON buckets
    USING (owner = current_user::uuid)
    WITH CHECK (
        (SELECT user_record_count(current_user::uuid) < 3)
    );

SET ROLE "f918ffd9-a611-4b2a-b4bb-df8f25d7569f";

INSERT INTO buckets (id, name, owner) VALUES ('1', 'one', current_user::uuid);
INSERT INTO buckets (id, name, owner) VALUES ('2', 'two', current_user::uuid);
INSERT INTO buckets (id, name, owner) VALUES ('3', 'three', current_user::uuid);
-- check before the insertion
INSERT INTO buckets (id, name, owner) VALUES ('4', 'four', current_user::uuid); -- ERROR:  new row violates row-level security policy for table "buckets"
SELECT * FROM buckets; -- this returns 3 rows

SET role "11b795e0-a566-491b-9ee7-62c025175dd8";
SELECT * FROM buckets; -- this returns nothing
INSERT INTO buckets (id, name, owner) VALUES ('4', 'four', current_user::uuid); -- success
DELETE FROM buckets where id = '4'; -- success
DELETE FROM buckets where id = '1'; -- delete 0
```
Here are 14 essential design principles for microservices:
Tags: webdev, beginners, programming, tutorial
Published: 2024-06-04 13:30:15

1. Interface Segregation: Different types of clients (e.g., mobile apps, web apps, CLI programs) should be able to interact with services through the contract that best suits their needs.

2. Deployability: In the microservice era, developers need to make critical design decisions and technology choices regarding packaging, deploying, and running microservices.

3. Event-Driven: Services should be modeled to be activated by asynchronous messages or events instead of synchronous calls.

4. Availability Over Consistency: End users often value the availability of the system over strong data consistency, and they are okay with eventual consistency.

5. Loose Coupling: Microservices should not have a tight dependency on each other to ensure scalability and ease of deployment.

6. Single Responsibility: Each microservice should have a single, well-defined responsibility and should only communicate with other microservices to accomplish tasks.

7. Decentralized Data Management: Each microservice should manage its data without relying on other microservices to ensure scalability and reliability.

8. API-Driven Design: Microservices should be designed around APIs, with each service exposing a well-defined set of APIs for communication with other services.

9. Statelessness: Microservices should be stateless, meaning they should not maintain any client-specific state between requests.

10. Independent and Autonomous/Self-Governing Services: Each microservice should be self-contained and operate independently of all other services in an application.

11. API Aggregation: Microservices should be designed to aggregate APIs for communication with other services.

12. Flexibility: Microservices should be designed to be flexible and adaptable to changing requirements.

13. Scalability: Microservices should be designed to scale independently and handle increased load.

14. Constant Monitoring and Failure Isolation/Resilience: Microservices should be constantly monitored and designed to isolate failures to ensure the overall system remains available and resilient.

These principles help ensure that microservices are designed to be scalable, reliable, and maintainable, making them essential for building robust and efficient microservices-based applications.