teleren/devto huggingface dataset:
String to integer aloi
Published: 2022-03-19 18:28:09

Lets say the string we are given is '4123'. Lets's start by figuring out how we are going to get to that number itself.

This way is cheeky. 

4123. When we look at any number we can do the first number times 10 plus then 2nd number. In this case

```
((4 * 10 + 1)* 10 + 2) * 10 + 3)
________
  {41}
((4 * 10 + 1)* 10 + 2) * 10 + 3)
________________
  {410}
((4 * 10 + 1)* 10 + 2) * 10 + 3)
______________________
        {412}
((4 * 10 + 1)* 10 + 2) * 10 + 3)
_________________________________
                   {4123)
```

Every time we multiply the number by ten we get a 0 in place that we can then change using addition. We keep adding numbers to the right hand side each iteration until we've got the entire number.

Another way to look at it is this.

```
41 ->
410 -> 
 +12 ->
____
412. 
*10 ->
4120
  +3 ->
____
4123
```

Now, let's get into how we're going to solve this problem. It's very simple with the code, and you'll be kicking yourself if you've been struggling with it once you see it.

1) turn the str into a number with parseInt method
2) if the number isn't a number, return 0
3) if the number is less then the lower bound, return the lower bound
4) if the number is greater the the higher bound, return the higher bound
5) if we don't hit any of these condition return the parseInt'd number


```
const aloi = (str) => {
 let num = parseInt(str) 
 if (Number.isNaN(num)){
 return 0
}
 if (num < -2**31) {
 return -2**31
}
 if (num > 2**31-1) {
 return 2**31-1
}
 return num
}
```
Terminal komandalari | Part 3
Tags: beginners, bash, linux, ubuntu
Published: 2022-03-19 18:11:07

### `date`

- `echo $(date '+%d-%m-%Y')` - ushbu komanda hozirgi sana (dd-mm-yyyy ) ko'rinishida ekranga chop etadi

- `mkdir $(date '+%d-%m-%Y')` - ushbu komanda orqali hozirgi sana (dd-mm-yyyy) ko'rinishida yangi papka yaratadi

- `code.main` - bu komanda joriy papkadagi main.cpp degan fayl (yo'q bo'lsa) yaratib uni **vscode**da ochadi.

- `code .` - ushbu komanda **vscode** dasturida worksspace (ishchi maydon) sifatida ochadi.

### `g++`

- Bu komanda C++da yozilgan kodlarni kompilyatsiya qilishda ishlatiladi.
- `g++ main.cpp` - bu komanda joriy papkadagi **main.cpp**dagi kodni kompilyatsiya qiladi  va by default `a.out` fayl yaratadi.
- `g++ main.cpp -o dastur` - ushbu komanda **main.cpp** faylidagi kodni kompilyatsiya qilib, uni `dastur` degan yangi papkaga saqlaydi.
- `g++ main.cpp -o dastur && ./dastur` - ushbu komanda orqali yuqoridagi amallarni birdaniga bajarishimiz mumkin.
Terminal komandalari | Part 2
Tags: beginners, foundation, linux, terminal
Published: 2022-03-19 18:08:13

### `Terminalda buyruqlar`


- ### `pwd` (print working directory) - Qaysi papkada turganimizni ko'rsatadi. 

- `mkdir` yangi papka yaratish uchun ishlatiladi.
`mkdir Test` - Test degan yangi papka yaratiladi.

### `ls` - ushbu buyruq biz turgan papka ichida joylashgan fayl va papkalarni ekranga chiqaradi.
- `ls -help` - bu parametr orqali dastur nima ish bajarishini ko'rishimiz mumkin.
- `ls --quot name` - papka va fayl nomlarini "Qo'shtirnoqqa" oladi.
- `ls --size` - fayl va papkalarning hajmini chiqaradi.
- `ls -a` - yashiringan fayl va papkalarni ekranga chiqaradi.
- `ls -l` - fayl va papka nomlarini ro'yxat ko'rinishida chiqaradi.
Yuqoridagi ikkita buyruqni bitta qilib, ya'ni
- `ls la` - yozish orqali yashiringan fayl va papka nomlarini ro'yxat ko'rinishida chop etishimiz mumkin.
- `ls -la | grep Do` - ushbu buyruqlar orqali "|" - dasturda chop qilinayotgan malumotlarni ekranga emas boshqa dasturga yo'naltirish mumkin.
- `ls ..` - komandasi orqali `HOME` manziliga o'tishimiz mumkin.
Important algorithms and problems every programmer should know..!!
Tags: programming, algorithms, codereview, codequality
Published: 2022-03-19 18:04:01

