teleren/devto huggingface dataset:
Aliased Associations Ruby on Rails
Published: 2023-03-16 20:43:07

     
In Ruby on Rails, foreign keys are used to establish associations between different models. They allow you to link records in one table to records in another table. These foreign keys create relationships between tables. Although sometimes you may need to have two different keys from the same model in a new model. In this blog post, I'm going to briefly demonstrate how to use foreign keys in Ruby on Rails to do it.

Let's say you have a "User" model, and you want to create a new model called "Meeting" to store information about meetings between users. Each user will have need a unique foreign key. Lets call the foreign keys "sender_id" and "receiver_id". Both of which will use the "id" column in the "User" model.

Now the first place to start when must creating this association is the new model.

Create the "Meeting" model: 

First, we need to create a new model called "Meeting" using the Rails generator:

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

This will create a new migration file for the "Meeting" model. Now we need to go into the migration file to update that before migrating.

Update the migration file:

Now we need to update the migration file to have foreign keys. One for the user receiving the meeting and one for the user sending the meeting. The foreign keys of "receiver_id" and "sender_id" will allow the user id to be passed as an alias to the meeting table twice one user as a receiver and one user as a sender.

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

Then run "rail db:migrate"

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

Update the models:

Finally, we need to update the "User" and "Meeting" models to establish the associations between them:


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

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

In the "User" model, we have two "has_many" associations with the "Meeting" model. The "has_many :sent_meetings" and "has_many :received_meetings" They both point to the class name of "Meeting" and have unique foreign keys. 

In the "Meeting" model, it has two "belongs_to" associations with the "User" model. We used the "class_name" option to specify the name of the associated model, and specified it to use the same foreign key that associates with it from the "User" model.

Now you can create and retrieve meetings between users. With each Meeting having two foreign keys from the "User" model you can now call "user.received_meetings" or "user.sent_meetings" to retrieve the associated data. As always still a student so I am still learning but hopefully this has been helpful.
Como mover os discos virtuais do WSL2
Tags: wsl2, windows, ubuntu, linux
Published: 2023-03-16 20:42:52

Para quem gosta de manter seus arquivos em partições ou mesmo em discos separados, o Windows não ajuda muito na hora da instalação das distribuições Linux utilizando o WSL, e para fazermos essa migração só precisamos seguir alguns passos bem simples.

Mas antes, vamos listar as distribuições instaladas para escolhermos quais serão movidas:

```
wsl -l
Distribuições do Subsistema do Windows para Linux:
docker-desktop (Padrão)
Ubuntu-22.04
docker-desktop-data
```

Agora vamos fazer o processo de exportação da distribuição para um arquivo .tar.

Depois será necessário remover o registro dessa distribuição do WSL e por fim, reimportar informando o novo local de destino.

```
wsl --export Ubuntu-22.04 Ubuntu-22.04.tar
wsl --unregister Ubuntu-22.04
wsl --import Ubuntu-22.04 .\path\destino .\Ubuntu-22.04.tar
```

Atenção: a nova instância será redefinida para o usuário root. Caso tenha criado algum usuário antes, e queira continuar usando o mesmo, faça o seguinte:

```
cd HKCU:\

set-location -path HKCU:\Software\Microsoft\Windows\CurrentVersion\Lxss\

Get-childitem -recurse -ErrorAction SilentlyContinue | Get-ItemProperty | Where-Object {$_.DistributionName -like "Ubuntu-22.04"} | Set-Itemproperty -Name DefaultUid -Value 1000
```

E assim finalizamos essa primeira, de muitas, dicas.

Espero ter ajudado e até a próxima.

Ops! Já ia me esquecendo... Você também pode usar o script do #PowerShell que fiz para agilizar esse processo. ;)

