teleren/devto huggingface dataset:
How to Use URL Parameters and Query Strings With React Router
Tags: webdev, programming, react, javascript
Published: 2021-01-23 19:51:12

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

React is a library for creating front-end views. It has a big ecosystem of libraries that work with it. Also, we can use it to enhance existing apps.

To build single-page apps, we have to have some way to map URLs to the React component to display.

In this article, we’ll look at how to access URL parameters in React Router routes.

* * *

### Define Routes That Accept URL Parameters, and Get Them

To define a `Route` with a `path` that takes an `id` as a parameter, we can put a colon before the parameter name.

For example, we can write:

```
<Switch>  
    <Route path="/:id" children={<User />} />  
</Switch>
```

Then we can use the `useParams` Hook to get the URL parameter.

We can write a full example as follows:

In the code above, we have the `Switch` component in `App` with the `Route` inside as a child. The `path` prop is set to `/:id` , which means that we can use the `useParams` Hook later to get the route parameter.

Then in the `children` prop, we pass in the `User` component, which we want to display.

Also, we added `Link` components with the links that we can click to go to the URL with the given URL parameters in the `to` prop.

Then in the `User` component, we get the `id` from the URL parameter with the `useParams` Hook.

Finally, we display the `id` in the `User` route.

* * *

### Get and Set Query Strings

We can define and use a `useQuery` Hook in a component to get query parameters. To pass in query parameters, we just add them to the `Link`s `to` props as usual.

For example, we can write the following:

We first defined the `useQuery` Hook to get the query parameters of the URL via the `URLSearchParams` constructor. We get the `useLocation()`s `search` property.

Then we create a `QueryScreen` component to call `useQuery()` and get the `URLSearchParams` instance assigned to `query`. This is where we can use `query` to get the `name` query parameter by calling `get` with `'name'` passed in.

Then we pass in the value returned by `query.get(“name” )` to the `User` component as a prop and display it there.

* * *

### Conclusion

We can use the `useParams` Hook to get a URL parameter defined in `Route`s.

We can accept URL parameters in a `Route` by putting a colon before the parameter name in the `path` parameter, like `path=”/:id”`.

To add query strings in a path, we just append it directly to the path.

Then we can convert the query string into a `URLSearchParams` instance, and we can use the `search` property of that to get the query string.

We can then use the `get` method with the key name to get the value.
💎 GUI / Windows library for JavaScript Canvas 
Tags: javascript, p5, html, library
Published: 2021-01-23 19:36:35

Hello all,

I want to offer you a quick pick into a JavaScript library for creating GUI / Windows "apps" on HTML5 canvas.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7wj2tjiih2mazdh3y5b3.png)

