teleren/devto huggingface dataset:
How to build PHP Image from Scratch
Tags: php, docker, cloud, programming
Published: 2023-01-04 20:07:00

PHP applications easily. Please keep in mind, this is development purposes for beginners. We will publish new article for production purposes.

Let's get started.

## Preparing Dockerfile for base PHP applications

Firstly, create Dockerfile to list configuration. At the beginning of the page, we start by adding this line.

`FROM php`

This enables us to install php.

Secondly, we add a new line to use files.

`COPY . .`

So that you can access every files in main root. However, if you wish use to only specific files, you can specify them manually like:

`COPY ./index.php ./`

Thanks to this, you can just move specific files and they are available to use.

In the next step, we expose desired port to run php application.

`EXPOSE 3000`

At the end of the file, we can run our app by executing following command line.

`CMD ["php", "-S", "0.0.0.0:3000"]`

To make life easier for you, you can get the file entirely.

`FROM php
COPY . .
EXPOSE 3000
CMD ["php", "-S", "0.0.0.0:3000"]`

## Installing docker image

Executing this command line, you can get php image.

`docker build . -t w3cloudhub/php`

## Running docker image

`docker run --name=php -p=3000:3000 w3cloudhub/php`

Congratulations! 🥳 If you see following line in the CMD, your dockerfile and image are ready to use.

`PHP 8.2.0 Development Server (http://0.0.0.0:3000) started`

Thank you for reading. Please leave a comment about your feelings and any issues.
number guess game with flet
Tags: python, flet, programming
Published: 2023-01-04 19:57:09

A simple number guessing game where players have to guess randomly generated numbers in a given range. which I created using flet which is a python module.

This number guessing game, written in Thai, is a great example of how to use the flet module in Python. In the game, players are asked to guess a randomly generated number within a given range. The range can be customized by the user, and can be as small or large as desired. After each guess, the player will be told whether their guess was too high, too low, or correct. The game will continue until the player correctly guesses the random number, at which point they will be declared the winner. Players can play as many rounds as they like, and the game will keep track of their win/loss record. Whether you're a seasoned pro or a beginner, this game is sure to provide hours of fun and challenge! The use of the flet module in this game allows for easy customization and flexibility, making it a great tool for any Python developer to have in their toolkit.

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

I use markdown files to assist me in writing out the instructions for how to play.

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

This code example

```python
with open(self.path_markdown, "r", encoding="utf-8") as f:
            self.filemarkdown = f.read()
        self.markdown_help = ft.Markdown(
            self.filemarkdown,
            selectable=True,
            extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
        )
```

I encountered a problem when trying to change the page, so I implemented a solution using a class and a method to delete all the controls within it in order to change the page.

```python
menu_game = MenuGame()
menu_game_all = menu_game.container_main
def back_to_menu_main_from_levelScene(e):
        """
        change to menu scene
        """
        page.add(menu_game_all)
        page.remove(level_scene_all)
```
This may not be the most effective way to solve this issue, but it did work for me. If anyone has a better solution, please feel free to submit a pull request.

