teleren/devto huggingface dataset:
Leetcode Problem: Construct the Rectangle
Tags: python, tutorial, challenge, algorithms
Published: 2022-04-13 14:59:55

In this article I would be going over a solution to leetcode problem [492: Construct the Rectangle](https://leetcode.com/problems/construct-the-rectangle/),

Two solutions were developed and I will be walking you through them

## Solutuion 1
The function accepts a parameter area, in this example we would go with 16
`area = 16`
Next we create our answer dictionary variable to hold the factors of the target area
`ad = {}`
Also setup a temp list with maximum and minimum values of infinity
`temp = [ float('inf'),  float('-inf')]`
First we wanna iterate over from 1 till the square root of the target area + 1 to avoid duplicates
`for 1,2...sqrt(16)+1 --> 5`
For every iteration, if we find a factor of that number then we want to save it to the answer dictionary
```
 # 16/1
 # 16/2
 # 16/3
 # 16/4
 ad = {'1':'16', '2':'8', '4':'4'}
```
Now we can iterate through the answer dictionary to select the best length and width combination with the lowest absolute difference 
```
 for k,v in ad:
    if abs(k-v) < abs(temp[0]-temp[1])
    temp[0], temp[1] = min(k, v), max(k,v)
    return temp
```
At the end of this process we have the answer in temp list

Code Below

```
import math
class Solution:
    def constructRectangle(self, area: int) -> List[int]:
        answer_dict = {}
        temp = [float('inf'),  float('-inf')]
        for n in range(1, int(math.sqrt(area))+1):
            if area%n == 0:
                answer_dict[n] = area // n
        for k, v in answer_dict.items():
            if abs(temp[0] - temp[1]) > abs(k-v):
                temp[0], temp[1] = max(k, v), min(k, v)
        return temp
```
The first solution was long and it could be made a lot simpler
This second solution makes use of one list to keep the prospective lengths and breadths
Easy to understand
```
class Solution:
    def constructRectangle(self, area: int) -> List[int]:
        ans = []
        for i in range(1, int(sqrt(area))+1):
            j = area // i
            if i * j == area:
                if i <= j:
                    ans.append([max(i,j), min(i,j)])
        return ans[-1]
```
A little task for the readers, what is the time and space complexities of both solutions
Also do let me know if you have a better solution, or any improvements to be made

Happy Cocding :)
Medusa, the open source Shopify alternative, passed 10K stars on GitHub!
Tags: news, opensource, showdev, github
Published: 2022-04-13 14:58:58

If you're not familiar with [Medusa](https://medusajs.com), it's an open source headless commerce platform that has been gaining a lot of popularity in the past 9 months. 

Medusa aims to provide a good developer experience with a lot of customization capabilities that eliminate the need for hacky solutions. This also allows merchants to pick and choose with the services and features they want as part of their ecosystem.

As part of our celebration for the 10K stars, here's a look back at some of the highlights from the past 9 months:

