teleren/devto huggingface dataset:
TIL - React Router
Tags: react, webdev, beginners
Published: 2020-08-30 17:51:44

##SPA
**'Classic' websites**: different pages with different path, which are usually loaded entirely one by one from the server.
 
**React: a Single-Page Applications (SPA)**:
In an SPA, an HTML document is loaded only when the application is opened, and will remain the same for the lifetime. The HTML document is "empty", in the `<body>` it just includes a `<script>` tags which loads the application, along with one empty tag, intended to contain the DOM generated by the application. The content of each visited page is entirely built inside the browser via React. 

Therefore a navigation System is not coming natural. We use React Router to determine what to display. This way we can
- display a custom url in the browser
- allow the user to use the bookmarks
- allow the user to use of the previous/next browser buttons


### 1. [Install](https://reactrouter.com/web/guides/quick-start) React Router. 

### 2. Wrap the parent component (index.js) with a `<BrowserRouter />`.
```javascript
import { BrowserRouter } from 'react-router-dom';
   <BrowserRouter>
       <App />
   </BrowserRouter>
```  
### 3. Create different Routes in the main `<App>` component.

```javascript
import { Switch, Route } from 'react-router-dom';
<Switch>
   <Route exact path='/' component={Home} />
   <Route path='/users' component={Users} />
   <Route path='/contact' component={Contact} />
</Switch>
``` 
Routing refers to establishing a correspondence between the current path (e.g. /users) and a component to be displayed (e.g. Users).
Only one of the Routes enclosed in a Switch can be active at a given time. 

### 4. Navigate between  components use `<Link>`
```javascript
import { Link } from 'react-router-dom';
<ul className='Header'>
   <li><Link to='/'>Home</Link></li>
   <li><Link to='/users'>Users</Link></li>
   <li><Link to='/contact'>Contact</Link></li>
</ul>
``` 
In the DOM the `<Link to="...">` produces `<a href="...">` elements as their output.

####Navlinks 
- target the active Link with `<Navlink>` 
```javascript

import { NavLink } from 'react-router-dom';

<ul className='Header'>
   <li>
       <NavLink activeClassName='active' exact to='/'>Home</NavLink>
   </li>
   <li>
       <NavLink activeClassName='active' to='/users'>Users</NavLink>
   </li>
   <li>
       <NavLink activeClassName='active' to='/contact'>Contact</NavLink>
   </li>
</ul>
```