{% embed https://gist.github.com/marksduarte/f6528f1d0485bbca636fbfeca6ba7687.js %}
Weekly Challenge #3 - Music Visualizer
Tags: weeklychallenge, beginners, codenewbie
Published: 2023-03-16 19:50:34

---
title: Weekly Challenge #3 - Music Visualizer
series: Weekly Challenge
published: true
tags: weeklychallenge, beginner, codenewbie
# cover_image: https://direct_url_to_image.jpg
---
Hey everyone! For this week's programming challenge, I'll challenge you to create a music visualizer. 

A music visualizer is a visual representation of a song as it's playing. It can pulse and change colors based on the rhythm, frequency, and tempo of the music. Creating a music visualizer is a great way to practice your skills with audio, graphics, and real-time programming. 

The key is to continuously analyze the playing audio and use that to influence how the visuals change and animate. With some experimentation, you can create a really interesting synced music visualizer!

If you want to expand after finishing the basics, think about incorporating interactivity. You can allow the user to customize the visuals by selecting different color schemes, visual elements, or themes. The user can also directly manipulate the visuals by dragging, scaling, or rotating visual elements. Adding interactivity makes the music visualizer more engaging and fun to interact with!

Here's a great example from a user here on DEV: 
{% embed https://dev.to/sirhamy/updates-to-my-vanillajs-audio-visualizer-consistency-across-processor-speeds-smooth-dom-animations-and-real-time-adaptation-39j1 %}

As this Weekly Challenge series racks up in entries, don't feel like you have to stay stuck on the challenge of the week. Feel free to go back and try any of the others challenges we've suggested. 

The DEV Team and I will be in the comments to moderate the challenges and provide our support!

Have fun and good luck!
Resolvendo problemas no HackerRank: Salve o prisioneiro!!!
Tags: javascript, beginners, programming
Published: 2023-03-16 19:49:17

Olá, seja bem vindo a mais um Resolvendo problemas no HackerRank: no problema precisamos salvar um prisioneiro de uma cadeia, que irá receber um doce "surpresa". Vejamos agora.

**Save the Prisoner! -**

Uma prisão tem vários prisioneiros e várias guloseimas para distribuir a eles. O carcereiro decide que a maneira mais justa de dividir as guloseimas é sentar os prisioneiros em torno de uma mesa circular em cadeiras numeradas sequencialmente. Um número de cadeira será sorteado de um chapéu. Começando com o prisioneiro naquela cadeira, um doce será entregue a cada prisioneiro sequencialmente ao redor da mesa até que todos tenham sido distribuídos.

O carcereiro porém está brincando com eles. O último pedaço de doce se parece com todos os outros, mas tem um gosto horrível .Devemos determinar o número da cadeira ocupada pelo prisioneiro que receberá aquele doce.

- n =4 // número de prisioneiros
- m =6 // número de doces
- s =2 // número da cadeira que começa a distribuição

Vejamos agora um exemplo. A primeira linha representa o número de testes feitos, já a segunda tem três espaços de números:

```
2(número de testes)
n m s
5 2 1
5 2 2
n m s 
```

O resultado será 2 e 3, pois a contagem iniciará na primeira no 1, como primeiro a receber o doce e terminarão os doces no  2 que será o premiado. O mesmo se aplica ao segundo caso.

Vejamos a criação do algoritmo:

```
function saveThePrisoner(n, m, s) {
    // Write your code here
    //n=numero de prisioneiros;m=numero de doces;s=cadeira a avisar!
 
  let warnPrisoner  = m % n;
  
    if ((warnPrisoner + s -1) % n == 0){
      return n;
    }
    else{ 
      return ((warnPrisoner + s -1)%n);
    }
}
```

O resultado será:

```
2
7 19 2
3 7 3

//result is:
6
3
```

Com isso, concluímos mais um desafio do _Resolvendo problemas no HackerRank:_ . Até a próxima!!!
Is Microsoft Designer here to compete Canva or Figma?
Tags: microsoftdesigner, canva, figma
Published: 2023-03-16 19:45:45

Microsoft designer just launch it's early access and I got the chance to use the designer, We know there is a huge market for web based designer platforms as **Adobe **is trying to acquire **Figma **for its large customer base and there are lot of products that are trying to capture these market shares and now we have a monopoly orient business model company like Microsoft that is trying the same thing and here my thoughts on this designer product;
You need to improve the product a lot, as I am also a canvas developer I can say this type of prototype is now being developed by students as their Semester Projects key features like
1. Templates
2. Customization
3. Collaboration
4. Integration

needs more improvement so I would for now stick to Canva and Figma for designing purposes.
How to use gif.js from CDN
Tags: javascript, animatedgif, gifjs, tutorial
Published: 2023-03-16 16:44:14

If you want to use the GIF.js library from a CDN in your web project, you can follow these steps:

## Step 1: Add the GIF.js library to your project.

Add the following code to the head section of your HTML file.
```html
<script src="https://cdn.jsdelivr.net/npm/gif.js@0.2.0/dist/gif.min.js"></script>
```

Alternatively, you can use ES6 import syntax to import the library.
```javascript
import 'https://cdn.jsdelivr.net/npm/gif.js@0.2.0/dist/gif.min.js';
```

## Step 2: Set up a GIF instance.

Get the container element that will hold your visualizations.

```javascript
let container = document.getElementById("my-container");
```

Now we need to fetch the worker script from the CDN because modern web browsers have security restrictions that require the worker script to be loaded from the same origin as the web page. So, we fetch the worker script and use URL.createObjectURL to create a Blob URL, which ensures that the worker script
is loaded from the same origin as the web page.

```javascript
let gifLoading = fetch('https://cdn.jsdelivr.net/npm/gif.js@0.2.0/dist/gif.worker.js')
  .then((response) => {
    if (!response.ok)
      throw new Error("Network response was not OK");
    return response.blob();
  })
```

Create a new instance of GIF and configure it.

```javascript
  .then(workerBlob => {
    let gif = new GIF({
      workers: 4,
      workerScript: URL.createObjectURL(workerBlob),
      quality: 10,
      width: container.clientWidth,
      height: container.clientHeight
    });
```

Set up the 'finished' event listener for the GIF.js instance. This will open the GIF in a new tab when the GIF is completed.

```javascript
    gif.on('finished', function(blob) {
      window.open(URL.createObjectURL(blob));
    });

    return gif;
  });
```

## Step 3: Use the GIF.js instance.

Now you can use the GIF.js instance to create your GIF. First, add your visualizations to the container element and call the addFrame method for each frame.

```javascript
gifLoading.then(gif => {

  // Add visualization frames to the container element
  // ...

  // Add frames to GIF
  gif.addFrame(container, { delay: 100 });

  // Repeat ...

  // Call the `render` method to generate the GIF
  gif.render();
});
```

That's it! You can now use GIF.js to create animated GIFs from your visualizations.
Need help in My Project ?
Published: 2023-03-16 19:26:07

Let me brief about my Project 

The project is I have created a chrome extension IN html,Css and Javascript that exports the cookie and also imports the cookie locally...Suppose there are two different computers and I just exported the cookie of xyz.com and send it to other computer and import that cookie so I can login the xyz.com without password but there is a lot of hassle here to give the cookies to another person.to Tackle this What I need to setup a Server When a use login into my extension he can exports his browser cookies to the server and the server will store it and Whenever the second persons needs it He Can import cookies to his Browser.So Can anyone help me to setup this thing ?
Started cloudprojectbootcamp.com
Published: 2023-03-16 19:25:42

# Week 0 — Billing and Architecture

Before the bootcamp, I had already registered a domain and created a hosted zone using Amazon Route53 on my main AWS account. Follow this [documentation](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-register.html)



Once you log into your [Student portal](https://student.cloudprojectbootcamp.com/users/sign_in), From the Resources section, you watch all the [Video Instructional Content Playlist](https://www.youtube.com/watch?v=8b8SvQHc4Pk&list=PLBfufR7vyJJ7k25byhRXJldB5AiwgNnWv) 

- You can also watch the same, Click on Submissions, Week 0, From the ToDo List. Proceed with setting up of things that you need for this bootcamp as per the instructions given in the videos.
- update the Checklist

# Required Homework/Tasks

## 1. Create a Github Account 

As I already have [my Github Account](https://github.com/awsmine), I did not create a new one.

  * 1b. I setup a MFA on my GitHub account for extra security. 
[aws-bootcamp-cruddur-2023/journal/assets/week_0_user_bobby_setup_MFA](https://github.com/awsmine/aws-bootcamp-cruddur-2023/blob/main/journal/assets/week_0_user_bobby_setup_MFA.pdf)


**2.** Create a Free Gitpod Account which is used for Cloud Developer Environment (CDE) to work with the code.

**3.** I got the Gitpod Button on my Github Account. 

**4.** Create Gitpod Codespaces, in case the I used up all the Gitpod free-tier.


Once the repository was created


















# Architecture Diagram

Here is the link to my Logical Diagram from Lucid Chart
https://lucid.app/lucidchart/61cf470e-1feb-42c5-afdb-792fb1e4fb85/view?page=0_0&invitationId=inv_4088e3a2-9db3-4c69-951d-5895298985bc#

Here is my Conceptual Diagram from Luci Chart
https://lucid.app/lucidchart/540635e4-8c10-4855-9d62-652763d2a6c1/view?page=0_0&invitationId=inv_02a3c339-9428-4489-a816-8313cbfd28d8#

Here is link to my Logical CI/CD Diagram from Lucid Chart
https://lucid.app/lucidchart/3f5a105a-3ee6-4af9-b150-e1fc58b1b895/view?page=0_0&invitationId=inv_89d37443-e0b0-46a7-902d-63f22edd1de3#
🚀 Configure Vitest with React Testing Library 🚀
Tags: react, vite, test
Published: 2023-03-16 19:23:30

---
title: 🚀 Configure Vitest with React Testing Library 🚀
published: true
description: Make your development workflow 1000X faster with Vitest + React testing library
tags: react, vite, test
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6sybbuekz0sd6gkn8xvr.png
---

It is 2023 and we have so many options to create a react app that it can be hard to choose between tools, but most people are choosing Vite because of its simplicity and speed. If you are one of those people and are looking for an easy way to setup your tests, you came to the right place!

Let's go right to the point with setting up a new application:

## Create a new React app with Vite:

```
yarn create vite
```

## Install the dependencies

```
yarn
```

## Install the necessary dependencies

```
yarn add -D vitest jsdom @testing-library/react @testing-library/jest-dom
```

## Add a `test` script

In your `package.json` file, add the following line under the `scripts` attribute:

```diff
"scripts": {
+  "test": "vitest"
}
```

## Create a setup tests file

Create a new file under `tests/setup.ts` with the following content:

```ts
import { expect, afterEach } from 'vitest';
import { cleanup } from '@testing-library/react';
import matchers from '@testing-library/jest-dom/matchers';

expect.extend(matchers);

afterEach(() => {
  cleanup();
});
```

## Configure vite to use this setup

Edit the file `vite.config.js` in the root folder

```diff
  plugins: [react()],
+  test: {
+    environment: 'jsdom',
+    setupFiles: ['./tests/setup.ts'],
+    testMatch: ['./tests/**/*.test.tsx'],
+    globals: true
+  }
```

That is all the configuration needed.
Now, let's go ahead and create a quick test to try this out

## Your first test

Create a test file at `tests/App.test.tsx`

```
touch tests/App.test.tsx
```

### Add the following content

```tsx
import { render, screen } from '@testing-library/react';
import App from "../src/App";


describe('App', () => {
  it('renders headline', () => {
    render(<App />);
    const headline = screen.getByText(/It works and you found me!/i);
    expect(headline).toBeInTheDocument();
  });
});
```

### Run the tests (and expect to fail)

```
yarn test
```


## Fix the test

Replace the html content of the `App.tsx` file with the following:

```diff
+  return (
+    <div>
+      <h1>It works and you found me!</h1>
+    </div>
+  )
```

## Run the tests

Try running again the tests, it should be working fine now!

![it works](https://media.giphy.com/media/Z97CalNlWHQNTdVSZ7/giphy-downsized-large.gif)
Not open project React native
Tags: reactnative
Published: 2023-03-16 19:03:43

Guys hello.

I change the project´s folder and after not workking the mobile simulator android.
please help me fix this error. 

 "To reload the app press "r"
To open developer menu press "d"

warn No apps connected. Sending "devMenu" to all React Native apps failed. Make sure your app is running in the simulator or on a phone connected via USB.
info Opening developer menu..."

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1w8raqk6wrtzgnsgdrjm.png)
```
What can we do to create a healthier workplace culture?
Tags: wecoded, career, discuss
Published: 2023-03-16 18:42:50

---
title: What can we do to create a healthier workplace culture?
published: true
description: 
tags: wecoded, career, discuss
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dfr46h0y22wjdr2oj0wl.png

---
A healthy workplace culture is one where employees feel engaged, supported, and have the resources to thrive. It provides opportunities to socialize and enables employees to open up and get to know one another. It celebrates both team and individual wins, big and small. Whether it's a successful project launch or someone's work anniversary, a healthy workplace culture finds reasons to bring positivity and joy into the workplace.

Inclusion is part of building a healthy workplace. Our workplaces need to address issues like interpersonal conflict or toxic behaviors promptly and professionally. A healthy culture depends on a respectful work environment free from harassment. Working to make our workplaces inclusive is essential not just for productivity and retention, but real bonding and relationship building between colleagues.

So I'd like to ask: 
###What can we do to create a healthier workplace culture?

Please leave your thoughts or any helpful articles on this topic in the comments below! The DEV Team and I will be here to help moderate the discussion.
Hoisting in JavaScript
Tags: javascript, programming, webdev, tutorial
Published: 2023-03-16 18:39:29

Hoisting simple gives **higher specificity to javascript declarations.** Thus, it makes the computer read and process declarations first before analyzing other code in program.

Note: Hosting does not mean JavaScript rearranges or move code above one anothers.

E.g.

```
console.log(name); 
// Uncaught ReferenceError: name is not defined
let name = 'Deepa'; 
```

- variables declared with let and const are hoisted but not initialized with a default value.
- Accessing let or const before it's declared will give: Uncaught ReferenceError: can't access before initialization
- Remember the error message tells variable is initialized somewhere.

## Variable hoisting with var

When interpreter hoists a variable declared with var, it initialized its value to undefined, unlike let or const.
E.g.

```
console.log(name); // undefined
var name = 'deepa';
console.log(name); // deepa
```

Now let's analyze this behaviour:

```
var name;
console.log(name); // undefined
name = 'partha';
console.log(name); // partha
```

Remember, the first console.log(name) outputs **undefined because name is hoisted**, and given a default value (not because variable is never declared).

**Using undefined variable will throw ReferenceError**

`console.log(name); // Uncaught ReferenceError: name is not defined`

Now let's see if we don't declare var what happens.

`console.log(name); // partha
name = 'partha';`

name = assigning a variable that's not declared is valid.

**JavaScript let us access variable before they're declared.** This behaviour is an unusual part of javascript and can lead to errors.

Using variable before it's declaration is not desirable.

## The temporal Dead Zone

The reason why we get reference error when we try to access let or const before its declaration is **Temperal Dead Zone**

- The TDZ starts at beginning of the variables enclosing scope and ends when it is declared.

- Accessing variable in TDZ gives ReferenceError

E.g.

```
{
    // start of foo's TDZ
    let bar = 'bar';
    console.log(bar); // bar
    console.log(foo); // ReferenceError: Because we're in TDZ
    let foo = 'foo';
    // end of foo's TDZ
}
```

- type of TDZ for let or const: ReferenceError

- type of TDZ for var: undefined

## Functional Hoisting

Function declarations are hoisted too. Function hoisting allows us to call function before it is declared or defined.

```

foo(); 
function foo() {
    console.log('foo'); // foo
}
```

Note: only function declaration are hoisted not function expressions.

E.g.

```
foo(); // Uncaught TypeError: foo is not a function
var foo = function() {

}

bar(); // Uncaught ReferenceError
let bar = function() {

}
```
**Uncaught ReferenceError**: can't access 'bar' before initialization similarly for const.

For function that is never declared:

```
foo(); // Uncaught ReferenceError: foo is not defined
```
Why Is EsLint Important In Nodejs
Published: 2023-03-16 18:32:27

ESLint is a popular tool used in Node.js development as a devDependency. Its main function is to analyze and find issues in your code that may cause errors or affect code quality. ESLint is a static analysis tool that checks your JavaScript code for syntax and style errors, as well as other common issues.

When ESLint is added to a Node.js project as a devDependency, it can help improve code quality, consistency, and maintainability. It enforces coding standards and helps prevent mistakes that can lead to bugs and security vulnerabilities. By detecting issues early in the development process, it can save time and effort in the long run by reducing the time spent on debugging and maintenance.

ESLint can be configured to match your team's coding style and preferences, which ensures that everyone adheres to the same coding standards. It can be integrated into your development workflow, such as your text editor or Continuous Integration (CI) pipeline, to provide immediate feedback as you write code.

Overall, ESLint is an essential devDependency for Node.js development, as it helps ensure that your code is high-quality, maintainable, and free from errors.

Don't forget to like and also follow for more simple analogies of complex concepts in web development and DevOps