1. In September of last year, we posted about [Medusa on Hacker News](https://news.ycombinator.com/item?id=28481913) and it was #5 on the front page!

2. In October and during Hacktoberfest, our community size grew twice as much, and almost 90 PRs!

3. In December, Medusa went viral as we were #1 trending on GitHub, had over 1000 post upvotes on Reddit, and had over [19000 reads on our intro article here on DEV](https://dev.to/medusajs/get-started-with-medusa-the-open-source-alternative-to-shopify-305j).

4. In January of this year, we launched [Medusa on Product Hunt](https://www.producthunt.com/posts/medusa). It ranked #1 of the day and #3 of the month. We also surpassed 1400 upvotes.

5. In March, we had a new record of usage with over 1500 monthly projects and 1600 community members.

This all wouldn't have been done without the help and support of our community. Thank you to everyone that contributed to Medusa or used it in their project. We hope to continue working hard and celebrate 20K soon!

You can check Medusa out on [GitHub](https://github.com/medusajs/medusa) as well as join our community on [Discord](https://discord.gg/medusajs).
Ionic 6.1: Improved Virtual Scroll Compatibility
Published: 2022-04-13 14:42:37

Ionic Framework 6.1 improves built-in feature compatibility for features such as fade header/footers, infinite scroll and item reordering with virtual scroll libraries. This allows applications to benefit from native designed features from Ionic with the performance of virtual scrolling.  

With the `.ion-content-scroll-host` classname, implementations can specify which container is responsible for scrolling. Many custom features in Ionic make use of the scroll position and scroll listeners. 

Below are a few usage examples for popular virtual scrolling libraries in React, Vue and Angular.

### React (react-virtuoso)

```tsx
const Footer = () => {
  return (
    <IonInfiniteScroll threshold="100px">
      <IonInfiniteScrollContent></IonInfiniteScrollContent>
    </IonInfiniteScroll>
  )
}

const Example = () => (
  <IonPage>
    <IonContent fullscreen scrollY={false}>
      <Virtuoso 
        className="ion-content-scroll-host"
        data={items}
        style={{ height: "100%" }}
        itemContent={(item) => <IonItem>{item}</IonItem>}
        components={{ Footer }} />
    </IonContent>
  </IonPage>
);

```

### Vue (vue-virtual-scroller)

```vue
<template>
  <ion-page>
    <ion-content :fullscreen="true" :scroll-y="false">
      <RecycleScroller 
        class="ion-content-scroll-host scroller"
        :items="items"
        :item-size="50"
      >
      <template v-slot="{ item }">
        <ion-item>{{ item }}</ion-item>
      </template>
      <template #after>
        <ion-infinite-scroll threshold="100px">
          <ion-infinite-scroll-content></ion-infinite-scroll-content>
        </ion-infinite-scroll>
      </template>
      </RecycleScroller>
    <ion-content>
  </ion-page>
</template>

<style scoped>
  .scroller {
    height: 100%;
  }
</style>
```

### Angular (@angular/cdk/scrolling)

```html
<ion-content [fullscreen]="true" [scrollY]="false">
  <cdk-virtual-scroll-viewport itemSize="50" class="ion-content-scroll-host">
    <ion-item *cdkVirtualFor="let item of items">
      {{ item }}
    </ion-item>
    <ion-infinite-scroll threshold="100px">
      <ion-infinite-scroll-content></ion-infinite-scroll-content>
    </ion-infinite-scroll>
  </cdk-virtual-scroll-viewport>
</ion-content>

```

We hope that you find value in this feature and others in the 6.1.0 release.
Ionic 6.1: Dynamically changing the breakpoint of a Sheet Modal
Published: 2022-04-13 14:42:25

Ionic Framework 6.1 introduces the ability to dynamically change the current breakpoint of a sheet modal. This features enables developers to animate sheet modals to predefined breakpoints based on your application needs.

To get started with this feature, you will need to use a sheet modal in Ionic. The below example is of Angular, but this feature applies to the vanilla web component implementation and all supported frameworks.

```html
<ion-button id="sheet-modal">Click to open modal</ion-button>
<ion-modal #modal 
  trigger="sheet-modal"
  [initialBreakpoint]="0.25" 
  [breakpoints]="[0.25, 0.5, 1]">
  <ng-template>
    <ion-content>
      <ion-list>
        <ion-item button (click)="moveTo(0.25)">
          <ion-label>Move to 0.25</ion-label>
        </ion-item>
        <ion-item button (click)="moveTo(0.5)">
          <ion-label>Move to 0.5</ion-label>
        </ion-item>
        <ion-item button (click)="moveTo(1)">
          <ion-label>Move to 1</ion-label>
        </ion-item>
      </ion-list>
    </ion-content>
  </ng-template>
</ion-modal>
```

The above sheet modal will initially display when the button is clicked, to the 0.25 breakpoint. It has available breakpoints for 0.25, 0.5, and 1 (fully expanded). 

To change the breakpoint dynamically, we need to query the `ion-modal` element to access the public API function: `setCurrentBreakpoint`.

```ts
import { Component, ElementRef, ViewChild } from '@angular/core';

@Component({
  selector: 'app-sheet-modal-example',
  templateUrl: 'sheet-modal-example.component.html'
})
export class SheetModalExample {

  @ViewChild('#modal') modal: ElementRef;

  moveTo(breakpoint: number) {
    const { nativeElement } = this.modal;
    if (!nativeElement) {
      return;
    }
    nativeElement.setCurrentBreakpoint(breakpoint);
  }

}
```

That is it, your sheet modal should now dynamically change the breakpoint value after interacting with the individual items to move to a specific breakpoint.

You can use this concept to make features such as an iOS maps clone:

<video src="https://user-images.githubusercontent.com/13732623/162064250-015b2f8d-b36f-4357-a793-a3049a5f1fe7.mp4" controls></video>

Source code: https://github.com/sean-perkins/ionic-6.1.0-maps-example

We hope that you find value in this feature and others in the 6.1.0 release.
Ionic 6.1: Disabling Specific Dates, Weekends and Holidays
Published: 2022-04-13 14:42:07

Ionic Framework 6.1 introduces the ability to control the disabled status of each individual day within an `ion-datetime`. 

With the `isDateEnabled` function, you can write custom rules to disable specific dates, weekends, months, holidays, etc. 

`isDateEnabled` accepts a ISO 8601 date string and must return a boolean (true for enabled, false for disabled).

Here are a few common scenarios you may run into with your applications:

### Disabling Specific Dates

Disables January 1, 2022.

![Datetime with January 1, 2022 disabled](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pk8e6fi2fiz9d2pvnc5x.png)

```html
<ion-datetime></ion-datetime>
```

```ts
import { getDate, getMonth, getYear } from 'date-fns';

const isDateEnabled = (dateIsoString: string) => {
  const date = new Date(dateIsoString);
  if (getDate(date) === 1 && getMonth(date) === 0 && getYear(date) === 2022) {
    return false;
  }
  return true;
};

const datetime = document.querySelector('ion-datetime');
datetime.isDateEnabled = isDateEnabled;
```

### Disabling Weekends

Disables Saturday and Sunday.

![Datetime with weekends disabled](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rx5j93wrslp9f23nwnqj.png)

```html
<ion-datetime></ion-datetime>
```

```ts
import { isWeekend } from 'date-fns';

const isDateEnabled = (dateIsoString: string) => {
  const date = new Date(dateIsoString);
  return !isWeekend(date);
};

const datetime = document.querySelector('ion-datetime');
datetime.isDateEnabled = isDateEnabled;
```

### Disabling Holidays

Similar to disabling specific dates, you can also disable specific dates and months without comparing the year.

Disables December 25th.


![Datetime with December 25th disabled](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/go4rjfoz2afywc2b3iqa.png)

```html
<ion-datetime></ion-datetime>
```

```ts
import { getDate, getMonth, getYear } from 'date-fns';

const isDateEnabled = (dateIsoString: string) => {
  const date = new Date(dateIsoString);
  if (getDate(date) === 25 && getMonth(date) === 11) {
    return false;
  }
  return true;
};

const datetime = document.querySelector('ion-datetime');
datetime.isDateEnabled = isDateEnabled;
```

We hope that you find value in this feature and others in the 6.1.0 release.
Most Important Array functions in Javascript
Tags: javascript, webdev, beginners
Published: 2022-04-13 14:23:16

As a beginner, I also face difficulty in remembering all the functions associated with a particular topic. So I thought of writing about some important and widely used array functions in javascript which I personally feel are very useful and a must know for beginners. However, one should have at least a basic idea of all the functions. 

## 1. Filter() 

The Filter() method creates a new array filled with              elements that pass a test provided by a function. However it does not change the original array.
For example,
```
const numbers = [32, 33, 16, 40];
const result = numbers.filter(checkNumber);

function checkNumber(number) {
  return number >= 30;
}
```
The filter will return [32,33,44] as these elements are greater than 30.



## 2. forEach()

The forEach() method calls a function for each elements in an array. It's somewhat similar to the **for** loop for all elements.
For example,

```
let text = "";
const numbers = [1,2,3,4]
numbers.forEach(functionMe);
document.getElementById("para").innerHTML = text;
function functionMe(item, index) {
  text += (index+1) + ": " + item + "<br>"; 
}
```
The output comes to be

```
1: 1
2: 2
3: 3
4: 4
```



## 3. map()
The map() method creates a new array from the results of calling a function for every element.
For example,

```
const numbers = [1, 4, 9, 16, 25];
document.getElementById("para").innerHTML = numbers.map(Math.sqrt);
```
It will display the square root of every element.

```
1,2,3,4,5 
```



## 4. Splice()

Splice() method overwrites the original array by adding or removing elements.
for example,
```
const avengers = ["Captain America", "Iron Man", "Hulk", "Thor"];
 
fruits.splice(3, 0, "spider man", "Dr. Strange");
// here 3 signifies index, 0 signifies that no element is to be deleted .
//If we wish to delete some elements ,then index and number of elements to be deleted should be provided.

document.getElementById("para").innerHTML = fruits;
```
this will add 2 elements at the index 3. 


Hope this helps some peeps new to coding and web development.
For more detailed explanation of these topics you may follow this playlist [(https://www.youtube.com/playlist?list=PLgBH1CvjOA62PBFIDq55-S6Beivje30A2)]
Pair-Programming: the advantages of this system
Tags: womenintech, 100daysofcode, codenewbie, programming
Published: 2022-04-13 14:37:12

Always developers do their utmost when they are empowered and inspired, it means that when they are equipped with the tools and resources they need they will deliver better products and it will be faster. They are many methods that can help developers to be efficient in their work today, I am going to talk about pair-programming which is one method that boosts efficiency.

**What is pair-programming?** 
Pair-programming is when two developers work on a project using only one machine, one works as a driver who codes while the other serves as an observer who checks the code that is being written and offer help where is needed. They switch roles after sometimes then the driver becomes an observer and vice versa.

**Advantages of pair-programming**
The pair-programming strategy has many advantages but lets me list some of them:

- _**Better code**_: This means when you are coding together it will be easier to detect bugs and errors compared to when you are doing solo programming and this will increase the quality of your codes because you might not notice how bad your codes are when you are alone but together you can share ideas to deliver the best work


- **_Time management_**: We can understand how quickly you can finish one project when you are working on it as 2 developers than when you are doing it solo. This means when you are 2 you don't spend much time on maybe one error because you help each other to figure out the issue than when you are working alone, which makes the process quicker and easier.

- _**Sharpen interpersonal skills**_: Collaborating on one project helps developers to develop and appreciate communication and teamwork.

- _**Creativity**_: When you are coding solo it is easier to stick to one solution that comes first to your mind, but when you are collaborating you will first explain to your partner how you think you can approach the issue, by sharing your idea your partner may disagree with your solution and share his/her ideas so this discussion might lead to more effective solutions.

- **_Sharing knowledge_**: When you are coding together everyone has different knowledge and experiences, collaborating will help each one to learn new things from each other 

As a developer who personally used pair-programming I would encourage anyone to try it out it is so much fun and educative at the same time.
NextJS or ReactJS- A Feature-based Comparison
Tags: reactjsvsnextjs, bestfrontendframework, nextjsorreactjs
Published: 2022-04-13 14:24:43

Here is the article that will add value to your knowledge on the features and abilities of ReactJS and NextJS as the frontend frameworks. This article focuses on providing with detailed information on the best frontend framework by step-by-step and feature-based comparison between ReactJS and NextJS. This article will truly help you decide on the best framework that will match your requirements and can build effective solution for you. Discover the full Article- https://www.techbii.com/next-js-vs-react-better-framework-frontend/
C random
Published: 2022-04-13 14:24:34

## the definition of rand() & srand()
`rand(): generate random numbers in the range [0, RAND_MAX).
srand(): Set Seed for rand() Function. Standard practice is to use the result of a call to srand(time (0)) as the seed.`
Notes: If random numbers are generated with rand() without first calling srand(), your program will create the same sequence of numbers each time it runs.

## how to generate a random number in the fixed range
`int a = rand() % 10;         //[0,9]
int b = rand() % 10 + 5;     //[5,14]
int c = rand() % (upper-lower+1) + lower;    //[lower,upper]`
Use Storybook with Lando
Tags: storybook, lando, javascript, docker
Published: 2022-04-13 14:01:21

If you're using Lando to manage your containers because you're that cool, I'll show you my way to make Storybook works painlessly with Lando.

First open your `.lando.yml`, and add the mandatory node service: 

```yaml
services:
  node:
    type: node
```

Then, you're gonna need some tools to install Storybook and run it:

```yaml
tooling:
  npm:
    service: node
  npx:
    service: node
```

Now you can install Storybook. If you're using TailwindCSS and Laravel, you can [follow my guide over here](https://dev.to/rachids/use-storybook-with-laravel-jetstream-inertia-and-tailwindcss-41oa).

In order to provide access to it, you need to add a proxy to the port, like this:

```yaml
proxy:
  node:
    - storybook.my-lando-app.lndo.site:6006
```

Final file:
```yaml
name: storynertia
recipe: laravel
config:
  webroot: app/public
  php: '8.1'
proxy:
  node:
    - storybook.storynertia.lndo.site:6006
services:
  node:
    type: node
tooling:
  npm:
    service: node
  npx:
    service: node
```

Enjoy your containerized Storybook!
Anti-Theft GPS Tracker and Recovery System
Tags: iot, sms, gps, cellular
Published: 2022-04-13 14:00:21

{% youtube 222JbIOauIg %}

The words “asset tracking” typically bring to mind moving dots on a map: cars, trucks, planes, and the like. Things that are supposed to move.

But think about things that _shouldn't_ move, things that, if they are on the move, means something is amiss: historical statues, expensive environmental monitors, high value equipment in storage, or even (believe it or not) beehives.

In this [Hackster project](https://www.hackster.io/paige-niedringhaus/blues-where-s-my-car-5eac7d), I built a [Blues Wireless Notecard](https://blues.io/products/notecard/)-powered anti-theft tracker that integrates with [Twilio](https://www.twilio.com/) to send SMS alerts to a user’s phone when motion is detected, complete with last known location coordinates and a simple Google Maps URL link.

At a high level, here’s how it works:

* The ultra-low-power [cellular Notecard](https://blues.io/products/notecard/) (a mere ~8uA when idle) is configured to act as a GPS device, and only begin taking location readings when motion is detected.
* When it’s in motion, it begins taking GPS tagged readings every minute and sending them as JSON data to [Notehub](https://notehub.io/) - a thin cloud service that securely accepts data from the Notecard.
* Notehub immediately transforms the raw JSON with the help of [JSONata](https://docs.jsonata.org/overview.html) into a payload of relevant info for [Twilio](https://www.twilio.com/), and routes this data on.
* Finally, Twilio forwards this data along to the user’s phone and they receive an alert like the screenshot below, with a clickable [Google Maps](https://www.google.com/maps/) link. Hopefully speeding up recovery of whatever’s gone missing.

![Twilio alert complete with Notecard name, last time seen, and location and Google Maps link.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fgrywmfwsnmhgt82p30k.png)_The Twilio alert complete with Notecard name, last seen time and location and Google Maps link._

To see how I built this, [view the full tutorial on Hackster](https://www.hackster.io/paige-niedringhaus/blues-where-s-my-car-5eac7d), where I detail exactly how to set up the hardware and software that made this anti-theft and recovery device possible.
Day 8: Almost finished with React
Tags: 100daysofcode, beginners, javascript, react
Published: 2022-04-13 13:53:56

*The Feynman technique says that teaching a subject makes you better at it, which is what I'm trying to do here. You may correct me if you saw mistakes in this post*

## State updates based on previous state

Sometimes we want to update a state based on its previous... state. For example, a Count Dracula 🧛 button where each time people click it, the state increments by one (Gonna add this one on my future portfolio site.)

React is very well built, however. Too well build. React will bundle state updates to save resources. The impact is things become *asynchronous*, which is a massive pain in the ass to debug 🤧.

To fix this, we can use this syntax:
```jsx
this.setState((state, props) => ({
  count: state.count + props.increment
}));
```
The brackets around the object is just a syntax.

## Stateful components, and where to ~~find~~ use them 🐉.

The *main* paradigm of React is a unidirectional data flow. It just means that data is passed down from parents to children, and children should only communicate to parents by calling functions.

So what does this means? Well, you only need a few (if not one) stateful component as parent, handling the app logic. The rest of the components only serve to handle the bling-bling ✨.

You can break down the whole app into small components, that can be controlled by a few, big stateful components.

## Afterwords

The React course on FreeCodeCamp at this point focuses on more examples and practices. So tomorrow would be kinda mind-bending 💫, but almost no new thing. I dunno what to post tomorrow 🤣.

Follow me on [Github](https://github.com/Kemystra)!
Also on [Twitter](https://twitter.com/kemystra)!
C++ Creator Bjarne Stroustrup Interview
Tags: cpp, webdev, programming, writing
Published: 2022-04-13 13:48:59

We had a great talk with Bjarne Stroustrup, the designer and original implementer of C++. He is also the author of The C++ Programming Language (Fourth Edition), A Tour of C++ (Second edition), Programming: Principles and Practice using C++ (Second Edition), and many popular academic publications.

[Enjoy full interview here!](https://evrone.com/bjarne-stroustrup-interview)