teleren/devto huggingface dataset:
Daily Challenge #1 - String Peeler
Tags: challenge, beginners
Published: 2019-09-15 01:17:39

Depois de entrar no grupo da hashtag #100daysofcode acabei achando esse desafio do Dev.to e aproveitei para usar ao meu favor.
O post desse desafio para quem ainda não conhece:

{% link https://dev.to/thepracticaldev/daily-challenge-1-string-peeler-4nep %}

Vamos ao código!

```python
def stringpeeler(entrada):
    saida = entrada[1:len(entrada)-1]
    return saida
```

Como achei o desafio simples demais, acabei aproveitando pra aprender um pouco de TDD e mexer com a biblioteca pytest. 

```python
# Dev.to Daily Challenge #1 - String Peeler
# https://dev.to/thepracticaldev/daily-challenge-1-string-peeler-4nep
# stringpeeler.py

import pytest

def stringpeeler(entrada):
    if not isinstance(entrada, str):
        raise TypeError('A entrada deve ser uma string')
    if len(entrada)<3:
        return ValueError('A entrada deve ter no mínimo 3 caracteres')
    saida = entrada[1:len(entrada)-1]
    return saida
```

E o arquivo de testes:
```python
# Dev.to Daily Challenge #1 - String Peeler
# https://dev.to/thepracticaldev/daily-challenge-1-string-peeler-4nep
import pytest
from stringpeeler import stringpeeler

#TDD Training
NOT_STRING = 3524
EMPTY_STRING = ""
TOO_SHORT_STRING = "ab"
TEST_STRING = "zabcdey"

def test_ifString():
    with pytest.raises(TypeError):
        value = stringpeeler(NOT_STRING)

def test_emptyString():
    with pytest.raises(ValueError):
        value = stringpeeler(EMPTY_STRING)

def test_tooShortString():
    with pytest.raises(ValueError):
        value = stringpeeler(TOO_SHORT_STRING)

def test_stringPeeler():
    assert stringpeeler(TEST_STRING) == "abcde"
```

Usei como referência essa série de posts de TDD em pytest para iniciantes, que é bem educativo e fácil de acompanhar.

{% link https://dev.to/wangonya/python-tdd-with-pytest-----getting-started-4l07 %}

Não sei se vou conseguir fazer todo dia, mas estou me divertindo por enquanto. Espero ficar craque em TDD até o último desafio!
Share your most embarrassing shell pipeline
Tags: awk, sed, grep, discuss
Published: 2019-09-15 00:43:24

Sometimes airing your code smells can be cathartic, and motivate you to fix it.

Here's possibly the most embarrassing shell pipeline I currently have in my Bash dotfiles:

```sh
            \grep -Rn "alias ${1}=" ${DOTFILES}/source \
                | awk -F: '{print "⍺:\t" $3 "\t--> " $1 ":" $2}' \
                    | sed "s/${1}=//g"
```

Yes, I'm combining *all* the filters, `grep`,`awk`, and `sed` to print out an information of where a shell alias is defined in my files. It's part of my `describe` function for handling aliases:


```
$ describe gdfs
⍺:      alias 'cpulimit -l 2 -p $(pgrep -f "crash_handler_token=")&'    --> /Users/mjl/.dotfiles/source/40_osx.sh:28
```

I'm *sure* all of this can actually be done in `awk` alone (especially the `sed` part), but I haven't figured a way to make it so.
Upgrading my site with blog links
Published: 2019-09-15 00:41:55

Until now, my website ([andrewsosa.dev](https://andrewsosa.dev)) was just some Github project links, but now, with the power of [gatsby-source-dev](https://github.com/geocine/gatsby-source-dev), we now have some blog links too. 

Woo, blog links!


#### _obligatory tutorial part_

##### 1. you install the plugin
```bash
npm i gatsby-source-dev
```

##### 2. you add the config

```js
module.exports = {
  // ...
  plugins: [
    {
      resolve: `gatsby-source-dev`,
      options: {
        // This is your username on Dev.to
        username: `andrewsosa`,
      },
    },
   // ...
  ],
};

```


##### 3. _to be continued_
Nice tests to run in CI before deploying any website
Tags: testing, devops, webdev
Published: 2019-09-14 23:50:25

Since I'm the only dev behind my startup, [Giffon 🎁](https://giffon.io), I've to take care of all the technical things from development to deployment. Though I've been following best practices and be careful about edge cases, still I don't trust the code I wrote very much.

I added a number of tests in CI to check my website before deployment, and they have caught my mistakes many times. The cool thing is, many of those tests are generic enough to be applicable to any website, so you should consider using them too!

## 1. Markup validation

The first easy low-hanging fruit is HTML (and CSS/SVG) validation. Most HTML templates do not enforce valid HTML, so it's quite easy to output documents with mismatched tags, which can be a pain to spot! Giffon uses [ReactDOMServer](https://reactjs.org/docs/react-dom-server.html), which prevents tag mismatches, but the validation still caught me many times about putting block-level elements (e.g. `<ul>`) in `<p>`, and also missing `alt` attribute in `<img>`.

Giffon's CI uses the [html5validator](https://github.com/svenkreiss/html5validator) command line tool against a development server. It's basically calling the commands as follow:

```sh
html5validator --html http://localhost:3000/every/page
html5validator --css www/css/*.css
html5validator --svg --errors-only www/images/*.svg
```

## 2. Detecting browser console error messages

The second generic error detection is to check the browser console. It reports JS run-time errors as well as broken image references and some invalid HTTP respond headers too.

Giffon's way to do it is to use [Selenium web driver](https://www.seleniumhq.org/projects/webdriver/), navigates to each page and calls `driver.get_log("browser")`, asserts that there is no log.

## 3. Detecting horizontal scrollbars

Most websites don't use horizontal scrollbars. It's annoying (especially on mobile) when one appears due to layout bugs.

Again, Giffon's CI makes use of Selenium. The CI navigates to each page and detects the present of horizontal scrollbars by asserting the following code returns zero:

```python
driver.execute_script(
    "document.scrollingElement.scrollLeft = 1;" +
    "return document.scrollingElement.scrollLeft;"
)
```

## 4. Spellchecking

Who doesn't make typos? It may not be critical, but having typos in your website does give a bad impression to visitors.

Giffon's CI uses [spellchecker npm library](https://www.npmjs.com/package/spellchecker). Giffon has its UI text strings isolated when I implement multi-language support, so it's easy for me to iterate over all the strings and call `SpellChecker.checkSpelling(str)`.

If you don't have your strings isolated, you may save the html output as a file and use the good old [aspell](http://aspell.net/) cli to list all misspelled words as follows:

```sh
cat path/to/my.html | aspell --mode=html list
```

# Any others?

Do you run similar tests in you CI pipelines? Let me know if you have any good ones to share!
Software Studio Help....
Tags: career, startup
Published: 2019-09-14 23:29:49

  So I am at a place in my career where I think its time I branch off from the normal 9-5 and start my own Software Studio. I have been researching online and seems everyone plagiarizes each other. Does any one have any great sources they themselves have used? How successful is your shop from using those resources or did you have to "make your own luck"? 

  Some friends have suggested writing a game which is something I have never done before. I do have stories with characters I have written so the natural next step would be to story board and then create a game. I thought about creating a platform for the masses since scalable web applications are my area of expertise. Which path should I choose, which path has the best chance of success? My plan is to be working full-time for my studio this time next year. I'm interested in hearing from the community.
Infinite list of prime numbers using Python generators
Tags: python, generators, primes
Published: 2019-09-14 21:55:14

---
title: Infinite list of prime numbers using Python generators
published: true
description: Improve your coding speed using your editor correctly
tags: python, generators, primes
---

Sometimes we want to create collections of elements that are very expensive to calculate. The first option is to create a list and wait until all the elements are calculated before we use it. Although this works, it is not very efficient. To make it a bit more efficient, modern languages provide a way to create custom iterators so each element is calculated only when needed (this is also called lazy initialization). Also, iterators allows us to create infinite collections!

Python has, in my opinion, one of the most succint and elegant ways to declare iterators: [generators](https://wiki.python.org/moin/Generators).

Without further ado, let's try to create an infinite list of prime numbers.

The first thing we need is a way to detect if a number is prime:

```python
from math import sqrt

def is_prime(n):
    if (n <= 1):
        return False
    if (n == 2):
        return True
    if (n % 2 == 0):
        return False

    i = 3
    while i <= sqrt(n):
        if n % i == 0:
            return False
        i = i + 2

    return True
```

Now, using our `is_prime` function we can do:

```python
def prime_generator():
    n = 1
    while True:
        n += 1
        if is_prime(n):
            yield n
```

And that's it! Just call the function and get elements from it:

```python
generator = prime_generator()

for i in range(10):
    print(next(generator))
```

Or create a list of the first N prime numbers:

```python
from itertools import islice

array = [x for x in islice(prime_generator(), 10)]
```

As you could see, the iterator definition is one of the shortest and simplest among all languages.

<a href="https://www.buymeacoffee.com/alebian" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/black_img.png" alt="Buy Me A Coffee" style="height: 41px !important;width: 174px !important;box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;-webkit-box-shadow: 0px 3px 2px 0px rgba(190, 190, 190, 0.5) !important;"></a>
Hack Rails with vulnerabilities by OWASP
Tags: ruby, rails, hack, security
Published: 2019-09-14 20:57:05

---
title: Hack Rails with vulnerabilities by OWASP
published: true
description: rails app for testing your hacking skills
tags: ruby, rails, hack, security
---

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/1o2y3c6dop0e64k3hgpl.png)

I found the [rails app](https://github.com/OWASP/railsgoat) includes
XSS, CSRF, SQL Injection vulnerabilities


## Getting Started with Docker


```bash
git clone https://github.com/OWASP/railsgoat
cd railsgoat

docker-compose build
docker-compose run web rails db:setup
docker-compose up
```

Open [localhost:3000](http://localhost:3000)

Analyze source code and try to find vulnerabilities.
For hints use [wiki](https://github.com/OWASP/railsgoat/wiki) and [brakeman](https://github.com/presidentbeef/brakeman)

Happy Hacking!

Follow me on [GitHub](https://github.com/dukaev)
ApiGateWay
Tags: javascript, node
Published: 2019-09-14 20:52:23

I have several projects and each requires authentication
so I created another one to manage the session for the user and the token Like GateWay or an access point 
So, I have to authenticate once
and my session has to go from one project to another
but I do not know how to do that
is there a way to add a module in this  GateWay to create a unique key and transmit it with each redirection  or just with JWT 
I hope you can help me with your advices .

If you need any further information let me know .

Thanks in advance !
ELI5: The role of Discrete Mathematics in programmatic problem solving
Tags: explainlikeimfive
Published: 2019-09-14 19:47:19

---
title: ELI5: The role of Discrete Mathematics in programmatic problem solving
published: true
description: 
tags: #explainlikeimfive
---

I've run across this question like 3 times in the past month and I'm curious as well. It gets discussed a lot but my NVLD ass don't get it. 😂❤️
Daily Challenge #66- Friend List
Tags: challenge
Published: 2019-09-14 18:58:35

---
title: Daily Challenge #66- Friend List
published: true
series: Daily Challenge
description: Make a program that makes the string uppercase and alphabetized by last name
tags: challenge
---

John has invited some friends. His list is:

`s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";`

Could you make a program that:
-makes this string uppercase
-gives it sorted in alphabetical order by last name

When the last names are the same, sort them by first name. Last name and first name of a guest come in the result between parentheses separated by a comma.

So the result of function `meeting(s)` will be:

`"(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"`

It can happen that in two distinct families with the same family name two people have the same first name too.


***
_Today's challenge comes from g964 on [CodeWars](<https://codewars.com/>), who has licensed redistribution of this challenge under the [2-Clause BSD License](<https://opensource.org/licenses/BSD-2-Clause>)!_

_Want to propose a challenge idea for a future post?  Email **yo+challenge@dev.to** with your suggestions!_
How to make social friend?
Tags: beginners, discuss
Published: 2019-09-14 18:28:06

**First thing why make friends?** You make friends to expand your reach and audience to grow and understand yourself. People have different profession. Friends helps each other to remove the difficulty according to their profession.

**Making social friend.** There are many social sites you can use to make friends. Mostly, Facebook, Twitter are most commonly used social website. Depending on your location, social sites exist for region base.

**How to expand your reach?** Share to the world what things you like and post about the things which you are interested in. People know you as the profession you do and they know it well as you post it on the social site.

I use [Twitter](https://twitter.com/taimoorsattar7) to post the things that interest me.
What are the biggest challenges when onboarding and contributing to a new codebase/project?
Tags: discuss, watercooler, tools
Published: 2019-09-14 18:25:35

---
title: What are the biggest challenges when onboarding and contributing to a new codebase/project?
published: true
description: 
tags: discuss, watercooler, tools
---


Hey All!

In your experience, what have been some of the biggest challenges you (or others on your team) have faced when getting setup and familiar with a new codebase, and then ultimately, merging in your first change? For example:

* Setting up your machine with the right SDKs to build/run the app (e.g. specific version of Node/Java)?

* Knowing which IDE and extensions are needed in order to productively work on the app?

* Configuring access to private repositories, package managers or registries?

* Setting up the needed service dependencies for the app (e.g. a database)? 

* Actually getting familiar with the codebase itself? (e.g. it’s directory organization, any specific style conventions)

* Understanding architectural decisions that have been made, and how to best apply those for future work?

* Learning the team processes for how to handle commits/PRs (e.g. thoughts on rebasing, do we use conventional commits?)

* Determining who to ask questions about specific parts of the codebase? 

* Something else?

Many of these have potential solutions, and so I’d love to hear not only what challenges you’ve faced, but also, how you’ve worked around them. In general,
I’m just very curious to hear how teams are able to improve the onboarding and contribution process for new members. Thanks!
Add a LAMP Stack to a server with Centos OS
Tags: lamp, apache, mysql, php
Published: 2019-09-14 18:16:42

<strong>Log in as root</strong>

ssh root@your.ip.address.here 

<strong>add a new user with sudo privileges</strong>  

[root@myserver ~]# adduser admin
[root@myserver ~]# passwd admin
Changing password for user admin.
New password: 
Retype new password: 
passwd: all authentication tokens updated successfully.
[root@myserver ~]# usermod -aG wheel admin

<strong>change from root to new user</strong>

[root@myserver ~]# su - admin
.
[admin@myserver ~]$ sudo ls -la /root

[sudo] password for admin: 

<strong>update Centos </strong>

[admin@myserver ~]$ sudo yum update

<strong>add apache</strong>

[admin@myserver ~]$ sudo yum install httpd

<strong>start apache</strong>

[admin@myserver ~]$ sudo systemctl start httpd.service

<strong>add mariadb</strong>

[admin@myserver ~]$ sudo yum install mariadb-server mariadb

<strong>start mariadb</strong>

[admin@myserver ~]$ sudo systemctl start mariadb

<strong>secure mariadb</strong>

[admin@myserver ~]$  sudo mysql_secure_installation

<strong>system will ask these questions. answer with y</strong>

Set root password? [Y/n] y
New password: 
Re-enter new password: 
Password updated successfully!
Reloading privilege tables..
 ... Success!

Remove anonymous users? [Y/n] y
 ... Success!

Disallow root login remotely? [Y/n] y
 ... Success!

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reload privilege tables now? [Y/n] y
 ... Success!
Cleaning up...

<strong>let system start maria db</strong>

[admin@myserver ~]$ sudo systemctl enable mariadb.service

<strong>add php and mysql</strong>

[admin@myserver ~]$ sudo yum install php php-mysql

<strong>restart apache</strong>

[admin@myserver ~]$ sudo systemctl restart httpd.service

<strong>install nano editor</strong>

[admin@myserver ~]$ sudo yum install nano

<strong>add php info file so you can check your installation</strong>

[admin@myserver ~]$ sudo nano /var/www/html/info.php

<strong>info page is at http://youripaddress/info.php</strong>


<strong>that's it. go to your ip address and you should have the apache start page</strong>
How To Write Your 1st Blog Post as a Developer
Tags: productivity, writing
Published: 2019-09-14 18:13:13

# **Like this.** 


_Starting new things can be a daunting task. Just jump in._ 🏊‍♀️



###### Cover Photo by [Kaitlyn Baker](https://unsplash.com/@kaitlynbaker?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/)
Get BAT price with Python
Tags: blockchain, python
Published: 2019-09-14 17:56:02

BAT (Basic Attention Token) is a decentralized ad exchange platform built on the Ethereum platform.

The token aims to correctly price user attention within the platform. Advertisers pay BAT to website publishers for the attention of users. 

The BAT ecosystem includes Brave, an open-source, privacy-centered browser designed to block trackers and malware. It leverages blockchain technology to anonymously and track user attention securely and rewards publishers accordingly.

## Earning BAT

At this point in time, you can only collect BAT, but there doesn't seem to be a way to withdraw it to other crypto-currency. But you could collect BATs and wait for withdraw support in the future.

Edit: You can now collect BAT tokens, <a href="https://old.reddit.com/r/BATProject/comments/chbr90/brave_browser_added_ability_to_withdraw_bat/">withdraw BAT</a>

<img src="https://proxy.duckduckgo.com/iu/?u=https%3A%2F%2Flh3.googleusercontent.com%2FRCxdR3ZH7vEcys_jWSVjXHM_78Bi5q0p95F4Ev0pYtOw9wT11ofMVGvTeITuMImKbgU%3Dh900&f=1&nofb=1">

## Exchange

BAT can be exchanged for other crypto-currencies or you can exchange to another btc and then to fiat currency.

You can get the current price of BAT with Python:

    #!/usr/bin/python3
    import requests
    import json
    from forex_python.converter import CurrencyRates
    import os
    
    c = CurrencyRates()
    rate = c.get_rate('USD', 'EUR') 
    print(rate)
    
    basic_attention_token_api_url = 'https://api.coinmarketcap.com/v1/ticker/basic-attention-token/'
    response = requests.get(basic_attention_token_api_url)
    response_json = response.json()
    print(response_json)
    
    for coin in response.json():
        price = coin.get("price_usd", "U$S Price not provided")
        coin_price = float(("{0:.2f}").format(float(price)))
        print("$ " + str(coin_price))
        coin_price_eur = float(("{0:.2f}").format(float(price)*rate))   
        print("E " + str(coin_price_eur))


ref: https://github.com/codesharedot/basic-attention-token-price/

Read more:

* <a href="https://basicattentiontoken.org/">Basic attention token</a>
* <a href="https://brave.com/">Brave browser</a>
* <a href="https://pythonbasics.org">Learn Python</a>
Flutter Performance Tips (#2): use ListView.builder() for list with a large amount of items
Tags: flutter, dart
Published: 2019-09-14 17:45:35

We have more than one constructors in the `ListView` class and sometimes you maybe wondering which one to use in determined case.

### **ListView(children: <Widget>[])**
This is the default ListView's counstructor that takes a list of Widgets. We must use this in cases where we have a small list views items.

### **ListView.builder(...)**
This is the constructor that we must use for cases that we have a large number of list view items because different than `ListView(children: <Widget>[])` this constructor *only build items that are visible in the screen*. Each time the user scroll the list it build the next visible item.

### **ListView.separated(...)**
This one do the same as the `ListView.builder(...)` but with a bonus: it takes an `separatorBuilder` to give us the ability to add a separator between our items.
Search and Filtering Without Tears (Parts 1 & 2)
Tags: javascript, filtering, searching
Published: 2019-09-14 17:35:56

In the two videos I released this week (I publish every Tues and Thurs) I talk about search and filtering of the data you ship to the front-end in your web apps. Even if you're shipping a lot of data to the user's browser these days, there's no reason why building search and filtering has to be hard to write, nor does it have to be slow. In about 30 minutes, I'll show you how to do it right.

{% youtube EQHj43m8fwI %}

{% youtube TOl9LokXYXQ %}

Notes: Wow. Building up a YouTube channel is super hard :) But you probably knew that already. I'm making great strides on getting enough viewing time to hit YouTube's requirements of 4000 watched minutes within a year. I won't have a problem hitting that. But they also require 1000 subscribers before they will monetize your channel and I'm no where near that. So please like and subscribe if you enjoy what I produce.

Thanks,
John
Tracli - A command line app that tracks your time
Tags: node, javascript, github, opensource
Published: 2019-09-14 17:11:07

### What is Tracli?

Tracli is a time tracking project, especially for developers. Or a simpler way to tracking your time than Toggle. 

### The story behind the project

How much time do we work on the command line as a developer? Can I answer? A lot of… The simple reason for that is I don’t like using the mouse. Two hands-on the keyboard more productive for me.
I can work on the command line. Why I can’t track my time on the command line? There are a few solutions for that. For example, Toggle has an open-source command-line app that builds from somebody. But you have to connect your data to Toggle. Of course, there are few projects just work on local. But you have to work on local. 
What do we suggest? Simple… If you want to work on local, work on local. Sometimes if you need a cloud solution. Then move your data and continue from the cloud. When you don’t need cloud then return your local with all data.

### Products

**Tracli Terminal** - v0.2.1
**Tracli Web** - Coming Soon
**Tracli API** - Coming Soon



https://github.com/ridvankaradag/tracli-terminal/