teleren/devto huggingface dataset:
Animating two images transitioning horizontally with Python
Tags: python, datascience
Published: 2021-11-01 18:10:04

Hi, I'll start with showing what I'm trying to achieve (I couldn't come up with a shorter title).

![GIF](https://media.giphy.com/media/SxgzToumtHt8zmbzQS/giphy.gif)

We have two images, the second one slowly replaces the first (horizontally).

To do this we'll need to prepare two images with the same shape (I won't show how to scale them in python). 

> This method can be used to make any number of images transition (with a little bit of work).

## Loading images

First things first. Let's load two images.
```python
# We'll need them later
import numpy as np
import matplotlib.pylab as plt

from PIL import Image

image1 = np.array(Image.open('image1.png').convert('RGB'))
image2 = np.array(Image.open('image2.png').convert('RGB'))
```
In my case, this is the first image:
![Pikachu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bidvfa6hdxtge1z021hf.png)

And the second:
![Contour of Pikachu](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tktz260owo4lp12dga4m.png)

Both images are of shape: (339, 339, 3)

## Generating frames

Firstly, let's flatten our images, we'll take advantage of that later.

```python
fimage1 = image1.reshape((-1,3))
fimage2 = image2.reshape((-1,3))
```

To create animation we'll need to know how each frame will look. In my case I wanted to define a frame by a given part (`perc`) of pixels of the second image. For example if `perc=0.1` then first 0.1 pixels are from second image, and 0.9 are from first. `Fade` is a function that will do that. Given two flattened images, the original shape of the image and perc, it will concatenate the two images and return the image to the original shape.

```python
def fade(shape, fimage1, fimage2, perc):
    i = int(fimage1.shape[0] * perc)
    return np.concatenate((fimage2[:i], fimage1[i:, :])).reshape(shape)
```
Where:
- shape: tuple, shape of the original image
- fimage1: array, image flattened to shape (-1, 3)
- fimage2: same as fimage2
- perc: float, part of image2 to show

Here are some images that I generated with it:

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

## Creating animation

I won't go into details on how to create animations in Matplotlib, here's my code. 

```python
fig = plt.figure(figsize=(12, 10.8)) # Depends on aspect of your images
ax = plt.axes()
pic = ax.imshow(np.zeros(image1.shape)) # Create empty image of the same shape as image to plot
frames = 150 # Number of frames to generate

def init():
    pic.set_array(np.zeros(image1.shape))
    return [pic]

# This funtion generates i-th frame.
def animate(i):
    pic.set_array(fade(image1.shape, fimage1, fimage2, i/frames))
    return [pic]

anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=frames, blit=True)

anim.save('animaton.mp4', fps=60, extra_args=['-vcodec', 'libx264'])

plt.show()
```
The file `animation.mp4` should generate, depending on number of frames.
What is React #day31
Tags: javascript, programming, beginners, webdev
Published: 2021-11-01 18:04:07

#100daysofcode #day31

What Is React?
=> React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It lets you compose complex UIs from small and isolated pieces of code called “components”.

#DEVcommunity
#programming #react #javascript
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qq8dpkqzegguw0lt15va.png)
Bootstrap a consul cluster in AWS
Tags: aws, devops, consul
Published: 2021-11-01 17:39:28

I recently needed to stand up a test consul cluster, and I thought it might be useful to share my notes. Here's what you can do to quickly get a consul cluster going...

First, create an IAM role named `consul` and attach the AmazonEC2ReadOnlyAccess policy to the role.

Next, boot three Ubuntu instances, assigning the just-created role to them as the IAM role, and the following user data:

```
#!/bin/bash

curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add -
sudo apt-add-repository "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main"
sudo apt-get update && sudo apt-get install consul

echo "datacenter = \"$(ec2metadata --public-hostname | cut -d. -f2)\"" >> /etc/consul.d/consul.hcl 
echo 'server = true' >> /etc/consul.d/consul.hcl
echo 'bootstrap_expect = 3' >> /etc/consul.d/consul.hcl
echo 'retry_join = ["provider=aws tag_key=Role tag_value=consul"]' >> /etc/consul.d/consul.hcl

systemctl start consul
```

This will install the latest consul on each of the instances, configure consul to operate in server mode, and bootstrap the cluster.

You also want to add the `Role` tag with the value of `consul` to the instances. This is how the instances will find each other to form a cluster.

