teleren/devto huggingface dataset:
Select HTML Elements by ID, Class, Tag Name Using Vanilla JavaScript
Tags: html, javascript, beginners, tldr
Published: 2023-01-26 18:25:57

## Select An Element Using ID With getElementById()

```js
let para3 = document.getElementById("pid3");

para3.onclick = () => {
    para3.style.backgroundColor = '#ccff00';
}
```

## Select The First Element With querySelector()

The `querySelector()` can be used to select a particular element. But when there are multiple options, it will select the first match.

```js
document.querySelector('#pid4').style.backgroundColor = '#ccff00';
document.querySelector('.para').style.backgroundColor = '#ccff00';
document.querySelector('p span').style.backgroundColor = '#ccff00';
```

## Select All Elements With querySelectorAll()

The `querySelectorAll()` method returns a NodeList.

```js
let paragraphs = document.querySelectorAll('p');

paragraphs.forEach(paragraph => {
    paragraph.style.backgroundColor = '#ccff00';
});
```

Likewise, you can also select `classes` and `ids` with `querySelectorAll`.

```js
document.querySelectorAll('.para');
document.querySelectorAll('#pid4');
```

## Select All Elements With getElementsByClassName()

The `getElementsByClassName()` returns an HTMLCollection object. You can use `for`, `forEach` and `from` to loop through elements.

Using `for` loop.

```js
let paragraphs = document.getElementsByClassName('para');

for(paragraph of paragraphs) {
    paragraph.style.backgroundColor = '#ccff00';
}
```

Using `forEach`.

```js
let paragraphs = document.getElementsByClassName('para');

[].forEach.call(paragraphs, function (paragraph) {
    paragraph.style.backgroundColor = '#ccff00';
});
```

Using `from`.

```js
let paragraphs = document.getElementsByClassName('para');

Array.from(paragraphs).forEach(paragraph => {
    paragraph.style.backgroundColor = '#ccff00';
});
```

## Select All Elements With getElementsByTagName()

`getElementsByTagName()` returns an HTMLCollection object. You can use `for`, `forEach` and `from` to loop through elements.

```js
let paragraphs = document.getElementsByTagName('p');
```

## Select All Elements With getElementsByName()

`getElementsByName()` returns an HTMLCollection object. You can use `for`, `forEach` and `from` to loop through elements.

```js
let phone_numbers = document.getElementsByName('phone_numbers');
```

