teleren/devto huggingface dataset:
Asynchronous PHP: An Introduction to Fibers
Tags: php, webdev, programming, coding
Published: 2023-06-10 16:14:00

With the arrival of PHP 8.1, we've been introduced to a new and exciting feature that promises to transform the way we tackle asynchronous programming in PHP - **Fibers**. It's a change that not only simplifies how we write code but also drastically improves the efficiency of our applications.

_Disclaimer: ChatGPT (GPT-4) was used to improve the wording of this post._

## What Are Fibers?
First, let's get a basic understanding of Fibers. In computer science, a fiber is a mechanism that allows us to write asynchronous code in a more straightforward, synchronous-looking style. PHP 8.1 has added native support for fibers, which means we can now handle tasks like I/O operations, network requests, or database queries more efficiently.

## Why Do Fibers Matter?
Fibers matter because they make asynchronous programming in PHP much more intuitive. Before fibers, if you wanted to write asynchronous PHP code, you'd have to rely on extensions and libraries.

Fibers, on the other hand, allow us to write asynchronous code that looks and feels like synchronous code. This makes our code easier to read, write, and maintain.

One of the biggest features of Fibers, is that they can be paused and resumed. Libraries like [AMPHP](https://amphp.org/) use this to provide efficient parallel execution. We will take a closer look at this in a different post.

## Working with Fibers: Some Tips
While fibers can simplify asynchronous PHP code, they also require you to think a bit differently about how you structure your code.

1. Catch Exceptions: Fibers throw a `FiberError` exception when they fail, so be sure to catch these exceptions in your code.
2. Be Careful with Shared State: Just like with threads, fibers can potentially lead to issues with shared state, especially if you're not careful. Make sure to properly manage shared resources to avoid race conditions.

## Conclusion
Fibers represent a significant step forward for PHP, providing developers with a powerful tool to write efficient code natively. While they require a slightly different way of thinking about your code, the benefits they offer in terms of efficiency make them well worth considering for your next PHP project.

This post only scratched the surface of possibilities with Fibers. We will look at other features (like pausing and resuming execution) in another post. 

## Addendum

Check out the PHP manual for detailed information about Fibers:
- [Fibers Overview](https://www.php.net/manual/en/language.fibers.php)
- [The Fiber class](https://www.php.net/manual/en/class.fiber.php)

_Cover Photo by <a href="https://unsplash.com/@hjrc33?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Héctor J. Rivas</a> on <a href="https://unsplash.com/photos/Nh6NsnqYVsI?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>._
Build your own Discord Chat GPT Bot.
Tags: openai, discord, python, chatgpt
Published: 2023-06-10 16:08:24

Are you looking to create a Discord bot that can interact with users using natural language processing? Then, you're in luck! In this tutorial, we'll walk you through the steps to create a Discord bot and integrate it with OpenAI.

Step 1: Create a Discord Bot
The first step is to create a Discord bot. You can create a bot by following the official Discord Developer Portal documentation. Once you have created a bot, you will receive a token that you will need to use in your code.

Step 2: Install Dependencies
To use OpenAI in your bot, you will need to install the openai Python package. You can install it using pip:
```
pip install openai
```
You will also need to install the discord.py package to interact with the Discord API:
```
pip install discord.py
```
Step 3: Create a Python Script
Next, create a Python script that will handle the bot's logic. Here's a sample script that responds to user messages using OpenAI:
```python
import discord
import openai
from discord.ext import commands

openai.api_key = "YOUR_API_KEY"

bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return

    response = openai.Completion.create(
        engine="davinci",
        prompt=message.content,
        max_tokens=60
    )

    await message.channel.send(response.choices[0].text)

bot.run("YOUR_DISCORD_BOT_TOKEN")
```

Replace YOUR_API_KEY with your OpenAI API key and YOUR_DISCORD_BOT_TOKEN with your Discord bot token.

Step 4: Run the Bot
To run the bot, save the Python script as bot.py and run the following command in your terminal:
```
python bot.py
```
This will start the bot and connect it to your Discord server.

Step 5: Test the Bot
Finally, test the bot by sending a message on your Discord server. The bot should respond with a message generated by OpenAI.

That's it! You have successfully created a Discord bot that can interact with users using OpenAI. With this powerful combination, you can create a bot that can answer questions, provide recommendations, and much more.
react.children.only expected to receive single react element child
Tags: react, reactjsdevelopment, javascript
Published: 2023-06-10 16:01:01

react.children.only expected to receive single react element child is the error which we might have faced somehow or someday. This error often occur when we try to add multiple children, or you can say tags inside the JSX code. It often occurs when we put two tags or children inside the return() of any component in simple react codes. Also, you may face this error when you use some library which expects only one child.

You can solve this error using react fragment or using <div>.

Let’s take a simple example when this problem will occur:

Read full article [here](https://reactjsguru.com/react-children-only-expected-to-receive-single-react-element-childreactchildrenonly-expected-to-receive-single-react-element-child/)
How to Clear Textbox in React JS
Tags: react, reactjsdevelopment, javascript
Published: 2023-06-10 15:57:35

In this article, we are going to learn “How to Clear Textbox in React JS”. Clearing text box is pretty easy to do, also it will be good to have in our React application. We can perform this operation in multiple ways, and we will see all of these ways to clear out a text box or input field.

Basically, we are going to see three methods to clear textbox in React JS:

- Using State
- Using Ref
- Clearing Form Inputs
[Full Article Here
](https://reactjsguru.com/how-to-clear-textbox-in-react-js/)
DEV Showcase v4
Tags: codenewbie, beginners, career, showdev
Published: 2023-06-10 15:00:00

Welcome back to the DEV Showcase - a weekly thread where you can share what you've been working on and get feedback and encouragement from the DEV community.

This is your chance to show off your latest project, share a cool hack or technique you've learned, or ask for advice and feedback from other developers. Whether you're a seasoned developer or just starting out, this is the place to connect with others and get inspired.

Here are a few questions to think about if you're stuck:

- What have you been working on lately?
- What tools or resources have you found helpful?
- Have you learned any new skills or techniques recently?
- What challenges have you faced, and how can the community help you overcome them?
- What are your goals for your project or your career moving forward?

Remember, this isn't a competition or a challenge - it's just a space to share and connect with others. So don't be shy! Share your work and get feedback and encouragement from the DEV community.

We're excited to see what you've been working on, and to support you as you continue to grow and develop your skills.
DAY 7- Minimum number of Coins
Tags: programming, learning, beginners, cpp
Published: 2023-06-10 14:57:23

Hello to anyone reading this. I am still relatively new to coding and this platform as well, so please feel free to drop any corrections/advice for me.
I am trying to do the 100 Day-Challenge of consistent coding and this is Day 7.Looking forward to a positive interaction with all of you.

## DAY 7 Problem 1: Minimum number of Coins

_Given an infinite supply of each denomination of Indian currency { 1, 2, 5, 10, 20, 50, 100, 200, 500, 2000 } and a target value N._

_Find the minimum number of coins and/or notes needed to make the change for Rs N. You must return the list containing the value of coins required. _


_Example 1:_

> Input: N = 43
> Output: 20 20 2 1
> Explanation: 
> Minimum number of coins and notes needed to make 43. 

## Intuition:
The problem is very direct. Here we have to find the minimum number of coins such that we can make the required number.
Another way we can look at this problem is that we need to find the coins with maximum value that exactly add up to this number.

## Approach:

- So what we will do in this case, is apply greedy theorem. It basically comes in handy where we make the locally best choice and reach the global optimum solution from there.
- We will take the number N and run it through the array of currencies starting from the largest till we find a value that is not greater than the existing number.
- It will be the largest number in currencies that satisfies the condition.
- Then we shall subtract that number from our currency and add the number to our list of answers.
- Running this loop till the number is 0, we get our required result.

**Code: **

```
vector<int> minCoins(int N)
    {
        int currency[10] = {1,2,5,10,20,50,100,200,500,2000};
        vector<int> ans;
        int i = 9;
        while(i >= 0)
        {
            if(N >=currency[i])
            {
                ans.push_back(currency[i]);
                N = N - currency[i];
            }
            else
            {
                i--;
            }
        }
    return ans;    
    }
```
**Complexity Analysis**
> Time Complexity: O(V)
> Space Complexity: O(1)

Since the space is only used to store the output our space complexity shall remain 1.

Here we saw today an approach of greedy algorithm. Until now, I have been doing questions randomly but I will be trying to make it in more of learning matter now.
FinOps in the Data Area!
Tags: money, devops, datascience, database
Published: 2023-06-10 14:53:16

Hi,

I have seen many strategies and concepts for controlling and reducing costs in the data area, which I summarized in a medium post.

To know more:

https://jlgjosue.medium.com/finops-in-the-data-area-d26f9aaec5b7

Thanks for reading; share this post! :)
Azure Mobile App and Its Functions
Published: 2023-06-10 14:49:37

Azure mobile apps is a very powerful tool that help one to manage azures services on the go in a mobile environment., if you are not using the mobile app, you are might not be that effective in using azure services, the following are the benefits of azure mobile usage

- It helps you access all your azure resources in your environment 
  from the convenient of your phone.
- It helps you quickly diagnose and fix issues that may arise in 
  your environment.
- Monitor resources and get Azure Service Health alerts.
- Manage your resources through Azure Cloud Shell

It’s a home build, dashboard like field that has multiples latest list and chart. Showing up services that are most important in an environment adapter. With the azure mobile app one can see recent resources that one has created, you can start and stop you VMs and other services. You can see and view service health of your resources and resource groups. 

**Azure Mobile Apps features**
The following features are important to cloud-enabled mobile development:
•       Authentication and authorization: Use Azure Mobile Apps to 
        sign-in users using social and enterprise provides. Azure 
        App Service supports Azure Active Directory, Facebook™, 
        Google®, Microsoft, Twitter®, and OpenID Connect®. Azure 
        Mobile Apps supports any authentication scheme that is 
        supported by ASP.NET Core.

•	Data access: Azure Mobile Apps provides a mobile-friendly 
        OData v4 data source that's linked to a compatible 
        database via Entity Framework Core. Any compatible 
        database can be used including Azure SQL, Azure Cosmos DB, 
        or an on-premises Microsoft SQL Server.

•	Offline sync: Build robust and responsive mobile 
        applications that operate with an offline dataset. You can 
        sync this dataset automatically with service, and handle 
        conflicts with ease.

•	Client SDKs: There's a complete set of client SDKs that 
        cover cross-platform development (.NET, and Apache 
        Cordova™). Each client SDK is available with an MIT 
        license and is open-source.

**Azure App Service features**
The following platform features are useful for mobile production sites:
•	Autoscaling: With App Service, you can quickly scale up or 
        scale out to handle any incoming customer load. Manually 
        select the number and size of VMs, or set up autoscaling 
        to scale your service based on load or schedule.

•	Staging environments: App Service can run multiple 
        versions of your site. You can perform A/B testing and do 
        in-place staging of a new mobile service.

•	Continuous deployment: App Service can integrate with 
        common source control management (SCM) systems, allowing 
        you to easily deploy a new version of your mobile service.

•	Virtual networking: App Service can connect to on-premises 
        resources by using virtual network, Azure ExpressRoute, or 
        hybrid connections.
Mastering GitHub Pages: Creating Stunning Websites with GitHub
Published: 2023-06-10 14:41:33

Are you ready to showcase your projects, portfolios, or personal websites to the world? GitHub Pages is an incredibly powerful and user-friendly tool that allows you to publish and host static websites directly from your GitHub repositories. In this comprehensive guide, you'll learn everything you need to know to create stunning websites using GitHub Pages to [surah-taghabun-pdf](https://islampdf.com/surah-taghabun-pdf/)

From setting up your GitHub Pages repository to choosing a theme and customizing your site, this book covers the entire process of creating professional-looking websites. You'll explore different design options, including layout, color schemes, and typography, to ensure your website reflects your unique style and vision.
Secure Your Next.js Application: Essential Security Practices and Tools
Tags: webdev, nextjs, security, react
Published: 2023-06-10 14:38:33

🚀 Pro Tip: Security should be a top priority when developing Next.js applications. Let's explore essential practices and tools to safeguard your application and protect user data!

🔒 Tip 1: Implement Input Validation and Sanitization
Always validate and sanitize user input to prevent security vulnerabilities like cross-site scripting (XSS) and SQL injection attacks. Utilize libraries like **validator** or **express-validator** to validate and sanitize user inputs effectively.

```
const { body, validationResult } = require('express-validator');

app.post('/login', [
  body('username').isEmail().normalizeEmail(),
  body('password').isLength({ min: 6 }),
], (req, res) => {
  // Validate input and handle login logic
});
```

🔐 Tip 2: Protect Sensitive Data with Encryption
Ensure sensitive data such as user passwords, API keys, and tokens are properly encrypted. Utilize encryption libraries like **bcrypt** or **crypto** to secure sensitive information and mitigate the impact of data breaches.

```
const bcrypt = require('bcrypt');
const saltRounds = 10;

const hashedPassword = bcrypt.hashSync(plainTextPassword, saltRounds);
```

🛡️ Tip 3: Use Helmet for HTTP Security Headers
The helmet middleware helps set essential HTTP security headers to enhance your application's security posture. Enable headers like **X-XSS-Protection**, **Strict-Transport-Security**, and **Content-Security-Policy** to mitigate common web vulnerabilities.

```
const helmet = require('helmet');

app.use(helmet());
```

🔒 Tip 4: Employ JWT for Authentication and Authorization
Implement JSON Web Tokens (JWT) for secure authentication and authorization in your Next.js application. JWT provides a stateless, token-based authentication mechanism that ensures the integrity and confidentiality of user data.

```
const jwt = require('jsonwebtoken');

const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
```

🔍 Tip 5: Regularly Update Dependencies and Libraries
Keep your project dependencies and libraries up to date to leverage the latest security patches and bug fixes. Regularly review and update your project's dependencies using tools like **npm audit** to identify and address any security vulnerabilities.

💡 By following these essential security practices and utilizing the right tools, you can strengthen the security of your Next.js application and protect your users' data. Stay proactive, stay secure!
Coding Period GSoC'23 | Week 1 + 2
Tags: gsoc, javascript, programming
Published: 2023-06-10 14:18:35


The Google Summer of Code 2023 Coding Period kicked off on May 29th, following a community bonding period of approximately three weeks. As I have completed the second week I am happy to share my accomplishments and future plans with you all.

> Checkout my previous blog about [My Journey to GSoC'23](https://dev.to/prerna0202/my-journey-to-gsoc2023-656)

### **Community Bonding Period (May 4th - May 28th)**

During the community bonding period, we had two meetings. The first meeting involved all the contributors and mentors, where we introduced ourselves and had a discussion on how we work in the GSoC program. The second meeting was specifically with my project mentors, where we discussed the project's timeline and the tasks of the project. Also, I must admit, I was quite nervous during the second meeting and ended up rambling a bit! ;-)

### **Work done (29th May - 11th June)**

I initially started with the task of "implementing a safe recovery from simulator crashes". However, After having a discussion, we decided to complete the task of "implementing a state machine for the simulator to handle uncaught exception errors" before working on the simulator crash recovery task. So, I put the crash recovery task on hold and began implementing the state machine.

In state machine task, I created two states for the simulator that are "normal" and "error". When there are no errors in the circuit, the simulator remains in the normal state. However, as soon as an uncaught exception error occurs, the state transitions from normal to error. In the error state, the user can only delete or undo components in the circuit. So, Once the user removes the erroneous component, the simulator returns to the normal state and resumes its proper functioning.

After completing the state machine implementation, I resumed working on the recovery from simulator crash task. Previously, when a simulator crashed, all the circuit data would be lost. To address this, I developed an autosave feature where the circuit's data is saved in the local storage every time we click on the simulator. This allows us to restore the circuit to a previous state after a simulator crash.

### **Pull Requests:**

- [Implemented safe recovery from simulator crash](https://github.com/CircuitVerse/CircuitVerse/pull/3767)
- [Implemented state machine for simulator](https://github.com/CircuitVerse/CircuitVerse/pull/3781)

### **So, what's next?**

I will be working on the task of "Making a better system for high-impedance values handling" and then moving on to "expose helpful functions while debugging the circuit." My aim is to complete these tasks by the end of the fourth week.

As I wrap up the initial weeks of coding, I'm filled with enthusiasm to continue learning alongside CircuitVerse. The journey ahead is filled with excitement, and I can't wait to see what lies ahead!🚀

![Dancing cat](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r7ts2sfqktx1jn1pyr39.gif)
Python: argparse action store
Tags: python, beginners, programming
Published: 2023-06-10 13:58:51

As we already saw in this series, `argparse` is a built-in Python module that can help you build friendly CLI tools:

{% embed https://dev.to/jmau111/python-why-using-argparse-11j7 %}

It's quite straightforward, but some parts, like actions, may be confusing for beginners.

## Create on/off flags

It's not uncommon to need some on/off flag in our CLI commands:

```Python
import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="My client")
    parser.add_argument('-v', '--verbose', action='store_true')
```

The [action](https://docs.python.org/3/library/argparse.html#action) parameter allows setting how arguments should be handled:

>'store', 'store_const', 'store_true', 'append', 'append_const', 'count', 'help', 'version'

It might seem self-explanatory, but you might struggle to understand how to use values like `store_true`.

Don't be confused. `store_true` will default to `False`. If you need to set a default value to `True`, use `store_false` instead.

## Create arbitrary actions

If you need something like `--exec` / `--no-exec`, you can leverage `BooleanOptionalAction` (Python 3.9):

```Python
parser.add_argument('--exec', action=argparse.BooleanOptionalAction)
```
Need a suggestion on the approach I should take to implement the multi-version surveys system.
Published: 2023-06-10 13:28:07

I have an existing survey feature in my application. As standard, a survey has many questions, and many answers are submitted against a question by different users. There is a result model per survey for a user to see his report for submitted answers.

Now I need to extend this feature into a multi-version part. A new survey version will be created whenever a change is made. It could be text change or adding/deleting a question in it. With this, I need to make sure the users previously assigned a survey still see their own version. So if the question was added to a survey. They should not see it. The new version of surveys will be available for new assignments only.

I need a suggestion on what approach I should take to extend this feature with these requirements. I have already looked at (and used in the past) the PaperTrail gem and also looked at [active_snapshot](https://github.com/westonganger/active_snapshot).

Think of a scenario where I had Question A in Version 1 of the survey but that question got deleted from it now. A user was previously assigned Version 1 of the survey and he is answering Question A. How should I manage the Database structure to manage the associations in such cases?