teleren/devto huggingface dataset:
How to send emails with FastAPI
Tags: fastapi, email, python, nelsoncode
Published: 2023-01-18 16:09:57

In this example we will send an email through a POST type endpoint that will receive the information from the recipient

```bash
pip install fastapi uvicorn
```

```python
# main.py
from fastapi import FastAPI
from fastapi.exceptions import HTTPException
from pydantic import BaseModel
from smtplib import SMTP_SSL
from email.mime.text import MIMEText

app = FastAPI()

OWN_EMAIL = "hello@example.com"
OWN_EMAIL_PASSWORD = "your-password"

class EmailBody(BaseModel):
    to: str
    subject: str
    message: str

@app.post("/email")
async def send_email(body: EmailBody):
    try:
        msg = MIMEText(body.message, "html")
        msg['Subject'] = body.subject
        msg['From'] = f'Denolyrics <{OWN_EMAIL}>'
        msg['To'] = body.to

        port = 465  # For SSL

        # Connect to the email server
        server = SMTP_SSL("mail.privateemail.com", port)
        server.login(OWN_EMAIL, OWN_EMAIL_PASSWORD)

        # Send the email
        server.send_message(msg)
        server.quit()
        return {"message": "Email sent successfully"}

    except Exception as e:
        raise HTTPException(status_code=500, detail=e)
```
#### Run project
```bash
uvicorn main:app --reload --port 8000
```
Mix static & client-side rendering on same page with SvelteKit
Tags: jamstack, static, csr, sveltekit
Published: 2023-01-18 16:08:39

I love static websites, because they are very fast and very good for SEO, google can 'read' it much better. But these days you need JavaScript almost everywhere.

And I like Svelte as very easy to learn and use lightweight framework.

I've found out, that it's not very simple to mix static rendering and CSR on same page. But possible. I will use time (JavaScript Date() result) as example data, but in production it can be your data, e.g. "BFGoodrich tyre" or "Red apples" or "War and Peace by Leo Tolstoy".

Our example page will print very simple text:
```
Date: Wed, 18 Jan 2023 15:49:03 GMT
Build: Wed, 18 Jan 2023 15:49:01 GMT
```

First line (Date:) is content you calculated on client-side, when page is loaded. Second line (Build:) is build-time, something you calculated during `npm run build` which must be visible to search engine.

## Create project
```shell
npm create svelte@latest hybrid
cd hybrid
npm install
```

## Enable static adapter
Install it: `npm i -D @sveltejs/adapter-static`

In svelte.config.js disable adapter-auto and use adapter-static: 
```js
import adapter from '@sveltejs/adapter-static';
```

Now you can generate static website with `npm run build` and preview it with `npm run preview`.

## src/routes/+page.server.js
```js
export const prerender = true
export function load() {
	return {
		t: new Date().toUTCString()
	}
}
```

## src/routes/+page.svelte:
```js
<script>
    import { browser } from '$app/environment';
    
    export let data;
    var buildtime = data.t
</script>

Date: {#if browser}{new Date().toUTCString()}{/if}
<br>
Build: {buildtime}
```

## Result
run: `npm run build && npm run preview` and open http://localhost:4173/ you will see result. If you will reload page in a second, Date will change, but Build will stay same.

Also, if you will open build/index.html you will see there:
```html
...
Date: 
<br>
Build: Wed, 18 Jan 2023 15:58:18 GMT
...
```

As you see, our statically generated content is clearly visible in page. 

## Explanation
in `+page.server.js` we set `prerendering=true` to generate static HTML site (with JS) as a result. And we return data with current Date(). We must convert it to string here, because client browser may have different timezone and Build: date will be "flashing" (initially it will have date in our timezone, and in fraction of second it will be overwritten). Not nice.

