teleren/devto huggingface dataset:
Autofixing Variable Case in PHP
Tags: php, phpcsfixer, linters, programming
Published: 2020-09-18 17:57:40

---
title: Autofixing Variable Case in PHP
published: true
description: How to autofix variable casing in PHP using PHP-CS-Fixer
tags: php, phpcsfixer, linters, programming
---

I’m currently working on a PHP project that had a mix of camelCase and snake_case for variables and methods. We had recently started using [PHP-CS-Fixer](https://github.com/FriendsOfPHP/PHP-CS-Fixer) on the project and, unfortunately, there was not an existing rule to make this kind of change. So I decided to write a variable case fixer myself! Now: this is inherently risky. Instance variables in PHP are called using `$this->variableName`, which is really similar to how you call a function. Those could also be defined above the constructor like `private $variableName` and that would be fixed with a fixer like this, but any call site would not. So there’s some of the risk 😅. There are also [predefined variables](https://www.php.net/manual/en/reserved.variables.php) in PHP that we would not want to update. Ok, let’s get started!

Since I was using an existing project, I did not have to worry about getting each file and was able to trust PHP-CS-Fixer to parse each file and get me the tokens. The hardest part of this was actually figuring out how to pick out the tokens. So all this does is check to see if the token ( smallest block of code) is either of the two [variable types](https://www.php.net/manual/en/tokens.php) and not in the list of predefined variables.
```
foreach ($tokens as $index => $token) {
  if ((T_VARIABLE === $token->getId()) || (T_STRING_VARNAME === $token->getId())) {
    if (in_array($token->getContent(), $predefinedVariables)) {
      continue;
    }
    $tokens[$index] = new Token([$token->getId(), $this->updateVariableCasing($token->getContent())]);
  }
}
```
That is actually the bulk of it! `updateVariableCasing` just takes the configuration and then calls whatever function we need (ie `camelCase()` if `configuration['case']` is equal to `camel_case`. The functions to change case were found somewhere on StackOverflow. Overall, this works very well! The only places we ran into problems were where private variables were defined at the top, converted there, but then not converted when called in the code (as `$this->variable_name`). Something to keep in mind if you decide to implement something like this in your project.

I did put up (a PR to add this rule to PHP-CS-Fixer)[https://github.com/FriendsOfPHP/PHP-CS-Fixer/pull/5097], but I think they were reluctant to add it since it’s not safe and I don’t have a ton of extra time to keep trying to get it in.
{% gist https://gist.github.com/jmkoni/0afb692e93c57ca39e2efa43a1c4a600 %}
Create README test coverage badges from istanbul reports
Tags: testing, coverage, badges, javascript
Published: 2020-09-18 17:51:34

### There are fantastic tools for coverage badges such as [Coveralls](https://coveralls.io/) but, for **free**, they only cover **public** repositories

### What then if a repository is **private**? Bind it to a process run locally with [**Istanbul Readme Badges**](https://github.com/olavoparno/istanbul-badges-readme)

![Process](https://dev-to-uploads.s3.amazonaws.com/i/2vavlvz8rtcw0a0z2x5a.gif)

### One can follow the very [README.md](https://github.com/olavoparno/istanbul-badges-readme#readme) of the project but in short here is what is needed:

- Install it

```sh
npm i -D istanbul-badges-readme
```

- A _README.md_ file with additional [markup](https://github.com/olavoparno/istanbul-badges-readme#example-markup-paste-it-anywhere-in-your-readmemd) into which the badges are inserted

```md
| Statements                | Branches                | Functions                | Lines                |
| ------------------------- | ----------------------- | ------------------------ | -------------------- |
| ![Statements](#branches#) | ![Branches](#branches#) | ![Functions](#branches#) | ![Lines](#branches#) |
```

- Run the script anywhere, either in a, e.g. `pre-commit` [husky hook](https://github.com/typicode/husky), or in a pure NPM script directly

```sh
node_modules/.bin/istanbul-badges-readme
```

- _Voilà_!

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/zegw541c78ydd30jex46.png)
Don't Let Kids Code It Alone
Tags: codingforkids
Published: 2020-09-18 17:43:33

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8e7o7ihhvwdppxcnfip1.jpg)
As we enter the digital age, the promotion of digital literacy has been on the rise. This trend has trickled from college education down to preschool! Yes, even preschool! My 4 year old launched into his coding career with a [Thames and Kosmos robot.](https://www.thamesandkosmos.com/index.php/product/category/science-kits/kids-first-coding-robotics)
The internet is flooded with resources aimed at coding for kids of all age! The prices and qualities range the gamut. The ones that flash "FREE" certainly appeal to the wallet! But we've found that kids need a little bit more in the way of support to really flourish in coding. 

Children need community to help them thrive and learning to code is no different! 
- **Hands-on teachers** can encourage, correct, and prompt their students. 
- **Peers** can inspire, challenge, and motivate. 
- **Class times** hold students accountable, setting aside a time and space to practice. 
- **Year round school** ensures that those skills are solidified and not forgotten. 

You're right, this is a skill worth investing in. Even if you're afraid your child isn't that interested in coding, it's a wise idea to find a live teacher. They will *work* to engage your child. That is, after all, their job! (And you can always find [programs with a Money Back Guarantee](https://codewizardshq.com/coding-programs-for-kids/).)
Displaying output using ITestOutputHelper when executing `dotnet test` command
Tags: dotnet, netcore, xunit
Published: 2020-09-18 17:38:00

---
title: Displaying output using ITestOutputHelper when executing `dotnet test` command
published: true
description: 
tags: dotnet,netcore,xunit
//cover_image: https://direct_url_to_image.jpg
---

xUnit.net allows you to capture the output of your tests by using `ITestOutputHelper`.

In Visual Studio's Test Explorer, The captured output can be viewed by selecting the test case.

On the other hand, if you run a test with the `dotnet` command, the captured output is not displayed anywhere, which is a bit of a problem if you want the output to be displayed when you run it in CI.

## Solution
Use the `verbosity=detailed` option for the `logger` to display the output in the console while using the `dotnet` command.


```bash
dotnet test ./tests/MyApp.Tests --logger:"console;verbosity=detailed"
```

Now you can see the captured output in the console.

```
  √ MyApp.Tests.TestCases.Test1 [4ms]
  Standard Output Messages:
 Hello from Test
 ```
[Tutorial Linux] Terminal: movendo/renomeando arquivos e diretórios
Tags: mv, terminal, linux, womakerscode
Published: 2020-09-18 17:37:56

Esse comando é semelhante ao recortar do Windows.

## Mover um arquivo para dentro de um diretório

Para mover um arquivo para um diretório, digite:

```
$ mv <nome_do_arquivo> <nome_do_diretório_para_onde_se_deseja_mover>
```

- **$** indica que você deve usar o **usuário comum** para fazer essa operação.

- **mv** do inglês, move, para mover um arquivo.

- digite o nome do arquivo sem os sinais **< >**.

## Mover uma pasta para dentro de outra pasta

Mover um diretório para dentro de outro diretório, é bastante similar ao comando anterior:

```
$ mv <nome_do_diretório> <nome_do_diretório_para_onde_se_deseja_mover>
```

## Mover o conteúdo de um diretório para outro

Mover todo o conteúdo de um diretório para dentro de outro diretório, digite:

```
$ mv <nome_do_diretório>/* <nome_do_diretório_para_onde_se_deseja_mover>
```

- __*__ o asterisco, conhecido como  **curinga ou referência global**, indica ao terminal que ele deve pegar todo o conteúdo de dentro do diretório, independente de qual seja a extensão deles.

## Renomear um arquivo ou diretório

Esse comando também é utilizando para renomear um arquivo; quando o destino é o mesmo diretório. Assim, digite:

```
$ mv <arquivo_original> <arquivo_renomeado>
```

Para renomear uma pasta, digite:

```
$ mv <diretório_original> <diretório_renomeado>
```
Automatización de tareas
Tags: python, fabric, devops
Published: 2020-09-18 16:58:26

En algunos proyectos que tengo a cargo tengo que realizar tareas repetitivas como deploy, reconstruir docker incluso backup de bases de datos.

Entonces para esto desarrolle un pequeño script que me ayuda a realizar estas tareas de forma más rápida.

{%github https://github.com/abelhOrihuela/tasks-spark %}

Consiste en tener un archivo hosts.yml donde tenemos configuradas nuestras instrucciones a ejecutar, ejemplo:

 ```yaml
hosts:
- host: XX.XX.XX.XX #ip
  name: Landing prod #simple name
  user: app #user
  steps:
  - cd: landing
    steps:
    - run: git reset --hard
    - run: git checkout master
    - run: git pull
    - run: npm i
    - run: npm run build
```

Con estas instrucciones lo que yo hago es hacer deploy de un sitio estático.

Al ejecutar el script de la siguiente forma:

```bash
python3 main.py
```

Obtendremos un listado de los hosts, al seleccionar uno nos pedira la contraseña para conectarnos e inmediatamente se ejecutaran los comandos y eso es todo.
How to success in Teer game
Tags: teer
Published: 2020-09-18 17:25:49

Dosto kya apko jitna hai dher sare paisa to is article ko dhyan se parhe. We will update you with all the old and new tactics of Teer game. 

First of all, we have to know that to become pro in the <a href="https://www.assamteerresults.com/">Teer Counter</a> game we need patience and Money to bid on numbers. Gradually you can understand the game. But we have to spend less amount on maximum numbers. 

Say you will bid on numbers today let it be 12 so if you are sure on 12 so at first, you can take complete house 1 (One). But you have to bid less amount like only Re 1. You may try this trick. Also you have to go through all the previous results and Common Number Published in Various Teer websites online in Internet!
My #100DOC - Day 23
Tags: challenge, 100daysofcode, log
Published: 2020-09-18 17:16:06

### Day 23: September 18, 2020

#### **Today's Progress**: 
1. **[Continued with Confección y Publicación de Páginas Web Course](https://github.com/pablohs1986/confecci-nYpublicaci-nDeP-ginasWeb_SEPE)** (1h 30min):<br>Today I ended with first part of unit 1 of the course doing the last exercise of HTML basics.
    
#### **What I learned**: 
* Review of HTML tables, lists, frames and divs.

#### **Total time**:
1h 30min.
Syntactic sugar, why, when and how
Tags: codequality, todayilearned
Published: 2020-09-18 17:09:39

*The term __Syntactic Sugar__ was coined by __Peter J. Landin__ in 1964. In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an alternative style that some may prefer.*

**The Why**
It demonstrates the domain of native APIs, brings more flexibility and readability to the code, it can help others to find new ways to write more short and concise code, and I can go ahead all-day long.

**When**
Every time you have a change!

**How... Let's go**

```javascript
 // don't
 let alex = personal.alex

 // do destructuring
 let {alex} = personal
```

```javascript
// don't if variable asignation may not vary
var isSuperHuman = superhuman ? "is super human" : "nahh"

// use const instead
const isSuperHuman = superhuman ? "is super human" : "nahh"
```

```javascript

// arrays to avoid for loops o foreach
arr.find(i => i.id === "01") // returns the object

// with destructuring
arr.find(({id}) => id === "01") // returns the object

arr.filter(({id}) => id === "01") // returns and array of matches elements

arr.some(({id}) => id === "01") // returns boolean value

arr.every(({type}) => type === "superhumen") // returns boolean value if every nodes matched the criteria

arr.reduce((acc, {age}) => acc + age, 0) // returns a reduced value in this case the sum of all ages

// concat and push are from the pass now we spread!
const a = [...arr, newElemet]

// or to place the new element at the top of the array
const a = [newElemet, ...arr]

// mergin to arrays
const a = [...arrB, ...arrC]

// or flatted!!
const a = [arrB, arrC].flat()

// get the unique values (names) from array, lets map?
const a = ...new Set(data.map(i => i.name))

// as array?
const a = [...new Set(data.map(i => i.name))]
```

- But Alex I already know that man!

```javascript
// number to strings?
100.toString() // "100"

// what about!
100 + "" // "100"

// strings to number?
Number("100") // 100
parseInt("100") // 100
parseFloat("100").toFixed(2) // 100.00

// what about!
"100" * 1 // 100
```

- Of curse, I know that too!

If that is the case, my friend you may be the sweetest person in the whole world!

Just let me know how do you declare functions?

```javascript

// as a declaration
function sum(a,b) {
  return a + b
}

// as expression 
const sum = function(a,b) {
  return a + b;
};

// as an arrow?
const sum = (b,c) => b + c

// as shorthand method definition?
const operation = {
  add: (a,b) => a + b
}

// or 
const operation = {
  add(a,b){return a + b}
```

See ya at the next sugar! Let me know yours.
OSD600 - 1
Tags: opensource
Published: 2020-09-18 17:08:41

**Introduction**
Hi, my name is Michael Brackett. I started programming when I was in grade 10 and have been loving it ever since. I found OSD600 very interesting while researching what my potential pro topics were going to be, what really intrigued me was the [Hacktoberfest](https://hacktoberfest.digitalocean.com/) portion of the course. I got interested in Open Source when I was looking into chess engines and researching about [Stockfish](https://github.com/official-stockfish/Stockfish) which made me realize that all the code is free and can be seen by anyone for this project.  Looking at the repository right now there is an [issue](https://github.com/official-stockfish/Stockfish/issues/3090) that I think I can do. Hopefully, it doesn't get taken before I really get into Open Source development!

**Where are you**
I'm currently located in the GTA

**Hopes**
I'm hoping to contribute to projects, learn more about open source programming, and learn a new programming language. I don't really have a preference for which projects I work on as long as I'm learning and it's fun. If I had to pick one I'd say my first choice is the previously mentioned Stockfish repository.

**Github Fork**
The project that I forked is the [Ciphey](https://github.com/Ciphey/Ciphey) repository. I chose to fork this repo because I think that encryption is a key technology that is currently being used and will become even more important as time goes on. Seeing something that is light weight and can decrypt fairly fast which is accessible to anyone is incredible.
LibreAV - Free And Open-Source Anti-Malware For Android Using Machine Learning
Tags: machinelearning, contributorswanted, hacktoberfest, showdev
Published: 2020-09-18 17:03:41

![LibreAV Graphic] (https://dev-to-uploads.s3.amazonaws.com/i/r3yqgtpmiskgks8iiu8k.png)

[<img src="https://fdroid.gitlab.io/artwork/badge/get-it-on.png" width="200" />](https://f-droid.org/packages/tech.projectmatris.antimalwareapp)

###Feel free to contribute on [Github] (https://github.com/projectmatris/antimalwareapp)
##Background
Android is the most popular operating system today. The popularity of the Android platform has also attracted malware developers towards it. Malware attack is a challenging issue among the Android user community. So it is necessary to make the platform safe for users by providing a defence mechanism against malware.
Traditional virus detection relies on the use of signatures. The problem with signatures alone is that new types of viruses such as polymorphic ones can mutate their code, making signature generation difficult or impossible. By utilising a machine learning approach, we can detect malware without explicit knowledge of their presence.
##What is LibreAV?
**LibreAV is an attempt to detect malware on Android devices using a machine learning approach** that is powered by TensorFlow. We use a two-layer neural network trained with a carefully selected set of features. The neural network is tuned in such a way that it performs efficiently on mobile devices where computational resources are limited. Tests show that LibreAV performs efficiently and effectively even on low-end mobile devices. With LibreAV, you can scan all the installed apps in your device in a matter of seconds. It also has a real-time scan feature which alerts you whenever an app is installed or updated.

We welcome contributions from your side. That is why we released it as open-source under GNU GPLv3. The motivation behind LibreAV is to make the digital world a safe and secure place. LibreAV is expected to be supported by the open-source community. So your contributions are very important to us.

Check out LibreAV, let's fight malware together.

> Android is a trademark of Google LLC.
This app will win me my fantasy football league
Tags: javascript
Published: 2020-09-18 16:50:49

Or at least I hope it will :)

In Week 1 of my Fantasy Football League, I lost bad. Like 2nd lowest score in the whole league bad. Only 1 other person did worse than me. 🤣

![Fantasy week 1 scores](https://dev-to-uploads.s3.amazonaws.com/i/utzk2rsma4e7ec95p621.png)

And this got me thinking, I really need some better players (plus my defense did NOTHING). By random circumstance, I found the ESPN has an API for getting league and team information, and lightbulb, let me build a webapp that can help me win my fantasy league. 

The documentation definitely needs some work as ESPN actually provides none, and a nice fellow dev Mike Kreiser was kind enough to help us out. If you want to learn more about working with the ESPN API that is available via an npm package, check out his documentation [here](https://github.com/mkreiser/ESPN-Fantasy-Football-API). 

Digging into the source code, you learn a little bit more about what is available from this API, and one of the endpoints is to your league's free agent list. I thought to myself, this could be helpful.

![Free agent function declaration](https://dev-to-uploads.s3.amazonaws.com/i/r6qihub60pu5z0lkawj5.png)

So I started playing around with the API and trying to figure out exactly how this could help me. I am not fantasy football expert, and I noticed one of the fields returned is a Percent Started. This percentage is based on how many other leagues started this player. So while I might not be the best, maybe a lot of other people playing know what they are doing. This got me thinking, I could start looking for free agents in our league with high percentages and scoop them up.

![Free Agent's table](https://dev-to-uploads.s3.amazonaws.com/i/hnw73ftmhxz7e9s9zj1t.png)

I started working an app where I can see all the available players, make sure they aren't injured or not a team (and therefore won't be scoring any points), and then use this list to make better decisions for my team. 

So far, I have the table up and running, and next up is for filtering and sorting. Stay tuned for progress and to see if it did help me win 😁
Generating a Sitemap for a JAMstack Site
Tags: seo, jamstack, nuxt
Published: 2020-09-18 16:45:30

Sitemaps are a great way of helping search engines understand your website. While modern search engines primarily rely on links to create their search indexes, this can leave lesser-known sites at a disadvantage due to a lack of external backlinks.

Search engines will look for a `sitemap.xml` file at the root directory of your website, and if it exists, it will parse that file to find any links it did not previously index.

When generating a sitemap, you should be following the schema defined on [http://sitemaps.org](http://sitemaps.org).

```xml
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
  <url>
    <loc>https://www.example.org/path</loc>
  </url>
</urlset>
```

Many of the JAMstack frameworks have plugins that can generate a sitemap for you. Still, if the framework you chose doesn't have one, or if you'd prefer to minimize dependencies, it's easy to create a sitemap after running your workflow's site generation step. I'll use Nuxt in this example, but the code can be easily modified to fit your stack.

Nuxt creates a `dist` folder on static site generation, with `.html` files for each route within the website. Knowing this, I can write a script that will search that directory for HTML files and generate XML nodes for each unique page.

```javascript
const fs = require('fs')
const { resolve } = require('path')
const glob = require('glob')

const sitemap = resolve(__dirname, 'dist', 'sitemap.xml')

const nodes = [
  '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
]

glob('dist/**/index.html', (err, files) => {
  if (err) { throw err }
  files.forEach((f) => {
    nodes.push(`<url><loc>https://jessie.codes${f.replace('dist', '').replace('index.html', '')}</loc></url>`)
  })
  nodes.push('</urlset>')
  fs.writeFile(sitemap, nodes.join(''), (err) => {
    if (err) { throw err }
  })
})
```

Since I built my site using JavaScript, I can use `npm`'s ability to create a `post` hook that will run after the `generate` script. Every time a new page is added, the sitemap will automatically be updated, allowing search engines to update their index for my website even if no external backlinks exist.

```json
{
  "scripts": {
    "generate": "nuxt generate",
    "postgenerate": "node ./sitemap.js"
  }
}
```
_Originally published on [jessie.codes](https://jessie.codes/article/sitemap-for-jamstack)_