After you boot the instances, edit the security group to allow inbound traffic from the security group (so the instances can connect to each other).

Once those steps are done, you can confirm the cluster is working by connecting to any of the instances and running `consul members`. You should see the three instances listed as servers.

Now you can use your consul cluster by pointing consul clients at the private IP of any of the instances.
You (probably) don't need that useState + useEffect
Tags: react, javascript, codequality
Published: 2021-11-01 17:06:17

The `useState` and `useEffect` hooks were a godsend for the React community. However, like any tool, these can easily be abused.

Here's one an example of one misuse I've seen a lot in my tenure as a software dev:

```javascript
const MyAwesomeComponent = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState();
  // ---- PROBLEMATIC HOOKS: ----
  const [items, setItems] = useState([]);
  const [itemsLength, setItemsLength] = useState(0);

  useEffect(() => {
    someAsyncApiCall().then(res => {
      setData(res.data);
      setLoading(false);
    });
  }, [setData, setLoading]);

  // ---- UNNECESSARY USAGE OF HOOKS: ----
  // anytime data changes, update the items & the itemsLength
  useEffect(() => {
    setItems(data.items);
    setItemsLength(data.items.length || 0);
  }, [data, setItems, setItemsLength]);

  return (
    // ...JSX
  );
};
```

The problem with the above use case is that we are keeping track of some redundant state, specifically `items` and `itemsLength`. These pieces of data can instead be **derived** functionally from `data`.

## A Better Way:

Any data that can be derived from other data can be abstracted and re-written using pure functions.

This is actually pretty simple to pull off - here is one example:

```javascript
const getItems = (data) => {
  // I always like to protect against bad/unexpected data
  if (!data || !data.items) return [];

  return data.items;
};

const getItemsLength = (data) => {
  return getItems(data).length;
};
```

Then, our component is simplified to the following:

```javascript
const MyAwesomeComponent = () => {
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState();

  // DERIVED DATA - no need to keep track using state:
  const items = getItems(data);
  const itemsLength = getItemsLength(data);

  useEffect(() => {
    someAsyncApiCall().then(res => {
      setData(res.data);
      setLoading(false);
    });
  }, [setData, setLoading]);

  return (
    // ...JSX
  );
};
```

## Takeaways

The cool thing about this pattern is that `getItems` and `getItemsLength` are very easy to write unit tests for, as the output will always be the same for a given input.

Perhaps the above example was a little contrived, but this is definitely a pattern I have seen in a lot of codebases over the years.

As apps scale, it's important to reduce complexity wherever we can in order to ward off technical debt.

## tl;dr:

Using `useState` and `useEffect` hooks is often unavoidable, but if you can, abstract out any data that can be derived from other data using pure functions. The benefits can have huge payoffs down the road.

Banner Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Lautaro Andreani</a> on <a href="https://unsplash.com/s/photos/react?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
WordPress: How to disable XMLRPC
Tags: wordpress, xmlrpc, security
Published: 2021-11-01 17:05:21

You should open the .htaccess file in the main directory of WordPress and put a couple of strings of code like in example below.

```
<Files xmlrpc.php>
order deny,allow
deny from all
</Files>
```
Or you can open it for an IP address

```
<Files xmlrpc.php>
order deny,allow
deny from all
allow from 192.168.0.1
</Files>
```
Hawk Open Source Project
Tags: python, showdev, github, security
Published: 2021-11-01 17:04:50

Hawk is a network and pentest utility that I developed so that I could perform different kinds of task using the same suite, instead of jumping from one tool to another.
Currently, this script can perform a good variety of tasks such as: 
- ifconfig, 
- ping, 
- traceroute, 
- port scans (including SYN, TCP, UDP, ACK, comprehensive scan), 
host discovery (scan for up devices on a local network), 
- MAC address detection (get MAC address of a host IP on a local network), 
- banner grabbing, 
- DNS checks (with geolocation information), 
- WHOIS, 
- subdomain enumeration, 
- vulnerability reconnaissance, - 
- packet sniffing, 
- MAC spoofing, 
- IP spoofing, 
- SYN flooding, 
- deauth attack, 
- brute-force attack (beta).

Other features are still being implemented. Future implementations may include WAF detection, DNS enumeration, traffic analysis, XSS vulnerability scanner, ARP cache poisoning, DNS cache poisoning, MAC flooding, ping of death, network disassociation attack (not deauth attack), OSINT, exploits, some automated tasks and others.
If you want to become a contributor, make a pull request or issue.
Waiting for your feedback. Kudos.

