teleren/devto huggingface dataset:
Advent of Code 2021: Day 05 with Python, even more numpy
Tags: python, adventofcode
Published: 2021-12-05 06:30:16

[Link to challenge on Advent of Code 2021 website](https://adventofcode.com/2021/day/5)

## Loading the data
This time, there's no shortcuts to loading data, it's regex time. The data is a pair of coordinates, and an arrow, and then another pair of coordinates:

```
578,391 -> 578,322
274,585 -> 651,962
482,348 -> 294,348
```
We can read this in using regex pattern `(\d+),(\d+) -> (\d+),(\d+)`. We also grab the max bounds of the coordinates as well.

```py
lines = open("day_5.txt").readlines()
coords = np.array([re.match('(\d+),(\d+) -> (\d+),(\d+)', line).groups() for line in lines]).astype(int)
size = np.max(coords)+1
```

## Part 1
Part 1 asks us to draw these lines on the grid, and find out how many lines overlap. It also asks us to only consider horizontal and vertical lines.

Horizontal and vertical lines are characterized by having x or y coordinates equal, so we can filter those out:

```py
hv = coords[(coords[:, 0] == coords[:, 2]) | (coords[:, 1] == coords[:, 3])]
```

Then for each of these, we increment the specific indices of the array that they cover:

```py
def rrange(start, stop):
    return range(start, stop+1) if stop >= start else range(start, stop-1, -1)

grid = np.zeros((size, size))
for x1, y1, x2, y2 in hv:
    grid[rrange(y1, y2), rrange(x1, x2)] += 1
result = (grid >= 2).sum()
```

The `rrange()` function is a small helper to allow `range()` to run backwards properly. Because `range(1, 5)` works fine, but `range(5, 1)` does not unless specifying the step size as -1 with `range(5, 1, -1)`. The coordinates are also adjusted to make the values inclusive.

Once the grid values have been incremented, we can find all the grid elements with values greater or equal to 2, giving the answer.

## Part 2
Part 2 asks us to look at not just horizontal and vertical lines, but also diagonal ones. Oddly, we already wrote the code in a way that's general, so no extra code is needed, we just iterate over the original unfiltered coordinates rather than the ones filtered for only horizontal/vertical lines

```py
grid = np.zeros((size, size))
for x1, y1, x2, y2 in coords:
    grid[rrange(y1, y2), rrange(x1, x2)] += 1
result = (grid >= 2).sum()
```

## Full code
```py
import numpy as np
import re

lines = open("day_5.txt").readlines()
coords = np.array([re.match('(\d+),(\d+) -> (\d+),(\d+)', line).groups() for line in lines]).astype(int)
size = np.max(coords)+1

def rrange(start, stop):
    return range(start, stop+1) if stop >= start else range(start, stop-1, -1)

grid = np.zeros((size, size))
hv = coords[(coords[:, 0] == coords[:, 2]) | (coords[:, 1] == coords[:, 3])]
for x1, y1, x2, y2 in hv:
    grid[rrange(y1, y2), rrange(x1, x2)] += 1
result = (grid >= 2).sum()
print("Part 1 result:", result)

grid = np.zeros((size, size))
for x1, y1, x2, y2 in coords:
    grid[rrange(y1, y2), rrange(x1, x2)] += 1
result = (grid >= 2).sum()
print("Part 2 result:", result)
```
React TS Interface and API Calls
Tags: react
Published: 2021-12-05 06:03:01

Hi community,

I am pretty new to React with TS or web dev in general. I've been struggling on how to design a interface to match up with the data structure from an api call. 

Here's the App.tsx file, and url of the fetch call "https://datausa.io/api/data?drilldowns=Nation&measures=Population"

```
import React from 'react';
import './App.css';

interface OuterModel {
  data: InnerModel[];
  source: object;
}

interface InnerModel {
  idNation: string;
  nation: string;
  idYear: number;
  year: string;
  population: number;
  slugNation: string;
}

function App() {
  const url = "https://datausa.io/api/data?drilldowns=Nation&measures=Population";
  const [data, setData] = React.useState<InnerModel[]>([]);

  function getData(): Promise<InnerModel[]> {
    return fetch(url).then(res => res.json()).then(result => (result as OuterModel).data as InnerModel[]);
  }

  React.useEffect(() => {
    getData().then(item => setData(item));
  }, [])

  return (
  <div>
    <h1>{data.length}</h1>
    <ul>
      {data?.map((item, idx) => <li key={idx}>{item.population}</li>)}
    </ul>
  </div>)
}

export default App;

```
I suppose the fetch call was successful, as h1 showed the count of array. yet the unordered list is always blank. don't know what the problem is. The interface? The way I used hooks? these no errors in console, but it's just not right.


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

Also, I wonder if I'm doing this the right way. It seems I have to make a call first, say in browser console, to see the structure of returned json, then I can declare an interface for it. I find it a bit awkward. Are there better approaches?

Appreciate any help on this.
Advent of code day 5; finally a fun one!
Published: 2021-12-05 06:03:01

I really enjoyed this one. It may also be because I was able to do it at a decent time in the day instead of near midnight...

This exercise allows me to show the advantages of 42 multiple 'for-in'; allowing to iterate on multiple collections at ones as if we where using a functional zip.

The core to the solution is to expand the line in a list of points.
I have found a couple of difficulties: at the start I did not understood that there was supposed to be diagonal lines, so my code originally looked like this:

```
method Point.List expand() = {
  (x1,y1)=\p1 //extract coordinates from points
  (x2,y2)=\p2
  if x1==x2 return \()(
    for y in Range(y1.min(y2) to=y2.max(y1)+1I) \add(\(x=x1,y=y)))
  X[y1==y2] return \()(
    for x in Range(x1.min(x2) to=x2.max(x1)+1I) \add(\(x=x,y=y1)))
  }
```
I was saved by my assertion! 'X[y1==y2]': checking that my assumption was right: lines are either vertical or horizontal.
This is not the case, there are other kinds of lines and we just have to ignore them.
So the code became
```
method Point.List expand() = {
  (x1,y1)=\p1 //extract coordinates from points
  (x2,y2)=\p2
  if x1==x2 return \()(
    for y in Range(y1.min(y2) to=y2.max(y1)+1I) \add(\(x=x1,y=y)))
  if y1==y2 return \()(
    for x in Range(x1.min(x2) to=x2.max(x1)+1I) \add(\(x=x,y=y1)))
  return \()
  }
```
and this was passing part 1.
For part 2, I made a method to avoid repeating the Range-max pattern all over, and also to reverse the range on need to expand the diagonal lines in the right way; The final code is as follows:
```
reuse [L42.is/AdamsTowel]
Fs = Load:{reuse[L42.is/FileSystem]}
Point = Data.AddList:Data:{I x, I y }
Line = Data.AddList:Data:{
  Point p1, Point p2
  class method This (S that) = (
    s = that.replace(S" -> " with=S",").split(S",")
    ns = I.List()(for n in s \add(\(string=n)))
    This(
      p1=Point(x=ns.val(0I) y=ns.val(1I)),
      p2=Point(x=ns.val(2I) y=ns.val(3I))
      )
    )
  R = {class method I.List (I that, I to)=(
    if that<to \()(for i in Range(that to=to+1I)\add(i))
    else     \()(for i in Range(to to=that+1I).reverse() \add(i))
    )}
  method Point.List expand() = {
    (x1,y1)=\p1
    (x2,y2)=\p2    
    if x1==x2 return \()(for y in R(y1 to=y2) \add(\(x=x1,y=y)))
    if y1==y2 return \()(for x in R(x1 to=x2) \add(\(x=x,y=y1)))
    return \()(for x in R(x1,to=x2), y in R(y1,to=y2) 
      \add(\(x=x,y=y)))
    }
  }
PMap = Collection.map(key=Point,val=I)
Main = (
  fs = Fs.Real.#$of()
  input = fs.read(\"input")
  lines = Line.List()(for s in input.split(S.nl()) \add(\(s)))
  map = PMap()
  for l in lines, for p in l.expand() (
    opt = map.val(key=p)
    if opt map.put(key=p, val=opt.val()+1I)
    else map.put(key=p,val=1I)
    )
  res=Match.Count()(for (val) in map \add(val>1I))
  Debug(res)
  )
```

See you tomorrow for the next one!
If you like those posts, consider checking out the main 42 website
(https://L42.is) or the youtube channel (https://www.youtube.com/MarcoServetto)
𝐑𝐞𝐚𝐝𝐦𝐞 𝐅𝐢𝐥𝐞 𝐒𝐭𝐲𝐥𝐞𝐬 𝐑𝐞𝐩𝐨𝐬𝐢𝐭𝐨𝐫𝐲
Published: 2021-12-05 05:49:31

**𝑅𝑒𝑝𝑜 𝐿𝑖𝑛𝑘 - :** [This](https://github.com/Mindula-Dilthushan/Readme-File-Styles)
Placeholder title
Tags: actionshackathon21
Published: 2021-12-05 05:29:14

[Instructions]: # (To submit to the GitHub Actions x DEV Hackathon 2021, please fill out all sections.)


### My Workflow
[Note]: # (Please make sure the project links to the appropriate GitHub Actions repository, and includes [an open source license](https://choosealicense.com/) and README.)


### Submission Category: 

[Note]: # (Maintainer Must-Haves, DIY Deployments, Interesting IoT, Phone Friendly, or Wacky Wildcards)


### Yaml File or Link to Code

[Note]: # (Our markdown editor supports pretty embeds. Try this syntax: `{% github link_to_your_repo %}` to share a GitHub repository)


### Additional Resources / Info

[Note:] # (Be sure to link to any open source projects that are using your workflow!)

[Note]: # (Be sure to include the DEV usernames of your collaborators, if any. )

[Reminder]: # (Submissions are due on December 8th, 2021 (11:59 PM PT or 2 AM ET/6 AM UTC on December 9th).
Closures in JavaScript - The easy way
Tags: javascript, css, webdev, programming
Published: 2021-12-05 05:00:19

## Intro
Closure is a **function** inside another function that has access to outer function **variables**
## Example 👇
```javascript
function foo() {
     let cat= '🐈'
     function bar() {
          console.log(cat, ' is a cat!')
     }
     bar()
}
foo()
```
### Explanation
In the above code, **foo()** created a local variable called **cat** and a function named **bar()**. The **bar()** function is an inner function that is defined inside **foo()**.

Note that **bar()** don't have it's own variables. However, since inner function have access to variables of outer functions, **bar()** can access the variable **cat**.

## Reason
Why do we learn it❓
Answer ➡️ These are used when one wants to extend the behavior such as pass variables, methods, etc. from an outer function to the inner function.😎

JavaScript is not a pure Object-Oriented Programming language, but you can achieve most of the OOP based behavior through closures.

## Usage
Practical use case of closure is when you want to define a behavior and you want to attach some functions to manipulate those behavior with events.
I think this is the most obvious way of using closures and you should definitely use it to make your code shorter and development faster.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lkwmb6jp7bmwhhzwf4te.gif)
Let's see one of the best use case with code 👇
### Example
Suppose we want to add a button to a page to adjust the text size. One way to do this is to attach **font-size** in pixels (px) inside body element and then set the size of other elements on page using relative **em** units.
```html
<body>
     ...
     <h1>Heading</h1>
     <p>Some Text</p>
     ...
</body>
```
```css
body {
     font-size: 12px;
}
h1 {
     font-size: 1.5em;
}
```
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uynh4nnwecrskb8wg0kn.gif)
 
Now, closure function is given below ⏬
```javascript
function makeSizer(size) {
     return function() {
          document.body.style.fontsize = size + 'px'
     }
}
var size12 = makeSizer(12)
var size14 = makeSizer(14)

document.getElementById('size-12').onClick = size12
document.getElementById('size-14').onClick = size14
```

📍IKR, there are much better use cases of closures out there, but this was just to make the concept clear for young developers.

Why don't you all share your own use cases in the comments so that others may see live use cases of closures, **in-action 😜**
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpch9o9jpx3v2xb1dhdo.gif)
random quote machine
Tags: codepen
Published: 2021-12-05 04:54:53