[Router in depth](https://blog.pshrmn.com/simple-react-router-v4-tutorial/)

##Render Props

```javascript
<Route path="/contact"
       render={ props => (
              <Contact tabs= {"valuePassed"} {...props}  />  
        )}
 />
```
Tabbordion v2 first beta finally out
Tags: opensource, watercooler
Published: 2020-08-30 17:40:50

So here is just something I want to get out of my head right now.

The past over a week or so I've been working on my old React component, Tabbordion. I happened to notice that it's usage had gone up suddenly during the summer. I hadn't been happy with it's state and the lack of time I had given it over the years. So now I had to go for a complete rewrite, including upgrading all the tooling.

So I've done almost everything from scratch!

1. Bundling: custom Babel/Webpack awfulness replaced with Microbundle
2. Tests: way too many libs replaced with just Riteway (for now)
3. Test execution performance: run using Sucrase instead of Babel
4. CI: use GitHub Actions in addition to Travis CI
5. Lint/codestyle: forget Eslint and use Prettier instead
6. Demo: include simple Deno server to run a demo on localhost

All that work **in addition** to all the code changes where I've thrown away React legacy context API usage and simplified the internal state management. Oh and throwing out legacy browser tricks in favor of solutions such as `ResizeObserver`. All this while maintaining high compatibility with the v1 API.

The new version is now available `npm install react-tabbordion@2.0.0-beta.0` and the code and unfinished docs and tests are available on [GitHub v2 branch](https://github.com/Merri/react-tabbordion/tree/v2).

Tomorrow I probably need to fix the README to acknowledge v1 better and release next version because I don't want npm to be displaying the v2 README.
Deno Server to generate random activity
Tags: deno, typescript, node, javascript
Published: 2020-08-30 17:35:25

A deno Server that makes API call to fetch activity from an open API. Each time the user refreshes the page a new activity will be generated.

From my opinion deno enables typescript and this denotes the future of javascript coding. It is no way a replacement of nodejs due to the usability and usage of nodejs in wide range applications. Deno is in the initial stages of development and higher level of permission constraints in comparison to nodejs.

Here is my github link :
[100 Days of Code](https://github.com/dhanushnehru/100DaysOfCode)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/xxpz6i7rtn7h6pihxvdc.png)
My #100DOC - Day 4
Tags: 100daysofcode, challenge, log
Published: 2020-08-30 17:18:55

### Day 4: August 30, 2020

#### **Today's Progress**: 
1. **[Started my Addicted Developer Twitter Bot project](https://github.com/pablohs1986/addictedDEV_TwitterBot)** (1h 57min):<br>I started a new project to implement my JavaScript knowledge and learn some basic Node.js, a Twitter Bot called *Addicted Developer*. I prepared the project and made an sketch of the methods.
2. **[Helped on Stack Overflow](https://es.stackoverflow.com/questions/385929/como-llamar-una-variable-que-esta-en-otro-metodo/386014#386014)** (15min):<br>I answered a colleague's question about variables in Java, which allowed me to review the different ways to access them.
    
#### **What I learned**: 
* Start a JavaScript back-end projecto with Node.js.
* How the Twitter api works.
* How a bot works.
* Review of ways to access variables in Java.

#### **Total time**:
2h 12min.
Basic Network Utilities
Tags: networking, utilities
Published: 2020-08-30 17:05:35

**IPCONFIG:** This command displays all the current TCP/IP network configuration values. It gives you information about the IP address, the router's IP address, DNS server IP address, DHCP server IP address etc. We can find out the IP for our default gateway which is the connection to the outside world.
*"ipconfig /all"* gives the details of the computer's configuration.

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

We have several flags which can be passed to the command to make the computer behave in a certain way.
**ipconfig -?**

![ipconfig-options](https://dev-to-uploads.s3.amazonaws.com/i/pvr65ftbvdwd9vidjff8.png)

**PING:** It is used to send a test packet to a machine to find out if the machine is reachable and how long a packet takes to reach the machine.

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

The above command shows that a 32-byte packet was sent to the destination and returned. The TTL or the "Time to Live" counts how many intermediary steps or hops the packet should take so as to reach the destination before giving up.

**TRACERT:** This is a detailed version of the PING command or the "PING DELUXE". It gives information about whether the packet reached the destination and how long did it take but also the necessary information about all the intermediate hops it took to reach there. In LINUX/UNIX, *tracert* is called *traceroute*. This command also gives you the time taken in all the intermediate hops also the corresponding IP addresses.

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

**NETSTAT:** This is the short form for "Network Status". It tells us the connections the computer currently has. On a local machine it shows a lot many connections. This would show several private IP addresses which would refer to the internal communication.

![netstat](https://dev-to-uploads.s3.amazonaws.com/i/xocs4rka24b09q6fd871.png)
Difference between (*a) and (a) 
Published: 2020-08-30 17:03:34

 What is the difference of (*a) and (a) in this program???






def func(*a):
    for i in range (0,len(a)-1):
        if a[i]==3 and a[i+1]==3:
            return True
    return False
print(func([1,3,3]))


Output:- False





def func(a):
    for i in range (0,len(a)-1):
        if a[i]==3 and a[i+1]==3:
            return True
    return False
print(func([1,3,3]))


Output:-True
Use OBS to Stream on Teams from another laptop
Tags: teams, obs
Published: 2020-08-30 16:34:11

<sub><span>Photo by <a href="https://unsplash.com/@vanillabearfilms?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Vanilla Bear Films</a> on <a href="https://unsplash.com/s/photos/video-camera?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></span></sub>

On my work laptop i use Teams to communicate. But this laptop is lacking resources to demonstrate some stuff using kind for example.

I can use my other computer but i can't install Teams and complying with company restrictions.

So i stream using OBS from my computer to my laptop.

I followed [Aaron Powell tutorial](https://dev.to/aaronpowell/a-guide-to-virtual-workshops-1jh4) to use OBS NDI plugin.

And of course i used [chocolatey](chocolatey.org/) to install OBS with plugin:

```Bash
choco install obs-studio -y
choco install obs-ndi -y
choco install obs-virtualcam -y
```

Do not forget to configure Firewall to [allow OBS](https://howto.streamlabs.com/streamlabs-in-general-21/windows-firewall-how-to-open-9). I was forced to set "Allow Edge Traversal" in Firewall rule > Properties > Advanced.


You can read [this tutorial](https://collab365.community/using-obs-studio-with-microsoft-teams/), too on how to use OBS, and what to produce for Teams.

Hope this help !
Headless WordPress + Sapper, JAMstack Security (Part 6)
Tags: svelte, javascript, sapper, wordpress
Published: 2020-08-30 16:29:14

Now that you have the complete frontend that works independent of WordPress you can completely rid the PHP frontend of WordPress and use only as a backend.


#### #1 Security
Preventing access to `wp-admin` and `wp-login.php` by IP address and forbid access. This requires you to modify the `.htaccess` file on your WordPress instance you need to add these rules.

Note, `10.0.0.1` should be replaced with your current IP if you need to allow access to multiple IP addresses if you have several authors then you need to add extra `allow from 11.0.0.1`.


```
<Files wp-login.php>
order deny,allow
deny from all
allow from 10.0.0.1
</Files>
```

But if you are behind Cloudflare like me then the above configuration will not work you need to do something like [this](https://community.cloudflare.com/t/combining-htaccess-file-match-deny-allow-and-ip-address/88150/6).

```
SetEnvIF CF-Connecting-IP "10.0.0.1" MySecretIP
<Files wp-login.php>
order allow,deny
allow from env=MySecretIP
</Files>
```

If you try going to your `wp-admin` from another IP (test via mobile data) you will hit `403 Forbidden`.


#### #2 Ditching the WordPress frontend

The final step, getting rid of WordPress frontend, assuming you already have `YOUR-DOMAIN` pointing to WordPress you might need to move to something like `SUBDOMAIN.YOUR-DOMAIN` and have `YOUR-DOMAIN` pointed to your Sapper frontend. Easiest way is to use any migration plugins to move to your subdomain so that you don't mess much with the delicate backend and if you have the `WordPress.com` version then you will have an easier time with this because you can consume the APIs from your custom WordPress URL. 

Also do not forget to change the API Endpoints on your `.env` file.



Here is my repo. The `trash` folder has the default blog of Sapper.

https://github.com/peopledrivemecrazy/Sapper-WordPress


Here is the Sapper version of the site https://sapper.anoram.com/
Binary Operator Hack and Tricks
Tags: golang101, programming, go
Published: 2020-10-05 02:29:57

---
title: Binary Operator Hack and Tricks
published: true
date: 2020-08-30 11:00:00 UTC
tags: Golang101,programming,golang,golang101
canonical_url: https://lumochift.org/posts/binary-operator/
---


A binary operator is a way to manipulate binary data. We already know there are `&`, `|`, `^`, `<<` and `>>` operators, but not all of us know the secret of each operator. Let's explore what tricks behind those operators using go language.

## Multiply or Divide By 2

Multiply 2 using `* 2` or divide using `/ 2` is the normal way, but how we can achieve the same with the binary operator?

|          |       |             |
|----------|-------|------------|
| divide by 2 | shift right by 1|`someNumber >> 1` |
| multiply by 2 | shift left by 1 | `someNumber << 1` |

```go
    // multiply by 2
	fmt.Println(4 << 1)
    // Output: 8
    
    // divide by 2
    fmt.Println(4 >> 1)
	// Output: 2
```

## Change case of character


```go

    // to upper case char
	fmt.Println((string)('c' & '_'))
	// Output: C

    // to lower case char
	fmt.Println(string('A' | ' '))
	// Output: a
```

## Invert case of character

Invert char can be achieved by `xor` with space

```go
	fmt.Println(string('A' ^ ' '), string('b' ^ ' '))
	// Output: a B
```

## Get letter position

Get a letter's position in the alphabet (1-26) using `and with 31`

```go
	fmt.Println('z' & 31)
	// Output: 26
```

## Check number odd or even

Simple check if the number is odd/even using `and with 1`, if the number is odd will return true

```go
    // odd number return true
    fmt.Println(7 & 1 > 0)
    // Output: true
    
    // even number return false
    fmt.Println(8 & 1 > 0)
	// Output: false

```

Try it yourself at https://play.golang.org/p/-wsIlDgBTmF
Reversing a String
Published: 2020-08-30 16:28:53

Reverse string  using the split, reverse, and join methods.
If an exception is thrown, catch it and print the contents of the exception's  on a new line.
Print  on a new line. If no exception was thrown, then this should be the reversed string; if an exception was thrown, this should be the original string. 

     function reverseString(s) {
       try {
        let reversString = s.split("").reverse()
        console.log(reversString.join(""))  
        }
     catch (e) {
         console.log(e.message);
        console.log(s)
        }   
      }
#### Explanation:
-The split method converts the string into array.
-The reverse methods reverse the entries of an array. 
-The Join methods finally prints the array entries with joining 
 them according to the condition you pass in parenthesis.

Output:

         reverseString("1234")
         Output = 4321


####Try,Catch
I have used this try catch because if the data type will be other than string so the split function will not be applicable it will give runtime error,But in my case if there will be any error it will sent to catch block rather than displaying runtime error it will display a message.  

Hope you find this helpful.

Happy Coding!
Como eu organizo meu dia de trabalho (also in EN)
Tags: productivity, ubuntu, linux
Published: 2020-08-30 16:28:49

### THIS POST WAS ALSO WRITTEN IN: [🇨🇦️ ENGLISH](https://dev.to/gugacavalieri/how-do-i-organize-my-work-day-tools-2gd6)

Todos os dias, antes de começar a trabalhar, eu sempre reservo 5-10 minutos para planejar o meu dia. Isso envolve fazer uma lista de todas as tarefas que eu quero terminar naquele dia incluindo:

* Qualquer tarefa que estou trabalhando na [Kudos](https://www.kudos.com/)
* Tarefas pessoais
* Coisas de casa
* Algum Hobby (Música, Leitura, Podcasts...)
* Qualquer outra coisa que esteja na minha cabeça (que provavelmente eu dormi com ela na cabeça).

E foi assim que eu comecei a organizar o meu dia!

## As ferramentas mágicas 

### 1. ElementaryOS
Tenho que dizer que sou um grande fan do Linux e especialmente um mega fan do **[ElementaryOS](https://elementary.io/)**. Acho que posso dizer que é a minha distribuição favorita nos últimos 3 anos pois além de ser linda é super fácil de usar e se adaptar (sem contar que é open-source e gratuita).

### 2. Planner
E por usar o ElementaryOS no meu dia-a-dia nos últimos anos eu acabei descobrindo uma ferramenta super legal chamada [Planner](https://blog.elementary.io/appcenter-spotlight-planner/).

Vou listar aqui as funcionalidades do Planner que me salvam todos os dias:
* Separar taferas por projetos (Trabalho, Pessoal, Casa, etc...)
* Criar tarefas recorrentes (Pagar o aluguel todo mês por exemplo)
* Colocar prazos
* Criar sub-tarefas
* Sincronizar na núvem (Caso eu queira acessar algo do celular)
* **O mais importante:** Listar todas as tarefas que estão marcadas para serem entregues no dia de hoje 🎉️ 🚀️

![My Planner](https://dev-to-uploads.s3.amazonaws.com/i/3n3rkxfpbjn753hci2td.png)

## Como eu uso o Planner

Simples assim: Antes de começar qualquer coisa no dia eu abro o "Planner" e escrevo tudo que eu quero terminar até o apagar das luzes.

A medida que as tarefas são feitas elas são marcadas como concluídas e se algo fica inacabado eu simplesmente clico em um botão e a envio para o dia seguinte. E isso vai ser a primeira coisa que eu verei quando abrir o meu computador na próxima manhã.

## Tente você mesmo

Antes de começar o seu dia, reserve um tempinho para escrever tudo que você quer entregar naquele dia. E não importa se você está usando o Planner ou qualquer outra ferramenta. O importante é escrever porque **uma vez que você escreveu você  magicamente sentirá que acabou de se comprometer a fazer algo.**


## Bonus

Se você não usa o ElementaryOS ou o Planner aqui vão algumas outras ferramentas que podem te ajudar:

* 📰️ Um Caderno (Sim! Clássico e efetivo)
* [Todoist](https://todoist.com/pt-BR)
* [Google Keep](https://keep.google.com/)
* [Trello](https://trello.com/)
* [Notion](https://www.notion.so/)

> Quais outras dicas vocês têm para planejar/organizar o seu dia?
Creating a social media app part 3
Tags: react, python, mongodb, sideprojects
Published: 2020-08-30 16:25:59

I was able to write out the UI and functionality pretty well. Although, I did find that using mongodb was not the best choice. As this data is relational, SQL would have been better considering there are friends and finding friends of friends. Other than that, developing this project wasn't terrible. I am using React Native and Expo for the front end. It's not a bad experience, but static typing or rather more specific errors would be good.
How to store user data in Shopify App ?
Tags: help, shopify, shopifyapps
Published: 2020-08-30 16:23:55

Hi,

I have recently started looking into shopify app development. I know how to build UI for Shopify App for now. 

My App Idea uses an API which provides an `api_key`.

Now when a Shopify Customer installs my app, he enters this API key on the Frontend Form that I had created and tries to submit. 

## DOUBT
`How and where to store this information ? How to retrieve this information once saved ?`

_I have been burning the midnight oil for this. So, if any experienced people are present. Please lend me a hand._
I am very much willing to clarify any doubt in my explanation.

Thanks in advance,
Formatting date phrases becomes easy in javascript
Tags: webdev, javascript, productivity, codenewbie
Published: 2020-08-30 16:19:53

Modern web applications often use phrases like “yesterday”, “42 seconds ago”, or “in 3 months” instead of full dates and timestamps. There is no direct solution given by javascript until now. You have to write manually function which is cumbersome in itself or rely on any third party library like [**moment.js**](https://momentjs.com/) etc. But you don't have to rely on any third party library to achieve this.

The brand new Intl.RelativeTimeFormat API shifts that burden to the JavaScript engine, which can ship the locale data and make it directly available to JavaScript developers. Intl.RelativeTimeFormat enables localized formatting of relative times without sacrificing performance.

These are some examples to get you better idea :-)

![](https://cdn-images-1.medium.com/max/1024/1*H7S1h02_aurC9H4DvxQ3aw.png)

Not only this you can convert these into your native language. For example :

![](https://cdn-images-1.medium.com/max/1024/1*pCkjU4xX0TLcC1r8Mxl5lw.png)

That’s all from my side. Congrats yourself for learning new thing. You can explore more on [mdn](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) docs.
Django Tests
Tags: actionshackathon
Published: 2020-08-30 15:55:54

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


### My Workflow
My workflow checks for any linting errors or any changes that breaks the code and doesn't pass the tests on every new pull request or push to the repository! This makes sure that nothing is added to the repository that breaks the workflow. This helps in maintaining the quality of the code base.


### Submission Category: 
Maintainer Must-Haves


### Yaml File
```yaml
name: Django Tests

on: [push, pull_request]

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v1
    - name: Set up Python 3.6
      uses: actions/setup-python@v1
      with:
        python-version: 3.6
    - name: Setup environment variables
      run: |
        cp .env.example .env
        export DJANGO_SETTINGS_MODULE=main.settings
    - name: Install dependencies
      run: |
        sudo apt-get install libpq-dev 
        pip3 install -r requirements.txt

    - name: Linting
      working-directory: ./src
      run: |
        flake8 .
    - name: Migrations
      working-directory: ./src
      run: |
        python3 manage.py makemigrations
        python3 manage.py migrate
    - name: Coverage
      working-directory: ./src
      run: |
      	pip3 install coverage
        coverage run --source='.' manage.py test
        bash <(curl -s https://codecov.io/bash) || echo 'Codecov failed to upload'
```
fun ways to remember syntax?
Tags: es6, javascript, react, redux
Published: 2020-08-30 15:47:39

so far i have learnt code by repetition till its second nature.
is there a more efficient way of retaining syntax, order and when and where to use symbols?
with other topics id learn by making a fun song or a saying to get me to remember a order of events but with this topic its quite different.
im currently using JavaScript, redux, react and es6.
preemptive thanks
Global hidden mouse pointer when typing
Tags: linux, tutorial
Published: 2020-08-30 15:38:53

Lately I have been trying to focus on using the keyboard for all the things rather then constantly switching from mouse to keyboard and back. As I have tip toed down this path I realized one thing. I really don’t like it when the mouse pointer is hovering over where I am trying to interact with the screen. Whether it be typing a post or jamming out some code, talk about annoying to have to reach over and move the mouse pointer out of the way! Without further elaboration here is what I did.

# Requirements

[Fedora](https://getfedora.org/) 32 Linux running X11
[xbanish](https://github.com/jcs/xbanish)

## Install libs for build
This command will be different if running Ubuntu pretty much just change devel to dev

```
dnf install \
 make \
 libXi-devel \
 libXfixes-devel \
 libXt-devel \
 libX11-devel \
 ;
```

## Clone, Build, Copy

```
git clone https://github.com/jcs/xbanish ~
cd ~/xbanish
make
cp xbanish /usr/local/bin/
```

## Create Systemd Service Unit File

```
open ~/.config/systemd/user/xbanish.service
```

## And paste this into the file

```
[Unit]
Description=xbanish
After=default.target

[Service]
Type=simple
ExecStart=/usr/local/bin/xbanish
Restart=on-failure
StartLimitBurst=10
RestartSec=30

[Install]
WantedBy=default.target
```

## Tell the system about the new service

```
systemctl daemon-reload
```

## Enable the service as a user service

```
systemctl --user enable xbanish
```
## Start the service as a user service

```
systemctl --user start xbanish
```

Now when you type your mouse pointer will hide, and when need your mouse pointer just move the mouse and it will show up right where you left it!

Cheers!

# Optional steps needing to remove and or stop the service

## If needed stopping the service

```
systemctl --user stop xbanish
```

## If needed removing the service

```
systemctl --user disable xbanish
```