Demo: [https://www.youtube.com/watch?v=6gvR7OEuqYk](https://www.youtube.com/watch?v=6gvR7OEuqYk)

The library has an educational aspect and will be used primarily on the [codeguppy.com](https://codeguppy.com) website (free coding platform).

It is also intended to release the library as open-source library to all p5.js developers.

Please provide feedback if you are interested in this library. You can write a comment here or send Tweet to [@codeguppy](https://twitter.com/codeguppy).
Open-source JavaScript platform
Tags: node, javascript, webdev, programming
Published: 2021-01-23 19:36:17

__Total.js Platform__ is a collection of libraries, packages, UI components, practices, and complete products written in pure JavaScript / Node.js. Most of our libraries and UI components are without any 3rd party dependencies. Total.js Platform is a proven and stable platform for various cases like web apps, REST services, E-commerce, intranet apps, hybrid mobile apps, and real-time apps.

---

__Total.js Platform offers you__:

- Rapid and powerful development of web apps
- High performance
- Fully scalable
- [Node.js server-side framework](https://www.totaljs.com/framework/) called Total.js without dependencies and with significant functionality
- [Client-side library](https://www.totaljs.com/jcomponent/) for creating SPA and reusable UI components
- More than [230 free and reusable UI components](https://componentator.com)
- Clean and beautiful [documentation](https://docs.totaljs.com)
- [Live chat support](https://platform.totaljs.com) with authors and contributors (or on [Total.js Telegram](https://t.me/totaljs))
- [Cloud development](https://www.totaljs.com/cloud/)
- [Visual programming interface for the building of server-side apps](https://www.totaljs.com/appbuilder/)
- [Visual programming interface for IoT](https://www.totaljs.com/flow/)
- [Attractive Node.js Process Manager Node.js Process Manager](https://www.totaljs.com/superamdin/) tool with monitoring and auto-generating of SSL
- [Cloud Code editor](https://www.totaljs.com/code/)
- [Node.js CMS with an embedded database and zero configuration](https://www.totaljs.com/cms/)
- [Intranet platform](https://www.totaljs.com/openplatform/)
- A lot of resources
- Total.js Platform is a free and open-source
- You won't need any external tools for web development

---

Website: https://www.totaljs.com
Do you have any questions? [Join to community](https://t.me/totaljs)

{% youtube Gc2tStqKtBA %}

- [Start to develop in two minutes](https://blog.totaljs.com/posts/506916001sr61b/)

### Sneak peek

![Total.js apps](https://dev-to-uploads.s3.amazonaws.com/i/u2562ss22prh3ztc5sd5.jpg)
Verificar a idade em Python
Tags: beginners, python, programming
Published: 2021-01-23 19:28:13

Estou apredendo a programar, então se o código abaixo estiver com alguma informação incorreta, por favor deixe a explicação correta nos comentários.

```python
while True: 
idade = int(input("Informe sua idade: "))
     if idade <= 5 :
        print("Você é uma neném")
     elif idade <10 :
        print("Você é uma criança")
     elif idade >18 :
        print("Boa sorte com os boletos")
     else
        print("Favor inserir um valor númerico")
        break
```
Como o código aparecerá para o usuário:

Informe sua idade: 22
Boa sorte com os boletos

OU

informe sua idade: ab
Favor inserir um valor númerico

Explicação do código:
```python
while True: 
#para que assim que fechar o código possa repetir o código automaticamente

idade = int(input("Informe sua idade: ") )
#variável para guardar a informação que o usuário irá inserir

     if idade <= 5 :
 #se a idade informada pelo o usuário for menor que 5, irá aparecer a imagem você é um neném

        print("Você é uma neném")
     elif idade <10 : 
        print("Você é uma criança")
     elif idade >18 :
        print("Boa sorte com os boletos")
     else:
#caso o usuário não informe um número o programa mostrará a mensagem abaixo e fechará o programa

        print("Favor inserir um valor númerico")
        break
```
PII in GCP
Published: 2021-01-23 19:26:12

Due to the cancelation of the **privacy shield framework** and **Schrems II**, you might no longer be able to use store customer details in the GCP.

A solution for it can be **pseudonymisation**.

I am running an open-source project that can help you with that. 

Check out the following article for more information:

https://databunker.org/use-case/schrems-ii-compliance/
Comprar pão em Python
Tags: beginners, programming, python
Published: 2021-01-23 18:48:28

Estou apredendo a programar, então se o código abaixo estiver com alguma informação incorreta, por favor deixe a explicação correta nos comentários.


```python
def comprar_pao (preco = 1, dinheiro = 10);
     pao = int(input("Quantos pães você deseja comprar?" ))
     total_da_compra = pao * preco
     print("O valor da compra é R$" + total_da_compra)
     troco = total_da_compra - dinheiro

     if total_da_compra <= dinheiro :
        print("O seu troco é de R$ " + troco +". Obrigado volte sempre!")

    else:
       print("Infelizmente não foi possivel realizar a compra. Sentimos muito")
```

Como o código aparecerá para o usuário:

Quantos pães deseja comprar? 5
O valor da compra é R$ 5
O seu troco é de R$ 5. Obrigado volte sempre!

OU 

Quantos pães deseja comprar? 12
O valor da compra é R$12
Infelizmente não foi possivel realizar a compra. Sentimos muito


Explicação do código:
```python
def comprar_pao (preco = 1, dinheiro = 10); #O def será utilizado para definir a funçao. 
"""utilizamos underline na variável, pois o python não aceita variável aceita espaço"""
"""dentro da variável podemos definir alguns fuções"""

     pao = int(input("Quantos pães você deseja comprar?" ))
#definimos a variável pao,permitimos que ele responda utilizando o input
"""O int é utilizado para quando o usuário informar o número o python entenda que se trata de um número e não de texto assim permitindo realizar a conta"""

     total_da_compra = pao * preco 
"""variável total_da_compra criada para armazenar a multiplicação da quantidade de pães comprado e o valor do pão"""

     print("O valor da compra é R$ " + total_da_compra) 
"""irá mostrar o valor total da compra para usuário"""

     troco = total_da_compra - dinheiro

     if total_da_compra <= dinheiro :
"""fara a validação do valor que o usuário possui com o valor total da compra então se a compra deu pr exemplo 12 reais e o usuário só possui 10, automaticamente o python entende que ele não possui dinheiro suficiente e passa para a proxima etapa o else"""

        print("O seu troco é de R$ " + troco +". Obrigado volte sempre!")

    else:
       print("Infelizmente não foi possivel realizar a compra. Sentimos muito")
```
Ants Colony demo in Javascript
Tags: showdev, creativecoding, javascript
Published: 2021-01-23 18:44:05

Nice simulation, created a long time ago by Tom de Smedt, author of NodeBox
For more info see here : [PatternCanvas](https://github.com/clips/pattern/wiki/pattern-canvas)
Enjoy :-)


{% codepen https://codepen.io/artydev-the-scripter/pen/mdrYapV %}
How to setup a minimal GraphQL server with Express and Apollo Server
Tags: graphql, apollo, express, beginners
Published: 2021-01-23 18:35:49

---
title: How to setup a minimal GraphQL server with Express and Apollo Server
published: true
description: A minimal GraphQL server developed with Express and Apollo Server
tags: graphql, apollo, express, beginners
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/2uphizmo6h6y87imkue6.jpg
---

At the end of this article you will be able to create a minimal GraphQL from scratch using ExpressJS and Apollo Server.

If you're reading this article I expect you to have a basic knowledge of ExpressJS, GraphQL and Apollo. If not, this article won't help you so much but you can still take a look to it if you're interested.

To make up for it, I leave here some useful URLs where you can learn more about those topics:

- https://expressjs.com/
- https://graphql.org/
- https://www.apollographql.com/

## Setting up and dependencies installation

```
mkdir graphql-server-express
cd graphql-server-express
```

```
npm init -y
```

```
npm install express apollo-server-express
npm install --save-dev @babel/core @babel/node @babel/preset-env babel-cli babel-preset-es2015 nodemon
```

Pretty straight-forward so far, right? Good.

### Let's jump into the code

Create a `.babelrc` file in the root folder

```
{
  "presets": ["@babel/preset-env"]
}
```

This file will enable us to use some ES6 capabilities such as the use of `import`. 

Create `src` folder and the `index.js` file in it as follows

```
import express from "express";
import { ApolloServer, gql } from "apollo-server-express";

const typeDefs = gql`
  type Query {
    hello: String
  }
`;

const resolvers = {
  Query: {
    hello: () => "Hello world!",
  },
};

const server = new ApolloServer({ typeDefs, resolvers });

const app = express();
server.applyMiddleware({ app });

app.listen({ port: 4001 }, () =>
  console.log(`Server listening on http://localhost:4001${server.graphqlPath}`)
);
```

A couple of things about this file:

- This is the entry point of the server
- I use one file for all the code just for simplicity - you can decide to split it into multiple files
- I use the port `4001` but you can use another port if you want

### How to start the server with `nodemon`

Now update the `script` command in the `package.json` file as follows

```
...
  "scripts": {
    "start": "nodemon --exec babel-node src/index.js"
  }
...
```
Now run `npm start` in the terminal. The GraphQL Playground will be available at `http://localhost:4001/graphql` (or any other address/port you used).

I published this little project on GitHub for future reference {% github rossanodan/graphql-server-express %}
The lowly Interface
Tags: typescript
Published: 2021-01-23 18:24:23

We want to hook up window resize events easily. So we create this function.

```typescript
import { Subject } from 'rxjs';
interface wh {
  width: string;
  height: string;
}
const sub = new Subject<wh>();
export function _resizeEvent(): Subject<wh> {
  debugger;
  window.addEventListener('resize', (ev) => {
    let window = ev.target as Window;
    let ele = window.document.activeElement as HTMLElement;
    let width = ele.offsetWidth.toString();
    let height = ele.offsetHeight.toString();
    sub.next({ width: width, height: height });
  });
  return sub;
}
```
To use the code above:
```typescript
import { _resizeEvent } from './functions/observers';

_resizeEvent().subscribe(result=>{
       this.width=result.width;
    }); 
```
Intellisense now shows us both properties as we type.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pgalxd32cfrbpl6qu71t.gif)

Note that interface definitions, unlike class definitions do not support the new keyword. This is pretty much the only difference between the two.
Please, just please, no more VSCode
Tags: codenewbie, webdev, jetbrains, vscode
Published: 2021-01-23 18:20:37

Edit: Dammit, I miss the VSCode html snippets extension. Love hate relationship with VSCode.. xD

Configuring projects in VSCode is incredibly annoying a lot of the time, especially when you are building projects in many different types of frameworks. It's great when you first start if you're sticking only to one thing and have a mentor to teach you, but once you use an IDE like any of JetBrains stuff, you'll never go back. People pay for WebStorm, PHPStorm, PyCharm for a reason.. 

I've spent way too many hours bleeding through my eyes trying to set up projects, configuring extensions and whatnot (especially ESLint and Prettier).

For example, in a Vue project, the "go to definition" doesn't work in .vue files.. (at least for me it didn't).

Open up PyCharm, BAM, just comes integrated with no problems. 

Never going back. <3

Before you VSCode lovers jump on me, tell me, have you tried a JetBrains IDE for a full project?

That is all
Asana Automatization with Python.
Tags: python, automatization, asana
Published: 2021-01-23 18:16:13

---
title: Asana Automatization with Python.
tags: python, automatization, asana
cover_image: https://files.realpython.com/media/Modern-Web-Automation-With-Python-and-Selenium_Watermarked.08e8e08b976d.jpg
published: true
---

**Asana** is an awesome tool for handling your projects. Within this tool you'll find Workspaces, Projects, Sections and Tasks.

![Asana](https://dev-to-uploads.s3.amazonaws.com/i/tw9as20gtisnwx8hykt6.png)

There are multiple ways for sorting your tasks and projects in Asana. My main setting is having several projects that contains multiple tasks, and finally a global project called Weekly Tasks where I'm able to see, just with a glance, all the tasks of the current week. Easy and simple.

![Weekly Tasks View](https://dev-to-uploads.s3.amazonaws.com/i/hfz91yavbaw2rgn56s4a.png)

This way of organization has allowed me managing better my team schedule at job and my own personal life, where multiple tasks from multiple projects and side-projects might gather.

> A Weekly View allows you to have the control of your week and therefore your time.

Of course it's an interesting topic how to organise projects effectively but this is a discussion for another post. The main problem here is that I spent a lot of time cleaning and organising the Weekly View Project every day, so instead of continuing throughout this boring routine, I automatized the task.

---

Useful things before showing you the whole code:
* I have used Python (latest version) and the [Asana Python Library](https://medium.com/r/?url=https%3A%2F%2Fgithub.com%2FAsana%2Fpython-asana)
* You have to connect first to the Asana API using your API_KEY. [Check here about how to get it](https://medium.com/r/?url=https%3A%2F%2Fforum.asana.com%2Ft%2Foauth-personal-access-token-api-key-how-to-get-connected-to-asana-through-our-api%2F814). My recommendation is writting an external json file (adding it to the .gitignore file) with the API_KEY and others important keys instead of hard-coding it inside the main script.

![Asana - Connecting to the API.](https://dev-to-uploads.s3.amazonaws.com/i/bi9129d8ajzqevi7amzz.png)

* After that, you have to gather all the tasks that are attached to you or your team and iterate through those tasks.

* Each task has attached a gid . This is the ID of each task. Everything in the API works with ids. You can see those IDs (for workspaces, projects, sections and even tasks) in the Asana URL when you tap inside each element.

* You have to associate each task, using the gid to the project and section that you want to relate. Disclaimer: Afaik, every task should have associate a due date if you want to run successfully the script.

Here the whole script.

![Script](https://dev-to-uploads.s3.amazonaws.com/i/ow3whnj9kdf9cla49dom.png)

Finally, the only thing that you have to do is to automatize it using a crontab.
I hope that you find this script useful. You can tweak it and use it for other interesting Asana projects configurations.

Juan.
Depth first search on Graphs
Tags: computerscience
Published: 2021-01-23 18:07:39

Depth first search on Graphs is a very basic question on graphs and is necessary to solve any graph question of graphs.
A graph is  a data structure which is defined in terms of vertices and edges,that is, G=f(V,E).

**ALGORITHM**
In depth first search, we first mark all the nodes as 'unvisited'. We start from the root of the graph and mark it as visited, and then move on to its connected nodes. If the present node has any unvisited node then we move on to that node. In the absence of any unvisited node, we backtrack and move to another node. 

Let us implement the Explore function

**Explore(i)**
**mark all nodes as unvisited**

**for all i node in graph**
**{**
    **if node unvisited**
        **mark node as visited**
        **Explore(i)**
**}**



![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/z44ellhycl58g7qlwaib.png)

Hope this helps you!
How to Route using Subdomain in React. 
Tags: react, javascript, watercooler, webdev
Published: 2021-01-23 18:02:03

#### When i was making my portfolio in React , i wanted to have all components in different subdomains.
#### Eg : 
#### My domain : https://fredy.rocks/ ,
I want my Projects component at https://projects.fredy.rocks/,  
My blog at https://blog.fredy.rocks/ and more..
I really wanted to do that , but i found nothing.
After asking some of my seniors i finally did it with conditional component rendering .

It means if a url is having a specific subdomain , the component ( which we have assigned for the subdomain) should be rendered.


### Code 
We all know the Web API's .
Lets use window.location API
```javascript
if (window.location.host.split('.')[0] == 'projects' 
{
console.log("projects component")
}
```
Well this is the core idea i am using.
### What is window.location
```javascript
>>console.log(window.location)
>>
{hash: ""
host: "projects.fredy.rocks"
hostname: "projects.fredy.rocks"
href: "https://projects.fredy.rocks/"
origin: "https://projects.fredy.rocks"
pathname: "/"
port: ""
protocol: "https:"}

```
So window.location gives us the details about the current website url and other stuffs like hostname,href,pathname,protocol etc.

Our goal is to find the subdomain in the url.
```javascript
>> console.log(window.location.host)
>> projects.fredy.rocks
// Here we get the host of the website and the subdomain can be extracted after spliting the above result.
>> console.log(window.location.host.split('.')[0])
>> projects
// Yes we got the subdomain after spliting the host and getting its 0th index which in here is the subdomain name.

```

### __Lets get back to React.__

Lets do some basic react stuffs after using CRA template.

```javascript
import Projects from "./projects/Projects";
// Projects is the component i want to render 
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
// If you are using react router inside the component better wrap the component in </Router>

function App() {
  if (window.location.host.split(".")[0] == "projects") {
// It checks if the subdomain is named projects.
    return (
      <Router>
        <Header />
        <Projects />
      </Router>
    );
  }
  
export default App;
// Exporting App
```
That's the whole code needed to setup a subdomain based router in react.

You can add a else block and render a Error page if needed.

## __Contact__

***

* Feel free to email [me](mailto:fredysomy@gmail.com) for Bugs Found or queries.
  * [Twitter](https://twitter.com/FredySomy)
  * [Linkedin](https://linkedin.com/in/fredysomy)

* I will be happy to help.
* Cover image taken from [here](https://www.slideshare.net/randfish/seo-ux-so-happy-together/20-Site_URL_StructureSubdomainRoot_DomainSubfolderTotally_unnecessarysubfolderPage)
Day 23 - Sort the Matrix Diagonally
Tags: leetcode, python, challenge
Published: 2021-01-23 18:00:45

## The Problem

>A __matrix diagonal__ is a diagonal line of cells starting from some cell in either the topmost row or leftmost column and going in the bottom-right direction until reaching the matrix's end. For example, the __matrix diagonal__ starting from `mat[2][0]`, where mat is a `6 x 3` matrix, includes cells `mat[2][0]`, `mat[3][1]`, and `mat[4][2]`.

>Given an `m x n` matrix `mat` of integers, sort each __matrix diagonal__ in ascending order and return the resulting matrix.

 
__Example 1:__

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/k2cbxds7itlyn61lmp51.png)

```
Input: mat = [[3,3,1,1],[2,2,1,2],[1,1,1,2]]
Output: [[1,1,1,1],[1,2,2,2],[1,2,3,3]]
```

__Constraints:__

* `m == mat.length`
* `n == mat[i].length`
* `1 <= m, n <= 100`
* `1 <= mat[i][j] <= 100`


## Tests

```python
import pytest
from .Day23_SortMatrixDiagonally import Solution

s = Solution()


@pytest.mark.parametrize(
    "mat,expected",
    [
        (
            [[3, 3, 1, 1], [2, 2, 1, 2], [1, 1, 1, 2]],
            [[1, 1, 1, 1], [1, 2, 2, 2], [1, 2, 3, 3]],
        ),
    ],
)
def test_diagonal_sort(mat, expected):
    assert s.diagonalSort(mat) == expected
```

## Solution

```python
from typing import List


class Solution:
    def sort(self, mat, x, y):
        current_diag = []
        while x < len(mat) and y < len(mat[0]):
            current_diag.append(mat[x][y])
            x += 1
            y += 1
        current_diag.sort()
        while x > 0 and y > 0:
            x -= 1
            y -= 1
            mat[x][y] = current_diag.pop()

    def diagonalSort(self, mat: List[List[int]]) -> List[List[int]]:
        # For each diagonal in the matrix starting at the bottom left
        for i in range(len(mat)):
            self.sort(mat, i, 0)
        # For each diagonal in the matrix starting at the top right
        for i in range(len(mat[0])):
            self.sort(mat, 0, i)

        return mat
```

## Analysis

This solution was accepted but the analysis view on leetcode appears to be broken currently.

## Commentary

The simplest way I could imagine to solve this was to add each diagonal to a list, sort that list and then put the sorted list back in place of the diagonal.