teleren/devto huggingface dataset:
Limitations with Live Video SDKs based on WebRTC
Tags: webrtc, live, video, sdk
Published: 2022-06-27 04:18:10

Most of the new live video SDKs are leveraging WebRTC technology and its popularity these days. The reason why WebRTC is preferred is that it allows for an interactive user experience. However, these same SDKs can also have their limitations which developers need to be aware of at the onset. This can help them avoid some headaches down the road if they choose to use WebRTC-based SDKs frequently.

I have worked with live video SDKs such as Agora, Twilio, and Zoom and each of these comes with functionalities and features that may differ from one another. All of these SDKs can be integrated into an app just by adding a few lines of code so which makes everything easier for a developer.

All of these SDKs can be compared based on their feature-set as well as how they function. That’s my goal with this post. While I will be brief with my comparisons, if you want to read a really in-depth comparison, I suggest you take a look at this comparison over at 100ms Blog where they compare a lot of these CPaaS companies and they go deep - [Agora vs Twilio vs Jitsi vs Zoom vs 100ms](https://www.100ms.live/blog/agora-vs-twilio-vs-jitsi-vs-zoom-vs-100ms-comparison).

## Agora.io

- Agora SDK can be integrated into an app built for iOS, Android, Web, macOS, Windows, and Linux.
- UIKit libraries allow developers to create and embed a live video UI just with a few lines of code.
- Agora has its own SD-RTN which is an acronym for Software Defined Real-time Network. This is a network of over 250 data centers that Agora uses for all its product availability.
- Agora has an Extensions Marketplace where you can find extensions you can integrate with a live video app you create with the service.
- Agora allows your app to have up to 17 hosts and 10,000 participants which also includes the hosts.

## Twilio

- You can go beyond live video use cases and use their Communications API to implement messaging, video conversations, and voice chats into any UI.
- Apart from live video, you can also use Twilio and its API to generate virtual phone numbers, SIP trunking, and also messaging.
- Unlike other services and products, Twilio’s live video SDK can only be integrated with apps built for iOS, Android, and Web. No support for native Windows or macOS apps or any other platforms and frameworks such as React Native or Flutter.
- Twilio can allow you to have 50 hosts and a total of 50 participants which also includes the hosts.

## Zoom Meetings SDK
Zoom’s video conferencing SDK can be integrated with the Web, iOS, Android, Windows, macOS, and React Native apps.
The Zoom Video SDK can be customized to its full extent and developers can modify the UI as per their requirements.
Zoom can have up to 300 hosts and a maximum of 1000 participants which also includes the hosts.

## Signing off
This was a pretty brief comparison for these services and make sure to check out the hyperlinked post in order to read an in-depth comparison.
Socket event listener fires multiple times in React component
Tags: socket, react, javascript
Published: 2022-06-27 03:53:36

Here is something I've learned doing my side project that I think it's fundamental but also often overlooked. 

## Some context
The project simply contains 2 major parts: 
- Front-end: React and Materials UI
- Back-end: REST API using Express, Typescript, Firebase and Socket.io

My goal was to inform the front-end when data is updated using Socket.io so that it would try to fetch data again. 

<img width="100%" style="width:100%" src="https://media.giphy.com/media/efk0JePDdPk7kmPnJR/giphy.gif">

## Incorrect attempts
I had these incorrect code snippets that listen to socket event and fetch data again

My first attempt was this, whenever there's any re-render, `socket.on('USER_JOINED')` would registers the same `callback` function passed into it so once the event `USER_JOINED` is emitted, the same callback will fire multiple times while we only need it to execute once to reduce api calls and performance obviously.
```js
const Expense = () => {
  const [initialValues, setInitialValues] = useState(null);
  const [expense, setExpense] = useState(null);
  const { socket, toLogIn } = useContext(SWContext);
  // ...
  socket.on('USER_JOINED', (socketData) => {
    // fetch data again
  });
}

```

My second attempt was to register the callback once when the component is mounted but I still experienced multiple callback executions. It's because even after the component is unmounted, the callback is still registered with `socket` (I use one single instance of socket (Singleton pattern)). And I wouldn't have access to new state if the state was updated. 

```js
  useEffect(() => {
    socket.once('USER_JOINED', (socketData) => {
      // fetch data again
    });
  }, []);
```

## Solution

This is what works for me so far. I register a socket event handler and a clean up `socket.off` every time `expense` changes. This way there's only one socket event handler being called at a time and detached when not needed

```js 
  useEffect(() => {
    socket.once('USER_JOINED', (socketData) => {
      // fetch data again
    });
    return socket.off('USER_JOINED');
  }, [expense]);
```

I imagine this practice can also apply for similar situations like `window.addeventlistener()`

---

Take a look at my project if you're curious https://github.com/TueeNguyen/SplitWise3
req.flash is missing after res.redirect in nestJS
Tags: nestjs
Published: 2022-06-27 03:51:10

I am unable to use req.flash('success') after redirect. Its empty after redirection.

main.ts

`
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import * as session from 'express-session';
import * as passport from 'passport';
import * as FileStore from 'session-file-store';
import flash = require('connect-flash');

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  const hour = 3600000;

  app.use(
    session({
      secret: 'thisIsAHorribleSecret',
      saveUninitialized: true,
      resave: true,
      store: new (FileStore(session))({}),
      cookie: {
        sameSite: true,
        httpOnly: false,
        maxAge: hour * 1,
      },
    }),
  );

  app.use(flash());

  app.use((req, res, next) => {
    **console.log(req.flash('success'));**
    res.locals.authUser = req.user;
    res.locals.success_msg = req.flash('success');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    next();
  });

  app.use(passport.initialize());
  app.use(passport.session());

  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'src/views'));
  app.setViewEngine('hbs');
  app.set('view options', { layout: 'layouts/layout' }); // default layout

  await app.listen(3001);
}`

users.controller.ts

` @UseGuards(LocalAuthGuard)
  @Post('/login')
  async login(@Req() req: Request, @Res() res: Response): Promise<any> {
    **req.flash('success', 'Login successful!');    **
    res.redirect('/users/change-password');
    // return res.render('users/login', {
    //   layout: 'layouts/layout',
    //   vars: { errMsg: null, sucMsg: 'Found @' + req.user['name'] },
    // });
  }`
SORTING IT OUT 👨🏿‍💻
Published: 2022-06-27 03:44:07

## Selection Sort 
I recently came across this algorithm problem in my studies. 
It took me a while to try to full grasp it. So hopefully I can save someone else some time. 

##The Concept 
In Selection Sort you are taking an array and sorting them by value. Until the entire array is in numerical order.
Example: 
```
Before Selection Sort:[4,3,1,5,2]
After Selection Sort: [1,2,3,4,5]
```

##How it works 
The idea behind selection sort.
1. Take the number at the first index in the array.
2. Compare in to the rest of the numbers in the array. 
3. If another number in the array is smaller than the one we are comparing it to. The lower number is compared to the rest of the array. 
4. After going through the array the lowest number is place in the spot of the number it was compared to. The process repeats itself until all number are in order and the entire array has been iterated through. 

##Final Thoughts 
I have seen this done a number of ways.But I hope this helps break it down for you. Up to this point my favorite solution is to create an empty array and push the results into the new array after being iterated through. 

I hope this helps break it down and makes it a little bit easier to understand. If you have a process that you like please feel free to share it in the comments. 

Happy Coding 👨🏿‍💻👨🏻‍💻🧑🏾‍💻👩‍💻
Basic HTML CSS Course
Tags: html, css, course
Published: 2022-06-27 03:41:01

Hi if your interested in doing a very **Basic HTML CSS Course** then I have the ideal course for you. If you need help please feel free to message me on my Twitter Handle https://twitter.com/nftcryptomix but it will cost you some reward tokens that you can easily earn by sharing, liking and commenting on my posts. Tell me how you get on, would love to here what you think of my very Basic HTML CSS Course. Here is the link https://forms.gle/CtiHsZRPPsdpGYHs9
What's your default .editorconfig?
Tags: dotnet, tooling, discuss, opensource
Published: 2022-06-27 03:37:19

I've been using EditorConfig to bring consistency to the way that I write my code.  I also find it's been helpful to standardise the way teams I work on deliver with a similar style.  It takes a little while to find settings that work for everyone, but I'm wanting to learn from others what their default configurations are and why you chose them.

---

If you're wondering what [EditorConfig](https://editorconfig.org/) is this is taken straight from their website.

> ### What is EditorConfig?
> EditorConfig helps maintain consistent coding styles for multiple developers working on the same project across various editors and IDEs. The EditorConfig project consists of a file format for defining coding styles and a collection of text editor plugins that enable editors to read the file format and adhere to defined styles. EditorConfig files are easily readable and they work nicely with version control systems.

---

## What I Use

I've been using [RehanSaeed's](https://github.com/RehanSaeed) [EditorConfig](https://github.com/RehanSaeed/EditorConfig) project on GitHub, which is pretty great.  I have [forked](https://github.com/stphnwlsh/EditorConfig) it and made some minor customisations that work for me. 

> Extensive code style settings for C# and VB.NET have been defined that require the latest C# features to be used. All C# related code styles are consistent with [StyleCop's](https://github.com/DotNetAnalyzers/StyleCopAnalyzers) default styles, with the exception of the file header definition, which has been changed to a more modern format. All .NET naming conventions are consistent with the .NET Framework Design Guideline's [Naming Guidelines](https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/naming-guidelines).

Would love to see what others have as a default.  Please share your versions or repo links in the comments.

---

## Further Reading

- [.NET Fundamentals - Code-style rule options](https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/code-style-rule-options?view=vs-2022)
- [JetBrains - EditorConfig](https://www.jetbrains.com/help/idea/editorconfig.html)
- [DevHints - editorconfig cheatsheet](https://devhints.io/editorconfig)
- [Michael Currin - Code Cookbook - EditorConfig](https://michaelcurrin.github.io/code-cookbook/recipes/other/editor-config.html)
- [EditorConfig Specification](https://editorconfig-specification.readthedocs.io/)
Criando classes dinâmicas com SCSS.
Published: 2022-06-27 02:19:42

## Classes dinâmicas

### O problema

Para começar, vou te sugerir um problema. Você está criando um arquivo de estilos padrão, nele você quer ter classes básicas para acelerar o desenvolvimento. Se fosse fazer isso da forma mais simples (e trabalhosa) as classes personalizadas de um margin-left ficariam mais ou menos assim:

```css
.ml-1{
  margin-left: 4px;
}
.ml-2{
  margin-left: 8px;
}
.ml-3{
  margin-left: 12px;
}
```
(Note que para cada número estou adicionando 4px. Esse é o padrão de spacing do [vuetify](https://vuetifyjs.com/en/styles/spacing/#how-it-works), ferramenta que uso atualmente e que motivou esse artigo.)

Nesse caso, além de escrever muitas classes (até onde iria? ml-16?) ainda criaríamos um problema, e se um dia por exemplo eu precisar mudar meu padrão de 4px para 2px? Sim, precisaríamos alterar todas as classes!!!

Mas calma, somos uma civilização avançada e temos frameworks que entregam muitas e muitas classes com muitas alternativas. O Bootstrap e o Vuetify que citei antes são bons exemplos. Porém nem todos os casos estão cobertos, no vuetify por exemplo não tenho a opção de usar o [gap](https://vuetifyjs.com/en/styles/spacing/#how-it-works) dinamicamente, olha uma tentativa de gap com 8px aí:

```vue
<div class="gap-2">
 ...
</div>
```
Como o vuetify não me entrega isso nativamente então terei que criar, sendo assim vamos botar a mão na massa.

### A solução

Para começar, vamos precisar adicionar no nosso arquivo .scss algo que **percorra** uma lista de números e gere algo a partir dela. Simplificando, vamos fazer um **for**.

```scss
@for $i from 0 through 16 {
  ...
}
```

E agora precisamos definir nossa classe, vou chamar ela de flex-gap mas fique a vontade para definir outro nome.

```scss
@for $i from 0 through 16 {
  .flex-gap-#{$i} {
    gap: #{$i * 4}px;
  }
}
```
Lembra da regra dos 4px? ela está sendo aplicada ali no nosso loop, por exemplo, na posição 1 do nosso loop teremos:

i = 1
nome da classe = .flex-gap-1
gap = 4px

Nesse caso, teremos nossas 16 classes em apenas algumas linhas de código. Sem contar que teremos a classe flex-gap-0, você poderia usá-la para remover o gap de algum elemento caso necessário.

Agora é só usar sua classe customizada! Você pode ver um exemplo funcional [aqui](https://codepen.io/viniciusrodrigues11/pen/LYdPLQY).


Se isso te ajudou deixa um comentário aí e fique a vontade pra me dar um oi no [Linkedin](https://www.linkedin.com/in/vinicius-rodrigues-dev/)
Run failed: Deploy to Dev - development
Tags: help, aws, github, deploy
Published: 2022-06-27 03:25:06


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3jih7t17zxawivd85tg.jpeg)
I tried to deploy on GitHub several times but it failed. 

I don't know why.

Does anyone know how to solve this?

Thank you :)
Hunting space gobblers in Ubuntu OS.
Tags: ubuntu, devops
Published: 2022-06-27 03:21:51

### Introduction

The other day one of my slack channels started buzzing. It said our DGraph database was down.This seems to happen sometimes, usually restarting works. But here it wasn't!
2 seconds after a restart, it goes down again.

### No Space
One thing I noticed while I was logged into the droplet where Dgraph was hosted, was the OS wasn't able to autocomplete my commands on pressing `tab` key. So there was no space.
I was stumped, what was happening ?!? 

So I ran 

`df -h` which showed  

```
Filesystem      Size  Used Avail Use% Mounted on
.
.
/dev/vda1        49G  45G   45G   100% /
.
.
```

Whoa! What is `/dev/vda1` and why is it's usage at 100% ?

### The hunt

So I used `du -h --max-depth=1` from root `/`, and I noticed `/var` had a huge usage. 
Moved into `/var` and ran the same, now `log` had a huge usage. 
Turns out it was `syslog` that was using up the space.

### Solution

Went ahead and truncated `syslog` now, `/dev/vda1` is at `9%` usage.
We also cleaned up `/tmp`. 
And set the logs to rotate. 

### Recommendation

We didn't see a need to backup the `syslog` but it's recommended that anybody clearing it up do backup for later analysis on why it fills up, if that happens regularly. 
In our case the server has been running for quite some time, some it was just a natural accumulation of logs.

### Another potentially useful command 

`du -sh [/path]`

### References

1. How to deleted `syslog` safely. [https://stackoverflow.com/questions/35638219/ubuntu-large-syslog-and-kern-log-files]
How To Validate URL In PHP With Regex
Tags: laravel, php, validation, regularexpression
Published: 2022-06-27 03:19:15

In this article, we will see how to validate URLs in PHP with regular expressions. Also, you can implement it in laravel or PHP. here we will give you an example of validating URL with a regular expression and without regular expression. So, you can both way to implement validate URL in PHP or laravel.

When a URL is submitted from a form input by the user, it is very important to check this URL is valid or not before taking any action on it. So, here we will provide the simple PHP code to validate URL in PHP. 

So, let's see validate URL, PHP gets URL, URL validation regex laravel, valid URL using a regular expression, how to validate URL in laravel, URL validation regex PHP.

PHP provide filter_var() inbuilt function with FILTER_VALIDATE_URL filter. So, we can easily validate a URL in PHP using javascript regex or regular expression.

Example : PHP FILTER_VALIDATE_URL Filter

The FILTER_VALIDATE_URL filter validates a URL.

```
<!DOCTYPE html>
<html>
<body>

<?php
// Variable to check
$url = "https://www.techsolutionstuff.com";

// Validate url
if (filter_var($url, FILTER_VALIDATE_URL)) {
  echo("Enter URL is a valid URL");
} else {
  echo("Enter URL is not a valid URL");
}
?>

</body>
</html>
```

Possible flags of validating URL in PHP.

```
FILTER_FLAG_HOST_REQUIRED - URL must include hostname (like https://www.techsolutionstuff.com)
FILTER_FLAG_PATH_REQUIRED - URL must have a path after the domain name (like www.techsolutionstuff.com/post)
```

---
 
**_[Read Also : How to Remove Elements From Array In Javascript](https://techsolutionstuff.com/post/how-to-remove-elements-from-array-in-javascript)_**

---
 
Example : Validate URL With Regex

Above function is simply to check URL validation. If you want to check or validate URLs manually or more securely then you can use regular expression. So, here I will give an example of code.

```
<?php 

$regex = "((https?|ftp)\:\/\/)?";
$regex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?";
$regex .= "([a-z0-9-.]*)\.([a-z]{2,3})";
$regex .= "(\:[0-9]{2,5})?";
$regex .= "(\/([a-z0-9+\$_-]\.?)+)*\/?";
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+\/\$_.-]*)?";
$regex .= "(#[a-z_.-][a-z0-9+\$_.-]*)?";

$url = 'https://techsolutionstuff.com/';

if (preg_match("/^$regex$/i", $url)) {
   echo('Enter URL is a valid URL');
}
```
 
---

You might also like :

**_[Read Also : How To Generate QRcode In Laravel](https://techsolutionstuff.com/post/how-to-generate-qrcode-in-laravel)_**

**_[Read Also : Google Map With Draggable Marker Example](https://techsolutionstuff.com/post/google-map-with-draggable-marker-example)_**

**_[Read Also : How To Create Dependent Dropdown In Laravel](https://techsolutionstuff.com/post/how-to-create-dependent-dropdown-in-laravel)_**
Pytest — How to test that a function is called with specific parameters?
Tags: django, pytest, python, unittest
Published: 2023-01-14 23:21:49

---
title: Pytest — How to test that a function is called with specific parameters?
published: true
date: 2022-06-27 03:12:52 UTC
tags: django,pytest,python,unittest
canonical_url: https://bhavaniravi.medium.com/pytest-how-to-test-that-a-function-is-called-with-specific-parameters-37090f23a01d
---

Unit tests are written to test single possible units of your system. When you interact with an external system, such as reading a file from AWS S3, your tests must run without any dependency on this external system. The standard testing practice for this use case is to mock the function interacting with this external system and ensure everything else works as expected.

To illustrate this example, Let’s start with a simple Python function that reads data from a CSV and writes it to another CSV.

```
def read_data(input_path=None, output_path=None): 
    input_path = input_path or "input_data/data.csv" 
    output_path = output_path or "output_data/output.csv" 
    with open(input_path, "r") as fin: 
        with open(output_path, "w") as fout: 
            fout.write(fin.read())
```

The test case we are interested in is to ensure that the open function is called with the passed param and not the default. Since open is a Python built-in, we don't have to test its logic explicitly.

Let’s start by mocking the builtins.open built-in mock\_open function using the patch decorator.

```
import pytest
import script

from unittest.mock import patch, mock_open, call

[@patch](http://twitter.com/patch)("builtins.open", new_callable=mock_open, read_data="data")
def test_file_logic(mock_open_obj):
    read_data(input_path, output_path)
```

Next, we have to ensure the read\_data function calls the open method with the expected input and output path. assert\_has\_calls is a function of the mock object, which will check the trace of calls and ensure that the call with specific params is present.

```
import pytest 
import script 
from unittest.mock import patch, mock_open, call 

@patch("builtins.open", new_callable=mock_open, read_data="data") def test_file_logic(mock_open_obj): 
    read_data(input_path, output_path)     
    mock_open_obj.assert_has_calls([call(expected_output_path, "w"),         
                                    call(expected_input_path, "r")], 
                                    any_order=True)
```

The any\_order is important because open go through various stack trace like \_\_enter\_\_ and doesn't appear in the order.

_Originally published at_ [_https://thelearning.dev_](https://thelearning.dev/pytest-how-to-test-that-a-function-is-called-with-specific-parameters)_._
Day 1: Back to the Basics
Tags: 100daysofcode, html, css, webdev
Published: 2022-06-27 01:51:09

## Starting my journey
Today I am so happy to be starting my `#100DaysOfCode` journey! Throughout the next few months, my primary goal is to learn JavaScript and a few frameworks such as VueJS and NodeJS. While I'm at it, I figured that I would also spend some time refreshing my knowledge of HTML and CSS, which I haven't used in a few years as most of my recent work has been with OOP languages like Java.

## Contributions for today
Today I just got myself set up with a new repository and created a pretty basic site. Most of my time was spent setting up some base HTML that I will be able to add some more in-depth styling to tomorrow.

```
<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    <body>
        <h1>Day 1 of 100</h1>
        <div id="container">
            <div id="left-side">
                <p>Super excited to be starting my #100DaysOfCode 
Journey! I hope to get a good refresher 
on my knowledge of HTML and CSS and 
take a deep dive into JavaScript.
                </p>
            </div>
            <div id="right-side">
                <p>New things I hopt to Learn</p>
                <ul>
                    <li>Base JavaScript</li>
                    <li>NodeJS</li>
                    <li>REST API</li>
                    <li>VueJS</li>
                </ul>
            </div>
        </div>
    </body>
</html>
```
```
h1{
    font-family: Arial, Helvetica, sans-serif;
    text-align: center;
    font-size: 48pt;
    background-color: rgb(23,23,23);
    width: 30%;
    margin-left: auto;
    margin-right: auto;
    padding: 40pt;
    padding-left: 220pt;
    padding-right: 220pt;
    border-radius: 10pt;
}

body{
    background-color: black;
    color: white;
}
```

So far, this is a super basic webpage, but I hope to spend the next few weeks expanding upon it and adding a lot more content and styling. It really has been some time since i have done front-end development so I want to make sure I take the time I need to refresh my memory and learn some new things along the way. Hopefully, this will provide me with a great foundation to spend the majority of the challenge working with JavaScript.

{% embed https://github.com/m-mcneive/100-days-of-code %}