![image desc](https://media.discordapp.net/attachments/585069498986397707/1060285380856909824/gamedfdsf.gif?width=342&height=625)


You can access the game at this link: https://github.com/watchakorn-18k/number_guessing_game
Welcome Thread - v207
Tags: welcome
Published: 2023-01-04 19:50:48

---
title: Welcome Thread - v207
published: true
description: Welcome to DEV! A thread of hellos and intros.
tags: welcome
canonical_url: 
---

![Person in dog suit spray painting "sup" and laying beneath it... think they're going for "sup dog"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qv7dy03sucolt5t8308v.gif)

### Welcome to DEV!

1. Leave a comment below to introduce yourself! You can talk about what brought you here, what you're learning, or just a fun fact about yourself.

2. Reply to someone's comment, either with a question or just a hello. 👋 

**Great to have you in the community!**
100 Days of Code Challenge: Day 2
Tags: 100daysofcode, python, csharp
Published: 2023-01-04 19:35:07

It is Day 2 of me doing the 100 Days of Code challenge from Angela Yu's [100 Days of Code: The Complete Python Pro Bootcamp](https://www.udemy.com/course/100-days-of-code/) where I learnt about mathematical operations and data type manipulation like string formatters. 

Compared to [day 1](https://dev.to/toyinariyo/new-years-resolutions-for-a-neurodivergent-junior-developer-4km3), it was definitely a bit more difficult as it involved a lot of mathematics and I am not good at doing that without a calculator. Using [Python Tutor](https://pythontutor.com/) definitely helped me build and understand the project more as it allowed me to break down the program line by line so I can see how each variable was calculated. 


![Screenshot of code shown line by line in Python Tutor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lb49iimaw8rv80w0gvck.png)


For the C# equivalent, it was a lot harder to program than Day 1 because Python and C# are so different. The C# program manages to run but it does not seem to show the correct result: for the above input, it would say the final amount is 14.00 instead of 15.40. 


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

```
using System;

class Program {
  public static void Main (string[] args) {
    Console.WriteLine ("Here is Toyin's tip calculator!");
    Console.WriteLine("What was the total bill?");
    decimal bill = decimal.Parse(Console.ReadLine());
    Console.WriteLine("Was the tip 10, 12 or 15?");
    int tip = int.Parse(Console.ReadLine());
    Console.WriteLine("How many people are splitting the bill?");
    int people_split = int.Parse(Console.ReadLine());
    int tip_percentage = tip / 100;
    decimal total_tip = bill * tip_percentage;
    decimal total_bill = bill + total_tip;
    decimal bill_per_person = total_bill / people_split;
    decimal final_amount = Math.Round(bill_per_person, 2);
    Console.WriteLine("Each person should pay: " + "$" + final_amount.ToString("0.00")); //Prints out wrong answer: 14 instead of 15.4 for total bill of 70, tip of 10 and 5 people splitting bill
    }
}
```

I'm not sure where the issue was in converting the Python code and why it is displaying a different result. Enjoyment wise, I am definitely liking how simple the syntax is with Python, I really wish I started using this programming language a lot earlier. 

I plan on posting about Day 3 of the Code Challenge tomorrow.
Creating Delays in Python Programs
Tags: python, beginners, tutorial
Published: 2023-01-04 19:30:54

Short breaks can be fun and functional in some programs. Creating a waiting time before displaying a text, for example, can make the process of using that program more real.

For that, let's import the `sleep()` method from the `time` module:

```py
from time import sleep
```

And now just call the `sleep()` method specifying the time in seconds:

```py
# 3 second delay
sleep(3)

# 1 minute delay
sleep(60)
```

Example of how delays can make a program more real:

```py
print('Jo')
sleep(1)
print('Ken')
sleep(1)
print('Po')
sleep(1)
```
Create and deploy an Express API to Cloud Run
Tags: googlecloud, node, api, websockets
Published: 2023-01-04 19:24:57

## Overview

In this article, I'm going to walk you through quickly generating either a basic starter Express API app or a simple example Express API app and deploying it to [Cloud Run](https://cloud.google.com/run).

## Prerequisites

See the prerequisites for using `run`, a lightweight CLI for creating and deploying Cloud Run apps [here](https://github.com/subfuzion/run#prerequisites).

## Create the app

Choose either `express-api` or `example-express-api` when asked to choose a project template. The example version demonstrates using various Express methods for a mock database.

```
run create
```
_Selecting a template_
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltc629fhdxk8h3bldzk4.png)

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

You can run the app locally, if you want.

## Deploy the app

To deploy to Cloud Run, enter:

```
run deploy
```

Since this is the first deployment, you'll be presented with a series of prompts. Your settings will be saved to a a local configuration file (`run.yaml`).

> Note: In the current version of `run`, only the new project option works.

## Test the app

When the deployment is finished, the `run` will print the URL for accessing the app.

If you chose `example-express-api`, the README includes instructions about testing the API using `curl` commands in a test script.

## View app logs

To get the link to view the logs web page, enter:

```
run logs
```
## Wrapping up

The `run` command to delete the project when finished is not yet implemented. For now, use `gcloud` to delete the project using its ID (if you forget the project ID, it's stored in `run.yaml`).

```
gcloud projects delete PROJECT
```

If you run into any problems, check to see if there is an issue [here](https://github.com/subfuzion/run/issues) and, if not, please create one.

## References

I provide background on `run` in my [last article](https://dev.to/subfuzion/streamlining-gcloud-with-a-custom-cli-for-serverless-javascript-developers-2oba).

If you prefer to use `gcloud`, see [this article](https://dev.to/subfuzion/getting-started-with-the-google-cloud-cli-interactive-shell-for-serverless-developers-45l) if you need help getting started. You'll still use `run` to create the app from a template.
Criando Pausas em Programas em Python
Tags: python, beginners, tutorial, braziliandevs
Published: 2023-01-04 19:23:37

Pausas curtas podem ser divertidas e funcionais em alguns programas. Criar um tempo de espera antes de apresentar um texto, por exemplo, pode tornar o processo de uso daquele programa mais real.

Tecnicamente isso é um delay, e não uma pausa no sentido literal. Para tal coisa, vamos importar o método `sleep()` do módulo `time`:

```py
from time import sleep
```

E agora basta chamar o método `sleep()` especificando o tempo em segundos:

```py
# Pausa de 3 segundos
sleep(3)

# Pausa de 1 minuto
sleep(60)
```

Exemplo de como as pausas podem tornar um programa mais real:

```py
print('Jo')
sleep(1)
print('Ken')
sleep(1)
print('Pô!')
sleep(1)
```
How to create a TelegramBot using ZettaBlock GraphQL API
Published: 2023-01-04 19:22:12

To create a bot using the ZettaBlock GraphQL API, you'll need to follow a few steps. First, make sure you have an API key and access to the ZettaBlock GraphQL endpoint where you will get API ID and API Key which you need to input in the .env file. Then, you'll need to create a bot on Telegram and then choose a programming language and a framework to build your bot with. Some popular options for building bots include Node.js, Python.

Follow the steps shown below to make an awesome Telegram Bot:

1. Make a Data Query

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

2. Create an SQL Query to fetch Solana tokens on the Mainnet-Beta(Here we are building a Solana Token Tracker Bot)

```
SELECT
  "name",
  "symbol",
  "decimals",
  "token_authority",
  "supply",
  "type",
  "address"
FROM
  solana_mainnet.token_metadata
LIMIT
  20 
```

3. Create API to Query the data.
Indexed the data by selecting the name, symbol and supply field


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

4. Get your API Key, API ID, Bot token and Hop on to Github

[Github - TelegramBot](https://github.com/TheDARKFURY/EarnWeb3DAO---ZettaBlockAPI)

Run following command

`npm i`

Add API ID, API Key and Bot Token in .env.example and rename the file to .env

Now, run the following command and you're good to test your bot on Telegram

`node index.js`
203. Remove Linked List Elements
Tags: java, linkedlist, leetcode, beginners
Published: 2023-01-04 18:59:37

Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head.

 

**Example 1:**


**Input:** head = [1,2,6,3,4,5,6], val = 6
**Output:** [1,2,3,4,5]
**Example 2:**

**Input: **head = [], val = 1
**Output:** []

**Example 3:**

**Input:** head = [7,7,7,7], val = 7
**Output:** []
 

**Constraints:**

The number of nodes in the list is in the range [0, 104].
1 <= Node.val <= 50
0 <= val <= 50

**Solution:**
```
class Solution {
    public ListNode removeElements(ListNode head, int val) {
       if (head == null)
			return null;

		ListNode curr = head;
		ListNode prev = null;

		while (curr != null)
		{
			if (curr.val == val)
			{
				if (prev != null)
					prev.next = curr.next;
				else
					head = head.next;
			}
			else
			{
				prev = curr;
			}
			curr = curr.next;
		}
		return head;
    }
}
```
Amazon S3 Trivia
Published: 2023-01-04 18:59:22

Reference to this trivia, https://youtu.be/d33MO713Ja4 let us look at this 8 Keywords for Amazon Simple Storage Service (S3).

**1. Durability **
Amazon S3 is a highly durable object storage service which provides 11 9s of durability(99.999999999%) which ensures data is not lost. S3 achieves this by redundantly storing  your objects on multiple devices across multiple facilities in the Amazon S3 Region you designate.

**2. Latency**
Amazon S3 provides low latency in data transfer by taking advantage of the globally distributed edge locations in Amazon CloudFront. It ensures transfer of gigabytes to terabytes of data regularly across continents. 

**3. Redundancy**
Amazon S3 redundantly stores your objects on multiple devices across multiple facilities in the Amazon S3 Region you designate. 

**4. Replication **
Amazon S3 easily replicates your data objects across buckets. This offers you flexibility and functionality require to fully control your data to meet you business needs.

**5. Encryption**
Amazon S3 ensures your data is secured by  encrypting it both in transit and at rest. It also provides with fine-grained data access control. 

**6. Auditing **
Amazon S3 provides you with several tools for monitoring your Amazon S3 resources and responding to potential incidents.

**7. Macie**
Amazon S3 provides you with ability to use Machine Learning to automatically discover, classify, and protect sensitive data in AWS.

**8. Compliance **
Amazon S3 provides you with ability to govern your data to ensure it meets your security and compliance needs.
How to make Google's "Report issue" feedback form
Tags: webdev, javascript, npm, productivity
Published: 2023-01-04 18:54:48

Do you want to make your own feedback form with screenshot taking & screenshot editing functionality?

Google's feedback form:
![Google Feedback Form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o7hmqayb8wai2i4taze4.png)

**Let's make one just like Google's**

---

Luckily for you, there's a library built already for this purpose. Introducing, [FeedbackPlus](https://github.com/ColonelParrot/feedbackplus).

{% embed https://github.com/ColonelParrot/feedbackplus %}

With FeedbackPlus, you can capture screenshots without having to worry about browser support. The library uses the browser's display API to ensure the screenshot is accurate, and fallbacks to html2canvas for better browser support.

# Screenshotting

```js
// import FeedbackPlus from 'feedbackplus/src/feedbackplus'
// ^^^ if you're using node ^^^
const feedbackPlus = new FeedbackPlus();
```

```js
feedbackPlus.capture().then(result => ...)
```

You can then very quickly just draw the result to a canvas:


```js
const canvas = document.getElementById("canvas")
feedbackPlus.capture().then(({ bitmap, width, height }) => {
  canvas.width = width;
  canvas.height = height;
  canvas.getContext("2d").drawImage(bitmap, 0, 0);
});
```

## Screenshot Example

```html
<canvas id="canvas"></canvas>
<button id="btn">Take screenshot</button>
```
```js
const canvas = document.getElementById("canvas")
btn.addEventListener('click', () => {
  feedbackPlus.capture().then(({ bitmap, width, height }) => {
    canvas.width = width;
    canvas.height = height;
    canvas.getContext("2d").drawImage(bitmap, 0, 0);
  })
})
```

# Editing Screenshot

Once you have obtained the image bitmap from a screenshot, you can store it in a variable and pass it to `showEditDialog` to edit it.

```js
feedbackPlus.showEditDialog(bitmap, function (canvas) {
    // user completed edit
    FeedbackPlus.canvasToBitmap(canvas).then(({ bitmap }) => {
      canvas.getContext("2d").drawImage(bitmap, 0, 0);
      feedbackPlus.closeEditDialog();
    });
  }, function () {
    // user cancelled edit
    feedbackPlus.closeEditDialog();
  }
);
```

**It's that easy!** Try it out yourself with the [demo](https://colonelparrot.github.io/feedbackplus/).
I need a solution
Tags: php, html, database, sql
Published: 2023-01-04 18:35:48

The first time I send data to the database, I get this message: Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1 in C:\xampp\htdocs\buy.php:18 Stack trace: #0 C:\xampp\htdocs\buy. php(18): mysqli_query(Object(mysqli), 'INSERT INTO `or...') #1 {main} thrown in C:\xampp\htdocs\buy.php on line 18.

The code for the database:

<?php

$conn = mysqli_connect('localhost','root','','loin team_db');

if(isset($_POST['send'])){

$name = $_POST['name'];

$email = $_POST['email'];

$number = $_POST['number'];

$plan = $_POST['plan'];

$file = $_POST['file'];

$notes = $_POST['notes'];

$insert = "INSERT INTO `order_form`(`name`, `email`, `number`, `plan`, `file`, `notes`) VALUES ('name', 'email', 'number', 'file ','notes',)";

mysqli_query($conn, $insert);

header('location:buy.php');

}
Date and Time in Python
Tags: python, beginners, tutorial
Published: 2023-01-04 18:19:56

We can get data and time information in Python using the `datetime` module. Let's import it:

```py
import datetime
```

## Date

In the `datetime` module we can use the `date` class, which has `today()` to load the current day's data:

```py
date = datetime.date.today()
print(date)
```

Result example:

```
2023-01-04
```

We can also get each date information separately:

```py
day = datetime.date.today().day
month = datetime.date.today().month
year = datetime.date.today().year

print(day)
print(month)
print(year)
```

Result example:

```
4
1
2023
```

## Time

To get the time, we'll use the `datetime` class and its `now()` method:

```py
now = datetime.datetime.now()
print(now)
```

Result example:

```
2023-01-04 14:28:19.041413
```

Note that the time schedule is organized into:

`hour:minute:second.microsecond`

## Time formatting

We can change the way the time is being displayed through the `strftime()` method. By default, we have `%d` for day, `%m` for month, `%y` for year, `%H` for hour, `%M` for minute and `%S` for seconds. Let's use new variables to save these formatted values:

```py
format1 = now.strftime('%d/%m/%y')
print(format1)

format2 = now.strftime('%d.%m.%Y %H:%M:%S')
print(format2)
```

Result example:

```
01/04/23
04.01.2023 14:28:19
```

Note that using `%Y`, we have the year displayed with 4 characters.
Configurar basica MUI con Vite
Tags: react, vite, materialui
Published: 2023-01-04 18:17:19



## Instalación basica de MUI 

- Dependencias de MUI

```
yarn add @mui/material @emotion/react @emotion/styled
```

- Fuentes

Colocar el siguiente link en el index.html antes de la etiqueta `</head>`

```
<link
  rel="stylesheet"
  href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
```

- Iconos

```
yarn add @mui/icons-material
```


## Configuración de MUI en Vite

En el directorio `scr/`, crearemos un directorio llamado `theme/` y dentro crearemos los siguientes archivos:

1.- Crearemos un _higher order component_ con el nombre de `AppTheme.jsx`

```
import { ThemeProvider } from '@emotion/react';
import { CssBaseline } from '@mui/material';

import { greenTheme } from './greenTheme';

export const AppTheme = ({ children }) => {
  return (
    <ThemeProvider theme={ greenTheme }>
      <CssBaseline />
      { children }
    </ThemeProvider>
  )
}

```

2.- Ahora crearemos el tema (en este caso) `greenTheme.js`

```
import { createTheme } from '@mui/material';
import { red } from '@mui/material/colors';


export const greenTheme = createTheme({

  palette: {
    primary: {
      main: '#35bf31'
    },
    secondary: {
      main: '#72bf31'
    },
    error: {
      main: red.A400
    }
  }

});
```

3.- Aplicamos la configuración en el `main.jsx`

```
import React from 'react'
import ReactDOM from 'react-dom/client'

import { AppTheme } from './theme/AppTheme'

import App from './App'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <AppTheme>
      <App />
    </AppTheme>
  </React.StrictMode>,
)
```

Con esta configuración minima tenemos MUI andando en un proyecto con Vite
Responsive Flyout in .NET MAUI
Published: 2023-01-04 18:13:55

NET Multi-platform App UI (**.NET MAUI**) is a cross-platform framework for creating native mobile and desktop apps with C# and XAML. Using .NET MAUI, you can develop apps that can run on Android, iOS, macOS, and Windows from a single shared code-base. In this post, I will show you how to implement a responsive Flyout in your .NET MAUI app using `Microsoft.Maui.Devices` class by detecting when the screen size changes for iOS and Android.

---
## Essentials
In .NET MAUI the Xamarin.Essentials were natively integrated, so you can get all the benefits along with improvements for the `DeviceDisplay` class.

## Responsive Layout
In the ContentPage we attach an event handler to catch up screen size changes occurring to that particular page, so we render the proper Flyout behavior based on the screen size 

```csharp
    protected override void OnAppearing()
    {
        base.OnAppearing();
        SetFlyoutBehavior();
        DeviceDisplay.MainDisplayInfoChanged += DeviceDisplay_MainDisplayInfoChanged;
    }

    private void DeviceDisplay_MainDisplayInfoChanged(object sender, DisplayInfoChangedEventArgs e)
    {
        SetFlyoutBehavior();
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        DeviceDisplay.MainDisplayInfoChanged -= DeviceDisplay_MainDisplayInfoChanged;
    }

    private void SetFlyoutBehavior()
    {
        // Get the screen points 
        double screenWidth = DeviceDisplay.MainDisplayInfo.Width / DeviceDisplay.MainDisplayInfo.Density;

        Debug.WriteLine(screenWidth);
        // sizes obtained from the official bootstrap CSS 
        switch (screenWidth)
        {
            case <= 576:
                Shell.Current.FlyoutBehavior = FlyoutBehavior.Flyout;
                Shell.Current.FlyoutIsPresented = false;
                break;
            case > 576:
                Shell.Current.FlyoutBehavior = FlyoutBehavior.Locked;
                Shell.Current.FlyoutIsPresented = true;
                break;
        }
    }
```

## Conclusion
This is just a sample of how to set the Flyout from App Shell to be locked or hidden based on the screen size, however, you can use it to accommodate other areas of the screen layout.

I hope this helps others to create their own responsive layouts in .NET MAUI.