teleren/devto huggingface dataset:
Create a Hilarious Joke API with Flask and Python
Tags: python, api, flask, backend
Published: 2024-03-17 15:04:11

In this guide, we'll walk you through the simple steps to create a Joke API using Flask, a lightweight web framework for Python. Our API will utilize a third-party package to generate jokes as responses, ensuring a delightful experience for users.

**Getting Started with Flask and Python:**

First, ensure you have Python installed on your system. Then, install Flask using pip:

```
pip install flask
```

**Generating Jokes with a Third-Party Package:**

To spice up our API responses, we'll use the `pyjokes` package. Install it with:

```
pip install pyjokes
```

**Coding the Joke API:**
Now, let's dive into the code. Create a Python file (e.g., `joke_api.py`) and add the following:

```
from flask import Flask, jsonify
import pyjokes

app = Flask(__name__)

@app.route('/joke', methods=['GET'])
def get_joke():
    try:
        joke = pyjokes.get_joke()
        return jsonify({'joke': joke}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)

```

**Understanding the Code:**

- We import `Flask` and `jsonify` for handling HTTP requests and responses.
- The `/joke` route is defined to handle GET requests.
- Inside `get_joke()`, we fetch a joke using `pyjokes.get_joke()`.
- We use `try-except` to catch any potential errors and return the appropriate status code.


**Testing the API:**
Run your Flask application:

```
python joke_api.py
OR
python3 joke_api.py
```
Now, navigate to `http://localhost:5000/joke` in your **browser** or make a `GET` request using tools like **Postman**.

```
{
  "joke": "A good programmer is someone who always looks both ways before crossing a one-way street."
}
```

**Congratulations!** You've successfully created a Joke API using Flask and Python. With just a few lines of code, you can now entertain your users with hilarious jokes. Feel free to expand upon this project by adding more features or integrating it into your existing applications.

If you enjoyed this tutorial, don't forget to give it a 👏 and share it with your fellow developers! Stay tuned for more exciting projects and tutorials on our blog. 🚀
Create a custom function to generate a URL from given parameters (with TS support) 💻
Tags: javascript, typescript, webdev, frontend
Published: 2024-03-17 15:00:56

We can achieve this using two options:

**First option:**

```javascript
const urlGenerator = (
    baseUrl: string,
    pathName: string,
    searchParamsArray: Array<Record<string, string | number>>
  ) => {
    const validSearchParams = searchParamsArray.filter((param) => {
      const [_, value] = Object.entries(param)[0];
      // We can put here any condition on the value
      return value;
    });
    const sortedSearchParams = validSearchParams.sort((a, b) => {
      const [aKey] = Object.entries(a)[0];
      const [bKey] = Object.entries(b)[0];
      if (aKey > bKey) {
        return 1;
      } else if (aKey < bKey) {
        return -1;
      } else return 0;
    })
    const searchParams = sortedSearchParams
      .map((param) => {
        const [key, value] = Object.entries(param)[0];
        return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;
      })
      .join("&");
    const url = `${baseUrl}${pathName}?${searchParams}`;
    return url;
  };
  const resultUrl = urlGenerator("http://example.com", "/", [
    { width: 200 },
    { height: 250 },
    { locale: "en" },
    { toolbar_bg: "" },
    { interval: "3h" },
    { search: "react19" },
  ]);
  console.log("resultUrl=", resultUrl);

// resultUrl= http://example.com/?height=250&interval=3h&locale=en&search=react19&width=200
```
**Second option:**
By using URLSearchParams as the following

```javascript
const urlGenerator = (
    baseUrl: string,
    pathName: string,
    searchParamsArray: Array<Record<string, string>>
  ) => {
    const validSearchParams = searchParamsArray.filter((param) => {
      const [_, value] = Object.entries(param)[0];
      // We can put here any condition on the value
      return value;
    });
    const sortedSearchParams = validSearchParams.sort((a, b) => {
      const [aKey] = Object.entries(a)[0];
      const [bKey] = Object.entries(b)[0];
      if (aKey > bKey) {
        return 1;
      } else if (aKey < bKey) {
        return -1;
      } else return 0;
    }).map((param)=>Object.entries(param)[0]);
    const searchParams=new URLSearchParams(Object.fromEntries(sortedSearchParams))
    const url = `${baseUrl}${pathName}?${searchParams.toString()}`;
    return url;
  };
  const resultUrl = urlGenerator("http://example.com", "/", [
    { width: "200" },
    { height: "250" },
    { locale: "en" },
    { toolbar_bg: "" },
    { interval: "3h" },
    { search: "react19" },
  ]);
  console.log("resultUrl=", resultUrl); 
// resultUrl= http://example.com/?height=250&interval=3h&locale=en&search=react19&width=200

```
Fix Fedora IoT upgrades when packages are layered
Tags: fedora, linux, ostree
Published: 2024-03-17 14:47:36