in `+page.svelte` we use this data. Also we conditionally display new Date() (I used `.toUTCString()` here just to have both dates to look similar, it's not really needed). 

Without `{#if}` you'd get one date built-in HTML (displayed immediately when page loaded) and other date will overwrite it. Not nice visual effect. With `{#if}` we suppress first date and display only CSR date over empty page space.

Using this method you can combine benefits for static and client-side rendered content at any SvelteKit page.
How to find an SRI hash on jsdelivr
Tags: javascript, cdn, sri
Published: 2023-01-18 14:05:53

---
title: How to find an SRI hash on jsdelivr
published: true
description: A description of how to find the right integrity hash for a library being served via jsdelivr
tags: javascript, cdn, sri
# published_at: 2023-01-18 13:55 +0000
---
[Sub-resource integrity hashes](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) are something that make using content from public CDNs that little be more secure but the common ones don't make it easy to find out what the hash should be.

[jsdelivr](https://www.jsdelivr.com/) is used in the Bootstrap documentation but the quickstart unhelpfully doesn't include the SRI by default.

The simplest way to get the hash is to search for the package you're using via the search function on [the main site](https://www.jsdelivr.com/). You can then get an option to copy the SRI to your clipboard as one of the options from the Install box.

However you can also see the value in the jsdeliver API by taking the resource path and replacing the start with `https://data.jsdelivr.com/v1/package/` and removing the path. This will show the all the API information for the entire package including the hash (which is **SHA 256**). See the [Bootstrap entry](https://data.jsdelivr.com/v1/package/npm/bootstrap) as an example.
Exploring the Internet of Things
Published: 2023-01-18 15:52:39

The Internet of Things (IoT) is a network of physical objects that contain embedded technology to communicate, sense, or interact with their internal states or external environment. 



This network of connected devices is able to collect and exchange data using sensors, actuators, and other embedded technology. It has become a major focus in the world of technology and is projected to have a significant impact on the way we live and work.

IoT is the concept of connecting devices such as vehicles, home appliances, and other items embedded with electronics, software, sensors, actuators, and network connectivity that enable these objects to collect and exchange data. 


This data can be used to improve efficiency, reduce costs, and provide better customer experiences. IoT devices provide real-time information about the state of the world around us, allowing us to make better decisions.


The growth of the Internet of Things is being driven by the increasing availability of connected devices, the availability of low-cost sensors, and advances in technology such as artificial intelligence, machine learning, and cloud computing. 


As the technology advances, more connected devices are being developed and deployed in homes, businesses, and public spaces. This growth has been further accelerated by the introduction of new standards such as the Zigbee and Bluetooth Low Energy (BLE) protocols.


The potential of the Internet of Things is vast. It can be used to monitor and control the environment, optimize energy use, improve safety and security, reduce traffic congestion, and improve healthcare.


In addition, it can be used to improve customer service, optimize supply chains, increase efficiency, and provide predictive analytics. As these technologies become more widely adopted, they are expected to significantly reduce costs and improve the efficiency of businesses.


The Internet of Things has the potential to revolutionize the way we live, work, and interact with the world around us. It has the potential to improve the quality of life for people across the globe. As the technology continues to evolve and become more widely adopted, it is likely to become an essential part of our daily lives.

[Clicked to visit full article originally published on:-18/01/23](https://www.javaoneworld.com/2023/01/exploring-internet-of-things.html)
Dart ??= Operatörü
Tags: dart, flutter, mobile, app
Published: 2023-01-18 15:49:39

### ??= Operatörü:

 ??= Operatörü bir değişkene yalnızca o değişken null ise değer atamak için kullanılır.

Örneğin:

```
int? a; // = null
a ??= 3;
print(a); // <-- Prints 3.

a ??= 5;
print(a); // <-- Still prints 3.
```


https://dart.dev/codelabs/dart-cheatsheet
Add Github Eslint Checker Action
Tags: github
Published: 2023-01-18 15:45:19

Add `.github/workflows/eslint.yml` file

Add this content
```
name: Lint
on:
  push:
    branches:
      - '*'
  pull_request:
    branches:
      - master
  workflow_dispatch:
jobs:
  ESlinter_JS:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@master
      - uses: actions/setup-node@v3
        with:
          node-version: '16.14.1'
      - name: Install Dependencies
        run: npm install

      - name: Run ESLint
        run: npm run eslint
```
Tools: quickly connect to pods in your Kubernetes cluster
Tags: kubernetes, bash
Published: 2023-01-18 15:43:23

It seems that almost all companies use or try to use Kubernetes. And you, as a developer, need from time to time connect to your app, but when it is in a Kubernetes cluster, it is not so simple.
How it can look like in your case:

```bash
# switch to appropriate context 
kubectl ctx your-context
# get pods
kubectl -n namespace get pods
# connect to the pod
kubectl -n nameapce exec -it pod/#{pod-name-from-previous-step} -- bash 
```

Do it every time - tedious, isn't it?
In my team, we are using next script:

```bash
#!/bin/bash

# how make script executable

# chmod +x k8s.sh

# this is necessary to split the command output on new lines

IFS='

'

show_help () {

  echo "Usage: k8s.sh [environment] [SUBENV] - ssh to a pod from the environment-subenv"

  echo "Example: k8s.sh staging web - connect to the web pod in the staging environment"

  echo "It uses current directory in order to build the pod name"

}




if [ "$1" = "-h" ] || [ "$1" = "--help" ]; then

  show_help

  exit 1

fi




ENVIRONMENT=$1

SUBENV=$2




working_dir=${PWD##*/}

project=$(echo "$working_dir" | tr '[:upper:]' '[:lower:]' )

namespace="$project-$ENVIRONMENT"




kubectl ctx |  grep "$ENVIRONMENT" | tr -d '\n'  | xargs -0 kubectl ctx




output=$(kubectl -n "$namespace" get pods | grep "$SUBENV" | Head -n 1)

podname=${output%% *}; remainder="${remainder#* }"




echo "ssh-ing you into $podname . . ."




kubectl --namespace=${namespace} exec -it pod/${podname} -- bash
```
It allows easily connect to pods from a specific namespace (a namespace depends on current directory - current project).
Subenv is necessary because we have different types of pods (web, activejobs, migration).
Our Journey In The Open Source World
Tags: javascript, typescript, opensource, github
Published: 2023-01-18 15:30:00

[Follow us on Github!](https://github.com/JointlyTech)

### Yes, I know, I already made a series about it! But this is not MY journey, this is OUR journey!

At **Jointly** - the company I'm currently working at -, we're excited to announce that we're diving into the world of Open Source. As a company, we've always been committed to making a positive impact in the industry, and we believe that open source is the way to do it.

Open source software allows for collaboration and innovation on a global scale, and we're eager to be a part of that community. We're currently working on a few open source projects that we can't wait to share with you in the near future!

One of our goals with open source is to give back to the community that has given us so much. We want to contribute to the development of tools and technologies that will benefit not only our clients, but also other businesses and individuals in the industry.

We're also looking forward to learning from the open source community. By collaborating with others and contributing to existing projects, we'll be able to stay up to date on the latest developments and best practices in the industry.

We believe that open source is the future of software development, and we're excited to be a part of it. We can't wait to see what the future holds and to work with all the open source community.

Stay tuned for more updates on our open source projects and contributions!
#Rust 🦀 – 🧵 String Interpolation in Rust (as usual, super fun 😄)
Tags: englishpost, rust, string
Published: 2023-01-20 13:36:14

---
title: #Rust 🦀 – 🧵 String Interpolation in Rust (as usual, super fun 😄)
published: true
date: 2023-01-18 15:19:05 UTC
tags: EnglishPost,EnglishPost,Rust,String
canonical_url: 
---

Hi !

Working with string is always a nice topic to learn. It’s nice to understand how a specific language process strings, sometimes small changes can have big performance improvements !

## String Interpolation

So let’s start (via Wikipedia) with some basic concepts.

> In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values. It is a form of simple template processing[1] or, in formal terms, a form of quasi-quotation (or logic substitution interpretation). The placeholder may be a variable name, or in some languages an arbitrary expression, in either case evaluated in the current context.
> 
> String interpolation is an alternative to building string via concatenation, which requires repeated quoting and unquoting;[2] or substituting into a printf format string, where the variable is far from where it is used. Compare:
> 
> <cite><a href="https://en.wikipedia.org/wiki/String_interpolation#:~:text=Rust%20provides%20string%20interpolation%20via%20the%20std%3A%3Afmt%20module%2C,compile-time%2C%20whereby%20each%20argument%20interacts%20with%20a%20formatter." target="_blank" rel="noreferrer noopener">String Interpolation – Wikipedia</a></cite>

```

apples = 4
print("I have ${apples} apples.") # string interpolation
print("I have " + apples + " apples.") # string concatenation
print("I have %s apples.", apples) # format string

```

## String Interpolation in Rust

Rust does not have general string interpolation, but provides similar functionality via macros. Rust provides formatting via the std::fmt module, which is interfaced with through various macros such as format!, write!, and print!.

The hello world example may look like this one:

![running the code
fn main() {
    println!("Hello {}!", "world");
}
output 
Hello world!](https://brunocapuano.files.wordpress.com/2023/01/image-25.png?w=771)

These macros are converted into Rust source code at compile-time, whereby each argument interacts with a formatter. The formatter supports positional parameters, named parameters, argument types, defining various formatting traits, and capturing identifiers from the environment.

We can also work with implicit named arguments. I like this option, the code is easier to read.

{% gist https://gist.github.com/elbruno/66be2b431a6b3add6e685dcb3f4e9c93 %}

At this moment, I think I’ll read more about the way Rust works with Strings. Mostly in the official [Rust Documentation for Strings](https://doc.rust-lang.org/std/string/).

Happy coding!

Greetings

El Bruno

More posts in my blog [ElBruno.com](https://www.elbruno.com).

* * *
0 conversion from Product Hunt, what's next?
Tags: gpt3, openai, laravel, sql
Published: 2023-01-18 15:17:18

Yesterday, I launched my new product, [Database Sensei](https://dbsensei.com), on Product Hunt, but it didn't go as well as I had hoped.

At first, I didn't make it to the homepage, despite having more upvotes and activity than other products.
But after reaching out to the moderators and a few hours later, I were featured on the homepage. Unfortunately, the initial burst of likes had already passed.

The aftermath is not too encouraging. I did receive feedback and more traffic than usual, but I had no conversions, meaning no one signed up for the free trial.

I've now changed to a no-card-upfront trial, so we'll see if that brings in more users.

**Where did you find your first users?**
Infrastructure as code - (When You Don't Know What The Heck Is It) Part 1
Tags: infrastructureascode, devops, cloudcomputing, provisioning
Published: 2023-01-18 15:15:53

OPENING ACT-
Ever wonder what is Infrastructure-As-Code? Let's jump right into it without further ado. 

Infrastructure as code (IAC) manages and provides IT infrastructure through code rather than manual configuration. This approach allows for the versioning, testing, and collaboration of infrastructure and the automation of provisioning and management tasks.

IAC typically uses code written in a high-level programming language to describe the desired state of infrastructure. This code is then executed by a tool that provisions the necessary resources and configures them according to the code. Some popular tools for IAC include Terraform, Ansible, and Puppet.

IAC enables teams to manage their infrastructure in a consistent and repeatable way, making it easier to scale and maintain. It can also help to reduce the risk of human errors.

**Where its going to hurt when you start with IAS**
While infrastructure as code (IAC) has many benefits, there are also some potential shortcomings. And it begins with adding **Complexity** to the infrastructure management process, especially for teams that are new to the concept. This complexity can make it difficult for team members to understand and troubleshoot issues.

There is a learning curve associated with it because teams must become proficient in the tools and languages used for IAC. It can be a significant barrier for teams that are new to the concept. IAC scripts are also not always easy to read or understand, making it difficult to understand how the infrastructure is configured and how changes may impact it. And the parameter of the complexity extends further with this.

Some IAC tools may only be able to handle some types of infrastructure or configurations. It can limit the flexibility of the infrastructure and make it difficult to adapt to changing requirements. When talking about configurations, IAC scripts may depend on specific versions of software or libraries, which could cause problems if those dependencies change in the future.

Although if you are aware of the above points and feel that your team can Infrastructure as code (IAC), stay tuned for [Part 2](https://dev.to/akshatkumar/infrastructure-as-code-when-you-dont-know-what-the-heck-is-it-part-2-41mg).
There are many benefits to using open-source software. Some of the main advantages include:
Tags: programming, opensource
Published: 2023-01-18 15:12:01

**Cost**: Open-source software is typically free to use, which can save organizations and individuals a significant amount of money.

**Customization**: The open nature of the source code allows developers to modify the software to suit their specific needs.

**Collaboration**: The open-source community allows developers to collaborate and share their knowledge, leading to more rapid development and innovation.

**Transparency**: With open-source, the code is open for anyone to see, which increases transparency and allows for more security.

**Accessibility**: Open-source software is typically more widely available and accessible to a larger number of people, including those in developing countries.

Open-source software is used by many organizations and individuals, from small businesses to large enterprises and governments. Some examples of popular open-source software include Linux, Apache, Firefox, and WordPress.

Open-source software is often developed, supported and maintained by a community of developers, which can make the software more reliable, and with the right community, can offer better support than proprietary software.
Paracetamol.js💊| #199: Explica este código JavaScript
Tags: javascript, webdev, programming, spanish
Published: 2023-01-18 15:00:00

## **<center>Explica este código JavaScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark></center>

```js
const miArreglo = [1, 2, 3, 4, 5];
console.log(miArreglo["2"] === miArreglo["02"])
```

A. `true`
B. `false`
C. `RefereceError`
D. `SyntaxError`

Respuesta en el primer comentario.

---

Respuesta:
B. `false`

Para acceder a las posiciones de un arreglo usamos la notación de corchetes (esto todos lo saben).
Quiza lo que no se sepa es que JavaScript internamente convierte los índices (que deben ser enteros positivos) en strings, esto con la finalidad de que su manipulación sea similar a como accedemos a las keys de un objeto.
Si hicieramos:

```js
console.log(miArreglo[2] === miArreglo[02]) //true
```
Nos da true por que los valores de los corchetes se evaluan.
Pero cuando los tratamos como strings claramente `'2'` es diferente que `'02'`y alli da `false`.

Esto lo hace JavaScript de manera interna, por eso se recomienda usar los índices como enteros positivos y dejar que el lenguaje los manipule por dentro.
Want to improve your code?
Tags: improve, goodcode, programming, beginners
Published: 2023-01-18 14:51:34

**This article I published originally** [**here**](https://medium.com/@pradeepradyumna/want-to-improve-your-code-b20064ea6a4b)

If you are a programmer and write lots a lot of code then it always important to keep a few things in mind like how you want to proceed. But also it is important to set the mentality right if you have intentions for improving your approaches. Here are some tips I believe which helped me a lot in writing and improving my code over the years.

**PATIENCE, INTEREST**
You always have to be patient and trust your gut. Always assume that your code will break. No matter how experienced you are. Just keep calm.

**PRACTICE**
Once you’re able to fix a problem, practice the habit of going through the solution once again. It brings confidence.

**TIME**
You cannot be the best overnight. It takes time and interest. And you need to make an effort for it.

**OBSERVE**
Always observe your code. Once you have written a logic/ code, just compare it with others. Get it reviewed by your peers and get their opinion. And see how better could it be. 

**MOTIVATED, POSITIVE**
Be motivated and if you do not, go get motivation when you want to do something good. Unless you are not, then you cannot improve your code.

**BREAK, BREATHE**
If you’ve spent hours writing a program and trying to clean it up the same time or breaking your head, probably it’s a bad idea. Go take a break. Breathe.  

End of the day, it’s the happiness and sense of satisfaction you get once you see your work. 


So what do you think? Let me know in the comments
O que um documento de projeto de software normalmente inclui?
Published: 2023-01-18 14:36:10

**Visão geral do projeto:** um resumo dos objetivos, escopo e entregas do projeto.

**Requisitos:** Uma descrição detalhada dos requisitos funcionais e não funcionais do software.

**Design:** Uma explicação do design geral do software, incluindo arquitetura do sistema, interface do usuário e design do banco de dados.

**Implementação:** Uma descrição das linguagens de programação, ferramentas e estruturas que serão usadas para implementar o software.

**Teste:** Um plano para testar o software, incluindo testes de unidade, testes de integração e testes de aceitação do usuário.

**Implantação:** Uma descrição do processo de implantação do software para produção, incluindo qualquer infraestrutura e operações necessárias.

**Manutenção:** Um plano para manter e atualizar o software após sua implantação.

**Orçamento e cronograma:** uma estimativa do tempo e dinheiro necessários para concluir o projeto.

**Gerenciamento de riscos:** Um plano para identificar e mitigar os riscos que podem surgir durante o projeto.

**Comunicação e colaboração:** um plano de como a equipe se comunicará e colaborará ao longo do projeto.