teleren/devto huggingface dataset:
100 Days of Code: Day 10
Tags: 100daysofcode, python
Published: 2023-01-27 23:13:20

Day 10 of Angela Yu's Python bootcamp was about functions with outputs (using the return statement to exit a function and to return a value). 

The main goal of today's project was to build a calculator that lets the user calculate two numbers by adding, subtracting, multiplying or dividing and then asking them if they want to continue calculating or start a new calculation. Here is the Python code:

```
import os
from art import logo


def cls():  # Cross-platform clear screen
    os.system('cls' if os.name == 'nt' else 'clear')


# Add
def add(n1, n2):
    return n1 + n2


# Subtract
def subtract(n1, n2):
    return n1 - n2


# Multiply
def multiply(n1, n2):
    return n1 * n2


# Divide
def divide(n1, n2):
    return n1 / n2


def calculator():
    print(logo)


operations = {
    "+": add,
    "-": subtract,
    "*": multiply,
    "/": divide
}

first_number = float(input("What's the first number? "))
second_number = float(input("What's the second number? "))
for sign in operations:
    print(sign)
    should_continue = True

while should_continue:
    operation_sign = input("Pick an operation from the line above: ")
    calculation_function = operations[operation_sign]
    answer = calculation_function(first_number, second_number)
    print(f"{first_number} {operation_sign} {second_number} = {answer}")
    if input("Type 'y' to continue calculating with {answer} or type 'n' to start a new calculation: ") == "y":
        first_number = answer
    else:
        should_continue = False
        cls()
        calculator()

calculator()
```
I will continue with Day 11 tomorrow.
Para não 'flopar' como dev...
Tags: skills, dev
Published: 2023-01-27 22:55:26

