teleren/devto huggingface dataset:
Lacework VS Code Extension
Tags: vscode, javascript, security, devops
Published: 2021-11-09 22:54:00

The Lacework VS Code vulnerability scanner extension is a new plugin that will quickly identify vulnerabilities in your base images right from your IDE. This is a first step and alpha release with expanded and additional capabilities to be released soon.

This blog covers how to install lw-scanner and leverage it to perform image assurance scans from within VS Code.

**Install lw-scanner**
The plugin assumes that lw-scanner is installed on your local system. Installation instructions can be found here: [support.lacework.com](https://support.lacework.com/hc/en-us/articles/1500001777821-Integrate-Inline-Scanner) and the the latest release of the scanner binary can be found at [github.com](https://github.com/lacework/lacework-vulnerability-scanner/releases)

Once lw-scanner is installed the next step is to download the Lacework plugin from the VS Code Marketplace.

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

With an active Dockerfile in the editor you can initiate an image assurance scan by clicking Command+Shift+P on macOS (Control+Shift+P on Windows/Linux).

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

Once the scan is complete you will see a summary next to the base image that will disappear along with a more detailed scan result available in the output window.

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

Source code can be found here for now: [github](https://github.com/jeffthorne/lacework-vscode-extension).

This is just a quick preview update. For suggestions or feedback please open an issue on the repo. PRs welcomed. Stay tuned for more.

Cheers,
Jeff
SQLAlchemy v2 will break with the past... and most likely, your web app
Tags: python, webdev, opensource, sqlalchemy
Published: 2021-11-09 22:43:03

Most mature Python Libraries care a lot about backward compatibility, so it was a surprise to discover that the upcoming version of [SQLAlchemy](https://docs.sqlalchemy.org/en/14/changelog/migration_20.html) is making huge changes in its API, breaking with how web developers have been using it for years.

By far, the most, dramatic change is that `session.query()` is beign deprecated. This means the following code no longer works:

```python
user = session.query(User).filter_by(username='peter').first()
```

Instead, you now have to use `select` to build a query and execute it in the session.

```python
user = session.execute(
	select(User).filter_by(username='peter').limit(1)
).scalars().first()
```

Other query patterns have changed as well:

Get an object by primary key:
```python
# 1.x style (before)
session.query(User).get(42)

# 2.x style (now)
session.get(User, 42)
```

Counting the number of objects:
```python
# 1.x style (before)
session.query(User).count()

# 2.x style (now)
session.scalar(select(func.count()).select_from(User))
# or
session.scalar(select(func.count(User.id)))
```

Join a related table:
```python
# 1.x style (before)
session.query(User).options(
    joinedload(User.addresses)
).all()

# 2.x style (now)
session.execute(
    select(User).
    options(joinedload(User.addresses))
).unique().all()
```

Join and filter by a  related table:
```python
# 1.x style (before)
session.query(User).join(Address).\
    filter(Address.email == 'e@sa.us').\
    all()

# 2.x style (now)
session.execute(
    select(User).join(Address).
    where(Address.email == 'e@sa.us')
).scalars().all()
```

The new versions are much more verbose, aren't they? Why the change?
In the words of SQLAlchemy devs:

> The fact that SQLAlchemy has both a select() construct as well as a separate Query object that features an extremely similar but fundamentally incompatible interface is likely the greatest inconsistency in SQLAlchemy.

So now they are getting rid of it, and breaking most "wrapper" libraries, like Flask-SQLAlchemy, that will have to be rewritten entirely.

Before migrating to Peewee or PonyORM in anger, consider trying this lightweight wrapper I wrote to for the new syntax: https://sqla-wrapper.scaletti.dev/ 😉
A gambiarra de hoje pode ser o Design Pattern de amanhã!?
Tags: braziliandevs, oop, designpattern, backend
Published: 2021-11-09 22:37:35

---
title: A gambiarra de hoje pode ser o Design Pattern de amanhã!?
published: true
description: Os padrões não nasceram padrões, como nasce um padrão de projetos? Qual a diferença entre um padrão de projetos e uma gambiarra?
tags: #braziliandevs #oop #designpattern #backend
//cover_image: https://direct_url_to_image.jpg
---

Escrito em 1994, por Erich Gamma, Richard Helm, Ralph Johnson e John Vlissides. O livro "Padrões de Projetos: Soluções Reutilizáveis de Software Orientados a Objetos" tinha como principal objetivo catalogar 23 dos padrões mais populares na época.

Atualmente algumas pessoas conhecem o livro como "Gang Of Four", por conta de seus autores, sem contar que é uma referência muito mais simples de ser feita do que o próprio nome do livro.

No livro, os padrões são segregados em três categorias:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/neig0qzxou9fnqegbvpe.png)
 
*NOTA: O objetivo deste artigo não é falar sobre os padrões, caso você não os conheça recomendo  o site [refactoring.guru](https://refactoring.guru/design-patterns), que possui também uma versão em [português](https://refactoring.guru/pt-br/design-patterns).*

Por definição, um padrão de projetos é uma solução vastamente utilizada para resolver um problema em comum, mas não necessariamente igual. É importante lembrar que, a implementação se torna mais simples ou mais complexa dependendo da linguagem em que ela está sendo implementada, no livro citado acima os padrões foram implementados em Smalltalk e C++.

O que atualmente conhecemos como um padrão de projeto, não nasceu um "padrão". Ele se tornou um padrão com o tempo, pois seu uso se demonstrou eficiente para resolver um problema "comum". 

Tais implementações são criadas basicamente, para contornar uma limitação tecnológica e possivelmente se tornará obsoleta com a evolução das linguagens de programação, como por exemplo:

* O STRAREGY atualmente pode ser implementado usando uma arrow function.
* O SINGLETON pode ser completamente abstraído através dos nossos frameworks de injeção de dependências.

Outros padrões acabam evoluindo, como por exemplo o MVC, que apesar de ser um pattern, é amplamente conhecido por seus frameworks que estão presentes em praticamente todas as linguagens utilizadas atualmente.

Quando você encontrar um problema onde não existe uma solução pronta na internet, lembre-se a solução pode vir a virar um padrão, afinal de contas, quem nunca pegou uma solução de um problema de um projeto e copiou para um projeto novo?

Podemos dizer então dizer que...

Um padrão de projetos é uma gambiarra que "viralizou"?

<u>Qual a sua opinião sobre isso? Manda ai nos comentários!!!</u>

**Aproveite para me seguir no [Instagram](https://www.instagram.com/fructuoso.dev/), [YouTube](https://www.youtube.com/channel/UC6GzoFA8EUgUklPyRebxOgg) e [LinkedIn](https://www.linkedin.com/in/victorfructuoso/)**
CRUD Operations in React and Redux Toolkit with a Node.js Backend | Video Tutorial
Tags: react, redux, webdev, javascript
Published: 2021-11-09 22:36:07

In the following 2 hours tutorial, you will learn how to perform CRUD requests using Redux Toolkit (Now the modern way of working with redux).

If you enjoy the content like the video and remember to subscribe to my YouTube channel for more.

##CRUD in Redux Toolkit 👇

{% youtube ypA9GUJ1AMY %}
Day 23 - The epiphany
Published: 2021-11-09 22:33:47

Well, I've been doing a [kind of "Today I learned" blog](https://todayjampalearned.wordpress.com/), but I've now decided to give Dev a go, and bring here all my insights at this whole coding path that I've decided to take.

Funny thing that I had to jump from day 11 to day 23, which makes for almost two weeks without thinking much about what I learned, but I guess it's because I've turned on the automatic at this point. You know, learning new stuff, trying to solve a coding problem, googling it up to find that answer to what to do next, playing videogames when I'm fed up, etc.

But then I came across this new problem -- the last exercise of the Fundamental part of [The Odin Project](https://www.theodinproject.com/). Nothing big, really, just you typical array of objects.

But then for some reason I froze before it. Couldn't fix it, couldn't solve it, whenever I found something that looked like a solution, the more it seemed to run through my fingers.

Weekend came and went and I'm still there, fighting myself and those little 10 lines of code.

And then, today, at work (and I obviously don't work with coding), it came to me, like a bucket full of cold water hitting me in the face: the solution.

Now, I've seen people talking about how Devs eventually have to stand up and take a walk and do other stuff that the solution eventually might come, and as far-fetch as it sounds, it seems to really work.

I guess I could call it an epiphany. Probably many of several ones yet to come.

Funny thing, the Solemnity of the Epiphany is the Catholic celebration of the Three Wise Kings that came to visit Jesus after he was born, following the Star of Bethlehem. The Brazilian folklore has a special celebration of this, with music, theatrical performances and such. My neighbor is part of the "King's troupe", and they were rehearsing yesterday.

It's a stretch, but, hey, I'll take whatever good news I can get.
Just a quick post to see what's up
Tags: firstpost
Published: 2021-11-09 22:22:05

Nothing but a hello and what's up. I'mma try to provide some outlines and documentation in the loosest sense of the word of new things I learn. Really this is just intended for me to have an outlet to post stuff on. If someone can get any value from this down the line that'd be cool even if that someone is just me rediscovering old lessons of my own.

Cheers and welcome to myself.
Reduce Vs For-Loop
Tags: javascript, reduce, programming, webdev
Published: 2021-11-09 22:19:28

Are you interested in more tech content? Check us out on Twitter [@nspiredTech](https://twitter.com/@nspiredTech)!

---

I was working through some JavaScript Functional Programming examples when I came across the `reduce` method. By definition `reduce` is used to iterate through an array and condense it into one value.

This caused me to wonder what was the programmatic difference between `reduce` and a traditional `for`-loop?

Here is an example of the reduce method in action:

```javascript
let singleVal = array.reduce(function(previousVal, currentVal) {
  return previousVal + currentVal;
}, 0);
```

The pattern above stores the return value from the reduce method. The reduce method receives a callback function with the parameters `previousVal` and `currentVal`. As the array is being iterated each elements is being added together.

Here is the same input but with a `for`-loop

```javascript
for(let i = 0; i < array.length; i++){
  singleVal += array[i];
}
```

The same result is achieved with a `for`-loop. For each pass, the element or `array[i]` in this case, is added and stored in `singleVal`.

---

So I decided to test the two algorithms and see which performed better. Here are the results from https://jsbench.me/.

![Benchmark](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/unjxajcepvamj93l982o.png)

As you can see the `for`-loop outperformed the reduce method.

The results from the tests showed me the performance benefits of using one over the other, however it did not explain the programmatic difference I was looking for. So I decided to keep looking…

Eventually, I found the answer!

Reduce in JavaScript is the alias for Fold, a higher order function that analyzes a recursive data structure and through use of a given combining operation, recombines the results of recursively processing its constituent parts, building up a return value. 

In simpler terms, the elements are combined in a way that reflects the combination with the next element, and so on until all elements are exhausted.

Folds and maps are used to transform each value of a data structure independently, and filters are used to eliminate some elements from the data structure. Using `for`-loops as a jack of all trades tends to obscure the actual operation the loop performs. So from a programming standpoint, reduce is more eloquent and clear in its purpose.

In summary, we are able to determine the distinctions between the two approaches are contingent upon input and the design pattern of the programmer.

Happy Coding!
Guiding Principles for Writing Documentation
Tags: beginners, programming
Published: 2021-11-09 22:08:22

Your documentation should be:

## :busts_in_silhouette: Inclusive and clear 
Write docs in an inclusive and clear manner. Your language should be easy to understand and inviting. Try not to make assumptions about user's base level knowledge. 

Easy to read documentation is an easy way to increase number of users and contributors to your project.

## :white_check_mark: Complete
Describe all aspects of your project. Try to document all of the common use cases. 

> :bulb: Support queries are usually holes in your documentation. If you find yourself answering to questions about your project, which could have been 'searched', you should add that to your documentation. 

## :sparkles: Up-to-date 
This is particularly hard. Outdated documentation might cause more harm than no documentation at all. 

For Python projects, [doctests](https://dev.to/chaitdwivedi/documenting-your-way-to-better-tests-in-python-h5n) does help to a certain extent in keeping documentation up-to-date, but really the onus of maintaining the docs lies on the developer. 

> :bulb: Adding documentation as a measure of completeness of coding tasks is very helpful. 

## :computer: Easy to contribute
Add clear instructions on how to contribute to your project. This may include coding guidelines and standards, running test suites etc. 

## :mag: Easy to find
If working on "inner source" projects, make sure your project is searchable within your organization. Some companies use Confluence/Sharepoint to host docs, you may be able to keep a static landing page that may point to your project's homepage, which might be generated dynamically.
Top 7 Featured DEV Posts from the Past Week
Tags: top7
Published: 2021-11-09 21:39:45

---
title: Top 7 Featured DEV Posts from the Past Week
published: true
description: A round up of the most-read and most-loved contributions from the community this past week.
tags: icymi
cover_image: https://thepracticaldev.s3.amazonaws.com/i/sfwcvweirpf2qka2lg2b.png
---
_Every Tuesday we round up the previous week's top posts based on traffic, engagement, and a hint of editorial curation. The typical week starts on Monday and ends on Sunday, but don't worry, we take into account posts that are published later in the week._ 

## There is no cookie cutter approach

... and no shortcut to improve your programming skills says @jenniferfu0811. Great tips in this post!

{% link https://dev.to/jenniferfu0811/how-to-improve-your-programming-skills-as-developers-and-non-developers-38f2 %}

## Get out of your own way

"Although we are all unique, there are some evergreen items we can all work on in order to get to our desired destination in the most efficient manner" says @tatianacodes. These learnings from their conversations with aspiring developers are really fascinating. 

{% link https://dev.to/tatianacodes/i-spoke-to-a-handful-of-aspiring-devs-heres-what-i-found-dhc %}

## Improving our problem solving as developers

@unitybuddy calls programming a "beautiful art" — and has a handful of great ideas about how you can add to your programming problem solving "palette". 

{% link https://dev.to/unitybuddy/7-ways-to-improve-your-logic-in-programming-55io %}

## Developer Tools in Microsoft Edge

@codepo8 is a principal product manager for developer tools in Microsoft Edge and shared a talk version of this post back in September. Here's what they encountered while working on the tools, documenting them, and going through user feedback. 

{% link https://dev.to/codepo8/developer-tools-secrets-that-shouldnt-be-secrets-361g %}

## The most important C# phases up to version 10.

... according to @mteheran 😊 

{% link https://dev.to/mteheran/c-evolution-3o9o %}


## The unexpected blessing of software development and technical writing

Until the pandemic, @codergirl1991 was a professional classical musician who spent all of my time performing, recording and teaching. Now, they are a software developer and technical writer! Here's how they got here. 

{% link https://dev.to/codergirl1991/how-i-overcame-my-fear-of-technical-writing-and-landed-a-job-at-freecodecamp-37d6 %}

## Will a job always be a job?

That's the question @heshiebee addresses in this post. Spoiler (opinion): it's important to stay close to your core motivation as a developer, which is creation.

{% link https://dev.to/heshiebee/the-key-to-developer-happiness-and-how-to-prevent-coding-from-becoming-just-another-job-4m60 %}



_That's it for our weekly wrap up! Keep an eye on dev.to this week for daily content and discussions...and if you miss anything, we'll be sure to recap it next Tuesday!_
Bypassing CORS in few lines of code
Tags: javascript, node, programming, webdev
Published: 2021-11-09 21:30:21

CORS - we all have our times with it. There are a lot of times where I want to make requests in the browser but this shows up:
```
Access to fetch at 'https://google.com/?safe=active&ssui=on'
 (redirected from 'https://google.com/') from origin 
'https://github.com' has been blocked by CORS policy: No 
'Access-Control-Allow-Origin' header is present on the 
requested resource. If an opaque response serves your needs,
 set the request's mode to 'no-cors' to fetch the resource 
with CORS disabled.
```
That's when I was sick of it and wanted to make a CORS bypasser (with a neat REST API).

# How it works
It will work by:
- Using Express to create paths
- Making HTTP requests using Axios (In NodeJS, CORS is not a worry!)
- Sending the HTTP request made by Axios


# Setting up your project
First, run these commands to set up your project (if you're on Linux, or have [Wingubash] (https://github.com/Unzor/Wingubash) installed on a Windows machine.)
```
mkdir cors-bypass
cd cors-bypass
touch index.js
```
Once index.js has been created, we will install our dependencies.
```
npm install express express-all-allow axios
```
This will install our dependencies.
Now open up index.js in your terminal, and add all your dependencies like this:
```javascript
var express_all_allow = require('express-all-allow'); // Not needed unless you want any site to interact with your CORS bypass
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(express.json());
app.use(express_all_allow()); // Also not needed unless you want any site to interact with your CORS bypass
var axios = require('axios');
```
Now we will create our bypass. This is probably not the safest way to do it, but it would be better if you could use an array, which is impossible.

```javascript
function method(a){
  eval(`app.${a}('/${a}', async function(req, res){
  var response = await axios.${a}(req.query.url, req.body);
  res.send(response.data);
  })`);
};
```
This will create a method to use the HTTP request method.
Now add as many methods as you want, like this:

```javascript
method('get');

method('post');

method('put');

method('delete');
```

Once you are done creating the methods, add this to the end of the code:
```javascript
app.listen(8080, function(){
console.log('Listening at localhost::8080')
})
```
Now run `node index`, and run this code anywhere to make a GET request (replace &lt;your url here&gt; with any url):
```javascript
fetch('https://localhost:8080/get?url=<your url here>')
    .then(res => res.text())
    .then(data => {
console.log(data);
});
```
That's it! 
Source code is at https://github.com/Unzor/cors-bypass/.
How to add support for HEIC images with ImageMagick in PHP
Tags: php, webdev, heic, imagemagick
Published: 2021-11-09 21:18:01

Apple released a new image format called HEIC/HEIF, and it broke many apps that handle image processing. The PHP library [Intervention Image](http://image.intervention.io/) caught up to it and added support for the new image format, but somehow, it isn't working at the time of this writing. So we had to come up with a solution.

As a prerequisite, you'll need to have the [ImageMagick](https://imagemagick.org/) software installed with HEIC support on your server. See how to do that in [this awesome post](https://eplt.medium.com/5-minutes-to-install-imagemagick-with-heic-support-on-ubuntu-18-04-digitalocean-fe2d09dcef1).

We will be using neither the GD library nor Imagick for this, as we're not relying on PHP libraries at all. We're going a level deeper and going to execute ImageMagick shell scripts. Why? Because, somehow, even though the Intervention Image library says that it has support for HEIC image formats, it failed every time we tried it. This may be fixed on a later release, or, it might not even be a bug at all. Maybe it's us, the developers, who are doing something wrong. But anyway, if you're stuck with this too, bear with me.

We wanted to convert the HEIC images into JPG. That is because, we want to render them in a browser, so they have to be converted. No modern browser [supports HEIC images so far](https://caniuse.com/heif). We're using Intervention Image to process our images, so aside from other code related to validation, processing, etc., here's the trick:
{% gist https://gist.github.com/GeniJaho/dd1839fd10fd8651d1ec0a7f46f86e43 %}
Hacky, I know. It could use some refactoring, make the method a bit shorter, but the idea is there. By using the `magick` command you avoid using PHP libraries and go straight to ImageMagick. It may not be the most performant solution out there, but it works. It's alive and well and you can see it working on production on [OLM](https://openlittermap.com/). You can sign up and upload a HEIC image from your iPhone, it needs to be geotagged.
## What about extracting image data? (EXIF)
Yeah, you probably can't extract EXIF data from HEIC images at this time, but the conversion we did above does copy the image data. To our surprise, it works only if we're converting to JPG images. It didn't work with PNG, and we haven't tried with other formats. So once you have the converted image in PHP, just go with `$image->exif()` and you should be just fine.
> The code used for illustration is taken from the [OpenLitterMap](https://github.com/OpenLitterMap/openlittermap-web) project. They're doing a great job creating the world's most advanced open database on litter, brands & plastic pollution. The project is open-sourced and would love your contributions, both as users and developers.