Link to the repository: 
https://github.com/medpaf/hawk
How to convert a Workday job listing login redirect to the actual job listing
Tags: career, workday, jobs, recruiting
Published: 2021-11-01 16:55:58

You just tried to apply directly to a job on the employer website from a job board link, but are greeted with a Workday login redirect that looks like this:

![Workday login redirect](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zhcnueibslki5io5arlp.png)

To get to the original actual job listing:

1. Click on the login page URL
2. Delete `login?redirect=%2FCompanyString%2F`
3. Delete `%2Fapply`
4. Replace remaining `%2F` strings with `/`
5. Click `Enter` or tap the browser `Go` icon

The original actual job listing should now load properly.
convert html & css & js code to android app for free in a few minutes
Tags: javascript, html, css, webdev
Published: 2021-11-01 16:41:50

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

check it now
https://urlgapp.com/home/htmlgapp

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

Today we present HTMLgApp - a tool designed to convert your HTML , CSS , JS Code into an Android app. 📲

HTMLgApp is a website (web tool) to convert your code to an android app with app bundle & apk with your own key store valid for 10,000 days on google play store

Features that we provide

Apk & App bundle
Google play Key
Media permission
Dialog Ask to exit app
Internet connection error . native page
Android native spinner
Do you have any example for this tool in google play ❓
yes we have you can download it from here
https://play.google.com/store/apps/details?id=com.urlgapp.app1635406887441
it’s very simple app

why you add a media permission ❓
HTMLgApp doesn`t know what type of website it you but if your user upload or download any file without any permission google play will remove your app from store so, we have added it by default to make sure your app is safe on google play

If you have any question, feel free to ask

check it now
https://urlgapp.com/home/htmlgapp
Observer Pattern Tutorial With a Fun Example
Tags: design, tutorial, programming, oop
Published: 2021-11-01 16:41:38

In this exciting tutorial we are going to learn about the observer pattern. Not your typical observer pattern tutorial. We toss the wikipedia article aside and apply the observer pattern to a game.

The game is simple, click the buttons at the top of the screen and the characters will perform the action. We coordinate the actions through the observer pattern. 

At its core the pattern revolves around a subject that the observer will observe. The subject has a list of observers(one-to-many relationship).  Observers can choose to register with the subject. The subject at any point in time can notify the observers by looping through all observers and calling the update method. 

For example let's say the our subject is the YouTube channel Coding With Adam. The observers would be YouTube users. YouTube users can register with the subject by subscribing. When the YouTube channel owner(subject) uploads a new video they can notify all subscribers(observers).

Learn more by watching the video.

{% youtube cR8P1HZAyP8 %}
convert html & css & js code to android app for free in a few minutes
Tags: javascript, html, css, webdev
Published: 2021-11-01 16:35:14

check it now 
https://xtaapp.com

Today we present xtaapp - a tool designed to convert your HTML , CSS , JS Code into an Android app. 📲

xtaapp is a website (web tool) to convert your code to an android app with app bundle & apk with your own key store valid for 10,000 days on google play store

Features that we provide
- Apk & App bundle
- Google play Key
- Media permission
- Dialog Ask to exit app
- Internet connection error . native page
- Android native spinner
- Notification

why you add a media permission ❓
xtaapp doesn`t know what type of website it you but if your user upload or download any file without any permission google play will remove your app from store so, we have added it by default to make sure your app is safe on google play

If you have any question, feel free to ask 

check it now 
https://xtaapp.com
Cómo crear un juego NFT
Tags: nfts, blockchain, solidity, nft
Published: 2021-11-01 16:22:35

---
title: Cómo crear un juego NFT
published: true
description: 
tags: nfts, blockchain, solidity, nft
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8munfoersowgy5319zxl.png
---

Proyectos como Plant vs Undead, Decentraland, Sandbox, Crypto Cars, Axie Infinity han demostrado que los juegos NFT tienen bastante potencial. En este video vamos a ver que necesitas para crear tu juego que interactue con NFTs o con cualquier smart contract y ecosistema DeFi.

{% youtube CvBN7sY34R4 %}

## Dependencias

