teleren/devto huggingface dataset:
Scaffolding REST APIs with JWT authentication
Tags: api, php, restful, scaffolding
Published: 2020-07-27 15:51:57

[repo](https://github.com/sroehrl/neoan3-demo-api)

## Scaffolding an API?

While walking students through a neoan3 tutorial the other day, I noticed a demo I built could actually be used to scaffold an API for all kind of use-cases. The result of what I built went far beyond the original plan: to create a simple backend for testing and developing. Through to the architecture of this creator tool, one can use it to quickly set up a simple API and later built it out to be a scalable and robust production solution. That's right! A cli-based generator of API endpoints that scaffolds a solid backend for you.

First, let's have a look at setting it up.

## Prerequisites
All you need is a local PHP installation (7.4), composer and [neoan3-cli](https://github.com/neoan3/cli) (make sure you install it globally and that it is available in your path)

## Installation

```bash
composer create-project sroehrl/scaffold-api
cd scaffold-api
neoan3 develop
```

At this point you should see that the server started on localhost:8080. All endpoints are exposed at ***localhost:8080/api.v1/***


#### What now?

The app already ships with authentication based on JWT, so we can use our existing app (or postman?) to register a user:

***POST /api.v1/users***

You can make changes to the register & login behavior by going to "/models/users/users.model.php", but by default, the model expects at least 

- userName and 
- password

as fields. You can add whatever else you want to store to the user. Once created, the API will respond with a status code of 200, as well as your user-object and a JWT token. 

_NOTE:_ per default, all custom endpoints require a valid baerer token. So unless you fire at the login (POST /api.v1/users/auth) or the registration (POST /api.v1/users), you will need to use this token as authorization header (look at the javascript examples in the readme).

## Custom endpoints

Now the interesting part: Authentication is the starting point, but what then? A simple command creates additional endpoints:

`php scaffold tags` for example, will generate the following files:

***/component/tags/tags.ctrl.php*** and ***/model/tags/tag.model.php***

Their content will make the following endpoints available:

***POST /api.v1/tags*** creates new tag

***PUT /api.v1/tags/:tag-id*** updates a tag

***GET /api.v1/tags*** lists/searches for tags (get-parameters with conditions can be used)

***GET /api.v1/tags/:tag-id*** retrieves specific tag by id.

Want to make your endpoint public for now? Simply comment out `Stateless::restrict()` in component/tags/tags.ctrl.php in the appropriate method function.

So far so good. Now simply send a POST call with a json-payload to /api.v1/tags and you have your first tag.

Let me know what you think!
Quick Tip When Searching for Basic Web Info
Tags: html, webdev, productivity, tech
Published: 2020-07-27 15:41:17

I was doing a little bit of work earlier and I needed to look up some info on the Content-Type header. When doing searches like this here's a quick tip that will help you get really good information:

Prefix your searches with the string **"mdn"**

So in my case I googled **"mdn Content-type"**. This will lead you to the relevant article on the Mozilla Developer Network. This is by FAR the best reference on basic web tech. Consider this the Encyclopedia Brittanica of the web. It's always best to start here, then broaden your search if you need more.

This tip is applicable when you need information on the following things: **HTML, CSS, JavaScript, Web API's (service workers, fetch, etc)**.

Happy coding!

Signup for my newsletter [here](https://thinkster.io/?previewmodal=signup?utm_source=devto&utm_medium=blog&utm_term=searchingforbasicwebinfo&utm_content=&utm_campaign=blog).

Visit Us: [thinkster.io](https://thinkster.io?utm_source=devto&utm_medium=blog&utm_term=searchingforbasicwebinfo&utm_content=&utm_campaign=blog) | Facebook: @gothinkster | Twitter: @GoThinkster
WFH Tip: Prevent Windows Locking
Tags: python, productivity, career
Published: 2020-07-27 15:40:52

I am a CS engineer and working from home since March 2020. I haven’t been to my office since the last 4–5 months (WFH all the way!!).

I have a dual monitor setup with my laptop, Xbox One and a third screen of the HP Probook (provided by my organization).

## The problem

When I am working on my personal laptop for extensive periods or streaming on Twitch ([spartan_259](https://twitch.tv/spartan_259/) 🎮), i.e. not using the office laptop, it would automatically lock. This would prevent any notifications from Microsoft Teams, Skype (would show my status as *inactive*, it doesn't look good) or even Outlook. As I don't have administrator rights so I couldn’t change the settings. This was an issue for me.

To prevent Windows from locking one can play a YouTube video at all times or maybe keep some keyboard button pressed or some other OOB method. We all must agree here that none of these are practical.

## Solution

I wrote a Python script ( I 💖 Python).

I have used a keypress simulation, I tried with a mouse cursor movement but it didn't work (Windows would lock and eventually sleep).

{% gist https://gist.github.com/shashankm28/9298fd49ec8c51ec988254a16b8b981e %}

When the script is executed, it asks for the key which keypress has to be simulated. A small note here, this code will keep running (infinite loop) and has to be manually stopped (CTRL + C).

I guess for most of us it would suffice. 😁

* Uses around 15mb of RAM and less than 1% of CPU (Windows Task Manager stats)
* Skype/Teams would always show *Available* -- Ultimate goal, wouldn't want to upset the boss | I don't use my office laptop whole day.

> I am working on a more feature rich version. Would update soon!

## Output

```
Prevent Windows lock
Enter keyboard button: capslock
Running
```

The script will prompt to enter a keyboard button, following buttons are supported -
https://pyautogui.readthedocs.io/en/latest/keyboard.html#keyboard-keys

Thanks for reading, I hope this helps.
Checkout Animation Microinteraction for E-Commerce
Tags: codepen, javascript, typescript, showdev
Published: 2020-07-27 15:34:57

# Checkout Animation Microinteraction for E-Commerce
This is a microinteraction when clicked on a button, the animation of a delivery truck will be shown, and it will appear to be delivering a product/s that was put inside the parcel box.

To make an illusion of speeding up entrance of the truck, I used CSS skewX property. -45deg for the entrance, and 45 for exit.

I used GSAP timeline to make the sequence of animation.

I created a simple SVG asset for the image of a truck, using Inkscape application on Linux.

The box is created with HTML element, adding CSS to make an appearance of a box.

the shadow at the truck, and parcel was done using CSS filter: drop-shadow. Its usage is almost as the same as using CSS box-shadow.

This animation may be used in e-commerce website, implementing online store.

I created the code using Typescript.

You may look how it works by clicking the link below.

[Checkout Animation Microinteraction for E-Commerce](https://codepen.io/takaneichinose/full/XWXOGeq)

### Testing on local

To test this animation on local computer, NodeJS is required to be installed in your device.

If you have NodeJS on your device, just run the command below at the same directory as the project

``` npm install gsap ```

More information about GreenSock

[GreenSock](https://greensock.com/)

### My repository

Please consider visiting my [Github repository](https://github.com/takaneichinose/checkout-animation) for this project.

{% codepen https://codepen.io/takaneichinose/pen/XWXOGeq %}
Design is Simple !
Tags: design, uiweekly, css, html
Published: 2020-07-27 15:30:01

>> Whenever Am working on a project or facing the UI issue in 
   project, I have only one thing in my mind that is "Design is 
   Simple".

>> If am facing the issue in UI firstly I don't panic and thought 
   it might be a simple one which I can fix in a minute and am 
   trying to do analysis of that cause from the root so it makes 
   my mind clear and lead my to go forward and I always try to 
   find a simple solution for that cause.

>> So make a thought that "Design is Simple !"
and one of my favorite Quote is - 

 " If you can't do great things, Do small thing in a great way ! "
Store array data in keyed-objects for better performance
Tags: react, webdev, performance, javascript
Published: 2020-07-27 15:18:52

There are plenty of ways to store client-side data in Javascript and React, not to mention  ES6's data structures like `Set` and `Map`, but sometimes all you need is a simple object. 

I use this pattern almost daily in combination with redux and/or context to streamline data access. I want to demonstrate how we can use a keyed-object to increase performance vs. storing data in a typical array.

# Problem Example
Let's say we're fetching an array of people from an API to display a list:
```javascript
[  
  {
    'id': 1,
    'name': 'Keanu Reeves',
    'bio': 'Bad ass' 
  },
  {
    'id': 2,
    'name': 'Elon Musk',
    'bio': 'Space cowboy' 
  },
  ...
  {
    'id': 20,
    'name': 'Tom Hanks',
    'bio': 'Toy cowboy' 
  },
]
```
Assuming we store this array somewhere client side, if we wanted to access a particular user by ID, we would need to do something like `people.find(x => x.id === 1)`. This has a **time complexity of O(n)** and can be expensive if the array is large.

*O(n) means the larger the array gets, the longer it can take to find what you're looking for! This is because it has to potentially check every item in the array 👎*

# Solution Example
By looping through the results in the API response, we can build a keyed-object.
```javascript
const keyedObject = {};
response.map(person => {
  const {id, ...rest} = person
  keyedObject[id] = rest
});
```
### Added bonus (looping)
If we need to loop through the data to display a list for example, we can create an array to store the IDs.

The final solution might look like this:
```javascript
const keyedObject = {};
const ids = response.map(person => {
  const {id, ...rest} = person
  keyedObject[id] = rest
  return id
});
```
Now we can quickly access our data by ID with **O(1) time complexity** and loop through the data using our `ids` array.

*O(1) is great for performance because no matter how large the array or object is, we can always go straight to the item we want! 👍*
```javascript
const name = keyedObject[personId].name
const allNames = ids.map(id => keyedObject[id].name)
```
Thanks for reading! 😃
REST API Snippets
Tags: rest, api, restful
Published: 2020-07-27 15:12:57

A ideia é trazer um conteúdo mais rápido e direto sobre REST API's. Vou tentar trazer um problema real, e uma sugestão de solução abordando temas como design de api, governança e métricas!!!

##Problema

Precisamos modelar um endpoint que vai fazer trazer informações de contratos.

### Contrato da API
```
{
  "idContrato": 000,
  "nome": "",
  "cpf": "",
  "status": "",
  "saldoDevedor: ""
}
```
### Endpoint GET

Vamos trabalhar com a obtenção dos dados de contrato, com algumas premissas:
 * Um cliente pode ter vários contratos
 * Proteger o backend de possíveis ataques para descobrir atualizações, ja que a regra de negócio nos permite atualizar esse status apenas uma vez por dia.
 
A primeira coisa a pensar é o design do endpoint, e aqui não tem muita coisa que inventar. Como estamos manipulando recursos (no plural) o ideal é que possamos utilizar **/contratos** como ponto de partida.

Agora a parte, que pouca gente se preocupa é que futuramente esse endpoint vai ser utilizado por outras soluções que precisam aplicar alguns filtros para trazer os dados. E aqui a dica é simples, use e abuse de query params.

Pensa que você precisa trazer todos os contratos inadimplentes, ou ainda, precisa de todos os contratos de um CPF específico. Para casos como esse (simples de certa forma), as boas práticas do REST, cobrem este ponto perfeitamente.

Exemplos:

* Lista todos os contratos do CPF em específico:
 * GET /contratos?cpf=0000000

* Lista contratos inadimplentes
 * GET /contratos?status="inadimplente"

* Contratos do CPF específico e que estejam adimplentes.
 * GET /contratos?cpf=00000&status="adimplente"

Parece besteira, mas com coisas assim habilitamos o negócio para construir os produtos sem reescrever tanto código.
Além da aceleração do negócio, conseguimos ganhar algumas coisas com implementações assim:
 * Cache - Podemos habilitar o cache, por algum query param, e viabilizar o correto dimensionamento de recursos. Pensa que neste caso hipotético, o status muda 1 vez por dia, então pra que ir no backend sempre? Podemos utilizar o CPF como chave do cache nessa consulta e manter o TTL de 1 dia. Caso precise invalidar o cache antes, condicione esta rotina ao chamar um endpoint de atualização do status por exemplo...
 * Aproveitamento de recursos - Com implementações assim, garantimos menos código para manter (imagina expor um endpoint pra busca por cada status, ou por cpf, ou ainda que combine duas coisas).

## Conclusão

Existem outras tecnologias, que poderiam ser incorporadas para tornar a implementação mais flexível (OData, GraphQL), mas novas tecnologias precisam ter seu propósito bem definido para valer o custo de implementação dentro de nossos projetos. Com coisas simples, e com menos dor de cabeça é possível atingir o mesmo objetivo. Afinal, menos é mais!!
What are UNIQUE index limitations?
Tags: database, computerscience, mongodb, discuss
Published: 2020-07-27 14:59:03

MongoDB will throw an error if string indices are being too large.

For SQLite, you can indeed create a unique index on `DESCRIPTION`, or `VARCHAR(VERY_LONG)` fields, and **probably not throw an error**; but are you really willing to accept the consequence?

Even for non-unique indices, probably not all indices helps querying performance that much?

Now that [I looked it up](https://en.wikipedia.org/wiki/Database_index#Types_of_indexes), I don't even understand most of the terms.

- Bitmap index
- Dense index
- Sparse index
- Reverse index
- Primary index
- Secondary index

Even for MongoDB and [nedb](https://github.com/louischatriot/nedb/), there are choices of Unique Indices, [whether sparse or not](https://github.com/louischatriot/nedb/#indexing).

Now, I am curious on how to design a **strongly typed** database, with good querying performance, especially if flat and involves minimal joins?

- About being well-typed, maybe [Nitrite](https://www.dizitart.org/nitrite-database.html) is a good one?
- Well-defined schema can potentially help with typing, but how? [Definitely not SQLite](https://sqlite.org/datatype3.html), though.
    - I like to work with Node.js, so TypeScript? What about the popular Golang?
    - **Does well-defined schema help with performance?**
Suteba - Simple Request Bin in PHP
Tags: showdev, php
Published: 2020-07-27 14:49:24

My day job requires me to perform troubleshooting on customer issues, some of which may include trying to understand what might be wrong in an API request payload.

While I could have used a service like [requestbin.net](http://requestbin.net/), it wouldn't be much of a learning experience, would it?

The solution, then, was to make my own little tool that I could use to help myself investigate these issues, which I have also decided to share with you guys, in case you might find it useful.

I present *Suteba*.

- Simple and light. No trackers. No bullshit.
- You own all the data.
- Multiple bins/buckets/dumps/whatever.
- Listing feature of requests per bin.

![Request list](https://dev-to-uploads.s3.amazonaws.com/i/e62kighi7qgcmcinwoqi.jpg)
![Single Request](https://dev-to-uploads.s3.amazonaws.com/i/y9f1a4f43rpktr5pj46o.jpg)

*Note:* Features are sparse to make Suteba simple and light. You're more than welcome to suggest additions, but please keep the simplicity in mind.

Available on
[SourceHut](https://git.sr.ht/~hxii/suteba)
[GitHub](https://github.com/hxii/suteba)
Hola mundo con React.js (para dummies)
Tags: react, javascript, webdev, spanish
Published: 2020-07-27 14:46:17

En el post [Como crear un proyecto desde cero con React.js](https://dev.to/crisfer4217/como-crear-un-proyecto-de-react-js-desde-0-create-react-app-49f6) comentamos el proceso a seguir para poder empezar a trabajar con esta tecnología. 

En el presente artículo aprenderemos a eleborar un Hola Mundo para ello seguiremos los siguientes pasos:

* Creamos un nuevo proyecto de React.js usando `create-react-app`. 

* Usando el editor de código o IDE de su preferencia (en mi caso VScode) abrimos el proyecto y tendriamos un sistema de carpetas como el siguiente: 

![img_1](https://raw.githubusercontent.com/crisdux/img-dev-to/master/react/1.png)

* Para realizar este ejemplo trabajaremos con el archivo `index.js` de la capeta `src` (`src/index.js`). Al abrirlo podremos observar las siguientes lineas de código:

![img_2](https://raw.githubusercontent.com/crisdux/img-dev-to/master/react/2.png)

Procedemos a borrar todo el contenido de ese archivo.

* Copiamos el siguiente código:

```javascript
import React from 'react'; // importamos react
import ReactDOM from 'react-dom'; // nos permite renderizar en el DOM
const HolaMundo = <h1>Hola Mundo</h1>
//selecionamos el id donde se renderizara el componente
const root =  document.getElementById('root'); // hay un div con id root en index.html
ReactDOM.render(HolaMundo, root); // pinta en la pantalla la constante HolaMundo en el div con id root
```
> ReactDOM se encarga de renderizar en pantalla el componente creado.

En `public/idex.html` se encuentra el siguiente código:

```javascript
<div id="root">
</div>
```
Es en este div donde se renderizará el componente.

Finalmente ejecutamos `npm start` para ver por pantalla el texto: "Hola Mundo".

---

## Referencias

* https://www.udemy.com/course/universidad-react-de-cero-a-master/
Dev.to Writing: Making a Series!
Tags: meta, writing, tutorial, howtodevto
Published: 2020-07-27 14:43:18

In response to the cry for help: 

{% link https://dev.to/sbu_05/a-cry-for-help-4pdp %}

Here's everything you need to know about series on Dev.to!

# Making a series

If you remember from the [previous article](https://dev.to/kallmanation/dev-to-writing-the-two-editors-mel), there's two editors here on DEV.

For the Basic markdown editor, simply add `series: My Series Name` to the front matter (aka the stuff between the dashes `---` at the top).

For the Rich + markdown editor, click the Post options button at the bottom of the editor (the little circle with a hexagon around it).

![Dev.to editor buttons, including the Post options button](https://dev-to-uploads.s3.amazonaws.com/i/xhd3jggcqkxaxl08skbi.png)

Then, enter a new value in the "Series" input box to create a new series, or click one of your already ongoing series.

![Dev.to Post option pop-up editor](https://dev-to-uploads.s3.amazonaws.com/i/8hkt1x6vi9tjuj5i624p.png)

And you've made a series!

# Actually making a series

If you preview or publish your first series post, you may notice something.

Nothing happened.

This is because Dev.to will only include that nice series list at the top and bottom of the article (as you can see on this one) once there are at least two published posts in the series. (This also applies to new unpublished posts in the series; in preview they will not appear in the list and only appear once they are published).

It makes sense, but probably is not intuitive the first time you try to make a series.

So to _actually_ make a series, you will need to _actually_ write a series (of posts :) ).

_And you may return to old, already published posts and edit them to add them to a series. So if you've written a "standalone" article; then realized you have a great follow up; just add them both to the same series and viola! Instant series!_

---

That's it. I hope this helped answer your question @CoolCodekid.

If you have your own question, just ask in a comment. I read all of them and would love to add another post in this series that will actually help other writers in this awesome community!
How did you become a mobile dev (especially if you are full stack)?
Tags: discuss, android, ios
Published: 2020-07-27 14:32:14

Mobile seems to be a big market, and money-maker, at least according to my non-dev friends.

Can you share your journey on how long does it takes, what does it takes, and why did you get the privilege to do mobile dev?

I would be interested to learn about whether mobile needs a server, how did you connected to it with security; and did you make the server at all in the first place as well (do you rely on third-party services or co-workers?).
Design for people!
Tags: design, uiweekly, ux, career
Published: 2020-07-27 14:20:25

👋 #Introduction
Since all these years I have been designing and for a couple of months now I have come to realize that design essentially is not for you to appeal or even the client at times if you look at in a way. For example, if you have a client whose business is to sell products and get sales then who are you designing for? If you ask me then it is for the end-users really. You design a poster and it has to be taken well by the probable customers of your client. Right? 

![story time gif](https://media.giphy.com/media/Idz7cyLRe2bVm/giphy.gif "story time gif")

🎤 #Storytime
Why am I coming up with this points? Because whenever I design something for the user and the client does not like it then I feel it is my job to explain to the client that why I have designed what I have designed and the reason I feel it will cater to the user better. For instance, I have had a client saying you should change the font, so I do not disagree instantly thinking he might have something to add it with respect to end-users and I ask why, but instead, they say that they did not like the font, it's not bad but they personally did not like it; now this is where I feel I should explain that why I have chosen that particular font and how it will affect the user psychology and cater to them. Here is when the client really understands and we try to come up with a middle-ground.

💡 #Clients are Smart!
I would also like to add that everything clients say does not have to be wrong while their design perspective can be immature but they are smart too they have been running a business and they understand the clients too, so try to communicate as much as possible, your designer ego might hurt but it is for the greater good :P

 ###One who empathizes is the one who designs the best
![feedback gif](https://media.giphy.com/media/4T3p7SAt2qGk59OQR4/giphy.gif "feedback gif")