<p>This is a project from <a href="https://www.freecodecamp.com" target="_blank">https://www.freecodecamp.com</a>
The objective: Build a random quote app.</p>

<h1>1 User Story: I can click a button to show me a new random quote.</h1>

<h1>2 User Story: I can press a button to tweet out a quote.</h1>

{% codepen https://codepen.io/enlineaweb/pen/WNZQLyB %}
Mapfil
Published: 2021-12-05 04:52:04

[MAP FILTERS](https://www.mapfilters.com) has been in the air filtration business since 2005. With our many years of experience in manufacturing, sales, and installation of cleanroom equipment’s Air filters, we have accumulated lots of experience which we continuously apply into our research and development to constantly improve our existing models as well as developing new models to meet new challenges in the industry We have grown into one of the leading CLEAN AIR Partners for Pharmaceutical, Hospitals and Allied Industries.
Why we need age calculator ?
Published: 2021-12-05 04:17:45

ere are the features I try to incorporate into the age calculator.what does age calculator ?
[Age calculator](http://lencis.net/) age calculator
1. You can estimate the age of your child in terms of days
2. [age calculator online](http://lencis.net/) calculates age in seconds.
3. [age calculator](http://lencis.net/) calulates age in minutes.
4. The 4 age calculator online calculates the age in months.
5.  [age calculator online](http://lencis.net/)  calculates in years,
<html>
<head>
    <title>Exact Age Calculator</title>
	<link rel='stylesheet' href='style.css'/>
	<script src="https://code.jquery.com/jquery-latest.min.js"></script>
	<script src='script.js'></script>
</head>
<body>
    <div id="main_container">
        <div id="birth_date_input">Birth Date*: <input type="date" id="birth_date"></div>
        <br/>
        <div id="calculate">Calculate your age**</div>
        
        <div id="age_container"><span id="exact_age">Age</span></div>
        <p><em>* The year here is 365 days and the month here is 30 days, that means your birthday may not mean you will be 0 days old.</br>  
        **Don't worry I will not share your input.</em></p>
        </p>
    </div>
</body>
</html>
In today’s day we use  [age calculator online](http://lencis.net/)  in various place specially when we have to calculate between days and time or it might be hours.Birth calculator gives you freedom to check your age in multiple differnt options.
How to fix ERROR 1153 (08S01) at line 1407: Got a packet bigger than ‘max_allowed_packet’ bytes in amazon RDS
Tags: aws
Published: 2021-12-05 03:06:57

If you got error message when you restore the database to amazon RDS . follow below steps to fix

Go to the aws console & switch to the RDS panel
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s5dsy6qm97otiz5uoxqj.png)
 
Click Parameter group . (because you can’t edit the default parameters )

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

Then select the parameter that you create and search the key word max_allowed_packet and add the maximum value as 1073741824 ,save it .

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

Like, share and follow me 😍 for more content:

- [LinkedIn](https://www.linkedin.com/in/milan-dikkumburage-9480b814b/)
How to send an email using the AWS SES service with Postfix
Tags: aws, email, postfix
Published: 2021-12-05 03:01:44



The full video is available here: 
{% youtube https://www.youtube.com/watch?v=Y0QvHbQQXmQ %}


Like, share and follow me 😍 for more content:

- [LinkedIn](https://www.linkedin.com/in/milan-dikkumburage-9480b814b/)
Pagination using AWS AppSync
Tags: aws, javascript, react, amplify
Published: 2021-12-05 02:24:54

**Step 1:**
Create three states:
1. Contain an array of tokens. 
2. Contain the current Page number 
3. A state maintaining our fetched data
 
![state creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hrp9dummk7enku65kp1.jpg)
  
**Step 2:**
Initiate the function to retrieve data from the graphql sever passing your tokens, here we use the useEffect and useCallback hook to manage the call function:

 ![step 2 function creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sl2ysmespcski1ris1ix.png)
 

**Step 3:**
Create the next and previous buttons. Add the onClick event handler; this takes care of incrementing the page number or decrementing it.

![Button Creation - Step 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ji3596w4zihll48z2mw8.png)
Will a Television purchased from the US work in other countries?
Tags: 65up7670puc, television
Published: 2021-12-05 01:54:16

# Overview
This article suggests a DIY definitive way to understand if you will fry your device connecting to a non 120V supply. 

# Will it work?

I purchased a LG Television 65UP7670PUC.AUS from a local Costco in the US where the supported voltage is 120V/60Hz to be used in India where the voltage is 240V/50Hz. I was curious if the television would work without a step down transformer. 

The specs on the LG Website says the television supports dual voltage.

![LG TV supported voltage](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4jw402mh75wk61gxdt2q.png)

However, when I received the unit, it had a label on it mentioning it supports only 120V. Quite misleading. 

![Label on TV](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xibob09yljozczw36gir.png)

Running the Television with a Step down transformer is a hassle. I wrote to LG asking if this particular model supports 220V and received a reply.

![LG Support Reply](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/785ysvg0x29f4yybmpyq.png)

Duh!

## 🪛 Time to open the backplate

Every television has an internal power supply board that converts the input AC voltage to the desired DC voltage.  

Removed the screws behind the television and with a little bit of prying was able to get the backplate off. On checking the input voltage rating on the internal power supply board, voila, it's written input 100-240V. There lies my answer. 

![Power Supply Unit](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z7l4ivumr3zdhi0lavrt.png)

If you have a television or any electronic equipment purchased from the US and wondering if that would work in your destination country, the definitive way is to check the input rating voltage labeled on the PCB of the internal power supply board.
Missed AWS re:Invent 2021? 
Tags: aws, reinvent, cloud, datascience
Published: 2021-12-05 01:51:30

You can watch them again at https://www.youtube.com/playlist?list=PL2yQDdvlhXf9jfiZENJYPXX8GYUOzQCuT

Many new services announcement and good use cases, e.g. #Nasdaq, #3M, #unitedairlines, #Capella, #libertymutual , ..., etc.

[simultaneous post at https://www.linkedin.com/posts/walterwlee_nasdaq-3m-unitedairlines-activity-6873075721795973120-u0Nx]
Github Actions for Dev Landing Page
Tags: actionshackathon21
Published: 2021-12-05 01:30:49

[Instructions]: # (To submit to the GitHub Actions x DEV Hackathon 2021, please fill out all sections.)


### My Workflow



Pushing the code to higher environment is a crucial step in the software development process. We have to make sure that all the code is clean and thoroughly tested.

Integrating Github actions was a piece of cake and I have automated running _lint_ and _tests_ on the application when new pull requests are created. This helps in checking for any lint errors in the code or if any test case is failing. If both the checks are done successfully, then only the code can promoted to `master` branch.

[Note]: # (Please make sure the project links to the appropriate GitHub Actions repository, and includes [an open source license](https://choosealicense.com/) and README.)

### Submission Category: 

Maintainer Must-Haves


### Yaml File or Link to Code

The `Yaml` file and code to my workflow can be found in the below repo in `.github/workflows` folder.

[Note]: # (Our markdown editor supports pretty embeds. Try this syntax: `{% github link_to_your_repo %}` to share a GitHub repository)

{% github https://github.com/chilupa/dev-landing-page/ %}
JavaScript Object: entries() vs fromEntries()
Published: 2021-12-05 00:51:16

Do you know what is Object.entries() and fromEntries()? 

Do you know what is the difference between the both?

No?? then keep reading.

>> Follow me on [Twitter](https://twitter.com/hellonehha)

## Object.entries() 

Convert a given object to an array of the enumerable own property.

It is different from 'for..in'. It iterates its own properties only. Whereas 'for..in' iterates properties in the prototype also. 

Use it when you want to convert an object to array.

```javascript
// Object.entries()

const fruits = { 
	'apple' : 3,
    'orange' : 4
}

const summerFruits = Object.create(fruits);

summerFruits.apple = 10;
summerFruits.kiwi = 5;

const summerFruitsList = Object.entries(summerFruits); // [['apple', 10], ['kiwi', 5]]
```
## Object.fromEntries() 

Transforms a list of given key/value to an object.

Use it when you want to convert a list to an object.

### Careful: 

- Keys should be different otherwise it will cascade it.

- Strictly follow key-value pair.

```Javascript
// Object.fromEntries()

const fruits = [ [ 'apple' , 3] , ['orange', 4] ]

const summerFruitsList = Object.fromEntries(fruits); // {apple: 3, orange: 4}
```

Happy learning!!
Remix: Learning Enhanced
Tags: learntocode, react, greatatwork, javascriptdevelopmen
Published: 2021-12-05 00:32:19

---
title: Remix: Learning Enhanced
published: true
date: 2021-12-05 00:30:57 UTC
tags: learntocode,reactjs,greatatwork,javascriptdevelopmen
canonical_url: https://medium.com/@bass41992ben/remix-learning-enhanced-53958e40f209
---

![](https://cdn-images-1.medium.com/max/1024/0*VaJIox-SKNnFDIt4)
_Photo by Ashin K Suresh on Unsplash_

_Hidden Benefits of Using Remix_

I have been wrestling a lot lately with a dilemma that I think most all web developers find themselves in at some point or another. Here it is:

I work on legacy code at work 👉 I want to use updated code and frameworks 👉 To do so I have to do this outside of work 👉 Doing so outside of work takes away from family time 👉 and on, and on, and on…

Now, admittedly, none of this solves the problem of working on legacy code at work and not being able to use updated frameworks and so on. But I have been agonizing to find a way to do something at work that I can get good at and this just so happens to be Javascript.

So where does Remix come in? One problem I face with other frameworks I have used is having to learn some different syntax or that frameworks way of ‘doing things’. Remix does sit on top of React but, as I have said before, the amount of React that you have to know to use Remix is very minimal.

#### **A Remix Secret**

If you have watched Remix demo’s from the Remix team, you will get to a point in the demoes about half way to three quarters through where they drop the secret:

> Your app can run with no Javascript in the browser.

So what does this mean for you. Honestly, you could research this question for a while because there are many benefits to no Javascript in the browser. But oddly enough, here is one benefit that I have recently discovered that ties into the whole work problem I mentioned above.

> Having apps that can run without Javascript actually gives you time to learn and write better javascript.

#### Fuuuu-siioooon Ha!

Ok, I just came up with a goofy subheading. If you are a Dragon Ball Z fan, you know the reference.

The goal, and why I said fusion, was that I find something that I can get good on at work but also implement in project outside of work. So the learning I am doing on the job for the job, also carries over to off the job. Remix makes it incredibly easy and speedy to build applications. I want to get better at Javascript.

One of the nice things is that even if I take time away from actually building apps with Remix, it is built off of the Web Fundamentals. So, I get to spend time learning Javascript with the knowledge that whenever I build an app with Remix, I am using web fundamentals.

In this sense I believe I am getting to contribute actively and significantly at work because we have incredibly large Javascript files. I also know that when I build stuff outside of work with Remix, or other Javascript frameworks, I will be better.

Remix’s opinions about building and using Web Fundamentals allows me to spend more time learning things important to me.