Para quem está se aventurando a iniciar nas carreiras de tecnologia como eu, seja no início da vida profissional ou para profissionais experientes que estão migrando de área, gostaria de sugerir a leitura do artigo de [André Menezes (https://devmenezes.dev)](https://demenezes.dev/posts/o-pior-front-end-da-empresa/), _Como ser o pior front-end da empresa e estragar a sua carreira_.

É quase um mantra nas mentorias da área tech que os talentos das organizações são recrutados pelas suas habilidades técnicas e são dispensados pela falta ou baixo desenvolvimento de suas _softskills_.

Para que façamos uma autoavaliação o autor propõe que pensemos nos comportamentos que falseiam a nossa percepção de progresso na carreira, mas que causam grandes impactos às culturas de trabalho que têm como valores a colaboração, diversidade, inovação e as pessoas como centro das ações.

Será que vocês leitores se identificam com algum desses comportamentos?

1. Nunca estudar fundamentos, porque acredita que a prática vale mais que a teoria.

2. Estudar apenas linguagens e tecnologias que no momento dão maior retorno financeiro e ignorar o ecossistema da _stack_ de atuação.

3. Não compartilhar conhecimento, porque pensa que é perda de tempo ensinar de graça o que levou tempo e dinheiro para aprender na faculdade ou em cursos de formação.

4. Pedir a solução pronta para um problema, de preferência pedir uma explicação por videochamada para implementar o código.

5. Nunca usar o git para gerenciar os projetos, preferir compactar pastas e enviar por e-mail ou FTP.

6. Nunca pedir um _code review_, e não seguir a orientação do time de desenvolvimento para a nomenclatura das _branches_ como master ou main e muio menos respeitar um _git flow_ estruturado como _develop_, _feature_ ou _release_.

7. Nunca usar _libs_ externas, sempre gastar mais tempo e escrever o código todo sozinho, ignorando a experiência do tme e da comunidade.

8. Abolir a prática da refatoração de código, terminou de escrever, rodou, segue para o próximo projeto.

Caso tenha se identificado com algumas dessas situações, compartilhe conosco e como você fez ou pensa fazer para superar esses hábitos e agir de forma mais assertiva.
Day 683 : FTP
Tags: hiphop, code, coding, lifelongdev
Published: 2023-01-27 22:28:31

_liner notes_:
- Professional : Pretty chill day. Met with my team and went through some repos to clean up. Responded to a question in our community channel. Replied to some folks that have been testing out some Web Components to get their feedback. Basically a lot of reading code and replying to folks.

- Personal : So, I made some headway into my new side project late last night. I realized that the token to authorize a user is not the same I would need to do certain things in system, which makes sense, but I wish I knew that before banging my head against this wall for like 2 days. haha Also went through some tracks for the radio show.

![In a lush green valley with mountainous sides that are partly covered in clouds under a blue sky in Yanacachi, Bolivia](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8h9ln4kjt8edefci30fp.jpg)

Going to go through a couple of more tracks and then put together the radio show. I want to play around with my side project and see how far I can get. I'm learning quite a bit about this platform I only used like once before on a shallow level. I'm really diving in now and seeing what's possible. The whole thing this time is will it be easy for a person to replicate it. So, there's supposed to be a video released later of yet another example of police brutality...FTP! Be safe out there.

Have a great night and weekend!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube YI6ckchsuU0 %}
🍃 How Long Your Phone Will Be Supported by the Manufacturer 📅
Tags: opensource, greenit, ios, android
Published: 2023-01-27 22:27:23

## 🌏 Intro

Recently I had the opportunity to participate to [La Fresque du Numérique](https://digitalcollage.org/), organized here in New-Caledonia by [Xavier Liénart](https://www.linkedin.com/in/xavier-li%C3%A9nart-msinc/)

{% embed https://digitalcollage.org/ %}

During this session I learned a lot...

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

I wanted to contribute. I thought that we were lacking some more interoperable datas, so I decided to contribute.

💡 This post is about the project I chose to contribute is helpful... and used by [GIZMODO](https://gizmodo.com/) 🙀

## ❔ About

As [spotted today](https://github.com/endoflife-date/endoflife.date/discussions/870#discussioncomment-4797169) by [`GIZMODO`](https://twitter.com/gizmodo):

{% embed https://www.gizmodo.com.au/2023/01/phone-update-support/ %}

There are some big questions round EoL (End of Life) considerations).

### 🪦 "Phones don’t live forever"

> Phones don’t live forever. They should live a lot longer than they do, but manufacturers typically won’t support a phone with updates for a long time, encouraging you to get a new one every three years.

### 🚧 How long might your phone be supported

> So, how long might your phone be supported for with updates? When will it stop receiving software and security updates? Let’s break down phone support lifecycles from each major manufacturer. 

## 🎯 What you'll learn

In this post, you'll see how [`endoflife.date`](https://endoflife.date/) can help a lot to answer these challenging questions... and how to go further.

## 📺 (`10'`) Showtime

{% youtube yF8dAr76Wu0 %}

## 🎁 What's coming next : Fairphone

{% embed https://github.com/endoflife-date/endoflife.date/issues/2338 %}

## 📑 Related resources

- 🧑‍🤝‍🧑 [La Fresque du Numérique](https://www.fresquedunumerique.org/index.html) : _"Un atelier pour comprendre en équipe et de manière ludique les enjeux environnementaux du numérique"_
- 🧑‍🤝‍🧑 [The Digital Collage](https://digitalcollage.org/) : _"A workshop to understand, as a team and in a fun way, the impact of digital technology on the environment."_
- [Here’s How Long Your Phone Will Be Supported by the Manufacturer](https://www.gizmodo.com.au/2023/01/phone-update-support/)
3 essential new features of PHP 8
Tags: php, programming, webdev, beginners
Published: 2023-01-27 22:22:57

## Constructor Property Promotion
This new feature allows developers to define class properties directly within the constructor method, without having to declare them separately at the top of the class. This can make the code more concise and readable, as well as reduce the amount of duplicated code.

In previous version of PHP, you would have to declare the properties at the top of the class, and then set the value of the properties in the constructor.

```
class Example {
    private string $name;
    private int $age;
    private bool $isActive;
    public function __construct(string $name, int $age, bool $isActive = true) {
        $this->name = $name;
        $this->age = $age;
        $this->isActive = $isActive;
    }
}
```

Now, the code from above can change to
```
class Example {
    public function __construct(
        private string $name,
        private int $age,
        private bool $isActive = true
    ) {}

    // ... other class methods ...
}

$example = new Example('John', 25);
```


## Union Types
In PHP 8, union types allow for specifying multiple types for a function or method parameter or return type. This allows for more specific type checking, and can help prevent errors caused by passing the wrong type of argument to a function. For example, a function that accepts either a string or an integer for a parameter could be declared like this:

```
function example(int|string $param) {
    // function body
}
```

This means that the example function accepts either a string or an integer as the value of $param.

Note that Union types are not supported for class and interface types, and also if you use the mixed type, the union types will be ignored.


## Match Expressions
Match expressions in PHP 8 provide a more concise and expressive way to perform pattern matching, as it allows checking the type of variable and perform different actions based on the type. For example, instead of writing an if-else or switch statement, you can use a match expression like this:
```
$message = match ($statusCode) {
    200, 300 => null,
    400 => 'not found',
    500 => 'server error',
    default => 'unknown status code',
};
```

## Conclusion
There are many new features and improvements in PHP 8. You can go over all of them [here](https://kinsta.com/blog/php-8/#php-8-improvements-and-new-features).
Time to level up as a Developer and a Person
Tags: levelup, challenge
Published: 2023-01-27 20:23:34



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nvyi7sljbhqkjyb5sw9a.jpg)
## Do I feel stuck as a developer?

I feel it, in my veins and all. I think that it's high time I have done something to level up my skills. The truth is the type of developer I am is being produced every day by countless coding boot camps. I am replaceable and that is why I feel stuck at the level I am.

## What is stopping my growth?
I, me and myself is the only reason that I am stuck at this phase where I feel like I am not growing. I know some stuff here and there but it is still a lot less than my potential. I am lazy and absent while taking action. I lack discipline. Now it's not that I lack the hunger, but I lack the urge to cast votes every day for becoming the person I want to be.


## What should I be doing to level up?
Be disciplined and a stone-cold committer. Be an absolute beast and do every day that I am supposed to do. I should be coding every day. Solve at least 2 coding problems. Spend a focused state on my client project. Also, spend another focused state on projects that will increase my knowledge of the domain and expand my horizon.

[note: these blogs are not a self-rant, but more like a self-documentary. I might even create a movie about my life. At this point I feel like I am in the shithole that I am supposed to be at the moment and I am gonna get out of this and prove my worth not to the world but to myself.]
Small Contributions to Starchart
Tags: opensource, remix, starchart, beginners
Published: 2023-01-27 21:41:42




This week, I set up the initial Starchart project using Remix's Blues Stack template. The [PR](https://github.com/Seneca-CDOT/starchart/pull/38) is the starting point for adding, modifying, and removing features and functionalities. There were some problems running the development environment, as the user had to copy the default Postgres credentials from `.env.example` to a new `.env` file. I most likely forgot about including it as a step in the "Steps to Test" section of my PR because the `.env` file was created by the script I used to generate the template for the project. However, as we do not intend to use Postgres to store our data, and the purpose of the PR was to provide a starter code for the team, the PR was successfully squashed and merged. 

I also got the opportunity to review a [PR](https://github.com/Seneca-CDOT/starchart/pull/39) in the Starchart repo that dealt with adding `package-log.json` to the tree and removing dependencies with security issues. The `package-log.json` was automatically added to `.gitignore` when I ran the script to generate Blues Stack project, so I pointed out that we should add it back to the tree as it's an essential file for several reasons. One is that it has an optimization purpose of letting `npm` skip previously installed dependencies during the installation process. Another thing worth pointing out was removing  `prom-client` since it is a Prometheus-related dependency we are trying to avoid.

Some of the errors from my end could have been avoided had I not felt the pressure of keeping other teammates waiting, as all the core features and functionalities rely on the initial Remix Blues Stack setup.
AWS Cloud Quest: Templating Serverless Applications Study Note
Tags: aws, cloud
Published: 2023-01-27 21:38:14

This is the DIY challenge of the Templating Serverless Applications task in AWS Cloud Quest.

### DIY Steps:
1. Add an Amazon DynamoDB table to the AWS SAM template `template.yaml`, you can read more about this topic [here](https://docs.aws.amazon.com/lambda/latest/dg/kinesis-tutorial-spec.html)
    ```
    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    Description: >
      appfn

      Sample SAM Template for appfn

    # More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
    Globals:
      Function:
        Timeout: 3

    Resources:
      HelloWorldFunction:
        Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
        Properties:
          CodeUri: hello_world/
          Handler: app.lambda_handler
          Runtime: python3.7
          Events:
            HelloWorld:
              Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
              Properties:
                Path: /hello
                Method: get
      DynamoDBTable:
        Type: AWS::DynamoDB::Table
        Properties: 
          AttributeDefinitions: 
            - AttributeName: id
              AttributeType: S
          KeySchema: 
            - AttributeName: id
              KeyType: HASH
          ProvisionedThroughput: 
            ReadCapacityUnits: 5
            WriteCapacityUnits: 5
          StreamSpecification:
            StreamViewType: NEW_IMAGE
    Outputs:
      # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function
      # Find out more about other implicit resources you can reference within SAM
      # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api
      HelloWorldApi:
        Description: "API Gateway endpoint URL for Prod stage for Hello World function"
        Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/hello/"
      HelloWorldFunction:
        Description: "Hello World Lambda Function ARN"
        Value: !GetAtt HelloWorldFunction.Arn
      HelloWorldFunctionIamRole:
        Description: "Implicit IAM Role created for Hello World function"
        Value: !GetAtt HelloWorldFunctionRole.Arn
    ```
2. Deploy the AWS SAM template
3. Push the update to AWS CodeCommit
    ```
    git add .
    git commit -m "diy"
    git push
    ```
How can Kubernetes help the stock exchange market?
Published: 2023-01-27 21:30:13

Kubernetes can help the stock exchange market in several ways:

Scalability: Kubernetes allows for easy scaling of applications and services, which is essential for a stock exchange that needs to handle a large volume of transactions.

High availability: Kubernetes provides built-in features for ensuring high availability of applications and services, which is critical for a stock exchange that needs to be online and operational at all times.

Resource management: Kubernetes enables better resource management and optimization, which can help a stock exchange reduce costs and improve performance.

Deployment Automation: Kubernetes provides a consistent and automated way to deploy and manage the stock exchange systems and applications.

Microservices: Kubernetes helps to enable the deployment of microservices architecture, which allows stock exchange services to be broken down into smaller, more manageable components.

Disaster recovery: Kubernetes provides features for disaster recovery and failover, which can help a stock exchange minimize downtime and maintain business continuity in case of unexpected events.

Security: Kubernetes has built-in security features, such as role-based access control, that can be used to secure the stock exchange systems and applications.
Python Convert JSON to SQLite
Tags: python, programming, sqlite, datascience
Published: 2023-01-27 21:12:37

Here are the detailed steps to convert JSON to SQLite using Python:

**Install the required libraries:**

```
pip install sqlite3
pip install json
```


**Import the required libraries:**

```
import sqlite3
import json
```

**Open a connection to the SQLite database:**

```
conn = sqlite3.connect('example.db')
```

**Open the JSON file:**

```
with open('example.json', 'r') as json_file:
    data = json.load(json_file)
```

**Iterate through the JSON data and insert it into the SQLite table:**

```
for item in data:
    conn.execute("INSERT INTO example_table (field1, field2, field3) VALUES (?, ?, ?)", 
                 (item["field1"], item["field2"], item["field3"]))
```

**Commit the changes and close the connection:**

```
conn.commit()
conn.close()
```

**Note:**

- Replace 'example.db' and 'example.json' with the appropriate file name, and 'example_table' with the appropriate table name

- Also, you may need to create the table before inserting the data, you can check this by using the below command

```
conn.execute("CREATE TABLE example_table (field1 text, field2 text, field3 text);")
```

**Example:**

```
import sqlite3
import json

conn = sqlite3.connect('example.db')
conn.execute("CREATE TABLE example_table (field1 text, field2 text, field3 text);")
with open('example.json', 'r') as json_file:
    data = json.load(json_file)
    for item in data:
        conn.execute("INSERT INTO example_table (field1, field2, field3) VALUES (?, ?, ?)", (item["field1"], item["field2"], item["field3"]))
conn.commit()
conn.close()
```

This will create a SQLite database file named 'example.db' in the current directory and insert the data from 'example.json' into a table named 'example_table'.
Simple way to manage Jupyter notebooks on Kubernetes without JupyterHub
Tags: kubernetes, jupyter, python, helm
Published: 2023-01-27 20:58:40

Hello,

I just open-sourced a tool to manage `Jupyter` notebooks on `Kubernetes` without `JupterHub` and its burden.

`notebook-on-kube` is a straightforward `FastAPI` application that relies on existing tools/features of the Kubernetes ecosystem (`Helm`, `RBAC`, `ingress-nginx`, `HPA`, `Prometheus` metrics) and helps managing `Jupyter` notebooks on `Kubernetes`, learn more about it at [https://github.com/machine424/notebook-on-kube](https://github.com/machine424/notebook-on-kube), give it a try and let me know :)
What was your win this week?
Tags: discuss, weeklyretro
Published: 2023-01-27 20:53:56

Hey y'all! 👋

Hope everybody has an awesome weekend!

Looking back on this past week, what was something you were proud of accomplishing?

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Fixing a tricky bug
- Celebrating a birthday 🥳

---

![A bunch of birds bobbing their heads up and down on a blank background with the words "Woot! Woot!" floating up above their heads](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/od11p2opdt5lhnq8dlnn.gif)
SPVM::File::Basename is released. This is the first module of SPVM using regular expressions.
Tags: perl, spvm
Published: 2023-01-27 20:22:30

<a href="https://metacpan.org/pod/SPVM::File::Basename">SPVM::File::Basename</a> has been released. SPVM::File::Basename is a porting of Perl's <a href="https://metacpan.org/pod/File::Basename">File::Basename</a> to SPVM.

It supports the fileparse, basename, and dirname methods.

## Regular Expressions

SPVM::File::Basename is the first module of SPVM that uses regular expressions.

Many Perl modules rely on regular expressions. In particular, it is safe to say that modules that deal with file paths always use regular expressions.

My concern was about a reliable Perl-compatible regular expression for creating modules in SPVM. At first, I created my own, but they were not very reliable. There are limitations to creating them alone.

I searched for I found that there is a Perl compatible regular expression called <a href="https://github.com/google/re2">Google RE2</a>. It is written in C++, and with Google RE2, I can use Perl-compatible regular expressions as a library.

I created a module called <a href="https://metacpan.org/pod/SPVM::Resource::Re2::V2022_06_01">SPVM::Resource::Re2</a> to make it available from SPVM.

Then, I created a module called <a href="https://metacpan.org/pod/SPVM::Regex">SPVM::Regex</a> to implement the regular expression methods of Perl's search and replace.

And the first module that uses SPVM::Regex in practice is SPVM::File::Basename, which handles file paths.

Please take a look at the code that handles regular expressions in SPVM.

```
use Regex;

  method fileparse : string[] ($path : string) {
    unless ($path) {
      die "The \$path must be defined";
    }
    
    my $dirpath = (string)undef;
    my $basename = (string)undef;
    
    my $re = Regex->new("(?s)^(.*/)?(.*)");
    if ($re->match($path)) {
      $dirpath = $re->cap1;
      $basename = $re->cap2;
    }
    
    unless (length $dirpath) {
      $dirpath = "./";
    }
    
    return [$basename, $dirpath, ""];
  }
```

<a href="https://github.com/yuki-kimoto/SPVM-File-Basename/blob/master/lib/SPVM/File/Basename/Unix.spvm">File::Basename::Unix</a>

Translated with www.DeepL.com/Translator (free version)