teleren/devto huggingface dataset:
AWS Redshift connects with Python Part 2 — Python code to connect AWS Redshift
Published: 2022-07-05 12:55:22


## AWS Redshift connects with Python Part 2 — Python code to connect AWS Redshift

In the Part 1 session, we set up the AWS Redshift account to connect to the outer world.

In this session, I will demonstrate some of the code that will be set up and connected to a python world to AWS Redshift.

And my main goal is to upload a pandas DataFrame in AWS Redshift.

Before going to the coding part let's bump into the Query Editor V2.

First logged in AWS Redshift Session or we can go to Redshift Dashboard.

After visiting the Dashboard page we will see the list of clusters on the CLuster Overview Session.

![](https://cdn-images-1.medium.com/max/2622/1*XCMN7ccEgUPpQwZ8mKaMQA.jpeg)

Now we see that I have 2 clusters created one is active which is “Available” and another one is inactive which is “Paused”. I am going to use redshift-cluster-3.

I will also show you how to activate or we can say how to make redshift-cluster-2 Available.

Click “redshift-cluster-2” name or your cluster name, and it will redirect to the cluster page, click on “Action”, and it will show a drop-down menu.

Inside the menu, you will see “Resume”, please click on that. After clicking it takes some more minutes to activate the cluster. So, you will see the status of the cluster on the AWS Redshift cluster dashboard and the message will be Resume Modifying and after some, it will become Available.

![](https://cdn-images-1.medium.com/max/2374/1*4eXTPWnRM1-TkEK3adz4MA.jpeg)

Once our cluster is “Available”, now, let's start working with python code.

We are going to install a redshift connector by running the command given below.
>  pip install redshift-connector

For connecting AWS Redshift via python we require certain credentials like Hostname, Database Name, Port Number, User and Password.

If we are inside our cluster side, we go to Properties, we will see the credentials we are looking for.

![](https://cdn-images-1.medium.com/max/2676/1*Ct0_du7js8O3DiZRLnvPbg.jpeg)

Now we are going to run the query in python to create a table on Redshift.

Before that let's create a sample DataFrames
{% gist https://gist.github.com/shoeb370/6593811f0719ec1bc8a94cbf88d0ef73.js %}
Now we are going to create a table inside the AWS Redshift cluster.
{% gist https://gist.github.com/shoeb370/11585f643c427e563d70439a21336800.js %}
We will see the table is created.

![](https://cdn-images-1.medium.com/max/2000/1*KOmoATIo4hi2-NpUjtlg9Q.jpeg)

Now we are going to insert DataFrame inside the table.
{% gist https://gist.github.com/shoeb370/142a4d00be403a2e3bcba37bf5902c41.js %}
Now in the query editor, we will see that our table is created and filled with data inside the table.

![](https://cdn-images-1.medium.com/max/2000/1*2bQjBXdJJCsygP-_85NMNQ.png)

This whole sample demonstrates how we can create an AWS Redshift cluster and how can I insert pandas DataFrames.

We can upload n number of Data inside DataFrame in Redshift cluster.
How to show images of the model in Django Admin?
Tags: django, webdev, programming, python
Published: 2022-07-05 12:51:47

In this tutorial you will learn how to show image of a django model in the django's admin site.

Suppose we have a model of image in our django website.
``` python
# models.py
class Image(models.Model):
    name = models.CharField(max_length=250)
    image = models.ImageField(upload_to='images/')

    def __str__(self):
        return self.name
```
And we want that the both fields of the model Image should be shown in our website's admin site.

But if we directly say django admin to show the image in the admin by list_display in admin.py it gives us the url of the image , it does not show the image there.
```python
# admin.py
from django.contrib import admin
from .models import Image
class ImageAdmin(admin.ModelAdmin):
    list_display = ['name', 'image',]

admin.site.register(Image, ImageAdmin)
```

![not showing image only url](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/80ax5bmr6snq4jz9lz1m.png)

So this is not a good approach to do that so we have a quick fix to solve this problem.

```python
# admin.py
from django.utils.html import format_html

class ImageAdmin(admin.ModelAdmin):

    def image_tag(self, obj):
        return format_html('<img src="{}" style="max-width:200px; max-height:200px"/>'.format(obj.image.url))

    list_display = ['name','image_tag',]

admin.site.register(Image, ImageAdmin)
```

![Showing Images also](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oveoe1pqlhyslxnwl8ij.png)

You must check if the static and media settings are included in our project/urls.py (main urls file) or not.

```python
# project/urls.py
from django.conf import settings 
from django.conf.urls.static import static
from django.urls import path,
urlpatterns = [
    ...
    '''your urlpatterns'''
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```
that's done.

Thank you for reading my post!
How to render data from multiple models using a serializer
Tags: rails, beginners
Published: 2022-07-05 12:47:13

If you've already learned how to relate models in rails using macro associations like: 
`belong_to`
`has_many` 
 or 
`has_many, through: `

You may be wondering how these relationships manifest themselves when you actually pull data from your models. The answer is: they don't. That is, unless you use a serializer with your model. 

A serializer is a separate file that kind of acts like a filter to its model. It determines what attributes from the model's records will be rendered or not rendered. 

So, for example, we could have a model whose records have 100 attributes, but in a specific fetch request, we only want to render 3 of them. We would program that using a serializer.

To create a serializer file, use the command: 
`$ rails g serializer Model_name`

By default, the serializer will be linked to the model that shares its name. 

Once the serializer is created, enter the file Model_name_serializer.rb and add the macro associations you want to use when rendering data.

`class ModelNameSerializer
has_many :other_models
end`

Now, when you pull a record from "Model_Name," it will not only render that specific record, but also the nested records of "Other_model" that belong to it. 

This can be useful if you want to use data from various related models in a single fetch statement.
Deserialization exploits in Java: why should I care?
Published: 2022-07-05 12:27:46

Hackers refer to deserialization in Java as “the gift that keeps on giving”. But what is actually the problem? In most cases, it is not even your own code that creates this security vulnerability. This problem is also not restricted to Java’s custom serialization framework. When deserializing JSON, XML, or YAML, similar issues can occur as well. 

I recently gave a talk about this during [Devoxx UK](https://www.devoxx.co.uk/), the largest and most prestigious Java community conference in the United Kingdom. In this talk, I explain how deserialization vulnerabilities work natively in Java and how attack chains are created. This was loosely based on my blog post: [“Serialization and deserialization in Java: explaining the Java deserialize vulnerability”](https://www.devoxx.co.uk/)

Of course, the recent Log4j security problems with the [Log4Shell vulnerability](https://snyk.io/blog/log4j-rce-log4shell-vulnerability-cve-2021-44228/) is part of this as well. I explained how Log4shell can be a kick-off point for a deserialization gadget chain where the sink gadget performs an arbitrary code execution. 

But also with types of deserialization like JSON, XML, and YAML you get into trouble. I already briefly explained it in the blog post ["Java JSON deserialization problems with the Jackson ObjectMapper"](https://snyk.io/blog/java-json-deserialization-problems-jackson-objectmapper/), but in this talk, I will dig in a bit deeper and demo the actual consequences.

The most important part is of course how to avoid these issues in your own application. This talk shows some great pointers on how to mitigate these problems in your own applications, this also includes [the new features in Java 17 like JEP 415](https://snyk.io/blog/new-java-17-features-for-improved-security-and-serialization/). I honestly believe that this session gives a better understanding of the problem space and be able to take action in your code to prevent it.

{% embed https://www.youtube.com/watch?v=zHZv2L9hDis %}
Fixing the Spring Boot LiveReload Server with Gradle for Thymeleaf and TailwindCSS
Tags: tailwindcss, gradle, springboot, webdev
Published: 2022-07-05 12:25:28


## LiveReloading with Thymeleaf

I couldn't get Live Reload with Spring Boot and Thymeleaf to work. The problem seems to be so widespread that even [@wimdeblauwe](https://twitter.com/wimdeblauwe) the author of Taming Thymeleaf uses gulp/npm to get Live Reloading working.

I thought why do we need to use Javascript to get our Spring Boot Developer Experience up to par with the big Javascript Frameworks? We have a perfectly fine Build Tool with Gradle!

### LiveReload.js

First we need to include a script tag which points to the LiveReload Server:

```html
<script src="http://localhost:35729/livereload.js"></script>
```
### Gradle Sync

The plan is the same as with the npm scripts. Sync the templates into the build output so LiveReload triggers properly. This is done with the Gradle Sync Task:


```kotlin
// build.gradle.kts
tasks.register("sync"){
	inputs.files("./src/main/resources/static","./src/main/resources/templates",)
	doLast {
		sync {
			from("./src/main/resources/static")
			into("build/resources/main/static")
		}
		sync {
			from("./src/main/resources/templates")
			into("build/resources/main/templates")
		}
	}
}
```

Now start a continuous build with:

```
.\gradlew -t sync
```

Each time one of the inputs.files directory changes the sync task is rerun and LiveReload works.

## Tailwind CSS

To use [TailwindCSS](https://tailwindcss.com/) we use the node-gradle plugin and create a npx task:
```kotlin
// build.gradle.kts
plugins {
    ...
    id("com.github.node-gradle.node") version "3.4.0"
}

tasks.register<com.github.gradle.node.npm.task.NpxTask>("tailwind"){
    command.set("tailwindcss")
    args.set(listOf("-i", "./src/main/resources/static/styles.css",  
        "-o" ,"./src/main/resources/static/output.css", "--watch"))
}
```

We then need to create a package.json:

```json
{
  "devDependencies": {
    "@tailwindcss/forms": "^0.5.2",
    "tailwindcss": "^3.1.4"
  }
}

```

Add a tailwind.config.js:

```javascript
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{html,js}"],
}

```

Add a styles.css in resources/static/:
```css
@tailwind base;
@tailwind components;
@tailwind utilities;
```
and include output.css in our html:
 
```html
<link href="/output.css" rel="stylesheet">
```

Now we can start the tailwind npx task in a new terminal:

```
.\gradlew tailwind
```

And it works:

<video style="width: 100%" controls>
  <source src="https://i.imgur.com/YVudYpn.mp4" type="video/mp4">
</video>

You can see an example at: [github.com/tschuehly/thymeleaf-livereload-gradle](https://github.com/tschuehly/thymeleaf-livereload-gradle)
Baby steps
Tags: javascript
Published: 2022-07-05 12:24:00

So, in my quest to switch from LAMP to PERN, I'm going to update my old MySQL DB manager and turn it into a modern Postgres DB manager. This time, I'm going to use modern authentication techniques rather than my old basic HTTP authentication.

So, how do we do this? The [Passport](https://www.passportjs.org/) library seems to be the most popular. Great, let's use that. Passport uses sessions. Which library should I use? The Express team maintains [express-session](http://expressjs.com/en/resources/middleware/session.html) and [cookie-session](http://expressjs.com/en/resources/middleware/cookie-session.html). Cookie-session looks simpler. Let's use that. Nope. [It's not compatible with Passport currently](https://github.com/jaredhanson/passport/issues/904).

Fine, we'll use express-session. express-session creates a session id and stores it in a cookie. How do I manipulate cookies in JS? I have to use something called encodeURIComponent. I've never used it. How does it differ from encodeURI? Time to do some research.

OK. I've updated my [encodeURI demo](https://sean.brunnock.com/Javascript/Core/encodeURI.html) so it now includes examples of encodeURIComponent and decodeURIComponent. That'll do for today.

Baby steps.
Banco de dados AWS
Tags: aws, devops
Published: 2022-07-05 12:12:45

Este artigo pretende ser mais um da série de resumos para aqueles que pensam em fazer o exame de AWS Certified Cloud Practitioner. Mais informações encontram-se ao fim do artigo. O assunto desse artigo é banco de dados no AWS.

A principio deve ser dito que o uso de banco de dados depende da sua necessidade. Existem diversos serviços que podem ser utilizados. Caso seja apenas um lugar para realizar o deploy do seu database, um serviço EC2 resolveria, para se ter completo controle.
Mas caso queira um PaaS para operar e ter controle de um banco de dados, mas não quer se preocupar com sua infraestrutura, o RDS seria a sua opção. 

Uma última opção seriam os SaaS para ter o mínimo de manutenção,  como DynamoDB, Elasticache ou Redshift.

## RDS
* Opere e escale um banco de dados relacional na Nuvem AWS
* Automatize tarefas administrativas demoradas
* Armazene e transmita dados de forma segura
* Suporta deployment entre multiplas zonas disponíveis
* Bancos disponíveis:
  * MySQL
  * PostgresSQL
  * MariaDB
  * Oracle Database
  * SQL Server
  * Amazon Aurora 


## DynamoDB
* Não-relacional
* Saas, o que quer dizer que está pronto para uso, sem necessidade de nenhuma manutenção ou preparo de infraestrutura ou da camada do banco de dados.
* Fornece as opções de chave-valor ou banco de documentos
* Baixa latência
* Suporta scaling automatizado baseado na configuração

## Amazon Aurora
* Banco de dados relacional compatível com PostgreSQL e MySQL

## Elasticache
* Armazena dados de cache
* Baixa latência
* Suporta Memcached e Redis

## Redshift
Serviço escalável  de Data warehouse que usa SQL para analisar dados estruturados e semiestruturados em data warehouses, bancos de dados operacionais e data lakes, usando hardware e machine learning projetados pela AWS para oferecer a melhor performance de preço em qualquer escala.

## AWS Database Migration Service
* Serviço para realizar a migração dos dados locais para a nuvem
* Suporta migração contínua ou única de dados
BASIC CONCEPT OF JAVA.
Tags: beginners, productivity, programming
Published: 2022-07-05 12:05:55

Java is a high-level programming language originally developed by Sun Microsystem and released in 1995.Java is an Object-Oriented Programming(OOP) structure. Java is a 0 index based language. To be exact, java is a case-sensitive language.

## Types of data types in java.

>> <u>Primitive Data Type</u> = build-in data types that are predefined.
examples-
//byte =1 [range from -128 to 127]
//short =2
//int =4 [1,2,3]
//long =8
//float =4 [1.2,1.6,5.9]
//double =8
//char =2
//boolean =1

##** notes= double is used to store larger  values.
          Boolean has two two possible values either 
          true or false.

>><u>Non-Primitive Data Type</u> = Data types that are not pre-defined and are created by programmers. 
example-
//String
//concatenate
//charAt
//Replace
//Substring
CallBack Functions in JavaScript
Tags: webdev, javascript, beginners, programming
Published: 2022-07-05 11:37:20

**Callback Functions**:let me explain to you in simple words .We call the second function through first function which takes second function as argument in 1st .

function printFirstName(firstname,cb)
{
    console.log(firstname);
    cb("Verma");
}

function printLastName(lastname)
{
    console.log(lastname);
}

printFirstName("pushan",printLastName);


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dj3dlmt4nijnmx59o0ye.png)
How to get more users on my website?
Published: 2022-07-05 11:37:19

 I know it's hard to get the first 2000 daily users on your website, but it's not that hard. 

## How to get more users on my website?
Here's how I did it...

### Never stop publishing
Publishing new content continuously is very essential. If you have a web app, keep adding news feature pages and tools to it. The more you publish, the higher the chance to get more users on the traffic.

If your website has a lot of promising features or content, why won't a user use it? So, keep publishing.

### Keep promoting
Platforms like LinkedIn Groups or Facebook groups can be quite nice to get new users on the website. The more you promote your website the higher the chances of getting new users.

### Do keyword research and reposting
Doing keyword research is still extremely essential. Research for the things that users search a lot related to your site's niche, and write an SEO-optimized article on it. And post it.

After posting it on your main platform, now what you have to do is reposting. Reposting simply means posting the same content on other platforms with little word tweaking.
You can repost your content in [MyBlog](https://webmatrices.com/t/my-blog), dev.to and medium.com.

## Things special in 2022
There is one main thing that'll help you to gain more users in 2022. So, here's how you can do it...

### Web [... know about that special thing](https://webmatrices.com/d/1272-how-to-get-more-users-on-my-website)
The new special thing to get traffic is being highly promoted by Google, so I really suggest you to apply it.


> _[This post](https://webmatrices.com/d/1272) was originally posted on webmatrices community._

Thanks for being with be.
MS is EOLing Azure Functions which use .NET Core 3.1 on December 3
Tags: dotnet, azure, dotnetcore
Published: 2022-07-05 11:36:52

Earlier this month, Microsoft sent out an email stating that "**On 3 December 2022, .NET Core 3.1 will be retired. As a result, Azure Functions runtime versions 2.x and 3.x, which use .NET Core 3.1, will also be retired on that date.**"  They went on to encourage folks to update their Functions applications to use runtime version 4.x before then.  My intention is to use this article to explore the differences between .NET Core 3.1 and more modern versions and ultimately figure out what changes you might need to make to your code.

Microsoft is infamous for supporting dependencies for a frighteningly long time.  If we look back at the **_breaking_** changes between .NET Core 3.0 and 3.1, the biggest change was to how [SameSite cookies](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite) (something supported since .NET Core 2.0) are handled.  There was a change to the standards that meant that if the SameSite attribute is not specified, the cooke would default to `SameSite=Lax`.  Previously, the default was that cookies were sent for all requests.  With `SameSite=Lax`, cookies are not sent on normal cross-site subrequests.  In .NET Core 3.1, it changed the behavior for `SameSiteMode.None` and added a new `SameSiteMode.Unspecified` value to deal with this change.

So, what version do you move to next?

[![.NET and .NET Core release lifecycle](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kg1n08u87h4qsb8795uh.png)](https://dotnet.microsoft.com/en-us/platform/support/policy/dotnet-core)

3.1 was the old LTS (Long Term Support) version.  With 5.0 going out of support on May 5th and 7.0 still being only a release candidate, your only remaining option seems to be the new LTS version (6.0.6).  Version 6 goes out of support on November 12, 2024.  Since .NET 6 isn't .Net _**Core**_ 6, the upgrade path looks a little complicated, though.  My suggestion would be to check out **[Migrate from ASP.NET Core 3.1 to 6.0](https://docs.microsoft.com/en-us/aspnet/core/migration/31-to-60?view=aspnetcore-6.0&tabs=visual-studio-mac)** on the microsoft site.

Have any any additional advice for folks dealing with this upgrade?  Have a question?  Please feel free to drop a comment, below.  I'm not normally a ".NET Guy", so I'm learning this stuff as I go too. :)
[RESOLVED] What's wrong Forem/DEV? #2
Published: 2022-07-05 11:25:52

## There's a problem... 🤔
This comes with the newly released Forem app for android which I am currently using. When the link goes too far out, the whole content moves to the left... 
<br>
### It's fine though
as it does not affect the quality of the app usage. Just something for the Forem team to work on if they are free... or maybe the app might crash after fixing the feature, so, just wanna point this out.
<br>
### Screenshot

![problem](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d7sbnxze7pejzcxl1n0g.jpg)
for Loop,while loop ,do-while loop,forEach Loop and forin loop
Tags: webdev, javascript, beginners, programming
Published: 2022-07-05 11:15:01

**for loop**

console.log("for loop");

for(let i=0;i<10;i++)
{
    console.log(i);
}

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

let i=0;
while(i<10)
{
    console.log(i);
    i++;
}
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iuqq1qa8p8xymcvqvzl5.png)
 
**do-while loop**

let i=0;
do
{
console.log(i);
i++;
}while(i<10)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xv3l6sx06mdrb0r4844a.png)
 
**forEach Loop** 
_(used for iterate every value , it is a type of syntactic sugar , to write in a better way)_

let arr2=[10,20,30,40];

arr2.forEach(function(element){
    console.log(element);
})
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cu00gs1d5oqg42yypi0e.png)
 

**forIn loop**
_(it is only used to iterate or display content present inside the object)_

for(let key in obj)
{
    // console.log(key);
    // console.log(obj[key]);
    console.log(`The ${key} of the person is ${obj[key]}`);
}
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k0s34bxo2lqr8gocek6y.png)
Shortcode in WordPress
Tags: wordpress, webdev
Published: 2022-07-05 11:14:18

Have you ever wanted to make a shortcode in WordPress? I will show you how to make it without plugin!

First we need to open functions.php file. This file is located in our theme directory. Paste there this code:

{% gist https://gist.github.com/texe/d5919cfb550d34127c59d4146927ee7a %}

Then on any page or post you can display message from this shortcode by writing this:

`[my_heading]`

The best method in WordPress is using the dedicated type of block: shortcode.

If you want you can use any HTML formatting in your shortcode, eg.:

```
function my_shortcode() {
    $message = '<h1 style="font-size:60px; font-weight: bold;">My big HEADING</h1>';
    return $message;
}
add_shortcode('my_heading', 'my_shortcode');
```

As you see in the second line, I used here CSS formatting.

Link to original article [Shortcode in WordPress](https://madlon.eu/blog/shortcode-in-wordpress/).