teleren/devto huggingface dataset:
record VC audio in discord!
Tags: discord, python
Published: 2022-07-16 10:28:31

I have been working on this side project where I can record the audio of a vc with the help of discord.py

in this post ill talk about how did I achieve this. you can also check out the [YouTube video](https://www.youtube.com/watch?v=Bgy6gTPF4Gw&t=7s&ab_channel=realhardik18) i made about this.

before we get to the fun part, you will have to make and set up a bot via the [discord developer portal](https://discord.com/developers). you will also need to have a fairly good amount of knowledge about discord.py and how it works!

now once you have a bot with a basic test command working, we can import the required modules!
``` python
import discord
from discord.ext import commands
from discord.ext.audiorec import NativeVoiceClient #important!
from secrets import token #bot's secret token
import random
```
now to record audio in the vc, we need to first make the bot join the vc in which the user is, which can be done using this command:
```python
@client.command()
async def join(ctx: commands.Context):
    channel: discord.VoiceChannel = ctx.author.voice.channel
    if ctx.voice_client is not None:
        return await ctx.voice_client.move_to(channel)
    await channel.connect(cls=NativeVoiceClient)
    await ctx.invoke(client.get_command('rec'))
```
as you can see, this command invokes a command named 'rec'. this 'rec' command is the main command which we will use to record the audio in the vc!

```python
@client.command()
async def rec(ctx):
    ctx.voice_client.record(lambda e: print(f"Exception: {e}"))
    embedVar = discord.Embed(title="Started the Recording!",
                             description="use !stop to stop!", color=0x546e7a)
    await ctx.send(embed=embedVar)
```
we start the recording and then send an embed notifying the user that the recording has started!
the recording can be stopped and saved by using this command
```python
@client.command()
async def stop(ctx: commands.Context):
    if not ctx.voice_client.is_recording():
        return
    await ctx.send(f'Stopping the Recording')

    wav_bytes = await ctx.voice_client.stop_record()

    name = str(random.randint(000000, 999999))
    with open(f'{name}.wav', 'wb') as f:
        f.write(wav_bytes)
    await ctx.voice_client.disconnect()
```
over here the bot basically gets all the audio data in the form of bytes and then writes al the data into a wav file(this file's name is randomly generated), which is then saved to the system
now since the bot's job is done, it leaves the vc!

some extras:
you can also add commands to make sure there is someone in the vc before the bot joins the vc, or uploading the audio file to a server on the cloud. all these points are discussed in my [youtube video](https://www.youtube.com/watch?v=Bgy6gTPF4Gw&t=8s&ab_channel=realhardik18), feel free to check it out!

all the code for this project is available on github too!
{% embed https://github.com/realhardik18/discord.py-voice-recorder  %}
Codewars Challenge Day 5: JS, Python + SQL and PHP
Tags: javascript, python, sql, php
Published: 2022-07-16 10:25:17

## JavaScript & Python

### Details
**Name Kata:** [Sum of Digits / Digital Root](https://www.codewars.com/kata/541c8630095125aba6000c00/)
**6kuy**
**Description:** Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.
**Example:**
```
    16  -->  1 + 6 = 7
   942  -->  9 + 4 + 2 = 15  -->  1 + 5 = 6
132189  -->  1 + 3 + 2 + 1 + 8 + 9 = 24  -->  2 + 4 = 6
493193  -->  4 + 9 + 3 + 1 + 9 + 3 = 29  -->  2 + 9 = 11  -->  1 + 1 = 2
```

### My Solutions

#### Python
```python
def digital_root(n: int) -> int:
    n_str = str(n)
    while len(n_str) > 1:
        r = 0
        for i in range(len(n_str)):
            r = r + int(n_str[i])
        n_str = str(r)
    return n if (n >= 0 and len(str(n)) == 1) else r
```

#### JavaScript(TypeScript4)
```javascript
export const digitalRoot = (n:number):number => {
    return String(n).length == 1 
      ? n : digitalRoot(
        String(n).split("").map((n) => Number(n)).reduce(
          (previousValue, currentValue) => previousValue + currentValue, 0)
      )
};
```

## PHP

### Details
**Name Kata:** [You're a square!](https://www.codewars.com/kata/54c27a33fb7da0db0100040e/)
**7kuy**
**Description:** You like building blocks. You especially like building blocks that are squares. And what you even like more, is to arrange them into a square of square building blocks!

However, sometimes, you can't arrange them into a square. Instead, you end up with an ordinary rectangle! Those blasted things! If you just had a way to know, whether you're currently working in vain… Wait! That's it! You just have to check if your number of building blocks is a perfect square.
Task

Given an integral number, determine if it's a square number:

    In mathematics, a square number or perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself.

The tests will always use some integral number, so don't worry about that in dynamic typed languages.
**Example:**
```
-1  =>  false
 0  =>  true
 3  =>  false
 4  =>  true
25  =>  true
26  =>  false
```

### My Solutions

```php
function isSquare(int $n): bool {
  return sqrt($n) == (int)sqrt($n) ? true : false;
}
```

## SQL

### Details
**Name Kata:** [SQL Basics: Truncating](https://www.codewars.com/kata/594a8fa5a2db9e5f290000c3)
**7kuy**
**Description:** Given the following table 'decimals':
decimals table schema

    id
    number1
    number2

Return a table with a single column towardzero where the values are the result of number1 + number2 truncated towards zero.

### My Solutions
```sql
SELECT TRUNC(number1 + number2) AS towardzero FROM decimals
```
Resources For Learning To Code
Tags: discuss, community, beginners, career
Published: 2022-07-16 10:09:33

## Introduction

Hey there 👋 how are you pals? back again, today with some exciting resources to get started with.

So in the previous posts we talked about:

- Advantages of being a self-taught developer 🤩.
- Disadvantages of being a self-taught developer 😥.
- Solutions for the disadvantages 😎.

Here now in this post our main focus will be on answering the questions like Where do I get started? Where can I learn to code? etc. resources
Free and paid as well.

Lets get started with paid stuff first [Good things at the end 😝😜]

<hr>

## Paid Resources

Paid resources are paid and can't be used as free 😂😅 lol

So lets get a little serious

There many great paid resources like:

1) [Udemy](https://www.udemy.com/)
2) [upGrad](https://www.upgrad.com/)
3) [Unacademy](https://unacademy.com/)

I personally haven't used any of the paid resources except Udemy. I have explored upGrad a little and it seemed like it has degrees in different fields offered by many reputed institutes/universities.

## Unpaid Resources

<hr>

There are plenty of unpaid resources, some on them even gives you the certificate after completing the course.

1) [Freecodecamp](https://www.freecodecamp.org/learn) (my mentor/ personal favourite)
2) [GeeksforGeeks](https://www.geeksforgeeks.org/)
3) [W3schools](https://www.w3schools.com/)
4) [MDN](https://developer.mozilla.org/en-US/) (Mozilla Developer Network)
5) [YouTube](https://www.youtube.com/) (The University of everything)
6) [Stack Overflow](https://stackoverflow.com/) (Ocean of questions and Answers)
 
These are just a few names which I have used. I am really sorry if I did not mention the resource you are using (Yeah!! I know it hurts sometimes😣).

Out of these Freecodecamp will give you certificates on completion of the course and everything is free there. They also have a [YouTube channel](https://www.youtube.com/c/Freecodecamp) where they share many useful courses. They have a [Forum](https://forum.freecodecamp.org/) as well where people post there issues and get the solution by other people there.

W3schools also has great interactive documentation of different courses, they offer exercises and quiz for every course. At the end there is a optional exam which you can attend by paying specified amount and you will also receive the certificate of the course.

> YouTube is great for learning anything

Stack Overflow is Golden Goose for every developers, really amazing.

That's pretty much it. All of these places will help you reach your destination and yeah to be consistent, you only need to give a little dedication and discipline 😎.

Stay tuned for next post 😈 Yes next post you read it correct haha 😂😅. The writer inside me is awaken I guess 😅. You can share other resources in comment section to help our fellow learners. 

Stay happy, Keep hustling,
Signing off Meet Bhalodiya,

Peace ✌
How can add checkbox in input from enter?
Tags: javascript, beginners, webdev, programming
Published: 2022-07-16 09:59:12


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbjpmsxkabmgypku8trg.png)`<html>
    <head>

    </head>
    <body>
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zlwsq2aj7e3rtxqi5r6f.png)
 Search: <input onkeyup="myFunction()" type="search" id="mySearch" value="">
<p>Click the button to display the value of the value attribute of the search field.</p>
<p id="demo"></p> 
 <table id="table">
   <tr>
   <td></td>
   </tr>
 </table>
 <script>
    function myFunction()
{
  if(event.keyCode === 13){
    debugger;
    var table = document.getElementById("table");
    var row   = table.insertRow(-1);
    var date  = row.insertCell(0);
    table.appendChild(row); 
    date.innerHTML  = document.getElementById("mySearch").value;
  
    //insert checkbox//
    function editTd()
    {
    var rows = document.getElementById('table').rows;
    for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
      for(var j =0; j<row.cells.length; j++){
        var inputs = document.createElement("input");
        inputs.type = "checkbox";
      rows.cells[j].appendChild(inputs);
      };
    };
    };      
    editTd();
  
  }
 
}
 </script>
    </body>
</html>`
2262. Leetcode Solution in Python3
Tags: python
Published: 2022-07-16 09:57:55

```
class Solution:
    def appealSum(self, s: str) -> int:
        dp = [0]*len(s)
        dp[0] = 1
        haxi_map = collections.defaultdict(int)
        haxi_map[s[0]] = 0
        for i in range(1, len(s)):
            dp[i] = i + 1 + dp[i-1]
            
            if s[i] in haxi_map:
                dp[i] -= (haxi_map[s[i]] + 1)
            haxi_map[s[i]] = i
        #print(haxi_map)
        #print(dp)
        return sum(dp)
```
#leetcode
#weekly contest
Here is the link for the problem.....
https://leetcode.com/contest/weekly-contest-291/problems/total-appeal-of-a-string/
Steps to deploy the laravel application on the Digital Ocean server
Tags: laravel, digitalocean, deploy, hosting
Published: 2022-07-16 09:56:36


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cslgpagaubo9nmvj9ubh.png)
I am considering your application is ready for release, and you want to deploy your application on the server. In this article, we deploy the laravel application on the Digital Ocean. Follow the steps to deploy the laravel application.

## Goto grab droplet for your project:

DigitalOceans is the best platform to host the laravel application. It supports managed Kubernetes clusters and "Droplets" feature and Cloud firewalls, scales up and down, or migrates between Droplets. you can check out the plans. Click Here

## Create Project on the DigitalOcean Platform and generate a public key

Add a Project name with a type of project. choose a plan, CPU options, and data center region.

[Read More] (https://bit.ly/3IGJQqe)
2261. Leetcode Solution in Java
Tags: java
Published: 2022-07-16 09:55:02

```
class Solution {
    public int countDistinct(int[] nums, int k, int p) {
        // k is number divisible elements
        // p is pivot
        Set<Long> numSubarray = new HashSet<>();

        for (int i = 0; i < nums.length; i++) {
            int count_div = 0;
            long hashCode = 1;
            for (int j = i; j < nums.length; j++) {
                hashCode = 199L * hashCode + nums[j];
                if (nums[j] % p == 0) {
                    ++count_div;
                }
                if (count_div <= k) {
                    numSubarray.add(hashCode);
                } else {
                    break;
                }
            }
        }
        return numSubarray.size();
    }
}
```
#leetcode
#weekly contest
Here is the link for the problem.....
https://leetcode.com/contest/weekly-contest-291/problems/k-divisible-elements-subarrays/
2260. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-16 09:52:43

```
class Solution {
public:
    int minimumCardPickup(vector<int>& cards) {
          int n = cards.size();
          if(n == 1) return -1;
        
          unordered_map<int, vector<int>> mp;
        for(int i = 0; i<n; i++){
            mp[cards[i]].push_back(i);
        }
        
        int ans = INT_MAX;
        
        for(auto i : mp){
            vector<int> tmp = i.second;
            if(tmp.size() <= 1) continue;
            
            int cur_ans = INT_MAX;
            for(int i = 1; i < tmp.size(); i++){
                int diff = tmp[i] - tmp[i-1] + 1;
                if(diff < cur_ans){
                    cur_ans = diff ;
                }
            }
              ans = min(ans, cur_ans);
        }
        
        return ans == INT_MAX ? -1 : ans;
    }
};
```
#leetcode
#weekly contest
Here is the link for the problem.....
https://leetcode.com/contest/weekly-contest-291/problems/minimum-consecutive-cards-to-pick-up/
2259. Leetcode Solution in Cpp
Tags: cpp
Published: 2022-07-16 09:50:39

```
class Solution {
public:
    string removeDigit(string number, char digit) {
        for (int i = 0; i < number.size() - 1; ++i) {
            if (number[i] == digit && number[i + 1] > digit) {
                return number.substr(0, i) + number.substr(i + 1);
            }
        }
         int lastIn = number.find_last_of(digit);
        return number.substr(0, lastIn) + number.substr(lastIn + 1);
        
        
    }
};
```

#leetcode
#weekly contest
Here is the link for the problem.....
https://leetcode.com/contest/weekly-contest-291/problems/remove-digit-from-number-to-maximize-result/
AWS S3?
Tags: aws, cloud, programming, javascript
Published: 2022-07-16 09:48:26

## What is AWS S3?

Amazon S3 (Simple Storage Service) provides object storage, which is built for storing and recovering any amount of information or data from anywhere over the internet. It provides this storage through a web services interface. While designed for developers for easier web-scale computing, it provides 99.999999999 percent durability and 99.99 percent availability of objects. It can also store computer files up to 5 terabytes in size.

## AWS S3 Benefits

- **Durability** :  S3 provides 99.999999999 percent durability.

- **Security** : S3 offers an impressive range of access management tools and encryption features that provide top-notch security.

- **Low cost** : S3 lets you store data in a range of “storage classes.” These classes are based on the frequency and immediacy you require in accessing files. 

- **Scalability** : S3 charges you only for what resources you actually use, and there are no hidden fees or overage charges. You can scale your storage resources to easily meet your organization’s ever-changing demands.

- **Availability** : S3 offers 99.99 percent availability of objects

- **Flexibility** : S3 is ideal for a wide range of uses like data storage, data backup, software delivery, data archiving, disaster recovery, website hosting, mobile applications, IoT devices, and much more.

- **Simple data transfer** : You don’t have to be an IT genius to execute data transfers on S3. The service revolves around simplicity and ease of use.

## AWS Buckets and Objects

An **object** consists of data, key (assigned name), and metadata. A **bucket** is used to store objects. When data is added to a **bucket*8, Amazon S3 creates a unique version ID and allocates it to the **object**.

## How Does Amazon S3 work?

First off, a user creates a bucket. When this bucket is created, the user will specify the region in which the bucket is deployed. Later, when files are uploaded to the bucket, the user will determine the type of S3 storage class to be used for those specific objects. After this, users can define features to the bucket, such as bucket policy, lifecycle policies, versioning control, etc.
Portfolio Project
Tags: javascript, nextjs, portfolio, webdev
Published: 2022-07-16 09:47:17

Hey people, I'm trying to build my portfolio website and this what i have so far **[Portfolio](https://prajyu.vercel.app/)**. If you have any suggestion or ideas write it in the comment section and let me know. _(and who knows it may be inspiration for other dev's out there)_
Media Streaming with ReactPHP
Tags: php, react, laravel, vue
Published: 2022-07-16 09:02:27

# Whats' Up with ReactPHP

When I first heard of [ReactPHP](https://reactphp.org), a few years ago, it looked very promising. 
Providing timers, asynchronous processing, streams, and sockets, all within PHP. 

However, in recent years, there seems to be stagnation. While you see commits, you seldom see any publication. 

The [Framework X](https://framework-x.org) is an attempt to make ReactPHP into a micro framework, but I see little mention of it. 

Overall, whenever I tried using ReactPHP, I found that it is better to use [Laravel](https://laravel.com) and its rich ecosystem.

# Streaming with ReactPHP

[Building Video Streaming Server with ReactPHP](https://sergeyzhuk.me/2017/07/17/reatcphp-http-server/) was a nice approach to building a streaming server with ReactPHP, which I could not see how to do as simple in Laravel. 

A recent article [Streaming ReactPHP in ReactJS](https://agiroloki.medium.com/streaming-reactphp-in-reactjs-2cda05de3b73) revived the topic and showed how you integrate with [React](https://reactjs.org).

This got me thinking about how far you can go with ReactPHP in terms of streaming. 

# A Media Server Design

A media server has three components:

1. Streaming of media files
2. Web interface to select files, login users, and control playback.
3. A backend to manage files and users

While ReactPHP is very good for the streaming part, web application programming with ReactPHP is not common and lacks an ecosystem of build tools and libraries. 

This is especially apparent if you want to build a dynamic modern interface, the way you do nowadays with a Single Page Application (SPA).

So it would seem natural to wrap the ReactPHP in a Laravel application. Laravel is well suited for managing files, including file upload, and has built-in user management.
  
 The web interface will be built by either some SPA framework such as React or [Vue](https://vuejs.org) or [Laravel Livewire](https://laravel-livewire.com) and [AlpineJS](https://alpinejs.dev).
Did you ever leave uncommitted changes in vscode to the delight of your colleagues? Then vote this feature request :)
Tags: vscode
Published: 2022-07-16 09:45:39

Hi all,

if you think vscode could and should warn you (optionally) when closing a window or switching to another project, with uncommitted or unpushed changes, then: 

please add a "thumbs up" reaction to the very first comment (the description) of this issue which is a backlog candidate:

https://github.com/microsoft/vscode/issues/152625
Avoid Else Statement In Your Function To Write a Clean Code
Tags: javascript, programming
Published: 2022-07-16 09:32:31

When I took programming class in college, one of fundamental topic is **control flow**, including `if - else if - else` statement.

```js
if (a === 'one') {
  // do something here
} else if (a === 'two'){
  // do something here
} else {
  // I said, do something!!
}
```

My lecturer taught me in a good way how to write and implement _if statement_. But I just remembered, I learn that if statement before I learn about function.

It is okay if we use `else` outside function or in top level code, moreover we are still need `else`.
```ts
const sayHi = true;
if (sayHi) {
  console.log("Hi!")
} else {
  console.log("....")
}
```
In a function that returned something, _in most cases_ we don't even need the else statment. Here is the example.
```ts
function func(isRich: boolean){
  if (isRich) {
    return "I am rich!";
  } else {
    return "Can you give me a money, please?";
  }
}
```
Since function will stop executing lines of code after `return` is written, we can just remove else statement.
```ts
function func(isRich: boolean){
  if (isRich) {
    return "I am rich!";
  }
  // intepreter, compiler, or anything won't execute codes bellow
  return "Can you give me a money, please?";
}
```
When we need to check another condition that has been specified we might use `else if` statement and write the logic inside the block.
```ts
function grade(score: number) {
  if (score >= 90) {
    return 'A';
  } else if (score >= 80) {
    return 'B';
  } else if (score >= 70) {
    return 'C';
  } else if (score >= 60) {
    return 'D';
  } else {
    return 'F';
  }
};
``` 
Or we can write it with `switch-case`.
```ts
function grade(score: number){
  switch (true) {
    case score >= 90:
      return 'A';
    case score >= 80:
      return 'B';
    case score >= 70:
      return 'C';
    case score >= 60:
      return 'D';
    default:
      return 'F';
  }
};
```
Two examples above work fine. But I prefer this style.
```ts
function grade(score: number){
  if (score >= 90) return 'A';
  if (score >= 80) return 'B';
  if (score >= 70) return 'C';
  if (score >= 60) return 'D';
  return 'F';
};
```
Thank you for reading!
How to integrate Allure report with cypress
Tags: cypress, javascript, testing, automation
Published: 2022-07-16 08:55:26


Why is Allure Reporting to Cypress?

  

-   Cypress does not have an inbuilt reporting solution
-     Easy to install
-     Allure reports provide great presentational diagrams
-     Clear and nice reporting UI
-     Can easily investigate test run

https://qaautomationlabs.com/how-to-integration-of-allure-report-with-cypress/