📌 **Sorting Algorithms -** Bubble sort - Insertion sort - Quick sort - Merge sort - Heap sort - Counting sort

📌 **Searching algorithms -** Linear search - Binary search (with all its variants) - Breadth-first search (BFS) - Depth-first search (DFS)

📌 **Array algorithms -** Kadane's algorithm - Floyd cycle detection algorithm - KMP algorithm - Quick select algorithm

📌 **Stack -** Tower of Hanoi problem - Infix to postfix conversion - Parenthesis matching

📌 **Tree and Heap algorithms -** Creation of heap - Implementation of Priority queue - Traversals - preorder, inorder, postorder

📌 **Graph algorithms -** Kruskal's algorithm - Prim's algorithm - Dijkstra's algorithm - Bellman ford algorithm - Topological sort algorithm

📌 **Dynamic programming -**(Recursion+Memoization) - Fibonacci series - Longest common subsequence - Matrix chain multiplication

📌 **Other -**Huffman coding for compression - Bit vector - Disjoint set data structure (Union find)
 


_`Thank You so much for getting to the end of the article! Let me know your thoughts below in comments `_
Diary of a developer #0: why development?
Published: 2022-03-19 17:41:41

This is a more relaxed post, a presentation for you to know a little about my work and my experiences before my posts, so let's go.

Not unlike you, I'm a technology lover and since I was 12 I've been working on hardware, luckily there was an electronic waste right next to my house so I don't even need to explain the rest.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/51kl5ek7hzg3xtukskth.gif)

A few years later I ended up moving to another area, still within information technology, the development area. Years of working with hardware made me wonder how combinations of 0 and 1 could transmit information across components, when I realized I was studying binaries, then decimals and so on.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3x2eheacdphodm7iaz41.jpeg)

My first language of study was python, which I even have a special affection for, but everything seemed very complex to me, it was really a new world that every day reveals itself more complex, there is no unique way of programming, despite being part of From an exact science, the way a developer can approach a challenge varies according to their knowledge, time, techniques that are acquired over time.

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

I don't want to linger, I think I gave a good introduction and just like the indices of an array, this is article number #0. In the next few days I will be posting some content that I have already reserved some curiosities, debates, and a little of the day to day of a programmer who seeks to improve his knowledge in his stack.
CSS Text Portrait
Tags: css, img, webdev
Published: 2022-03-19 17:34:33


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

```css
p {
  background: url('https://photostockeditor.com/asset/1080/16/1607/PSE154.jpg') center no-repeat;
  background-size: cover;
  width: 110%;
  -webkit-background-clip: text;
  -webkit-text-fill-color: rgba(255, 255, 255, 0);
  line-height: 0.80;
  text-transform: uppercase;
  font-size: 0.5em;
}
```