Para este tutorial ocuparás [NodeJs](https://nodejs.org/es/) que les recomiendo descargarlo el Linux via [NVM](https://github.com/nvm-sh/nvm#installing-and-updating) , un URL de RPC te recomiendo usar [INFURA](https://infura.io/), [Metamask](https://metamask.io/) con fondos de Rinkeby Testnet que puedes conseguir desde el [Faucet](https://faucet.rinkeby.io/).

## 1. Descarga e instala las dependencias

```bash
git clone https://github.com/FilosofiaCodigo/NFTGame
cd NFTGame
npm install
npm i -g lite-server
```

## 2. Lanza el contrato

Crea un archivo `.env` y coloca tus llaves siguiendo el ejemplo `.env.example`.

```bash
npx truffle deploy --network rinkeby --reset
```

Ahora copia `./bruild/MyNFT.json` en `./client/contracts/MyNFT.json`.

## 3. Levanta el cliente, juega y mintea

```bash
cd client
lite-server
```

**¡Gracias por ver este tutorial!**

Sígueme en dev.to y en [Youtube](https://www.youtube.com/channel/UCNRB4tgwp09z4391JRjEsRA) para todo lo relacionado al desarrollo en Blockchain en Español.
Omitir un Interceptor de Angular usando Context para Http Interceptors
Tags: angular, typescript
Published: 2021-11-01 16:21:18

Los interceptors en Angular llegaron desde la versión 4.3 y básicamente nos brindan un mecanismo para interceptar y/o mutar las solicitudes y respuestas http. Más detalles [aquí](https://dev.to/ricardochl/como-usar-httpinterceptors-en-angular-2o84).

Los interceptors en Angular interceptan todas las peticiones http por defecto, pero hay ocasiones en donde deseamos omitir un interceptor para algunas solicitudes.

Antes de la versión 12 de Angular era muy común hacer esto de alguna de las siguientes formas:

- Agregar encabezados http en la solicitud http y luego evaluar ese encabezado en el interceptor.
- Crear un nuevo httpClient para esa solicitud.
- Administrar sus inyecciones de HttpClient con tokens.
- Utilizar httpBackend y saltarse todos los interceptors.

##HttpContext

Desde la versión 12 de Angular tenemos una mejor forma de hacer esto, la cual consiste en pasar metadatos a los interceptors http. Ya podemos olvidarnos de pasar encabezados personalizados a nuestros interceptors.

Un caso de uso común es indicarle al interpcetor que la solicitud http actual es anónima y no necesita un JWT (JSON WEB TOKEN).

Otro caso también podría ser  indicarle al interceptor que una solicitud se puede almacenar en caché.

Nota: Recuerda que tenemos que tener la Angular v12 o superior en nuestro proyecto.

**HttpContext:** El contexto HTTP almacena valores arbitrarios definidos por el usuario y garantiza la seguridad de los tipos sin conocer realmente los tipos.

**Context:** Es mutable y se comparte entre solicitudes clonadas a menos que se especifique explícitamente.


```javascript

//token.interpcetor.ts

//Declaramos un nuevo HttpContextToken

export const BYPASS_JW_TOKEN = new HttpContextToken(() => false);

export class TokenInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, delegate: HttpHandler): Observable<HttpEvent<any>> {
//Aquí evaluamos el contexto y omitimos el interceptor.
    if (req.context.get(BYPASS_JW_TOKEN) === true) {
      return next.handle(request)
    }
    return this.addToken(request);
  }
}

```

```javascript
// service

/*
Así se ve una solicitud en la cual se quiere omitir el JWT, 
debemos pasar un nuevo contexto con el HttpContextToken 
declarado anteriormente en el interceptor.
*/

this.httpClient.get('/api/fakeEndPoint', {
  context: new HttpContext().set(BYPASS_JW_TOKEN, true),
});

```

Más detalles:

- El token pasado al contexto del http interceptor puede ser cualquier tipo de dato como ser booleano, número, cadena, objeto etc.
-El token pasado al contexto no debe confundirse con el JWT el cual es requerido para algunas solicitudes http.
- La declaración del HttpContextToken se puede realizar donde tenga más sentido, aunque lo común es declararlo en el interceptor que lo va a utilizar.


Muchas gracias por leer este post.

Sígueme en twitter [ricardo_chl](https://twitter.com/ricardo_chl)
6502- Lab4(Option 4): Screen Colour Selector Part A
Tags: programming, 6502
Published: 2021-11-01 15:51:49

# Introduction
In this blog, I will create a subroutine which displays on the character display a list of colours available on the bitmapped display, one colour per line, with one of the colours names highlighted in reverse video (white on black). The user may use the up/down arrow keys to change the highlighted row. Return the user's selection as a number in the accumulator (A) register when they press Enter.
Using this subroutine, get a colour from the user, then fill the bitmap display with this colour, and allow the user to select a different colour.

### Thoughts and Steps
-> Define values and variables.
-> Retrieve the keyboard action for UP and DOWN key.
-> Check the color value. Comparing to the first color(#$00) and the last color(#$0a).
-> Display color string on the screen.
-> Allow user to change the hightlight on the specific color.
-> Paint the bit-mapped screen using the selected colour.

### Define Variables
```
define COLOUR  $10
define COLOUR_INDEX $11
define POINTER  $40
define POINTER_H $41
define UP_KEY  $80
define DOWN_KEY $82
define SCINIT  $ff81 ; for screen initializing and clearing
define CHROUT  $ffd2 ; for displaying the output

```
Reverse the elements of a Singly Linked List using a Stack
Tags: go, algorithms
Published: 2021-11-01 15:49:38

Reverse the elements of a Singly Linked List using a Stack as an approach

It is not the most efficient way to solve this problem but it is good to know other ways to solve it by helping us with other data structures

https://play.golang.org/p/Obbq73zUrD2

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/psl1ft3kifjucgpduor4.png)
Set Up Blazing Fast Frontend Development Experience With Vite
Tags: webdev, javascript, tutorial, webpack
Published: 2021-11-01 15:34:36

Your production app is huge.

You hit `npm run dev` to start your development server.

After 1 minute, it's there! You can start your dev journey.

Although 1 minute doesn't seem like a long time  —  for us devs, it is. We are nitpicky and want everything **instantly**.

Luckily, there's a brand new tool that allows us that.

I present you  —  [Vite](https://vitejs.dev/).

---

## What is Vite?

Vite is a build tool that provides a blazing fast development experience.

Vite is a french word for "quick", and it's pronounced `/vit/` (not white!).

It's created by Evan You, the same guy who created Vue.js.

That doesn't mean that Vite is only for Vue.js  —  it's framework agnostic!

---

## Why Is It So Fast?

If you don't care about this and just want to set up Vite, just skip this section.

---

If you're still with me, amazing! I have a few history lessons for you.

Webpack, the most popular build tool today, was released in 2014.

Back then, browsers didn't support native module imports, so bundling the files made sense.

Not anymore in 2021.

It's an expensive process.

Plus, every time you update a single file, you need to update the whole bundle to see the change on the screen.

That's why Hot Module Reload can sometimes take many seconds!

Vite uses the power of native module imports, making your Hot Module Reload instant.

There are still some deeper reasons why it is so fast, so if you're interested, check out their website. But now, let's set up the app!

---

## Setting Up Vite… Is Simple And Fast As It Sounds

There's only one prerequisite: `Node version >=12.0.0`.

After it, you're all good!

Open your terminal and type:

```javascript
npm init vite@latest
```

Then, you have steps:

1. Project name
2. Framework (Vanilla JS, Vue, React, Preact, Lit, Svelte)
3. Typescript or pure JS

And that's it!

Now, you need to go to your project folder:

```javascript
cd <YOUR_PROJECT_NAME>
```

Install the dependencies:

```javascript
npm install
```

And start the development server:

```javascript
npm run dev
```

Here's what happens next:

![Blazing fast Vite](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vupmydplpqt3ehligkil.png)

It's ready in less than 0.3 seconds. That's insane!

Just for a comparison, the same app made with VueCLI + Webpack takes 10s initially. This makes Vite **39x faster**!

I won't even talk about the speed after the app gets bigger.

---

And Hot Module Reload is  —  instant.

Webpack takes around 2–3 seconds (initially), and up to 5 seconds for massive apps.

---

## Conclusion

What do you think about Vite?

New Frontend tools come out every day, but I can't remember when was I excited as this. I believe this could radically improve our already great Frontend development experience.

Have you tried it yet?

---

_[This post was originally published on Dom's personal blog. Check out dat new amazing blog design there ✨](https://domagojvidovic.com/post/set-up-blazing-fast-frontend-development-experience-with-vite)_