I recently installed Fedora IoT on my home server. I layered packages on it.

Recently an upgrade attempt failed resulting in multiple `cannot install both` messages.

I stumbled upon this bug report: https://bugzilla.redhat.com/show_bug.cgi?id=1928326

The solution is to add the `fedora-updates-archive` repository. For instance, for Fedora 39:

`sudo sh -c "curl https://src.fedoraproject.org/rpms/fedora-repos/raw/f39/f/fedora-updates-archive.repo > /etc/yum.repos.d/fedora-updates-archive.repo"`

`rpm-ostree upgrade` should now works everytime 🤗
Useful Websites for Cheat Sheets and Programming Resources
Tags: webdev, javascript, developer, programming
Published: 2024-03-17 14:41:31

> If you like this blog, you can visit my personal blog [sehgaltech](https://blog.sehgaltech.com/) for more content.


Here are some useful websites for cheat sheets and programming resources:

1. **Mozilla Developer Network (MDN)**: This is a comprehensive resource for developers, with references and guides on HTML, CSS, JavaScript, and other web technologies. (https://developer.mozilla.org)

2. **W3Schools**: This site offers free tutorials on all web development technologies, including HTML, CSS, JavaScript, PHP, SQL, and more. (https://www.w3schools.com)

3. **Stack Overflow**: This is a community of developers helping each other solve coding problems. It's a great place to find solutions to specific issues. (https://stackoverflow.com)

4. **GitHub**: This is a platform for version control and collaboration. It's also a great place to find open-source projects and libraries. (https://github.com)

5. **DevDocs**: This site combines multiple API documentations in a fast, organized, and searchable interface. (https://devdocs.io)

6. **OverAPI**: This site provides cheat sheets for many programming languages and technologies. (http://overapi.com)

7. **Codecademy**: This is an online interactive platform that offers free coding classes in 12 different programming languages. (https://www.codecademy.com)

8. **LeetCode**: This site offers a platform for learning and improving coding skills with an emphasis on problem-solving. (https://leetcode.com)

9. **freeCodeCamp**: This is a non-profit organization that consists of an interactive learning web platform, an online community forum, chat rooms, online publications, and local organizations that intend to make learning web development accessible to anyone. (https://www.freecodecamp.org)

10. **GeeksforGeeks**: A computer science portal for geeks. It contains well written, well thought and well-explained computer science and programming articles, quizzes, and practice/competitive programming/company interview questions. (https://www.geeksforgeeks.org)

Remember, the best way to learn is by doing. So, use these resources to practice and build projects.
<br>

> If you like this blog, you can visit my personal blog [sehgaltech](https://blog.sehgaltech.com/) for more content.
Is Workflow Automation The Next Big Trend?
Tags: workflow, workflowautomation, workflowautomationtools, trends
Published: 2024-03-17 14:35:17

In an era where efficiency is not just a goal but a necessity, [workflow automation](https://blog.productivity.directory/what-is-workflow-automation-1fe8fa117297) emerges as a beacon of innovation, transforming the very fabric of business operations. But what is propelling this significant shift towards automated processes?

The Catalysts Behind the Automation Revolution
==============================================

Digital Transformation: As businesses evolve, the push towards digitalization has become inevitable. Workflow automation stands at the heart of this transformation, offering a streamlined, efficient, and error-free approach to business operations.

AI and Machine Learning Integration: The infusion of AI and machine learning has revolutionized workflow automation. These technologies enable systems to tackle complex tasks, adapt to new information, and make informed decisions, thereby enhancing business processes beyond traditional capabilities.

The Remote Work Era: The global shift towards remote work has underscored the need for robust, automated workflows that support decentralized teams. Automation ensures that geographical boundaries do not impede productivity and operational efficiency.

Scalability and Growth: In the fast-paced business world, scalability is key. Automation allows businesses to expand their operations without the linear increase in workload and errors associated with manual processes.

Strategic Focus: Automating mundane tasks liberates the workforce to concentrate on strategic, value-adding activities. This shift not only boosts morale but also propels businesses toward innovation and growth.

Conclusion: Embracing the Future
--------------------------------

The trajectory towards [workflow automation](https://productivity.directory/category/workflow-automation) is not just a trend; it is a strategic move towards smarter, more efficient business practices. As organizations continue to navigate the complexities of the modern business landscape, the adoption of automated processes is becoming less of an option and more of a necessity. In this evolving work environment, the question is no longer if businesses should adopt workflow automation, but how quickly they can integrate it to remain competitive and future-ready
Add a Domain, SSL For a Laravel project
Published: 2024-03-17 14:35:09

In previous tutorial we added a Laravel project to EC2 server and get it running. Here is the link to previous tutorial.
[Deploy Laravel application with Ubuntu Nginx in EC2 server](https://dev.to/vimuth7/deploy-laravel-application-with-ubuntu-nginx-in-ec2-server-5c2a)

This tutorial is extension of that. 

First we need to connect our IP address to the domain we purchased. That can be done from the dashboard of DNS service. I use Namecheap and I have bought a domain. For that you have to go to **manage**section of your domain and then Advance DNS section add an A Record. 

An A record in DNS (Domain Name System) is a type of DNS record used to map a domain name to its corresponding IPv4 address.


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

Please make note that I have already added a site to this domain. So I used a subdomain **project** to show our site. And also we are hoping to use **test** to create test site also.

Now if you goes to the url in browser (since with subdomain it should be http://project.yourdomain.com/) you will see default nginx page.


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

> If you want to use your domain without subdomain you can replace **"project"** with **"@"** when creating the A record in dashboard

Then we need to modify the Nginx server block (sometimes referred to as a "virtual host") to tell Nginx to serve your Laravel project's public directory when requests for your domain come in.

`sudo vi /etc/nginx/sites-available/project`

Now we remove our ip address and add the domain like this

```
server {
    listen 80;
    server_name your_domain.com www.your_domain.com;
```

I added 'project.yourdomain.com' and now inside browser I see,


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

##Add SSL with Let's Encrypt

###Step 1: Install Certbot and Its Nginx Plugin
First, install Certbot and the Certbot Nginx plugin:

```
sudo apt update
sudo apt install certbot python3-certbot-nginx -y
```
 
###Step 2: Obtain a Let's Encrypt SSL Certificate

Run Certbot to automatically obtain and install an SSL certificate for your domain. Replace your_domain.com and www.your_domain.com with your actual domain name(s). Certbot will modify your Nginx configuration to serve your site over HTTPS.

`sudo certbot --nginx -d your_domain.com -d www.your_domain.com`

During the process, you'll be prompted to enter an email address for important account notifications, agree to the terms of service, and choose whether to redirect HTTP traffic to HTTPS (which is recommended).

###Step 3: Verify Certbot Auto-Renewal
Let's Encrypt certificates are valid for 90 days, but Certbot sets up automatic renewal out of the box. This happens using a cronjob automatically created by Certbot. Verify that automatic renewal is working with:

`sudo certbot renew --dry-run`

###Step 4: Reload Nginx
`sudo systemctl reload nginx`
Lottery game
Tags: python, gamedev, computerscience
Published: 2024-03-17 14:32:56

Hi, I just wanted to share a little Lottery game for the python terminal.
It is a little hard to setup because it takes a lot of keyboard work  but as a terminal game that's the best I can do.
It was made for single player but then I've added the multiplayer functionality because it was a lot boring.
I wish to get some feedback and suggestions on how can I improve it.
Below you can find the link to my git hub repository.
[https://github.com/andychild1/Lottery_game]
study volta One
Published: 2024-03-17 14:19:16

1.what is volta?
volta is a tool manager node,yarn, even some global npm binary package.
2.why do we use it?
  1.when we used global npm binary package, e.g., tsc ,npm, vue-cli 
    webpack in a project, other developer could have different 
    version of global tool. this case may lead to hard-to-identify 
    bugs or inconsistencies in behavior 
  2.Unrelated project on your machine may depend on different global binary package that mean you have to manage and switch them when you switch project [https://blog.volta.sh/2019/06/18/global-installs-done-right/](https://blog.volta.sh/2019/06/18/global-installs-done-right/)
   some expert advocate including the tool depends on your project in your dependence for example 

```
{
  "name": "autojsts",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "volta": {
    "node": "14.17.0",
    "typescript": "^5.4.2",
    "npm": "7.24.0"
  },
  "dependencies": {
    "@autojs/types-pro8": "^8.8.0",
    "jquery": "^3.7.1"
  },
  "devDependencies": {
    "mocha": "^10.3.0",
    "typescript": "3.7"
  }
}

```
typescript and mocha is including in package.json of your project
then using some _**script hash**_ in package.json to facilitate running those tools。 hash also called hash table mean {} in javascript so _**script hash**_  is  `"scripts": {
    "start": "node server.js",
    "test": "mocha"
  }`;
But they don't work for these bootrap project like create-react-app.because they have own custom script hash to run;
volta solved both of these set of problems;
you can  e.g. `volta intall node@11.0` you can use node in terminal everywhere;
С++ Урок #8
Tags: beginners, cpp, programming, tutorial
Published: 2024-03-17 14:07:23

## While loop

Привет, друзья! Сегодня мы поговорим о цикле while в языке программирования C++. Цикл `while` позволяет повторять выполнение блока кода, пока заданное условие истинно. Давайте ближе познакомимся с этим циклом и посмотрим на пример его использования.

```
#include <iostream>

using namespace std;

int main() 
{
    int count = 1;

    while (count <= 5) 
    {
        cout << "Текущее значение счетчика: " << count << endl;
        count++;
    }

    cout << "Цикл завершен." << endl;

    return 0;
}
```
В этом примере, цикл while будет повторяться, пока значение счетчика count меньше или равно 5. Каждый раз, когда цикл выполняется, мы увеличиваем значение счетчика на 1 и выводим текущее значение на экран.

Продолжайте практиковаться с циклом while и экспериментируйте с различными условиями! Если у вас возникнут вопросы, не стесняйтесь задавать их. Удачи в изучении C++! 🚀
Home page for home lab
Tags: opensource, docker, javascript, app
Published: 2024-03-17 13:51:49

When you have a large number of services accumulating in your home lab, you want to collect them all in one place. There are several ready-made solutions for this. Let's take a look at one of them - Mafl. This is my development.

Mafl is a minimalistic homepage. With the ability to easily customize the display of your services. Grouping, tags, download statuses, this is not all that Mafl can do. It is possible to connect third-party services to add dynamics to the display. The project is actively developing and new services appear in it.  

The most important thing is that absolutely everything has the same design. That looks very concise in the overall picture. The design is very similar to the list of applications on the iPad. In fact, I was guided by it.

## Getting started

To begin let's install Mafl with Docker.

docker-compose.yml
```
version: '3.8'

services:
  mafl:
    image: hywax/mafl
    ports:
      - '3000:3000'
    volumes:
      - ./config.yml:/app/data/config.yml
```

config.yml
```
title: My Home Page
services:
  Home:
    - title: Home Assistant
      description: Home automation system
      link: https://home-assistant.local
      icon:
        name: simple-icons:homeassistant
        wrap: true
        color: '#3dbcf3'
```

That's enough to start using Malf

![My Home Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1p3sxt96kzlygbukc0mh.png)

As you can see everything is easy, you just need to create 2 files and you will have your own homepage. 

If you are interested in the project, go to Github and read what features are available. I have tried to make an extensive documentation that describes all the features.

⭐ https://github.com/hywax/mafl
Kotlin Expression, 2024-03-17
Tags: kotlin
Published: 2024-03-17 13:43:30

Expression 값을 반환하면
Statement 명령을 지시

Kotlin은 모든 함수가 Expression이다

```
fun example(score : Int) : Unit {
}
```
Unit이 생략되어있음

_참조 : 유투브 강의 Code with Joyce_
MVC와 MVP와 MVVM 비교, 2024-03-17
Published: 2024-03-17 13:31:21

1. MVC
Model + View + Controller

1) 동작 순서

사용자의 Action들은 Controller에 들어오게 됩니다.
Controller는 사용자의 Action를 확인하고, Model을 업데이트합니다.
Controller는 Model을 나타내줄 View를 선택합니다.
View는 Model을 이용하여 화면을 나타냅니다.

* 참고 - MVC에서 View가 업데이트 되는 방법

View가 Model을 이용하여 직접 업데이트 하는 방법
Model에서 View에게 Notify 하여 업데이트 하는 방법
View가 Polling으로  주기적으로 Model의 변경을 감지하여 업데이트 하는 방법.

3) 특징
Controller는 여러개의 View를 선택할 수 있는 1:n 구조입니다.
Controller는 View를 선택할 뿐 직접 업데이트 하지 않습니다. (View는 Controller를 알지 못합니다.)

4) 장점
MVC 패턴의 장점은 널리 사용되고 있는 패턴이라는 점에 걸맞게 가장 단순합니다. 단순하다 보니 보편적으로 많이 사용되는 디자인패턴입니다.
5) 단점
MVC 패턴의 단점은 View와 Model 사이의 의존성이 높다는 것입니다. View와 Model의 높은 의존성은 어플리케이션이 커질 수록 복잡하지고 유지보수가 어렵게 만들 수 있습니다.

2. MVP
Model + View + Presenter

2) 동작
MVP 패턴의 동작 순서는 아래와 같습니다.

사용자의 Action들은 View를 통해 들어오게 됩니다.
View는 데이터를 Presenter에 요청합니다.
Presenter는 Model에게 데이터를 요청합니다.
Model은 Presenter에서 요청받은 데이터를 응답합니다.
Presenter는 View에게 데이터를 응답합니다.
View는 Presenter가 응답한 데이터를 이용하여 화면을 나타냅니다.

3) 특징
Presenter는 View와 Model의 인스턴스를 가지고 있어 둘을 연결하는 접착제 역할을 합니다.
Presenter와 View는 1:1 관계입니다.

4) 장점
MVP 패턴의 장점은 View와 Model의 의존성이 없다는 것입니다. MVP 패턴은 MVC 패턴의 단점이었던 View와 Model의 의존성을 해결하였습니다. (Presenter를 통해서만 데이터를 전달 받기 때문에..)

5) 단점
MVC 패턴의 단점인 View와 Model 사이의 의존성은 해결되었지만, View와 Presenter 사이의 의존성이 높은 가지게 되는 단점이 있습니다. 어플리케이션이 복잡해 질 수록 View와 Presenter 사이의 의존성이 강해지는 단점이 있습니다.

3. MVVM
Model + View + View Model

2) 동작
MVVM 패턴의 동작 순서는 아래와 같습니다.

사용자의 Action들은 View를 통해 들어오게 됩니다.
View에 Action이 들어오면, Command 패턴으로 View Model에 Action을 전달합니다.
View Model은 Model에게 데이터를 요청합니다.
Model은 View Model에게 요청받은 데이터를 응답합니다.
View Model은 응답 받은 데이터를 가공하여 저장합니다.
View는 View Model과 Data Binding하여 화면을 나타냅니다.

3) 특징
MVVM 패턴은 Command 패턴과 Data Binding 두 가지 패턴을 사용하여 구현되었습니다. 
Command 패턴과 Data Binding을 이용하여 View와 View Model 사이의 의존성을 없앴습니다.
View Model과 View는 1:n 관계입니다.
4) 장점
MVVM 패턴은 View와 Model 사이의 의존성이 없습니다. 또한 Command 패턴과 Data Binding을 사용하여 View와 View Model 사이의 의존성 또한 없앤 디자인패턴입니다. 각각의 부분은 독립적이기 때문에 모듈화 하여 개발할 수 있습니다.
5) 단점
MVVM 패턴의 단점은 View Model의 설계가 쉽지 않다는 점입니다.

_참조 : https://beomy.tistory.com/43_
Hello everyone!
Tags: android, flutter
Published: 2024-03-17 11:52:28

Hello everyone! My name is Erol, and I have been working as an Android developer for the past 6 years. During this time, I have had the opportunity to work on a variety of projects and learn from some of the best in the industry.  

One of the things that I am most passionate about is staying up-to-date with the latest trends and technologies in Android development. Recently, I have been diving deep into the world of the Compose UI library, and I am excited to share my experiences with others.  

In this blog, I will be focusing on the Compose UI library, showcasing how it can be used to create beautiful, responsive, and efficient user interfaces. I will also provide tips and best practices for using Compose, as well as real-world examples and case studies.  

Whether you are an experienced Android developer looking to learn more about Compose or just getting started, I believe this blog will provide valuable insights and help you improve your skills. So, join me on this journey, and let’s discover the power of Compose together!