Posted on Leave a comment

Create Web Text Editor using JavaScript with Editor.js

by Vincy. Last modified on October 20th, 2022.

Editor.js is a JavaScript solution to create a web text editor. It is a WYSIWYG editor that allows inline editing of web text content.

Online-hosted editors provide more features to create and format content in an enriched manner. The Editor.js JavaScript library helps to create our own editor in an application.

There are numerous online editors with advanced tools. But, having a custom editor can be sleeker to use and maintain.

The Editor.js has many features to embed rich text content by creating placeholders in the editor with the help of its tools. Tools are enabled by using the external libraries developed for Editor.js.

Those library tools enrich the capability of this web text editor plugin. The following table shows the tools enabled with this Editor.js JavaScript initiation. These tools are used to create different types of rich text content in different formats.

This demo allows you to experience the features of an online editor by integrating this library.

View Demo

Tool Description
Header Creates the H1, H2, H3, H4, H5 and H6 heading blocks for the web editor.
Link embeds It lets pasting URL and extracts content from the link pasted into this input.
Raw HTML blocks It allows embedding raw HTML codes to the web text editor.
Simple image It accepts the image full path or allows to paste of copied image content to render images without server-side processing.
Image It supports choosing files, pasting URLs, pasting images or dragging and dropping images to the rich text content area.
Checklist It is used to create checklist items.
List It adds ordered and unordered list items.
Embeds It embeds content by loading iFrame to the content.
Quote It creates quote blocks that have a toolbar to format rich text content and add links.

The official getting started tutorial has detailed usage documentation about this JavaScript editor. The list of the above tools is described with appropriate linking to their 3-party library manual.

create web text editor javascript

How to install and initiate Editor.js

The Editor.js and its libraries can be integrated by using one of the several ways listed below.

  1. Node package modules.
  2. By using the available CDN URLs of this JavaScript library.
  3. By including the local minified library files downloaded to the application folder.

After including the required library files, the Editor.js has to be instantiated.

const editor = new EditorJS('editorjs');

[OR]

const editor = new EditorJS({ holder: 'editorjs'
});

Here, the “editorjs” is used as the holder which is referring the HTML target to render the web text editor.

Fill the editor with the initial data

If the editor has to display some default template, it requires creating a landing template to render into this. This web editor plugin class accepts rich text content template via a data property. The format will be as shown below.

{ time: 1452714582955, blocks: [ { "type": "header", "data": { "text": "Title of the Editor", "level": 2 } } ], version: "2.10.10"
}

Example: Integrate Editor.js with Raw HTML block, Image, Link embeds and more

This example has the code that teaches how to configure the most used tools of the Editor.js library. It renders HTML code blocks and embeds images, and link extracts.

The image upload and link extract tools are configured with the server-side endpoint. It handles backend action on the upload or the extract events.

On saving the composing rich text content, the Editor.js data will be saved to the database. The data shown in the web editor is dynamic from the database.