> This is a TLDR short version, visit [https://devtonight.com/articles/select-html-elements-by-id-class-tag-name-using-vanilla-javascript](https://devtonight.com/articles/select-html-elements-by-id-class-tag-name-using-vanilla-javascript) for detailed explanations.
pyaction 4.15.0 Released
Tags: github, docker, python, showdev
Published: 2023-01-26 18:14:08

## TL;DR

I just released [pyaction](https://github.com/cicirello/pyaction) 4.15.0, a [Docker container with Python, git, and the GitHub CLI](https://dev.to/cicirello/pyaction-a-docker-container-with-python-git-and-the-github-cli-930).


## Changelog 4.15.0 - 2023-01-26

### Changed
* Bumped GitHub CLI to 2.22.0.


## Current Version List

This latest release of pyaction includes:
* Python 3.11.1
* [GitHub CLI 2.22.0](https://github.com/cli/cli/releases/tag/v2.22.0)
* git 2.30.2
* curl 7.74.0
* gpg 2.2.27



## More Information

For more information, see my earlier post about pyaction here on DEV, as well as pyaction's GitHub repository.

{% link https://dev.to/cicirello/pyaction-a-docker-container-with-python-git-and-the-github-cli-930 %}

{% github cicirello/pyaction %}



## Where You Can Find Me

Follow me here on DEV:

{% user cicirello %}

Follow me on GitHub:

{% github cicirello/cicirello %}

Or visit my website:

{% embed https://www.cicirello.org/ %}
How to run Javascript
Tags: javascript, beginners, programming, tutorial
Published: 2023-01-26 18:10:16

---
canonical_url: https://baransel.dev/post/how-to-run-javascript/
---

> [Sign up to my newsletter for more tutorials!](https://baransel.dev/newsletter/).

Since JavaScript commands run on the browser, we need to add JavaScript codes to our web page.

There are various methods of adding JavaScript code to a web page.

JavaScript codes can be written between the `<script>` and `</script>` tags.


```html
<script>
   alert("baransel.dev");
</script>
```

It can be written to `HTML` properties such as `onclick`, which indicates when the `HTML` element is clicked, `onmouseover`, which indicates that the `HTML` element is hovered.

```html
<button onclick="alert('baransel.dev')">Click</button>
```

After the JavaScript codes are written to the external `.js` file, the `<script>` tag can be written to the `src` property by specifying the file name.


### JavaScript codes (`example.js`)

```js
alert("baransel.dev");
```

### HTML Codes

```html
<script src="example.js"></script>
```

> Codes are written to the external JavaScript file without the `<script>` and `</script>` tags.

Written JavaScript codes can be inserted into `<head>` or `<body>` tags. 

```html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Baransel Arslan</title>
</head>

<body>
  <script>
    alert("baransel.dev");
  </script>
</body>

</html>
```

> Long JavaScript commands can slow down the page load.

> If the codes in the page or in external JavaScript files are added to the end of the `<body>` tag, the **page will open faster**.
Let's use pandas effectively in our code
Tags: python, datascience, machinelearning, analytics
Published: 2023-01-26 18:08:28

In the field of data science, the use of powerful and efficient tools is essential for effectively analyzing and interpreting large datasets. One such tool that is widely used by data scientists is Pandas, a library for Python that provides fast and flexible data structures for data analysis.

Pandas is a powerful library for Python that is widely used in the field of data science for data analysis and manipulation. It provides fast and flexible data structures, such as DataFrames and Series, that make it easy to work with large datasets. In this blog post, we will explore some of the most popular methods used in Pandas and how they can be effectively utilized in data science.

One of the most popular methods in Pandas is the `read_csv()` function, which is used to read and import data from a CSV file. This function can be used to import data into a Pandas DataFrame and is a quick and easy way to load data for analysis.

```
import pandas as pd
data = pd.read_csv('data.csv')
```
Another popular method in Pandas is the `head()` function, which is used to view the first few rows of a DataFrame. Always use this function to quickly inspect the structure and contents of a dataset.

```
data.head()
```
Output:

```
   col1  col2  col3
0     1     2     3
1     4     5     6
2     7     8     9
3    10    11    12
4    13    14    15

```
You can use `describe()`. This method returns the basic statistical summary of the numerical columns in a DataFrame.

```
df.describe()
```
Output:

```
           col1       col2       col3
count  10.00000  10.000000  10.000000
mean   17.50000  18.500000  19.500000
std    11.77439  11.774437  11.774437
min     1.00000   2.000000   3.000000
25%     9.25000  10.250000  11.250000
50%    17.50000  18.500000  19.500000
75%    25.75000  26.750000  27.750000
max    34.00000  35.000000  36.000000
```

Pandas also provides a variety of methods for data cleaning and preparation, such as the `dropna()` and `fillna()` methods. The dropna() method is used to remove rows or columns with missing data, while the `fillna()` method is used to fill in missing values with a specific value or method.

```
data.dropna()
data.fillna(value=0)
```
Pandas also provides powerful methods for data manipulation and transformation, such as `groupby()`and `pivot_table()`. The groupby() method is used to group data by a specific column, while the pivot_table() method is used to reshape data and create a pivot table.

```
data.groupby('column_name').mean()
data.pivot_table(values='column_name', index='grouping_column', aggfunc='mean')
```
Let's break it down. in first line we group the dataset by a column and by default it will give a mean value. But for writing cleaner code we can use `.pivot_table()`. The `pivot_table()` method allows you to create a new table by grouping rows based on one column and calculating aggregate values for another column.
Git at a Glance: A Cheatsheet of 30 Must-know Commands
Tags: github, git, cheatsheet
Published: 2023-01-26 18:00:00

Managing code and collaborating with others can be a daunting task, but Git makes it easy. This cheatsheet is here to help you take your Git skills to the next level by providing a comprehensive list of 30 essential commands. From initializing a new repository to merging changes, this cheatsheet covers all the basics you need to know to streamline your workflow and make your life as a developer much easier. Whether you're new to Git or an experienced user, this cheatsheet is a valuable resource to have on hand.


1. Initialize a new repository: `git init`
2. Clone an existing repository: `git clone [repository url]`
3. Check the status of your repository: `git status`
4. Add changes to the staging area: `git add [file name]`
5. Commit changes: `git commit -m "[commit message]"`
6. View the commit history: `git log`
7. View the difference between the working directory and the staging area: `git diff`
8. View the difference between the staging area and the last commit: `git diff --staged`
9. Discard changes in the working directory: `git checkout [file name]`
10. Discard changes in the staging area: `git reset [file name]`
11. Discard a commit: `git revert [commit hash]`
12. Remove a file from the repository: `git rm [file name]`
13. Rename a file in the repository: `git mv [old file name] [new file name]`
14. Show the branches in the repository: `git branch`
15. Create a new branch: `git branch [branch name]`
16. Switch to a different branch: `git checkout [branch name]`
17. Merge changes from one branch to another: `git merge [branch name]`
18. Show remote repositories: `git remote`
19. Show remote repositories: `git remote -v`
20. Add a new remote repository: `git remote add [remote name] [repository url]`
21. Push changes to a remote repository: `git push [remote name] [branch name]`
22. Pull changes from a remote repository: `git pull [remote name] [branch name]`
23. Show the tags in the repository: `git tag`
24. Create a new tag: `git tag -a [tag name] -m "[tag message]"`
25. Checkout a specific tag: `git checkout [tag name]`
26. Show the history of a file: `git log -p [file name]`
27. Show the commits that contain a certain string: `git log -S [string]`
28. Show the commits that were made by a certain author: `git log --author=[author name]`
29. Show the commits that were made in a certain date range: `git log --since=[date] --until=[date]`
30. Show the commits that were made on a certain branch: `git log [branch name]`


Please note that this is a list of commonly used Git commands, and there are many other commands that you can use as well. Additionally, each command has many options and flags that can be used to customize its behavior. I would suggest you to use the official Git documentation to learn more about the various commands and their usage.
Day 19: Local Transcription w .NET
Tags: challenge, beginners, tutorial, csharp
Published: 2023-01-26 17:52:37


Processing voice data on the [cloud comes at a cost](https://picovoice.ai/blog/local-voice-ai-with-cloud-accuracy/)

Historically, there’s been several roadblocks to local transcription. Not anymore with Picovoice [Leopard Speech-to-Text](https://picovoice.ai/platform/cat/) SDK for cross-platform .NET.

**1- Install Leopard NuGet Package**
```
dotnet add package Leopard
```
**2- Get a Picovoice AccessKey**
You should know how to do by now. However, it's your first time, then sign up for the [Picovoice Console](https://console.picovoice.ai/) and get your AccessKey for free.

**3- Code**
```
using Pv;
string accessKey = "${ACCESS_KEY}"
Leopard leopard = Leopard.Create(accessKey);
```
You can 
1. pass an audio file to Leopard OR
2. record audio and pass in the raw data. 

Let's pass it from the microphone:
```
short[] audio = //.. audio obtained from microphone
string transcript = leopard.Process(audio);
```
Looking for more:
[Open-source demo code](https://github.com/Picovoice/leopard/tree/master/demo/dotnet)
[Leopard GitHub repository](https://github.com/Picovoice/leopard)
[Speech-to-text Benchmark](https://picovoice.ai/docs/benchmark/stt/)
Don't touch parent timestamps, just this once.
Tags: laravel, php
Published: 2023-01-26 17:51:54

I have a couple models related to each other. We'll call them `Parent` and `Child`. Here's the child...

```php
class Child extends Model
{
  protected $touches = ['parent'];

  public function parent()
  {
    return $this->belongsTo(Parent::class);
  }
}
```

I ran into a situation where I create the parent model, save it to the db, then loop over some inputs, creating the children. But if that takes long enough (it usually does), the parent’s `updated_at` no longer matches its `created_at`. This was an issue for me because I'm showing the user an icon if the db record has been updated. With actual updates to the children, I want it to happen, but on the initial save, I don’t.

---

#### Laravel includes a couple undocumented ways to _not_ touch the parent timestamps, even when you've set up your model to do so.

---

The base `Model` includes a static method to turn off the touching.
```php
/**
 * Disables relationship model touching for the current class during given callback scope.
 *
 * @param  callable  $callback
 * @return void
 */
 public static function withoutTouching(callable $callback)
 {
   static::withoutTouchingOn([static::class], $callback);
 }
```

Although it didn't strike me as terribly intuitive, in my case I can toss this in the controller method responsible for saving a form.

```php
$parent = new Parent();
// set some props...
$parent->save();

foreach ($request->input('child-data') as $childData) {
  Parent::withoutTouching(function() use ($parent) {
    $child = new Child();
    $child->parent_id = $parent->id;
    $child->data = $childData;
    $child->save();
  }
}
```
This works to keep the creation of child records from updating the parent's `updated_at` value. Nice!

---

There is another, and in my opinion, much simpler way to accomplish this. The base Model's `save()` method accepts an optional `$options` array as an argument. As far as I can tell, there is currently only one `$options` key that the framework checks for. Lucky for us, it allows us to turn off touching!

Instead of nesting the child logic inside the callback of the static method, you can just pass an options array to the save method

```php
$parent = new Parent();
// set some props...
$parent->save();

foreach ($request->input('child-data') as $childData) {
  $child = new Child();
  $child->parent_id = $parent->id;
  $child->data = $childData;
  $child->save(['touch' => false]);
}
```

This one seems more intuitive to me, and definitely less complicated. Nicer!
AWS Well-Architected Tool
Tags: aws, cloud, awscommunity, 100daysofcloud
Published: 2023-01-26 17:33:13

[26/100] #100DaysOfCloud Today, I created a workload, reviewed the Pillar questions, saved the workload, took a milestone, and examined and downloaded the Well-Architected Review report.

AWS Well-Architected helps cloud architects build secure, high-performing, resilient, and efficient infrastructure for a variety of applications and workloads. Built around six pillars—operational excellence, security, reliability, performance efficiency, cost optimization, and sustainability—AWS Well-Architected provides a consistent approach for customers and partners to evaluate architectures and implement scalable designs.

- Operational Excellence Pillar
 - The operational excellence pillar focuses on running and monitoring systems, and continually improving processes and procedures. Key topics include automating changes, responding to events, and defining standards to manage daily operations.

- Security Pillar
 - The security pillar focuses on protecting information and systems. Key topics include confidentiality and integrity of data, managing user permissions, and establishing controls to detect security events.

- Reliability Pillar
 - The reliability pillar focuses on workloads performing their intended functions and how to recover quickly from failure to meet demands. Key topics include distributed system design, recovery planning, and adapting to changing requirements.

- Performance Efficiency Pillar
 - The performance efficiency pillar focuses on structured and streamlined allocation of IT and computing resources. Key topics include selecting resource types and sizes optimized for workload requirements, monitoring performance, and maintaining efficiency as business needs evolve.

- Cost Optimization Pillar
 - The cost optimization pillar focuses on avoiding unnecessary costs. Key topics include understanding spending over time and controlling fund allocation, selecting resources of the right type and quantity, and scaling to meet business needs without overspending.

- Sustainability Pillar
 - The sustainability pillar focuses on minimizing the environmental impacts of running cloud workloads. Key topics include a shared responsibility model for sustainability, understanding impact, and maximizing utilization to minimize required resources and reduce downstream impacts. 

You can try do it by yourself by following the steps from the link below:
[GitHub](https://github.com/aaditunni/100DaysOfCloud/blob/main/Journey/026/Readme.md)
Changing a state and updating the changes with a put request
Tags: react, node, beginners
Published: 2023-01-26 12:38:26

Hi !

I'm trying to change the state of an element in the React component, while in the same time updating the data with a put request.

There's an element "Pending" in the React component, and i'm looking to change it to "Paid".

Here's the code:
```
const [invoice, setInvoice] = useState([])

const paidInvoice =  () => {
    setInvoice((invoice) => {
      return({
        ...invoice,
        status:'Paid'
      });
    })

axios.put('http://localhost:5000/api/invoice/update/'+id, invoice)
    .then(response => console.log(response.data))
    .catch(error => console.log(error))
}

```

The problem is that when i call this function after a click, the state changes, but the data is not updated so when i refresh the page it's still the same as before clicking. 

The invoice object that i get:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hcfeeec9ij0grvvp36jx.PNG)
(The status must be paid not pending)
I also noticed that when i click two consecutive times to call the function, the problem resolves and the data updates correctly in the database...
Pagination : When to use server side and client side pagination
Tags: webdev, react, javascript, php
Published: 2023-01-26 16:52:24

While doing pagination for tables, developers blindly use server side or client side pagination many times. It is important to know when to use server side pagination and when to use client side pagination effectively. Lets discuss it in details. 

First, let's define what we mean by client-side and server-side pagination. Client-side pagination refers to the process of manipulating data on the client (usually the user's browser). This means that the data is transferred from the server to the client at once and the client is responsible for paginating and sorting the data.

On the other hand, server-side pagination refers to the process of manipulating data on the server. In this case, only a subset of the data is transferred from the server to the client and the server is responsible for paginating and sorting the data.

## When to use server side pagination : 

1. Performance: As the amount of data grows, client-side pagination and sorting can become slow and cumbersome. This can lead to a poor user experience and can even cause the client to crash. Server-side pagination and sorting allows the server to handle the data manipulation, which can be faster and more efficient.

3. Security: Server-side pagination and sorting allows you to control access to data and ensure that only authorized users can access and manipulate it. This can be important for security and compliance reasons.

5. Simplicity: Client-side pagination and sorting can require complex client-side code and can be difficult to implement and maintain. Server-side pagination and sorting can be simpler to implement and maintain, as the server handles the data manipulation.

7. Compatibility: Some clients (such as older browsers or devices) may not have the capabilities to handle client-side pagination and sorting. Server-side pagination and sorting can ensure that all clients can access and manipulate the data.

9. Scalability: As the amount of data grows, client-side pagination and sorting can become increasingly difficult to manage. Server-side pagination and sorting allows the server to handle the data manipulation, which can be more scalable and able to handle larger amounts of data.

## When to use client side validation : 

While client-side pagination and sorting can be convenient in some cases, server-side pagination and sorting offers several important benefits including better performance, security, simplicity, compatibility, and scalability. Therefore, it is always a good idea to use server-side pagination and sorting whenever possible.

Thanks for reading this article.  if this article provided you value in some way, you can show your support to me here by clicking on below link. 

[Buy me a coffee](https://www.buymeacoffee.com/lakinmohapatra)

You can connect me via [Linkedin ](https://www.linkedin.com/in/lakin-mohapatra-798b0a97/)or [Twitter](https://twitter.com/lakincoder)
Angular 13+ libraries migration Ivy partial lerna/Nx build parallel problem
Published: 2023-01-26 16:32:24

If you are moving to Angular 13+ and you are stick with building your parallel libraries locally or in the CI within a **monorepo** using lerna/Nx, you are in the right why to fix that.

```shell
 ❌ Another process, with id XXXXX, is currently running ngcc
```
## Steep 1

Check if you got in the **tsconfig.lib.prod** file the partial compilation mode under **angularComplierOptions** after running the **ng update** cmd like so :

```json
"angularCompilerOptions": {
   "compilationMode": "partial"
}
```
**And remove the enableIvy from the config is enabled by default**

## Steep 2
In the main workspace package.json file you need to add the postinstall script like so:

```json
"scripts": {
    "postinstall": "ngcc --properties es2015 browser module main",
}
```
Or you can also add options :

```json
"postinstall": "ngcc --properties es2015 es5 browser module main --first-only --create-ivy-entry-points"
```
****
If no **properties** flag is given, ngcc will process all package formats (fesm2015, fesm5, es2015, esm2015, esm5, main, module), which may not be what's desired.

The flag **first-only** tells ngcc to process the first property it finds in package.json, otherwise it'll process all entries listed above.

The **create-ivy-entry-points** will tell ngcc to create new properties for the Ivy generated entry, instead of overwriting the previous one.

And it will be compiling with Angular sources in Ivy partial compilation mode.

**⚠️ Note**: You need to respect the peerDependencies to install correctly the dependencies if it's not work try this


```shell
npm i --legacy-peer-deps
```


Hope this help you in the Angular 13+  migration 🎉