{% codepen https://codepen.io/wdrfree/pen/vYpGQwM %}
<script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>

[Image Source](https://unsplash.com/@photostockimages)
Bash script to backup directories and mysql databases from source file to any location
Tags: bash, linux, backup, rsync
Published: 2022-03-19 17:33:17

This script can create a tar archive of all directories listed inside a .txt file and
can exclude others directories from exclude.txt file. 

Also it can backup all mysql databases in separated .sql files if [backup-mysql script](https://github.com/alfiosalanitri/backup-mysql) is installed.

The tar archive will be copied to any directory like usb device if there are available free space. 

[Download from github](https://github.com/alfiosalanitri/backup-to-device)
Print your GitHub contributions as an artwork
Published: 2022-03-19 17:19:14


I made a tool to generate a GitHub contribution artwork https://getoss.art/

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2namkoza935vetilndr0.png)
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4g85ek9lcjavst9o3h53.jpg)
#66 Days of Data
Tags: python, datascience, 100daysofcode, ankitgupta
Published: 2022-03-19 17:03:03

## **Learning Python**  👨‍💻

D 35 of #66daysofdata 📈

Today I have learnt Python Built-in Functions ✌️
Too lengthy topic to cover!

Checkout 👉 [My #66 Days of Data timeline on Github](https://github.com/mrankitgupta/66DaysOfData)

Say me Hi! 
I'll be glad to connect on 
👇

**Twitter** @ [Mr_AnkitGupta01](https://twitter.com/Mr_AnkitGupta01)

**Github** @ [MrAnkitGupta](https://github.com/mrankitgupta)
Simple Flask App
Tags: flask, beginners, python, programming
Published: 2022-03-19 17:00:46

# Simple Flask App

## Introduction
In this post I'll show you the code for a simple flask app which collects data in a form and gives it back to you.

---

## Structure
Your files and folder needs to be structured like below:
```
-- main.py
-- templates
   |__ index.html
```

---

## Code
### `main.py`
```py
from flask import Flask, request, redirect, render_template
app = Flask(__name__)

@app.route('/')
def index():
  return render_template("index.html")

@app.route("/form", methods=['GET', 'POST'])
def form():
  if request.method == 'POST':
    fname = request.form['fname']
    lname = request.form['lname']
    return f"Your full name is {fname} {lname}"
  else:
    return redirect("/")

app.run(host='0.0.0.0', port=8080)
```

### `templates/index.html`
```html
<!DOCTYPE html>
<html lang="en-GB">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Simple Flask App</title>
  </head>
  <body>
    <h1>Simple Flask App</h1>
    <form method="POST" action="/form">
      <input placeholder="first name" name="fname" autocomplete="off" required><br>
      <input placeholder="last name" name="lname" autocomplete="off" required><br>
      <button>submit</button>
    </form>
  </body>
</html>
```

---

## Looks

The website will look something like this:

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

---


## Conclusion
After putting all of this code together, you will have a fully functional flask app!
Thanks for reading and if you want to view the code together, check it out [here](https://github.com/VulcanWM/simple-flask-app)!
Wordpress add menu in footer
Tags: wordpress, wp, beginners, webdev
Published: 2022-03-19 17:00:17

In wordpress we can create our custom menu and can place at any place in our wordpress website.

First of all paste this code in your functions.php file located at website_root_path/wp-content/themes/your_theme/functions.php

```php
register_nav_menus( array(
	'secondary' => __( 'Footer Menu', 'generatepress' ),
) );
```
generatepress’ is your theme name and ‘Footer Menu’ is your menu name. You can name it whatever you want and ‘secondary’ is the menu id you can also name it whatever you want.

Now open your wordpress dashboard and navigate to Appearance -> Menus and add your menu items to the Menu you have created.

Now we will show the our menu in wordpress theme let say we want to show menu in footer. Then we will paste the code given below to our footer.php file located at website_root_path/wp-content/themes/your_theme/footer.php

```php
wp_nav_menu( array( 
    'theme_location' => 'secondary', 
    'container_class' => 'footer-menu-class' ) );
```
In the code above ‘secondary’ is the menu id. And we have added in register_nav_menus ‘footer-menu-class’ is the class of our menu container used to styling or adding css to our menu. There are also many options to our function [wp_nav_menu](https://developer.wordpress.org/reference/functions/wp_nav_menu/).

---
Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please [visit my website](https://www.w3courses.org/tutorials/).

Thanks:)
Happy Coding:)
Curl get and post api in php
Tags: php, tutorial, beginners, curl
Published: 2022-03-19 16:40:17

Modern websites is using APIs for many purposes. Like for sending SMS, for sending EMAILs, for cloud storage, for mobile app APIs, for payment gateways. And also for integrating some native features of mobile apps or websites.

You can run easily your API using [php module CURL](https://www.php.net/manual/en/ref.curl.php). And it is almost available for all servers localhost or global servers.

There are two types of mostly used API methods GET and POST. Some others are PUT, PATCH, UPDATE, DELETE. But you can run your application by using these two GET or POST methods.

## If you want to run GET Method API then you can use the code given below.

```php
$url = 'https://apiprovider.com';

$headers =array();

$headers[] = 'X-Authorization-Token:fgfdg4545hKUertefgdds';

$ch = curl_init();

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_URL,$url);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$results=curl_exec($ch);

curl_close($ch);
```

## If you want to run POST Method API then you can use the code given below.

```php
$headers =array(); 

$headers[] = 'X-Authorization-Token:fghjfj4erJGFDgwrhgfhgfh';

$ch = curl_init();

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_URL,$url);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

curl_setopt($ch, CURLOPT_POST, 1);

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

$search_results=curl_exec($ch);

curl_close($ch);

return $search_results;
```
In the both code above $url is your API Url, $headers is your API headers, $data is your array post data passing to API and $results is your API results or output. So, just use this code and follow your API provider’s documentation.

Now using these codes, you can run CURL in php, run SMS API in php, run Email API in php, run Payment Gateway API in php, run Google API in php, run Cloud API in php, run AWS API in php, run WordPress API in php and also Image Manipulation API in php.

And also you can use this code for any PHP framework like Laravel, Cakephp, Codeigniter or php based CMS like WordPress, Magento, Joomla etc.

This method is also helpful to run REST API in php, XML API in php or JSON API in php.

---
Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please [visit my website](https://www.w3courses.org/tutorials/).

Thanks:)
Happy Coding:)
Create dynamic certificates in PHP
Tags: php, beginners, tutorial, module
Published: 2022-03-19 16:29:30

We will use the PHP GD Library or extension which will provide us the functions to manipulate our images dynamically.

## Uses of PHP GD Library:

- To create dynamic certificates
- Create dynamic captcha
- Creating dynamic charts
- Creating dynamic Reports
- We can create the watermarks on our images
- We can resize the images, increase or decrease the quality of images, change image mime type or extension
- Optimize or Compress Images

Here we will create a dynamic certificate in PHP by using PHP GD Library.

First of all we have to check is PHP GD Extension is enabled or not. Use the code below and check is gd enabled.

```php
<?php

/*Checking the PHP GD Extension Enabled or Not*/

phpinfo();

```

![PHP Info](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/29vbfcp2pbrjlrzgkxpm.jpg)

Now we will create the certificate dynamically by using php gd library.

```php
/*Using PHP GD Library to process images and creating dynamic certificates, captcha, reports etc.*/

/*Creating Certificate Dynamically*/

//Set the Content Type
header('Content-type: image/jpeg');

// Create Image From Existing File
$jpg_image = imagecreatefromjpeg('certificate.jpg');

// Allocate A Color For The Text
$white = imagecolorallocate($jpg_image, 54, 12, 110);

// Set Path to Font File
$font_path = 'font.ttf';

$name_text = "Chetan Rohilla";

$date_text = date('jS F,Y');

$signature = imagecreatefrompng('signature.png');

imagettftext($jpg_image, 26, 0, 480, 400, $white, $font_path, $name_text);

imagettftext($jpg_image, 20, 0, 220, 670, $white, $font_path, $date_text);

/*signature on image*/
imagecopy($jpg_image, $signature, 780, 620, 0, 0, 200, 58);
/*signature on image*/

// Send Image to Browser
imagejpeg($jpg_image);

// Clear Memory
imagedestroy($jpg_image);
```
After adding this code, you have to upload certificate.jpg file, signature.png file and font.ttf file in the folder where your php file is located.

Download [font.ttf](https://www.w3courses.org/wp-content/uploads/2021/01/font.zip)

That’s it Now you can create dynamic certificates in php, watermarks in php, captcha in php, charts in php or process images in php.

---

Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please [visit my website](https://www.w3courses.org/tutorials/).

Thanks:)
Happy Coding:)
Paracetamol.js💊| #81: Explica este código JavaScript
Tags: javascript, beginners, spanish, webdev
Published: 2022-03-19 15:58:51

## **Explica este código JavaScript**

```js
const numeros = [1,2,[3,4],5,6,[7,8],9,0];
console.log(numeros.flat()); // ?
```

A. `Error`, el método `flat` no existe.
B. `[1,2,3,4,5,6,7,8,9,0]`
C. `[1,2,3,4,5,6,[7,8],9,0]`
D. `[1,2,[3,4],5,7,8,9,0]`

Respuesta en el primer comnetario.

---
Composable Tailwind
Tags: tailwindcss, react, css, javascript
Published: 2022-03-19 15:54:53

[Tailwind CSS](https://tailwindcss.com) is one of the most popular [Atomic CSS](https://www.smashingmagazine.com/2013/10/challenging-css-best-practices-atomic-approach/) frameworks. The API is excellent, adding minimal mental overhead and no code bloat once set up. Their documentation is extensive, covering their API, as well as nearly all other use cases imaginable.However, there is a relatively common issue that is not mentioned – one that is inherent to all class-based styling solutions in JSX[^1]. This issue is **composing styles**.

Utility classes work great when there is a single source of truth for styling. However, once faced with more complex scenarios such as _conditional styling_ or _prop-based styling_, one can easily end up with a mess of _[template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals):_

```tsx
<div
  className={`m-4 p-4 ${condition1 == true ? 'text-white' : 'text-black'} ${
    condition2 == true ? 'bg-white' : 'bg-black'
  }`}
/>
```

The above can quickly become unreadable.

Fortunately, there are other ways we can approach this. As I have previously proposed in my [guide to CSS Modules](/articles/css-modules), we can instead reach for _string concatenation_ to compose classes. The above example would now look like this:

```tsx
<div
  className={[
    'm-4 p-4',
    condition1 == true ? 'text-white' : 'text-black',
    condition2 == true ? 'bg-white' : 'bg-black',
  ].join(' ')}
/>
```

This approach brings a few clear benefits to the table:

- More readable code
- Grouping by source
- Clear order of execution[^2]

Let us apply this to a real-world example. We'll have a button with two variants (primary and secondary), with an escape hatch for the possibility of customising the button, should that be necessary (this happens more often than you would expect).

```tsx
// Button.tsx
type ButtonProps = {
  variant: 'primary' | 'secondary'
  className?: string
}

export const Button: React.FC<ButtonProps> = ({
  children,
  property1,
  property2,
  className,
}) => (
  <button
    className={[
      'rounded border border-black px-8 py-4',
      variant == 'primary' ? 'bg-black' : 'bg-inherit',
      className,
    ].join(' ')}
  >
    {children}
  </button>
)
```

Now we can consume this button as expected:

```tsx
<Button variant="primary" className="mt-4">
  {children}
</Button>
```

[^1]: This is not an issue with CSS-in-JS styling solutions, such as [Stitches](https://stitches.dev). While they compile down to classes at the end of the day, the authoring is done as individual styles (in JS Object format), which are much easier to compose.
[^2]: What is meant by this is that the styles at the end override the styles at the beginning.
Array : Reduce method ( How it works and its applications )
Published: 2022-03-19 15:53:19

## Introduction 

As the title suggest we are going to discuss one of the most widely used array methods : **reduce**

The word itself describes that it **reduces** the input value to single output value. Let us see how it works!

---

- It iterates over each element in an array from left to right 
- It accepts a [callback function](https://dev.to/swasdev4511/dealing-with-asynchronous-data-in-javascript-episode-01-500a) which has following parameters accumulator , currentvalue , index ,array and an optional intial value. ( although it is optional but it's a best practice to use it )

- Syntax : 
```
reduce(function(accumulator, currentValue, index, array) {
   /* function-body */
}, initialValue)
```

**accumulator** (a) - it is the return value in last iteration or initial value

**currentvalue** (c) - it is the value of the current element in the current ongoing iteration

**index** - it is the index of the current iteration

**array** - it is an input array on which we are providing applying the reduce function

**initialValue** - it is the starting value that is to be returned to the accumulator in the very first iteration

---

Now enough theory let us take a look an example. In this example we are going to calculate the total of all the numbers given in an array of numbers.

```
let arr = [ 1, 2 ,3,4,5,6,7,8,9,10];
const sum = arr.reduce((accumulator,currentvalue) => accumulator + currentvalue,0);
console.log("Sum : ",sum);
```

- In the above example on the very first iteration, the value of accumulator is the initial value i.e 0 and current value is 1.

- Thus it returns 0 plus 1 resulting 1 and accumulator value becomes 1. ( as we have provided addition logic )

- Now in the next iteration, the value of accumulator is 1 and currentvalue is 2 so the next value of accumulator results into their addition as 3 

- This goes on till last iteration and the accumulator values is returned.

- Take a note that we can provide any logic as per our need inside the function body. And also, we can provide any initial value.

---


## Some of the practical use cases where we can use reduce function  are : 


-  create string from an array of characters.


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

- Find max. value in a given array of numbers

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

- Find the array of names for the given array of employees whose age is > 40 


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

- Find the frequency of same aged users from given array.  


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



Thank you for stopping by. If you find it useful consider sharing it. You can connect with me here : [linkedin](https://www.linkedin.com/in/swasdev4511/)
A good reason to make all your api's public
Tags: api, webdev, programming, cloud
Published: 2022-03-19 15:10:59

[https://fultonsramblings.substack.com/p/everything-should-have-a-public-api](Everything should have a public API on substack)

Hope this post changes the way you develop APIs and helps create a friendlier world for new operating system development.