<?php
require_once __DIR__ . '/dbConfig.php';
$content = "''";
$sql = "SELECT * FROM editor";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if(!empty($row["content"])) { $content = $row["content"];
}
?>
<html>
<head>
<title>Create Web Text Editor using JavaScript with Editor.js</title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="form.css" rel="stylesheet" type="text/css" />
<style>
#loader-icon { display: none; vertical-align: middle; width: 100px;
}
</style>
</head>
<body> <div class="phppot-container"> <h1>Create Web Text Editor using JavaScript with Editor.js</h1> <div id="editorjs" name="editor"></div> <input type="submit" onClick=save() value="save"> <div id="loader-icon"> <img src="loader.gif" id="image-size" /> </div> </div> <script src="https://cdn.jsdelivr.net/npm/@editorjs/editorjs@latest"></script> <script src="https://cdn.jsdelivr.net/npm/@editorjs/header@latest"></script> <script src="https://cdn.jsdelivr.net/npm/@editorjs/list@latest"></script> <script src="https://cdn.jsdelivr.net/npm/@editorjs/image@latest"></script> <script src="https://cdn.jsdelivr.net/npm/@editorjs/raw"></script> <script src="https://cdn.jsdelivr.net/npm/@editorjs/checklist@latest"></script> <script src="https://cdn.jsdelivr.net/npm/@editorjs/link@latest"></script> <script src="editor-tool.js"></script> <script> const editor = new EditorJS({ /** * Id of Element that should contain Editor instance */ holder: 'editorjs', tools: { header: Header, list: List, raw: RawTool, image: { class: ImageTool, config: { endpoints: { byFile: 'http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/upload.php', // Your backend file uploader endpoint byUrl: 'http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/upload.php', // Your endpoint that provides uploading by Url } } }, checklist: { class: Checklist }, linkTool: { class: LinkTool, config: { endpoint: 'http://localhost/phppot/jquery/editorjs/extract-link-data.php', // Your backend endpoint for url data fetching, } } }, data: <?php echo $row["content"]; ?>, });
</script>
</body>
</html>

It has the ladder of six tools of Editor.js with JavaScript code. In this example, it creates images, link embeds and more types of rich text content. Some of them are basic like header, list, the default text tool and more.

The Image and Link embed tools depend on the PHP endpoint URL to take action on the back end.

Image tool configuration keys and endpoint script

The image tool requires the PHP endpoint URL to save the uploaded files to the target folder. The JavaScript editor keys to configure the endpoint are listed below.

  1. byFile – This endpoint is used while pasting the file.
  2. byUrl – This endpoint is used while choosing the file, dragging and dropping files and all.
tools: { image: { class: ImageTool, config: { endpoints: { byFile: 'http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/upload.php', byUrl: 'http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/upload.php' } } }
}

PHP endpoint to upload file

This is simple and straightforward that performs the image upload operation in PHP. The image file is posted via JavaScript links to this server-side script.

<?php
$targetDir = "../uploads/";
$output = array();
if (is_array($_FILES)) { $fileName = $_FILES['image']['name']; if (is_uploaded_file($_FILES['image']['tmp_name'])) { if (move_uploaded_file($_FILES['image']['tmp_name'], $targetDir . $fileName)) { $output["success"] = 1; $output["file"]["url"] = "http://localhost/phppot/javascript/create-web-text-editor-javascript/ajax-endpoint/" . $targetDir . $fileName; } }
}
print json_encode($output);
?>

Extract content from link embeds

This tool is configured like below to set the PHP endpoint to extract the content.

In this example, it extracts contents like title, image, and text description from the embedded link.

tools: { linkTool: { class: LinkTool, config: { endpoint: 'http://localhost/phppot/jquery/editorjs/extract-link-data.php', // Your backend endpoint for url data fetching, } }
}

PHP endpoint to extract content from the remote file

It creates a cURL post request in the endpoint PHP file to extract the data from the link. After getting the cURL response, the below code parses the response and creates a DOM component to render the rich text content into the WYSIWYG web editor.

It uses the GET method during the cURL request to extract rich text content and image from the link. In a previous tutorial, we used the GET and POST methods on PHP cURL requests.

<?php
$output = array();
$ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $_GET["url"]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $data = curl_exec($ch);
curl_close($ch); $dom = new DOMDocument();
@$dom->loadHTML($data); $nodes = $dom->getElementsByTagName('title');
$title = $nodes->item(0)->nodeValue; $metas = $dom->getElementsByTagName('meta');
$body = "";
for ($i = 0; $i < $metas->length; $i ++) { $meta = $metas->item($i); if ($meta->getAttribute('name') == 'description') { $body = $meta->getAttribute('content'); }
} $image_urls = array();
$images = $dom->getElementsByTagName('img'); for ($i = 0; $i < $images->length; $i ++) { $image = $images->item($i); $src = $image->getAttribute('src'); if (filter_var($src, FILTER_VALIDATE_URL)) { $image_src[] = $src; }
} $output["success"] = 1;
$output["meta"]["title"] = $title;
$output["meta"]["description"] = $body;
$output["meta"]["image"]["url"] = $image_src[0];
echo json_encode($output);
?>

Save Editor content to the database

On clicking the “Save” button below the web text editor, it gets the editor output data and saves it to the database.

It calls the editor.save() callback to get the WYSIWYG web editor output. An AJAX call sends this data to the PHP to store it in the database.

function save() { editor.save().then((outputData) => { document.getElementById("loader-icon").style.display = 'inline-block'; var xmlHttpRequest = new XMLHttpRequest(); xmlHttpRequest.onreadystatechange = function() { if (xmlHttpRequest.readyState == XMLHttpRequest.DONE) { document.getElementById("loader-icon").style.display = 'none'; if (xmlHttpRequest.status == 200) { // on success get the response text and // insert it into the ajax-example DIV id. document.getElementById("ajax-example").innerHTML = xmlHttpRequest.responseText; } else if (xmlHttpRequest.status == 400) { // unable to load the document alert('Status 400 error - unable to load the document.'); } else { alert('Unexpected error!'); } } }; xmlHttpRequest.open("POST", "ajax-endpoint/save-editor.php", true); xmlHttpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xmlHttpRequest.send("btnValue=" + JSON.stringify(outputData)); }).catch((error) => { console.log('Saving failed: ', error) });
}

PHP code to save Editor.js data

This is the endpoint PHP file to process the editor’s rich text output in the backend. It creates the query to prepare and execute the insert operation to save the rich text content to the database.

<?php
require_once __DIR__ . '/../dbConfig.php'; $sql = "SELECT * FROM editor";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
if (isset($_POST['btnValue'])) { $editorContent = $_POST['btnValue']; if (empty($row["content"])) { $query = "INSERT INTO editor(content,created)VALUES(?, NOW())"; $statement = $conn->prepare($query); $statement->bind_param("s", $editorContent); $statement->execute(); } else { $query = "UPDATE editor SET content = ? WHERE id = ?"; $statement = $conn->prepare($query); $statement->bind_param("si", $editorContent, $row["id"]); $statement->execute(); }
}
?>

View DemoDownload

↑ Back to Top

Posted on Leave a comment

How to Print a NumPy Array Without Scientific Notation in Python

Rate this post

Problem Formulation

» Problem Statement: Given a NumPy array. How to print the NumPy array without scientific notation in Python?

Note: Python represents very small or very huge floating-point numbers in their scientific form. Scientific notation represents the number in terms of powers of 10 to display very large or very small numbers. For example, the scientific notation for the number 0.000000321 is described as 3.21e07. 

In Python, the NumPy module generally uses scientific notation instead of the actual number while printing/displaying the array items.

Example: Look at the following code snippet:

arr = np.array([1, 5, 10, 20, 35, 5000.5])
print(arr)

Output:

[1.0000e+00 5.0000e+00 1.0000e+01 2.0000e+01 3.5000e+01 5.0005e+03]

Expected Output: Print the given array without scientific notation in Python as:

[ 1. 5. 10. 20. 35. 5000.5]

Without further ado, let’s dive into the different ways of solving the given problem.

Method 1: Using set_printoptions() Function

The set_printoptions() is a function in the numpy module that is used to set how the floating-point numbers, NumPy arrays and numpy objects are to be displayed. By default, the very big or very small numbers of the array are represented using scientific notation. We can use the set_printoptions() function by passing the suppress as True to remove the scientific notation of the numpy array.

Approach:

  • Import the Numpy module to create the array.
  • Use the set_printoptions() function and pass the suppress value as True.
  • Print the array; it will get displayed without the scientific notation.

Code:

# Importing the numpy module
import numpy as np
# Creating a NumPy array
a = np.array([1, 5, 10, 20, 35, 5000.5])
print("Numpy array with scientific notation", a)
np.set_printoptions(suppress = True)
print("Numpy array without scientific notation", a)

Output:

Numpy array with scientific notation [1.0000e+00 5.0000e+00 1.0000e+01 2.0000e+01 3.5000e+01 5.0005e+03]
Numpy array without scientific notation [ 1. 5. 10. 20. 35. 5000.5]

Discussion: The set_printoptions() function only works for the numbers that fit in the default 8-character space allotted to it, as shown below:

Code:

import numpy as np
# Array with element index 1 having 8 digits
a = np.array([5.05e-5, 15.6, 2.1445678e5])
print("Numpy array with scientific notation", a)
np.set_printoptions(suppress = True)
print("Numpy array without scientific notation", a)

Output:

Numpy array with scientific notation [5.0500000e-05 1.5600000e+01 2.1445678e+05]
Numpy array without scientific notation [ 0.0000505 15.6 214456.78 ]

When we pass a number that is greater than 8 characters wide, exponential notation is imposed as shown below:

Code:

import numpy as np
# Array with element index 1 having more than 8 digits
a = np.array([5.05e-5, 15.6, 2.1445678e10])
print("Numpy array with scientific notation", a)
np.set_printoptions(suppress = True)
print("Numpy array without scientific notation", a)

Output:

Numpy array with scientific notation [5.0500000e05 1.5600000e+01 2.1445678e+10]
Numpy array without scientific notation [5.0500000e05 1.5600000e+01 2.1445678e+10]

Method 2: Using set_printoptions() Function with .format

As in method 1, the set_printoptions() function does not work when the number has more than eight characters. That is when set_printoptions(formatter) is used to specify the options for printing and rounding. We have to set the function to print the float variable.

Python’s built-in format(value, spec) function transforms the input of one format into the output of another format defined by you. Specifically, it applies the format specifier spec to the argument value and returns a formatted representation of value. Read more about the “Python format() Function.”

Code:

import numpy as np
# Creating a NumPy array
# Array with element index 1 having more than 8 digits
a = np.array([5.05e-5, 15.6, 2.1445678e10])
print("Numpy array with scientific notation", a)
np.set_printoptions(suppress = True, formatter = {'float_kind':'{:f}'.format})
print("Numpy array without scientific notation", a)

Output:

Numpy array with scientific notation [5.0500000e-05 1.5600000e+01 2.1445678e+10]
Numpy array without scientific notation [0.000051 15.600000 21445678000.000000]

We can also format the output to only have 2 units precision by using '{:0.2f}' .format as shown below:

Code:

import numpy as np
# Array with element index 1 having more than 8 digits
a = np.array([5.05e-5, 15.6, 2.1445678e10])
print("Numpy array with scientific notation", a)
np.set_printoptions(suppress = True, formatter = {'float_kind':'{:0.2f}'.format})
print("Numpy array without scientific notation", a)

Output:

Numpy array with scientific notation [5.0500000e-05 1.5600000e+01 2.1445678e+10]
Numpy array without scientific notation [0.00 15.60 21445678000.00]

Discussion: The disadvantage of using this method to suppress the exponential notion in the numpy arrays is when the array gets a very large float value. When we try to print this array, we are going to get a whole page of numbers.

Method 3: Using printoptions() Function

The printoption() function is a function in the Numpy module used as a context manager for setting print options. By passing the precision as 3 and suppress as True in the printoptions() function, we can remove the scientific notation and print the Numpy array.

Note: This function only works if you use NumPy versions 1.15.0 or later.

Approach:

  • Import the numpy module to create the array.
  • Use the printoption() function inside the “with” and pass the precision value as 3 and the suppress value as True.
  • Print the array; it will get displayed without the scientific notation.

Code:

import numpy as np
# Creating a NumPy array
a = np.array([1, 5, 10, 20, 35, 5000.5])
print("Numpy array with scientific notation", a)
print("Numpy array without scientific notation:")
with np.printoptions(precision = 3, suppress = True): print(a)

Output:

Numpy array with scientific notation [1.0000e+00 5.0000e+00 1.0000e+01 2.0000e+01 3.5000e+01 5.0005e+03]
Numpy array without scientific notation: [ 1. 5. 10. 20. 35. 5000.5]

Method 4: Using array2string() Function

The array2string() is a function in the numpy module that returns a string representation of an array. We can use this function to print a NumPy array without scientific notation by passing the array as the argument and setting the suppress_small argument as True. When the suppress_small argument is True, it represents the numbers close to zero as zero.

Approach:

  • Import the numpy module to create the array.
  • Use the array2string() function and pass the suppress_small argument as True.
  • Finally, print the array. It will get displayed without the scientific notation.

Code:

import numpy as np
# Creating a NumPy array
a = np.array([1, 5, 10, 20, 35, 5000.5])
print("Numpy array with scientific notation", a)
a = np.array2string(a, suppress_small = True)
print("Numpy array without scientific notation:", a)

Output:

Numpy array with scientific notation [1.0000e+00 5.0000e+00 1.0000e+01 2.0000e+01 3.5000e+01 5.0005e+03]
Numpy array without scientific notation: [ 1. 5. 10. 20. 35. 5000.5]

Conclusion

Hurrah! We have successfully solved the mission-critical question in numerous ways in this article. I hope you found it helpful. Please stay tuned and subscribe for more such interesting articles. 

💎Interesting Read: How to Suppress Scientific Notation in Python?


Do you want to become a NumPy master? Check out our interactive puzzle book Coffee Break NumPy and boost your data science skills! (Amazon link opens in new tab.)

Coffee Break NumPy
Posted on Leave a comment

How to Count the Number of Unique Values in a List in Python?

Rate this post

Problem Statement: Consider that you have been given a list in Python. How will you count the number of unique values in the list?

Example: Let’s visualize the problem with the help of an example:

Given: 
li = [‘a’, ‘a’, ‘b’, ‘c’, ‘b’, ‘d’, ‘d’, ‘a’]
Output: The unique values in the given list are ‘a’, ‘b’, ‘c’, ‘d’. Thus the expected output is 4.

Now that you have a clear picture of what the question demands, let’s dive into the different ways of solving the problem.

Method 1: The Naive Approach

Approach:

  • Create an empty list that will be used to store all the unique elements from the given list. Let’s say that the name of this list res.
  • To store the unique elements in the new list that you created previously, simply traverse through all the elements of the given list with the help of a for loop and then check if each value from the given list is present in the list “res“.
    • If a particular value from the given list is not present in the newly created list then append it to the list res. This ensures that each unique value/item from the given list gets stored within res.
    • If it’s already present, then do not append the value.
  • Finally, the list res represents a newly formed list that contains all unique values from the originally given list. All that remains to be done is to find the length of the list res which gives you the number of unique values present in the given list.

Code:

# Given list
li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a']
res = []
for ele in li: if ele not in res: res.append(ele)
print("The count of unique values in the list:", len(res)) # The count of unique values in the list: 4

Discussion: Since you have to create an extra list to store the unique values, this approach is not the most efficient way to find and count the unique values in a list as it takes a lot of time and space.

Method 2: Using set()

A more effective and pythonic approach to solve the given problem is to use the set() method. Set is a built-in data type that does not contain any duplicate elements.

Read more about sets here – “The Ultimate Guide to Python Sets

Approach: Convert the given list into a set using the set() function. Since a set cannot contain duplicate values, only the unique values from the list will be stored within the set. Now that you have all the unique values at your disposal, you can simply count the number of unique values with the help of the len() function.

Code:

li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a']
s = set(li)
unique_values = len(s)
print("The count of unique values in the list:", unique_values) # The count of unique values in the list: 4

You can formulate the above solution in a single line of code by simply chaining both the functions (set() and len()) together, as shown below:

# Given list
li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a']
# One-liner
print("The count of unique values in the list:", len(set(li)))

Method 3: Using Dictionary fromkeys()

Python dictionaries have a method known as fromkeys() that is used to return a new dictionary from the given iterable ( such as list, set, string, tuple) as keys and with the specified value. If the value is not specified by default, it will be considered as None. 

Approach: Well! We all know that keys in a dictionary must be unique. Thus, we will pass the list to the fromkeys() method and then use only the key values of this dictionary to get the unique values from the list. Once we have stored all the unique values of the given list stored into another list, all that remains to be done is to find the length of the list containing the unique values which will return us the number of unique values.

Code:

# Given list
li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a']
# Using dictionary fromkeys()
# list elements get converted to dictionary keys. Keys are always unique!
x = dict.fromkeys(li)
# storing the keys of the dictionary in a list
l2 = list(x.keys())
print("Number of unique values in the list:", len(l2)) # Number of unique values in the list: 4

Method 4: Using Counter

Another way to solve the given problem is to use the Counter function from the collections module. The Counter function creates a dictionary where the dictionary’s keys represent the unique items of the list, and the corresponding values represent the count of a key (i.e. the number of occurrences of an item in the list). Once you have the dictionary all you need to do is to extract the keys of the dictionary and store them in a list and then find the length of this list.

from collections import Counter
# Given list
li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a']
# Creating a list containing the keys (the unique values)
key = Counter(li).keys()
# Calculating the length to get the count
res = len(key)
print("The count of unique values in the list:", res) # The count of unique values in the list: 4

Method 5: Using Numpy Module

We can also use Python’s Numpy module to get the count of unique values from the list. First, we must import the NumPy module into the code to use the numpy.unique() function that returns the unique values from the list.

Solution:

# Importing the numpy module
import numpy as np
# Given list
li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a']
res = []
# Using unique() function from numpy module
for ele in np.unique(li): res.append(ele)
# Calculating the length to get the count of unique elements
count = len(res)
print("The count of unique values in the list:", count) # The count of unique values in the list: 4

Another approach is to create an array using the array() function after importing the numpy module. Further, we will use the unique() function to remove the duplicate elements from the list. Finally, we will calculate the length of that array to get the count of the unique elements.

Solution:

# Importing the numpy module
import numpy as np
# Given list
li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a']
array = np.array(li)
u = np.unique(array)
c = len(u)
print("The count of unique values in the list:", c) # The count of unique values in the list: 4

Method 6: Using List Comprehension

There’s yet another way of solving the given problem. You can use a list comprehension to get the count of each element in the list and then use the zip() function to create a zip object that creates pairs of each item along with the count of each item in the list. Store these paired items as key-value pairs in a dictionary by converting the zip object to a dictionary using the dict() function. Finally, return the dictionary’s keys’ calculated length (using the len() function).

Code:

# Given list
li = ['a', 'a', 'b', 'c', 'b', 'd', 'd', 'a']
# List comprehension using zip()
l2 = dict(zip(li, [li.count(i) for i in li]))
# Using len to get the count of unique elements
l = len(list(l2.keys()))
print("The count of the unique values in the list:", l) # The count of the unique values in the list: 4

Conclusion

In this article, we learned the different methods to count the unique values in a list in Python. We looked at how to do this using the counter, sets, numpy module, and list comprehensions. If you found this article helpful and want to receive more interesting solutions and discussions in the future, please subscribe and stay tuned!


Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

Posted on Leave a comment

How to Wait 1 Second in JavaScript?

by Vincy. Last modified on October 18th, 2022.

Wait is there every aspect of human life. Let’s get philosophical for a moment! For every good thing in life, you need to wait.

“There’s no such thing as failure – just waiting for success.” – John Osborne

Like in life, wait in programming is also unavoidable. It is a tool, that you will need some day on desperate situations. For example, a slider, a fading animation, a bouncing ball, you never know.

In this tutorial, we will learn about how to wait one second in JavaScript? One second is an example. It could be a “5 seconds” or any duration your code needs to sleep before continuing with operation.

Refer this linked article to learn about PHP sleep.

Wait

JavaScript wait 1 second

I have used the good old setTimeout JavaScript function to wait. It sleeps the processing for the milliseconds duration set. Then calls the callback function passed.

You should put the code to execute after wait inside this callback function. As for the wait duration 1000 millisecond is one second. If you want to wait 5 seconds, then pass 5000.

This code will be handy if you are creating a news ticker like scroll animation.

	var testWait = function(milliseconds) { console.log('Before wait'); setTimeout(function() { console.log('After wait'); }, milliseconds); } testWait(1000);

JavaScript wait 1 second for promise

If you are using a modern browser, then you can use the below code. Modern means, your browser should support ES6 JavaScript standard.

In summary, you need support for JavaScript Promise. Here we use the setTimeout function. It resolves the promise after the defined milliseconds wait.

// Promise is available with JavaScript ES6 standard
// Need latest browsers to run it
const wait = async (milliseconds) => { await new Promise(resolve => { return setTimeout(resolve, milliseconds) });
}; const testWait = async () => { console.log('Before wait.'); await wait(1000); console.log('After wait.');
} testWait();

JavaScript wait 1 second in loop

If you want to wait the processing inside a loop in JavaScript, then use the below code. It uses the above Promise function and setTimeout to achieve the wait.

If yours is an old browser then use the first code given above for the wait part. If you need to use this, then remember to read the last section of this tutorial. In particular, if you want to “wait” in a mission critical JavaScript application.

const wait = async (milliseconds) => { await new Promise(resolve => { return setTimeout(resolve, milliseconds) });
}; const waitInLoop = async () => { for (let i = 0; i < 10; i++) { console.log('Waiting ...'); await wait(1000); console.log(i); } console.log("The wait is over.");
} waitInLoop();

JavaScript wait 1 second in jQuery

This is for people out there who wishes to write everything in jQuery. It was one of the greatest frontend JavaScript libraries but nowadays losing popularity. React is the new kid in the block. Here in this wait scenario, there is no need to look for jQuery specific code even if you are in jQuery environment.

Because you will have support for JavaScript. You can use setTimeout without any jQuery specific constructs. I have wrapped setTimeout in a jQuery style code. Its old wine in a new bottle.

// if for some strange reason you want to write // it in jQuery style // just wrapping the setTimout function in jQuery style $.wait = function(callback, milliseconds) { return window.setTimeout(callback, milliseconds); } $.wait(function() { $("#onDiv").slideUp() }, 1000);

Cancel before wait for function to finish

You may have to cancel the wait and re-initiate the setTimeout in special scenarios. In such a situation use the clearTimeout() function as below. Go through the next section to know about such a special wait scenario.

let timeoutId = setTimeout(() => { // do process }) // store the timeout id and call clearTimeout() function // to clear the already set timeout clearTimeout(timeoutId);

Is the wait real?

You need to understand what the JavaScript wait means. When the JavaScript engine calls setTimeout, it processes a function. When the function exits, then a timeout with defined milliseconds is set. After that wait, then JavaScript engine makes the callback.

When you want to know the total wait period for next consecutive call. You need to add the time taken by your function to process to the wait duration.

So that is a variable unit. Assume that the function runs for five seconds. And the setTimeout wait duration is one second. Then the actual wait will become six seconds for the next call.

If you want to precise call every five seconds, then you need to define a self adjusting setTimeout timer.

You should account the time taken to process, then reduce the time from the wait milliseconds. Then cancel the current setTimeout. And start new setTimeout with the new calculated time.

That’s going to be tricky. If you are running a mission critical wait call, then that is the way to go.

For example, general UI animations, the above basic implementations will hold good. But you need the self adjusting setTimeout timer for critical time based events.

setInterval will come closer for the above scenario. Any other UI process running in main thread will affect setInterval’s wait period. Then your one second wait may get converted to 5 seconds wait. So, you should define a self adjusting setTimeout wait for mission critical events.

↑ Back to Top

Posted on Leave a comment

Plotly Dash Bootstrap Card Components

Rate this post

Welcome to the bonus content of “The Book of Dash”. 🤗

💡 Here you will find additional examples of Plotly Dash components, layouts and style. To learn more about making dashboards with Plotly Dash, and how to buy your copy of “The Book of Dash”, please see the reference section at the bottom of this article.

As you read the article, feel free to run the explainer video on the Card components from one of our coauthors’ “Charming Data” YT channel:

YouTube Video

This article will focus on the Card components from the Dash Boostrap Component library. Using cards is a great way to create eye-catching content. We’ll show you how to make the card content interactive with callbacks, but first we’ll focus on the style and layout.

Plotly Dash App with a Bootstrap Card

We’ll start with the basics – a minimal Dash app to display a single card without any additional styling. Be sure to check out the complete reference for using Dash Bootstrap cards.

Next, we’ll show how to jazz it up to make it look better — and more importantly — so it conveys key information at a glance.

from dash import Dash, html
import dash_bootstrap_components as dbc app = Dash(__name__, external_stylesheets=[dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]) card = dbc.Card( dbc.CardBody( [ html.H1("Sales"), html.H3("$104.2M") ], ),
) app.layout=dbc.Container(card) if __name__ == "__main__": app.run_server(debug=True)

Styling a Dash Bootstrap Card

An easy way to style content is by using Boostrap utility classes. See all the utility classes at the Dash Bootstrap Cheatsheet app. This handy cheatsheet is made by a co-author of “The Book of Dash”.

In this card, we center the text and change the color with “text-center” and “text-success“. The Bootstrap themes have named colors and “success” is a shade of green.

👉 Recommended Resource: For more information about styling your app with a Boostrap theme, see Dash Bootstrap Theme Explorer

card = dbc.Card( dbc.CardBody( [ html.H1("Sales"), html.H3("$104.2M", className="text-success") ], ), className="text-center"
)

Feel free to watch Adam’s explainer video on Bootstrap and styling your app if you need to get up to speed! 👇

YouTube Video

Dash Bootstrap Card with Icons

You can add Bootstrap and/or Font Awesome icons to your Dash Bootstrap components. In this example, we will add the bank icon as well as change the background color using the Bootstrap utility class bg-primary.

card = dbc.Card( dbc.CardBody( [ html.H1([html.I(className="bi bi-bank me-2"), "Profit"]), html.H3("$8.3M"), html.H4(html.I("10.3% vs LY", className="bi bi-caret-up-fill text-success")), ], ), className="text-center m-4 bg-primary text-white",
)

To learn more, see the Icons section of the dash-bootstrap-components documentation. You can also find more information about adding icons to dash components in the buttons article.

👉 Recommended Tutorial: Plotly Dash Button Component – A Simple Illustrated Guide

Dash Bootstrap Cards Side-by-Side

In business intelligence dashboards, it’s common to highlight KPIs or Key Performance Indicators in a group of cards. You can find many examples in the Plotly App Gallery:

This app places three KPI cards side-by-side. We use the dbc.Row and dbc.Col components to create this responsive card layout. When you run this app, try changing the width of the browser window to see how the cards expand to fill the row based on the screen size.

This app also demonstrates the usage of Bootstrap border utility classes to add and style a border. Here we add a border on the left and change the color to highlight the results. Another trick is to use the “text-nowrap” class to keep the icon and the text together on the same line when the cards shrink to accommodate small screen sizes.

from dash import Dash, html
import dash_bootstrap_components as dbc app = Dash(__name__, external_stylesheets=[dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]) card_sales = dbc.Card( dbc.CardBody( [ html.H1([html.I(className="bi bi-currency-dollar me-2"), "Sales"], className="text-nowrap"), html.H3("$106.7M"), html.Div( [html.I("5.8%", className="bi bi-caret-up-fill text-success"), " vs LY",] ), ], className="border-start border-success border-5" ), className="text-center m-4"
) card_profit = dbc.Card( dbc.CardBody( [ html.H1([html.I(className="bi bi-bank me-2"), "Profit"], className="text-nowrap"), html.H3("$8.3M",), html.Div( [ html.I("12.3%", className="bi bi-caret-down-fill text-danger"), " vs LY", ] ), ], className="border-start border-danger border-5" ), className="text-center m-4",
) card_orders = dbc.Card( dbc.CardBody( [ html.H1([html.I(className="bi bi-cart me-2"), "Orders"], className="text-nowrap"), html.H3("91.4K"), html.Div( [ html.I("10.3%", className="bi bi-caret-up-fill text-success"), " vs LY", ] ), ], className="border-start border-success border-5" ), className="text-center m-4",
) app.layout = dbc.Container( dbc.Row( [dbc.Col(card_sales), dbc.Col(card_profit), dbc.Col(card_orders)], ), fluid=True,
) if __name__ == "__main__": app.run_server(debug=True)

Creating Dash Bootstrap Cards in a Loop

In the previous example, notice that a lot of the code for creating the card is the same. To reduce the amount of repetitive code, let’s create cards in a function.

In this app, we introduce the dbc.CardHeader component and the "shadow" class to style the card. We’ll show you how to add more style later in the app that displays crypto prices.

from dash import Dash, html
import dash_bootstrap_components as dbc app = Dash(__name__, external_stylesheets=[dbc.themes.SPACELAB]) summary = {"Sales": "$100K", "Profit": "$5K", "Orders": "6K", "Customers": "300"} def make_card(title, amount): return dbc.Card( [ dbc.CardHeader(html.H2(title)), dbc.CardBody(html.H3(amount, id=title)), ], className="text-center shadow", ) app.layout = dbc.Container( dbc.Row([dbc.Col(make_card(k, v)) for k, v in summary.items()], className="my-4"), fluid=True,
) if __name__ == "__main__": app.run_server(debug=True)

Dash Bootstrap Card with an Image

This card uses the dbc.CardImage component. This is a great format for the “who’s who” section of your app. It works well for displaying information about products too.

from dash import Dash, html
import dash_bootstrap_components as dbc app = Dash(__name__, external_stylesheets=[dbc.themes.SPACELAB]) count = "https://user-images.githubusercontent.com/72614349/194616425-107a62f9-06b3-4b84-ac89-2c42e04c00ac.png" card = dbc.Card([ dbc.CardImg(src=count, top=True), dbc.CardBody( [ html.H3("Count von Count", className="text-primary"), html.Div("Chief Financial Officer"), html.Div("Sesame Street, Inc.", className="small"), ] )], className="shadow my-2", style={"maxWidth": 350},
) app.layout=dbc.Container(card) if __name__ == "__main__": app.run_server(debug=True)

Dash Bootstrap Card with an Image and a Link

This app has a card with the dbc.CardLink component.

When you run this app, try clicking on either the logo or the title. You will see that both are links to the Plotly site displaying the current job openings.

We do this by including both the html.Img component with the Plotly logo and the html.Span with the title in the dbc.CardLink component.

from dash import Dash, html
import dash_bootstrap_components as dbc app = Dash(__name__, external_stylesheets=[dbc.themes.SPACELAB]) plotly_logo_dark = "https://user-images.githubusercontent.com/72614349/182967824-c73218d8-acbf-4aab-b1ad-7eb35669b781.png" card = dbc.Card( dbc.CardBody( [ dbc.CardLink( [ html.Img(src=plotly_logo_dark, height=65), html.Span("Plotly Job Openings", className="ms-2") ], className="text-decoration-none h2", href="https://plotly.com/careers/" ), html.Hr(), html.Div("Engineering", className="h3"), html.Div("Intermediate Backend Engineer", className="text-danger"), html.Div("Remote, Canada", className="small"), ] ), className="shadow my-2", style={"maxWidth": 450},
) app.layout=dbc.Container(card) if __name__ == "__main__": app.run_server(debug=True)

Dash Bootstrap Card with a Background Image

This app puts the image in the background and uses the dbc.CardImgOverlay component to place content on top of the image.

We also use dbc.Buttons to link to other sites for more information. See the buttons article for more information. Be sure to run the app and check out the links. The Webb Telescope app is pretty cool!

👉 Recommended Tutorial: Before After Image in Plotly Dash

from dash import Dash, html
import dash_bootstrap_components as dbc app = Dash(__name__, external_stylesheets=[dbc.themes.SPACELAB, dbc.icons.BOOTSTRAP]) webb_deep_field = "https://user-images.githubusercontent.com/72614349/192781103-2ca62422-2204-41ab-9480-a730fc4e28d7.png"
card = dbc.Card( [ dbc.CardImg(src=webb_deep_field), dbc.CardImgOverlay([ html.H2("James Webb Space Telescope"), html.H3("First Images"), html.P( "Learn how to make an app to compare before and after images of Hubble vs Webb with ~40 lines of Python", style={"marginTop":175}, className="small", ), dbc.Button("See the App", href="https://jwt.pythonanywhere.com/"), dbc.Button( [html.I(className="bi bi-github me-2"), "source code"], className="ms-2 text-white", href="https://github.com/AnnMarieW/webb-compare", ) ]) ], style={"maxWidth": 500}, className="my-4 text-center text-white"
) app.layout=dbc.Container(card) if __name__ == "__main__": app.run_server(debug=True)

See this Plotly Dash app live: https://jwt.pythonanywhere.com/

Plotly Dash App with Live Updates

This app shows live updates of crypto prices. We use a dcc.Interval component to fetch the data from CoinGecko every 6 seconds.

The CoinGecko API is easy to use because you don’t need an API key, and it’s free if you keep the number of updates within the free tier limits. We pull the current price, 24 hour price change, and the coin logo from the data feed and display the data in a nicely styled card.

In this app we introduce callbacks to update the data, and show how to get the data from CoinGecko. All the other styling has been covered in previous examples.

Note that in this app, the color of the text and the up and down arrows are updated dynamically based on the data in the make_card function.

import dash
from dash import Dash, dcc, html, Input, Output
import dash_bootstrap_components as dbc
import requests app = Dash(__name__, external_stylesheets=[dbc.themes.SUPERHERO, dbc.icons.BOOTSTRAP]) coins = ["bitcoin", "ethereum", "binancecoin", "ripple"]
interval = 6000 # update frequency - adjust to keep within free tier
api_url = "https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd" def get_data(): try: response = requests.get(api_url, timeout=1) return response.json() except requests.exceptions.RequestException as e: print(e) def make_card(coin): change = coin["price_change_percentage_24h"] price = coin["current_price"] color = "danger" if change < 0 else "success" icon = "bi bi-arrow-down" if change < 0 else "bi bi-arrow-up" return dbc.Card( html.Div( [ html.H4( [ html.Img(src=coin["image"], height=35, className="me-1"), coin["name"], ] ), html.H4(f"${price:,}"), html.H5( [f"{round(change, 2)}%", html.I(className=icon), " 24hr"], className=f"text-{color}", ), ], className=f"border-{color} border-start border-5", ), className="text-center text-nowrap my-2 p-2", ) mention = html.A( "Data from CoinGecko", href="https://www.coingecko.com/en/api", className="small"
)
interval = dcc.Interval(interval=interval)
cards = html.Div()
app.layout = dbc.Container([interval, cards, mention], className="my-5") @app.callback(Output(cards, "children"), Input(interval, "n_intervals"))
def update_cards(_): coin_data = get_data() if coin_data is None or type(coin_data) is dict: return dash.no_update # make a list of cards with updated prices coin_cards = [] updated = None for coin in coin_data: if coin["id"] in coins: updated = coin.get("last_updated") coin_cards.append(make_card(coin)) # make the card layout card_layout = [ dbc.Row([dbc.Col(card, md=3) for card in coin_cards]), dbc.Row(dbc.Col(f"Last Updated {updated}")), ] return card_layout if __name__ == "__main__": app.run_server(debug=True)

Plotly Dash App with a Sidebar

A common layout for Dash apps is to put inputs in a sidebar, and the output in the main section of the page. We can place both the sidebar and the output in Dash Boostrap Card components.

See the app and the code live at the Dash Example Index

Plotly Dash Example Index

See more examples of interactive apps in the Dash Example Index

Reference

Order Your Copy of “The Book of Dash” Today!

The Book Of Dash

The Book of Dash Authors

Feel free to learn more about the book’s coauthors here:

Ann Marie Ward:

Adam Schroeder:

Chris Mayer:


Posted on Leave a comment

Python TypeError: ‘dict_keys’ Not Subscriptable (Fix This Stupid Bug)

5/5 – (1 vote)

Do you encounter the following error message?

TypeError: 'dict_keys' object is not subscriptable

You’re not alone! This short tutorial will show you why this error occurs, how to fix it, and how to never make the same mistake again.

So, let’s get started!

Solution

Python raises the “TypeError: 'dict_keys' object is not subscriptable” if you use indexing or slicing on the dict_keys object obtained with dict.keys(). To solve the error, convert the dict_keys object to a list such as in list(my_dict.keys())[0].

print(list(my_dict.keys())[0])

Example

The following minimal example that leads to the error:

d = {1:'a', 2:'b', 3:'c'}
print(d.keys()[0])

Output:

Traceback (most recent call last): File "C:\Users\...\code.py", line 2, in <module> print(d.keys()[0])
TypeError: 'dict_keys' object is not subscriptable

Note that the same error message occurs if you use slicing instead of indexing:

d = {1:'a', 2:'b', 3:'c'}
print(d.keys()[:-1]) # <== same error

Fixes

The reason this error occurs is that the dictionary.keys() method returns a dict_keys object that is not subscriptable.

You can use the type() function to check it for yourself:

print(type(d.keys()))
# <class 'dict_keys'>

Note: You cannot expect dictionary keys to be ordered, so using indexing on a non-ordered type wouldn’t make too much sense, would it? ⚡

You can fix the non-subscriptable TypeError by converting the non-indexable dict_keys object to an indexable container type such as a list in Python using the list() or tuple() function.

Here’s an example fix:

d = {1:'a', 2:'b', 3:'c'}
print(list(d.keys())[0])
# 1

Here’s an other example fix:

d = {1:'a', 2:'b', 3:'c'}
print(tuple(d.keys())[:-1])
# (1, 2)

Both lists and tuples are subscriptable so you can use indexing and slicing after converting the dict_keys object to a list or a tuple.

🌍 Full Guide: Python Fixing This Subsctiptable Error (General)

Summary

Python raises the TypeError: 'dict_keys' object is not subscriptable if you try to index x[i] or slice x[i:j] a dict_keys object.

The dict_keys type is not indexable, i.e., it doesn’t define the __getitem__() method. You can fix it by converting the dictionary keys to a list using the list() built-in function.

Alternatively, you can also fix this by removing the indexing or slicing call, or defining the __getitem__ method. Although the previous approach is often better.

What’s Next?

I hope you’d be able to fix the bug in your code! Before you go, check out our free Python cheat sheets that’ll teach you the basics in Python in minimal time:

If you struggle with indexing in Python, have a look at the following articles on the Finxter blog—especially the third!

🌍 Related Articles:

Posted on Leave a comment

Python – Return NumPy Array From Function

5/5 – (1 vote)

Do you need to create a function that returns a NumPy array but you don’t know how? No worries, in sixty seconds, you’ll know! Go! 🚀

A Python function can return any object such as a NumPy Array. To return an array, first create the array object within the function body, assign it to a variable arr, and return it to the caller of the function using the keyword operation “return arr“.

👉 Recommended Tutorial: How to Initialize a NumPy Array? 6 Easy Ways

Create and Return 1D Array

For example, the following code creates a function create_array() of numbers 0, 1, 2, …, 9 using the np.arange() function and returns the array to the caller of the function:

import numpy as np def create_array(): ''' Function to return array ''' return np.arange(10) numbers = create_array()
print(numbers)
# [0 1 2 3 4 5 6 7 8 9]

The np.arange([start,] stop[, step]) function creates a new NumPy array with evenly-spaced integers between start (inclusive) and stop (exclusive).

The step size defines the difference between subsequent values. For example, np.arange(1, 6, 2) creates the NumPy array [1, 3, 5].

To better understand the function, have a look at this video:

YouTube Video

I also created this figure to demonstrate how NumPy’s arange() function works on three examples:

In the code example, we used np.arange(10) with default start=0 and step=1 only specifying the stop=10 argument.

If you need an even deeper understanding, I’d recommend you check out our full guide on the Finxter blog.

👉 Recommended Tutorial: NumPy Arange Function — A Helpful Illustrated Guide

Create and Return 2D NumPy Array

You can also create a 2D (or multi-dimensional) array in a Python function by first creating a 2D or (xD) nested list and converting the nested list to a NumPy array by passing it into the np.array() function.

The following code snippet uses nested list comprehension to create a 2D NumPy array following a more complicated creation pattern:

import numpy as np def create_array(a,b): ''' Function to return array ''' lst = [[(i+j)**2 for i in range(a)] for j in range(b)] return np.array(lst) arr = create_array(4,3)
print(arr)

Output:

[[ 0 1 4 9] [ 1 4 9 16] [ 4 9 16 25]]

I definitely recommend reading the following tutorial to understand nested list comprehension in Python:

👉 Recommended Tutorial: Nested List Comprehension in Python

More Ways

There are many other ways to return an array in Python.

For example, you can use either of those methods inside the function body to create and initialize a NumPy array:

To get a quick overview what to put into the function and how these methods work, I’d recommend you check out our full tutorial.

👉 Recommended Tutorial: How to Initialize a NumPy Array? 6 Easy Ways

Related Tutorials

Programmer Humor

Q: How do you tell an introverted computer scientist from an extroverted computer scientist? A: An extroverted computer scientist looks at your shoes when he talks to you.
Posted on Leave a comment

Can a Python Dictionary Have a List as a Value?

5/5 – (1 vote)

Question

💬 Question: Can you use lists as values of a dictionary in Python?

This short article will answer your question. So, let’s get started right away with the answer:

Answer

You can use Python lists as dictionary values. In fact, you can use arbitrary Python objects as dictionary values and all hashable objects as dictionary keys. You can define a list [1, 2] as a dict value either with dict[key] = [1, 2] or with d = {key: [1, 2]}.

Here’s a concrete example showing how to create a dictionary friends where each dictionary value is in fact a list of friends:

friends = {'Alice': ['Bob', 'Carl'], 'Bob': ['Alice'], 'Carl': []} print('Alice friends: ', friends['Alice'])
# Alice friends: ['Bob', 'Carl'] print('Bob friends: ', friends['Bob'])
# Bob friends: ['Alice'] print('Carl friends: ', friends['Carl'])
# Carl friends: []

Note that you can also assign lists as values of specific keys by using the dictionary assignment operation like so:

friends = dict()
friends['Alice'] = ['Bob', 'Carl']
friends['Bob'] = ['Alice']
friends['Carl'] = [] print('Alice friends: ', friends['Alice'])
# Alice friends: ['Bob', 'Carl'] print('Bob friends: ', friends['Bob'])
# Bob friends: ['Alice'] print('Carl friends: ', friends['Carl'])
# Carl friends: []

Can I Use Lists as Dict Keys?

You cannot use lists as dictionary keys because lists are mutable and therefore not hashable. As dictionaries are built on hash tables, all keys must be hashable or Python raises an error message.

Here’s an example:

d = dict()
my_list = [1, 2, 3]
d[my_list] = 'abc'

This leads to the following error message:

Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 3, in <module> d[my_list] = 'abc'
TypeError: unhashable type: 'list'

To fix this, convert the list to a Python tuple and use the Python tuple as a dictionary key. Python tuples are immutable and hashable and, therefore, can be used as set elements or dictionary keys.

Here’s the same example after converting the list to a tuple—it works! 🎉

d = dict()
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
d[my_tuple] = 'abc'

Before you go, maybe you want to join our free email academy of ambitious learners like you? The goal is to become 1% better every single day (as a coder). We also have cheat sheets! 👇

Posted on Leave a comment

PHP Curl POST JSON Send Request Data

by Vincy. Last modified on October 13th, 2022.

Most of the APIs are used to accept requests and send responses in JSON format. JSON is the de-facto data exchange format. It is important to learn how to send JSON request data with an API call.

The cURL is a way of remote accessing the API endpoint over the network. The below code will save you time to achieve posting JSON data via PHP cURL.

Example: PHP cURL POST by Sending JSON Data

It prepares the JSON from an input array and bundles it to the PHP cURL post.

It uses PHP json_encode function to get the encoded request parameters. Then, it uses the CURLOPT_POSTFIELDS option to bundle the JSON data to be posted.

curl-post-json.php

<?php
// URL of the API that is to be invoked and data POSTed
$url = 'https://example.com/api-to-post'; // request data that is going to be sent as POST to API
$data = array( "animal" => "Lion", "type" => "Wild", "name" => "Simba", "zoo" => array( "address1" => "5333 Zoo", "city" => "Los Angeles", "state" => "CA", "country" => "USA", "zipcode" => "90027" )
); // encoding the request data as JSON which will be sent in POST
$encodedData = json_encode($data); // initiate curl with the url to send request
$curl = curl_init($url); // return CURL response
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // Send request data using POST method
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST"); // Data conent-type is sent as JSON
curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type:application/json'
));
curl_setopt($curl, CURLOPT_POST, true); // Curl POST the JSON data to send the request
curl_setopt($curl, CURLOPT_POSTFIELDS, $encodedData); // execute the curl POST request and send data
$result = curl_exec($curl);
curl_close($curl); // if required print the curl response
print $result;
?>

php curl post json

The above code is one part of the API request-response cycle. If the endpoint belongs to some third-party API, this code is enough to complete this example.

But, if the API is in the intra-system (custom API created for the application itself), then, the posted data has to be handled.

How to get the JSON data in the endpoint

This is to handle the JSON data posted via PHP cURL in the API endpoint.

It used json_decode to convert the JSON string posted into a JSON object. In this program, it sets “true” to convert the request data into an array.

curl-request-data.php

<?php
// use the following code snippet to receive
// JSON POST data
// json_decode converts the JSON string to JSON object
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data;
?>

The json_encode function also allows setting the allowed nesting limit of the input JSON. The default limit is 512.

If the posted JSON data is exceeding the nesting limit, then the API endpoint will be failed to get the post data.

Other modes of posting data to a cURL request

In a previous tutorial, we have seen many examples of sending requests with PHP cURL POST.

This program sets the content type “application/json” in the CURLOPT_HTTPHEADER. There are other modes of posting data via PHP cURL.

  1. multipart/form-data – to send an array of post data to the endpoint/
  2. application/x-www-form-urlencoded – to send a URL-encoded string of form data.

Note: PHP http_build_query() can output the URL encoded string of an array.
Download

↑ Back to Top

Posted on Leave a comment

Python Return String From Function

5/5 – (1 vote)

Do you need to create a function that returns a string but you don’t know how? No worries, in sixty seconds, you’ll know! Go! 🚀

A Python function can return any object such as a string. To return a string, create the string object within the function body, assign it to a variable my_string, and return it to the caller of the function using the keyword operation return my_string. Or simply create the string within the return expression like so: return "hello world"

def f(): return 'hello world' f()
# hello world

Create String in Function Body

Let’s have a look at another example:

The following code creates a function create_string() that iterates over all numbers 0, 1, 2, …, 9, appends them to the string my_string, and returns the string to the caller of the function:

def create_string(): ''' Function to return string ''' my_string = '' for i in range(10): my_string += str(i) return my_string s = create_string()
print(s)
# 0123456789

Note that you store the resulting string in the variable s. The local variable my_string that you created within the function body is only visible within the function but not outside of it.

So, if you try to access the name my_string, Python will raise a NameError:

>>> print(my_string)
Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> print(my_string)
NameError: name 'my_string' is not defined

To fix this, simply assign the return value of the function — a string — to a new variable and access the content of this new variable:

>>> s = create_string()
>>> print(s)
0123456789

There are many other ways to return a string in Python.

Return String With List Comprehension

For example, you can use a list comprehension in combination with the string.join() method instead that is much more concise than the previous code—but creates the same string of digits:

def create_string(): ''' Function to return string ''' return ''.join([str(i) for i in range(10)]) s = create_string()
print(s)
# 0123456789

For a quick recap on list comprehension, feel free to scroll down to the end of this article.

You can also add some separator strings like so:

def create_string(): ''' Function to return string ''' return ' xxx '.join([str(i) for i in range(10)]) s = create_string()
print(s)
# 0 xxx 1 xxx 2 xxx 3 xxx 4 xxx 5 xxx 6 xxx 7 xxx 8 xxx 9

Return String with String Concatenation

You can also use a string concatenation and string multiplication statement to create a string dynamically and return it from a function.

Here’s an example of string multiplication:

def create_string(): ''' Function to return string ''' return 'ho' * 10 s = create_string()
print(s)
# hohohohohohohohohoho

String Concatenation of Function Arguments

Here’s an example of string concatenation that appends all arguments to a given string and returns the result from the function:

def create_string(a, b, c): ''' Function to return string ''' return 'My String: ' + a + b + c s = create_string('python ', 'is ', 'great')
print(s)
# My String: python is great

Concatenate Arbitrary String Arguments and Return String Result

You can also use dynamic argument lists to be able to add an arbitrary number of string arguments and concatenate all of them:

def create_string(*args): ''' Function to return string ''' return ' '.join(str(x) for x in args) print(create_string('python', 'is', 'great'))
# python is great print(create_string(42, 41, 40, 41, 42, 9999, 'hi'))
# 42 41 40 41 42 9999 hi

Background List Comprehension

💡 Knowledge: List comprehension is a very useful Python feature that allows you to dynamically create a list by using the syntax [expression context]. You iterate over all elements in a given context “for i in range(10)“, and apply a certain expression, e.g., the identity expression i, before adding the resulting values to the newly-created list.

In case you need to learn more about list comprehension, feel free to check out my explainer video:

YouTube Video

Programmer Humor

Q: How do you tell an introverted computer scientist from an extroverted computer scientist? A: An extroverted computer scientist looks at your shoes when he talks to you.