teleren/devto huggingface dataset:
Send SMS with Node.js App
Tags: javascript, programming, twilio, node
Published: 2022-06-24 09:58:28

In this article, we are going to learn how we can send SMS or WhatsApp messages with your _Node.js app_.

> _Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser._

---

## Approach:
To send SMS and WhatsApp messages we are going to use the [Twilio](https://www.twilio.com/). The Twilio helps us to send SMS, make Calls within our Node.js app. So first, we will install the Twilio package with npm or yarn.

**Get the Twilio Credentials:** 

1. Go to [https://www.twilio.com/](https://www.twilio.com/)

2. Create a new account for trial.

3. Copy the account SID, auth token and provided phone number.

![Screenshot 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zvoagu6ux0ialva8ocgx.png)
 

**Create Node.js Application:** You can start creating Node.js project by following command: 

```shell
npm i
```
or

```shell
yarn
```
 _💡 Note: This will create a node_modules folder._



**Install the required package**: Now we will install the [twilio](https://www.npmjs.com/package/twilio) and [dotenv](https://www.npmjs.com/package/dotenv) package using the below command:

```shell
npm i twilio dotenv
```
or 

```shell
yarn add twilio dotenv
```
_💡 Note: This will install twilio and dotenv package for your project._



**Create following files in route directory:**

- `app.js`
- `.env`

_Your project structure should look like this:_
![Screenshot 3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x52o0oaje3vyrh3b3rah.png)
 


**Make Configuration**: add following code in `.env` file.

```js
TWILIO_SID=your-account-sid
TWILIO_AUTH_TOKEN=your-account-token
```
_⚠ WARNING: replace `your-account-sid` and `your-account-token` with your twilio credentials copied above!_
 


**To Send SMS:** add following code in your `app.js` file.

```js
require('dotenv').config()
const accountSID = process.env.TWILIO_SID;
const accountToken = process.env.TWILIO_AUTH_TOKEN;

const client = require('twilio')(accountSID, accountToken);

// send a sms
client.messages.create({
    body: 'Hi, this is a test sms!',
    from: 'your-provided-phone-number',
    to: 'the-recipient-phone-number'
}).then(message => console.log(message));
```
_⚠ WARNING: replace `your-provided-phone-number` with your provided dummy twilio phone number copied above! and `the-recipient-phone-number` with the phone number whom you want to give a sms._

### Explanation:
In the above example first, we are using twilio service to send SMS. After that, we are installing twilio package along with dotenv for configuration with the credentials provided by twilio.
 
**Steps to run the application**: Run the below command in the terminal to run the app.

```
node app.js
```

## Output:

![Screenshot 4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/48hj530ac6hczcdp2npk.png)




> _**💖 SUPPORT: Hit like if you like this article and feel free to ask queries!**_
Remove extra space from text with regex - Python
Tags: regex, text, cleaning
Published: 2022-06-24 09:22:59


Easy way to remove extra spaces from text, paragraph with regex in python

- Import regular expression packages

```Python
import re
```

- Remove extra spaces from text.

```Python
text = "  Hi python   is a case   sensitive language.    "
text = re.sub(' +', ' ', text)
print("text : ", text)
```

Explanation for above piece of code :

1. re.sub() - is a function in used to replace sub-string with another sub-string.
2. first argument in sub function is regular expression to find sub-string expression that will replace, 
   i.e: ' +'      (space with +) capture number of spaces.
3. second argument is what will replace in place of first argument, 
   i.e: ' '       (one single space to replace with number of spaces)
4. third argument is your piece of text variable that you want to clean.
A little thought about hacking
Published: 2022-06-24 09:05:58

How to bypass some protections, that's the question.

my English is poor.

code is very important,Whether you write the code by yourself or look at the source code.

After reading the code a lot, I seem to have come to a realization.

I'm excited for the next hack.

I know that if I want to write scripts or codes, I may use several computer languages, because I once wrote a small code in c language plus php, and used it to send data to the server, although it was not very successful.
Test Images in React with Jest
Tags: jest, javascript, testing
Published: 2022-06-24 09:24:18

---
title: Test Images in React with Jest
published: true
date: 2022-06-24 8:22:42 UTC
tags: Jest,JS,Testing
canonical_url: https://robertmarshall.dev/blog/test-images-in-react-with-jest/
---

I was recently asked how to test that an image is displayed in a React component. This short piece outlines a solution using Jest and a small touch of React Testing Library.

--------

This article was originally posted (and is more up to date) at https://robertmarshall.dev/blog/test-images-in-react-with-jest/

--------

With images, there are two things we can test for. That the image `src`  has been populated correctly, and the image `alt` tag has been populated correctly.

## The Example

We have a small component that renders an image depending on what argument is passed in.

```javascript
// This is the component we will test.
export const ImageComponent = ({ size }) => (
  <img
    src={`https://www.example.com/image-${size}.png`}
    alt={`The image alt tag for the ${size} image`}
  />
);

// This is where it is rendered in the app.
export default () => <ImageComponent size="big" />;
```

## How To Test Images in React with Jest

The tests need to be able to confirm that when the argument changes, the image that is rendered within the component is correct. Using Jest alongside React we can check for the correct `alt` and `src` values.

The Jest test would be as follows:

```javascript
import { render } from '@testing-library/react';
import { ImageComponent } from './';

describe('The image component', () => {
  test('alt contains correct value', () => {
    render(<ImageComponent size="large"/>)
    const testImage = document.querySelector("img") as HTMLImageElement;
    expect(testImage.alt).toContain("The image alt tag for the large image");
  })

  test('src contains correct value', () => {
    render(<ImageComponent size="large"/>)
    const testImage = document.querySelector("img") as HTMLImageElement;
    expect(testImage.alt).toContain("https://www.example.com/image-large.png");
  })
});
```

For more React and Jest hints and tips take a look at the [React Category](https://robertmarshall.dev/blog/category/reactjs/), and [Jest Testing Category](https://robertmarshall.dev/blog/category/jest/)!

Hopefully this helped you, and if you have any questions you can reach me at: [@robertmars](https://twitter.com/robertmars)
100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 24 (File, Directories and Paths)
Published: 2022-06-24 08:57:31

- Calling a file
````python
with open("high_score.txt", mode="a") as file:
    contents = file.read()
    print(contents)

```

- Absolute and relative paths
````python
# Absolute path
# with open("/Users/Tumatauenga/OneDrive/Desktop/my_file.txt") as file:
#     contents = file.read()
#     print(contents)

# Relative path
with open("../../../OneDrive/Desktop/my_file.txt") as file:
    contents = file.read()
    print(contents)

```

- Mail Merge

main.py
invited_names.txt
starting_letter.txt

- main.py
````python
PLACEHOLDER = "[name]"

with open("./Names/invited_names.txt") as names_file:
    names = names_file.readlines()
    print(names)

with open("./Input/Letters/starting_letter.txt") as letter_file:
    letter_contents = letter_file.read()
    for name in names:
        stripped_name = name.strip()
        new_letter = letter_contents.replace(PLACEHOLDER, stripped_name)
        with open(f"./Output/ReadyToSend/letter_for_{stripped_name},txt", mode="w") as completed_letter:
            completed_letter.write(new_letter)

```
- invited_names.txt
Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph

- starting_letter.txt
Dear [name],

You are invited to my birthday this Saturday.

Hope you can make it!

Mike
Язык программирования Си. Глава(Chapter) 1
Tags: c, russian
Published: 2022-06-24 08:40:40

**1.** Центральный Процессор(_Central Processing Unit_), короче ЦП(_CPU_), компьютера выполняет основную вычислительную(_Computing_) работу, помещая и выполняя программы или по другому, набор инструкций(_Instruction Set_) из Оперативного Запоминающего Устройства(ОЗУ), иначе Памяти с Произвольным Доступом(_Random Access Memory_(_RAM_)) в регистр комманд(_Instruction Register_).
![CPU](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tg8uqgwyopl56vse7t0k.png)

**2.** Язык программирования Си - императивный(_Imperative_) - с точным указанием последовательных инструкций -, высокоуровненвый(_High-level_) - с доступностью абстрактных указателей и пользовательских типов данных, то есть структур и объединений -, процедурный(_Procedural_) - с функциями и без классов - и аппаратно-ориентированный(_Bare Metal-Oriented_) - со свободным доступом к памяти.

**3.** Стандарты языка С: K&R C, ANSI/ISO C89/C90, C99, C11 и более новые.

**4.** Исходный файл(_Source File_) - код на языке Си с расширением(_Extention_) `.c` и `.h`, объектный файл(_Object File_) - код на машинном языке с указанием на библиотечный код с расширением `.o` или `.obj` и исполняемый файл(_Executable File_) - запускаемый код со встроенным библиотечным кодом на машинном языке с расширением `.exe` или `.out`.

**5.** Процесс компиляции(_Compilation_) компилятором(_Compiler_) - преобразование исходного файл в объектный файл; также процесс компоновки(_Linking_) компоновщиком(_Linker_) - объединение объектного кода(_Object Code_) используемых функций из библиотеки с объектным файлом исходного файла и встраивание кода запуска(_Start-Up Code_) программы для различных Операционных Систем(_Operation System_), то есть ОС(_OS_).
![Compilation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uwrzwmk2sij1tfd8ysnn.png)

**6.** Библиотека(_Library_) - набор объектных, то есть заранее скомпилированных файлов разных функций для компоновки с расширением `.a`.

> Язык программирования Си 6 издание. Стивен Прата
> C Primer Plus 6th edition. Stephen Prata
Are you making these 4 mistakes in automation?
Published: 2022-06-24 08:05:35

[Hyperautomation](https://fastpathautomation.com/) has begun to expand on more and more levels, especially recently, when there are more and more IT-managed [automation](https://fastpathautomation.com/) initiatives. With this information, should we pay attention to how the whole automation process works and what are the wishes we are trying to fulfill by implementing automation?

The benefits consist in improving the speed, the costs, and the quality of the work done; all these must be based on a well-developed plan so the data involved or the processes won't be harmed.
The desires related to automation are understandable, but we must not lose sight of the importance of correctly analyzing the future automation process. It is safer to rely on the resources you already have within the company. The chances of success can increase when you know your business and what you want to achieve in the end, but if we focus on what could go wrong? The types of mistakes encountered are through the implementation method, the approach, and impact.

We will take, in turn, the most common automation mistakes, and in each of them, we try to develop a little concept to be as straightforward as possible in the end on what is good to avoid.

Employees create a group atmosphere, build friendships, develop goals, and communicate. That's what a team looks like. Their opinion is critical when discussing the automation of processes. Different questions might come up, but here the HR teams must make sure that they present the situation in the most honest way possible, but at the same time, assure the employees that everything is under control and their job won't suffer. Still, only changes will be made to make their daily work easier.

Automation also means changing the process. You can't expect only by replacing handmade tasks to achieve the desired result, so human minds can still look at the big picture, anticipate possible problems, and find the best ways to achieve them—the purpose for which automation was desired from the beginning.

Many processes in organizations are not well developed; over time, fluctuations occur, and it is unclear whether it deserves automation at that point. In such situations, it is not worth wasting time and effort on these processes but instead focusing on more precise areas and repetitive processes. Instead, if automation is necessary, we can start with creating and implementing clearly defined rules and directions.

We always want to find solutions that are fast and easy to implement. However, automation will not be able to meet all the expectations that managers have, which can be a common mistake in the strong desire to implement. When automation intervenes, it is necessary to understand that the old systems that already work will have to be replaced, not kept in the same form.
Automating Serverless Best Practices Checks
Tags: aws, awscloud, bestpractices, lenses
Published: 2022-06-24 07:40:51

Amazon Web Services (AWS) 𝙇𝙚𝙣𝙨𝙚𝙨:
(1) extend the guidance offered by AWS Well-Architected to specific industry and technology domains, such as serverless applications.
(2) 𝙘𝙖𝙣 𝙗𝙚 𝙪𝙨𝙚𝙙 𝙩𝙤𝙜𝙚𝙩𝙝𝙚𝙧 with the AWS Well-Architected Framework and the six pillars to 𝙚𝙣𝙨𝙪𝙧𝙚 they are building in 𝙖𝙡𝙞𝙜𝙣𝙢𝙚𝙣𝙩 𝙬𝙞𝙩𝙝 𝙗𝙚𝙨𝙩 𝙥𝙧𝙖𝙘𝙩𝙞𝙘𝙚𝙨.
https://lnkd.in/e-yitdpH

Through the use of 𝙙𝙚𝙫𝙚𝙡𝙤𝙥𝙚𝙧 𝙩𝙤𝙤𝙡𝙨 such as Dashbird, it’s possible to 𝙖𝙪𝙩𝙤𝙢𝙖𝙩𝙚 𝙖 𝙡𝙤𝙩 𝙤𝙛 𝙩𝙝𝙚 𝙗𝙚𝙨𝙩 𝙥𝙧𝙖𝙘𝙩𝙞𝙘𝙚 𝙘𝙝𝙚𝙘𝙠𝙨 which the lenses reference to provide a continuous compliance approach to best practice aligned with a 𝙨𝙚𝙧𝙫𝙚𝙧𝙡𝙚𝙨𝙨 𝙧𝙚𝙫𝙞𝙚𝙬.
https://dashbird.io/blog/

Thanks to Tim Robinson and Stephen Salim for their blog post
𝘼𝙪𝙩𝙤𝙢𝙖𝙩𝙞𝙣𝙜 𝙎𝙚𝙧𝙫𝙚𝙧𝙡𝙚𝙨𝙨 𝘽𝙚𝙨𝙩 𝙋𝙧𝙖𝙘𝙩𝙞𝙘𝙚𝙨 𝙬𝙞𝙩𝙝 𝘿𝙖𝙨𝙝𝙗𝙞𝙧𝙙’𝙨 𝙎𝙚𝙧𝙫𝙚𝙧𝙡𝙚𝙨𝙨 𝙒𝙚𝙡𝙡-𝘼𝙧𝙘𝙝𝙞𝙩𝙚𝙘𝙩𝙚𝙙 𝙄𝙣𝙨𝙞𝙜𝙝𝙩𝙨
https://lnkd.in/eQ5UK-7J

𝙎𝙩𝙖𝙮 𝙩𝙪𝙣𝙚𝙙 𝙗𝙮 𝙛𝙤𝙡𝙡𝙤𝙬𝙞𝙣𝙜
https://lnkd.in/eA-uJNP


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xwaftfq4l3csnwp5dff.png)
How to handle same endpoints with different http methods ??
Tags: nextjs, webdev, javascript, react
Published: 2022-06-24 07:40:08

Suppose a endpoint in nextjs like /api/events
and corresponding directory must be like /pages/api/events.js

If i send request at /api/events with get method, it will run say handler1

If i send request at /api/events with post method, it will run say handler2 

Don't know, How to do this ??
Need help with code review 😕
Published: 2022-06-24 07:33:34

i am developing react native apps for 3 years now and i work as a freelancer so i don't have any leadership above to help me with the code i write. basically i complete the task but i don't know if the code i wrote is correct in terms of programming rules (memory optimisation, complexity). is there any way where i can take reference or put my piece of code so that any experience person can tell me how the can be improved more and most importantly what problems my existing code can produce which i am unaware of. all suggestions are wellcome, just looking to get better at what i do🙂.
United Airlines refund policy
Published: 2022-06-24 07:17:44

Passengers can make use of United Airlines' 24-hour refund policy to secure an instant reimbursement for a canceled flight ticket. Passengers can obtain a refund by simply filling out the form and including their booking reference ID and other details. To find out more about [United Airlines refund policy](https://www.bookunitedairlines.com/blog/united-airlines-refund-policy/), visit our website or contact us at +1-855-745-1194.
Crushing Job Interviews(DSA) - Sorted Squared Arrays
Tags: beginners, webdev, tutorial, devops
Published: 2022-06-24 07:15:06

### The Question
##### Difficulty: **Kind of Medium**

Write a function that takes in a non-empty array of integers that are sorted in ascending order and returns a new array of the same length with the squares of the original integers also sorted in ascending order.

**Sample Input**
```javascript
array = [1, 2, 3, 5, 6, 8, 9]
```

**Sample Output**
```javascript
[1, 4, 9, 25, 36, 64, 81]
```
##### Optimal Space & Time Complexity:
O(n) time | O(n) space - where n is the length of the input array

### The Thinking

It's important to ask your interviewer that can you mutate the original array given to you or you have to create a duplicate array.


So there are two way's to solve this, first is :

* Iterate through the array
* Square each number, and
* Add to new array
* Sort the array

This solution is simple but the we can do better.

In the second solution, we use pointers.

> P.S: Pointers in arrays context are used to keep track of the position while iterating through it.

So what we will do is:

* Iterate through the  array,
* Keep track of the first and the last position of the array using pointers,
* Compare the absolute value of the items the pointers are pointing at.
* IF the first index value is greater, then place that value at the index we are iterating through in the duplicate array we created and increment the first pointer by 1.
* ELSE, place the other pointer arrays value at the current index we are iterating through and decrease the second pointer by 1.

Sounds Confusing ? Well it is, but I'm sure you'll get a better understanding by looking at code once. I'll not be writing down the first solutions since it's very simple and I believe you can easily come up with the solutions. But if you still want it, drop down a comment and I'll post it.

### The Solution (2nd one)
```javascript
function sortedSquaredArray(array) {
  const toReturn = [...array]
  let smallerValueIdx= 0
  let largerValueIdx = (array.length) - 1
  for (let idx = array.length - 1; idx >=0; idx--) {
    const smallerVal = array[smallerValueIdx]
    const largeVal = array[largerValueIdx]

    if (Math.abs(smallerVal) > Math.abs(largeVal)) {
      toReturn[idx] =smallerVal * smallerVal
      smallerValueIdx++
    }
    else{
      toReturn[idx] = largeVal * largeVal
      largerValueIdx --
    }
  }
  return toReturn;
}
```

Got any doubt's ? Got a better solutions ? Drop a comment below and let's start a discussion.

Follow me on instagram for more awesome content on coding: https://www.instagram.com/dhruvindev
Custom React Hook to Check Nested Child Component Types
Tags: javascript, typescript, react
Published: 2022-06-24 06:25:08

---
title: Custom React Hook to Check Nested Child Component Types
published: true
description: React hook for getting the type of any nested child component
tags: javascript, typescript, react
---

A component may want to make assumptions about its children to satisfy layout constraints. This custom hook helps you to determine if there is any nested child with a specific type, and returns you the nested child itself to apply any layout constraints to it while rendering.

## Usage

```js
import useChild from 'use-child';

const Car = props => {
  const [wheelExists, WheelComponent] = useChild(props.children, Wheel);
  const [engineExists, EngineComponent] = useChild(props.children, Engine);

  return (
    <div>
      {wheelExists && WheelComponent}
      {engineExists && EngineComponent}
    </div>
  );
};

const Wheel = () => {
  return <div>I am a wheel</div>;
};

const Engine = () => {
  return <div>I am an engine</div>;
};
```

{% github ozanyurtsever/use-child %}
This Week In Python
Tags: python, discuss
Published: 2022-06-24 05:51:43


**Fri, June 24, 2022**


This Week in Python is a concise reading list about what happened in the past week in the Python universe. 


## Python Articles


- [Raising exceptions or returning error objects in Python](https://lukeplant.me.uk/blog/posts/raising-exceptions-or-returning-error-objects-in-python/)
- [Mapping the World of Package Management](https://enigma.com/blog/post/mapping-the-world-of-package-management) – Packaging is maybe one of Python's weaker spots. This articles tries to shed some light on the current landscape
- [When Python can’t thread: a deep-dive into the GIL’s impact](https://pythonspeed.com/articles/python-gil/) –  In many cases Python can only run one thread at a time, due to what’s know as the Global Interpreter Lock (“GIL”)
- [Getting the Stack Trace of a Running Python Program](https://levelup.gitconnected.com/getting-the-stack-trace-of-a-running-python-program-f6e2f156f53a) – Creating a simple strack trace utility in Python
- [Utilising caching in your applications](https://www.django-cms.org/en/blog/2022/06/14/caching-your-models/) – Speed up you Django app by using caching


## Projects

- [PyBoy](https://github.com/Baekalfen/PyBoy) – Game Boy emulator written in Python
- [pedalboard](https://github.com/spotify/pedalboard) – A Python library for manipulating audio
- [grumpy](https://github.com/google/grumpy) – Grumpy is a Python to Go source code transcompiler and runtime
- [urllib3](https://github.com/urllib3/urllib3) – Python HTTP library with thread-safe connection pooling, file post support, user friendly, and more
- [diagram](https://github.com/mingrammer/diagrams) – Diagram as Code for prototyping cloud system architectures
#angular #httpinterceptor
Published: 2022-06-24 06:14:03

I have 5 components in my angular app,I have implemented a global interceptor which displays the loading spinner in all the componenents.
Now my first component makes an api call and takes too much time to get the data,where as my other components gets the data from API in < 10seconds. so the catch is if i click on first component and then immediately on any other component then the loading symbol keeps on loading even if the data in the specific component has loaded,it is stopping after the first component has gets it's data...for example if the first component takes 100 seconds to load the data and the 2nd componnet takes 10seconds to load the data,then if i click on 1st component and then 2nd component then the 2nd component loads it's data in 10 seconds and the loading symbol loading for 100 seconds even if the 2nd component has already gets its data,how to solve this,any thoughts or ideas would be highly appreciable