Posted on Leave a comment

How to Detect Mobile Device using JavaScript

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

If you are looking for a client-side solution to detect a mobile device, your search stops here :-). There are properties to detect this on the client side by using JavaScript.

Two methods of detecting if a current device is a mobile device are listed below.

  1. By using JavaScript window.matchMedia() method.
  2. By using navigator.userAgent property.

Both are using JavaScript basic methods to create the mobile device detector code.

1) By using JavaScript window.matchMedia() method

This method is the best one compared to the one using JavaScript navigator.userAgent. Because the userAgent is a setting that can be configured by the end users. They can change it!

matchmedia.html

Quick example

function isMobileDevice() { return window .matchMedia("only screen and (max-width: 760px)").matches;
}
if (isMobileDevice()) { document.write("<b>Detected device is a mobile.</b>");
} else { document .write("<b>Detected device is not a mobile.</b>");
}

The matchMedia() JavaScript custom method is used to do this mobile device detection.

It accepts a media query string and returns an object. This object will contain the current device’s media property and its relevancy.

Then, this object is used to find the match between the current device’s media property with the media query passed.

This program sends the media query containing a max-width of a mobile device that is expected to have.

If the current device’s media screen properties are matched with this argument, then this JavaScript function returns a boolean true.

View Demo

This screenshot is taken from my computer that prints the result of the above quick example.

detect mobile device javascript output

Media match with CSS

It can also be done by CSS instead of JavaScript. Follow the below steps to implement this using CSS.

  • Keep two possible messages in the HTML markup with  style=’display:none’.
  • Write CSS media query section with @media screen and (max-width: 600px).
  • Show and hide the appropriate UI notification element according to the screen width.
<!DOCTYPE html>
<html>
<head>
<title>How to Detect Mobile Device using JavaScript</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.mobile { display: none;
} .not-mobile { display: block;
} @media only screen and (max-width: 600px) { .mobile { display: block; } .not-mobile { display: none; }
}
</style>
</head>
<body> <b class="mobile">Detected device is a mobile.</b> <b class="not-mobile">Detected device is not a mobile.</b>
</body>
</html>

2) By using a navigator.userAgent property

The alternate method is for checking the current userAgent to detect if it is a mobile device.

The isMobileDevice() function in the below example does the test with a regex pattern. The regex contains the most possible values of a mobile device’s userAgent.

We have already used regex pattern matching for a JavaScript email validation utility.

The script compares the current device’s userAgent property with the pattern. If a match is found, then this function returns true to print the appropriate result.

navigator.html

<!DOCTYPE html>
<html>
<head>
<title>How to Detect Mobile Device using JavaScript</title>
</head>
<body> <h1>How to Detect Mobile Device using JavaScript</h1> <p>Note: Browser users can change value of "userAgent" via UA spoofing. So be aware of that and do not use this feature to provide a critical function of your website.</p> <script> function isMobileDevice() { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i .test(navigator.userAgent); /* for a more detailed test /(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i .test(navigator.userAgent) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i .test(navigator.userAgent.substr(0, 4)) */ } if (isMobileDevice()) { document.write("<b>Detected device is a mobile.</b>"); } else { document .write("<b>Detected device is not a mobile.</b>"); } </script>
</body>
</html>

Note: Browser users can change the value of “userAgent” via UA spoofing. So be aware of that and do not use this feature to provide a critical function of your website.

View Demo Download

↑ Back to Top

Posted on Leave a comment

How to Capture Screenshot of Page using JavaScript

by Vincy. Last modified on September 19th, 2022.

We are going to see three different ways of capturing screenshots of a webpage using JavaScript. These three methods give solutions to take screenshots with and without using libraries.

  1. Using html2canvas JavaScript library.
  2. Using plain HTML5 with JavaScript.
  3. Using WebRTC’s getDisplayMedia method.

1) Using the html2canvas JavaScript library

This method uses the popular JS library html2canvas to capture a screenshot from a webpage.

This script implements the below steps to capture a screenshot from the page HTML.

  • It initializes the html2canvas library class and supplies the body HTML to it.
  • It sets the target to append the output screenshot to the HTML body.
  • Generates canvas element and appends to the HTML.
  • It gets the image source data URL from the canvas object.
  • Push the source URL to the PHP via AJAX to save the screenshot to the server.

capture-screenshot/index.html

Quick example

<!DOCTYPE html>
<html>
<head>
<title>How to Capture Screenshot of Page using JavaScript</title>
<link rel='stylesheet' href='form.css' type='text/css' />
</head>
<body> <div class="phppot-container"> <h1>How to Capture Screenshot of Page using JavaScript</h1> <p> <button id="capture-screenshot">Capture Screenshot</button> </p> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript" src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script> <script type="text/javascript"> $('#capture-screenshot').click(function() { const screenshotTarget = document.body; html2canvas(screenshotTarget).then(canvas => { // to image as png use below line // const base64image = canvas.toDataURL("image/png"); // show the image in window use below line // window.location.href = base64image; // screenshot appended to the body as canvas document.body.appendChild(canvas); dataURL = canvas.toDataURL(); // to print the screenshot in console use below line // console.log(dataURL); // following line is optional and it is to save the screenshot // on the server side. It initiates an ajax call pushScreenshotToServer(dataURL); }); }); function pushScreenshotToServer(dataURL) { $.ajax({ url: "push-screenshot.php", type: "POST", data: { image: dataURL }, dataType: "html", success: function() { console.log('Screenshot pushed to server.'); } }); } </script>
</body>
</html>

We have already used this library in codes generating canvas elements with dynamic data. For example, we used html2canvas for creating invoice PDFs from HTML using JavaScript.

capture screenshot javascript

Push the screenshot to PHP to save

This PHP script reads the screenshot binaries posted via AJAX. It prepares the screenshot properties in a JSON format.

capture-screenshot/push-screenshot.php

<?php
if (isset($_POST['image'])) { // should have read and write permission to the disk to write the JSON file $screenshotJson = fopen("screenshot.json", "a") or die("Unable to open screenshot.json file."); $existingContent = file_get_contents('screenshot.json'); $contentArray = json_decode($existingContent, true); $screenshotImage = array( 'imageURL' => $_POST['image'] ); $contentArray[] = $screenshotImage; $fullData = json_encode($contentArray); file_put_contents('screenshot.json', $fullData); fclose($screenshotJson);
}
?>

This will output a “screenshot.json” file with the image data URL and store it in the application.
Video Demo

2) Using plain HTML5 with JavaScript

This JavaScript code includes two functions. One is to generate an image object URL and the other is to take screenshots by preparing the blob object from the page.

It prepares a blob object URL representing the output screenshot image captured from the page. It takes screenshots by clicking the “Capture Screenshot” button in the UI.

It controls the style properties and scroll coordinates of the node pushed to the screenshot object. This is to stop users have the mouse controls on the BLOB object.

In a previous example, we have seen how to create a blob and store it in the MySQL database.

This code will show the captured screenshot on a new page. The new page will have the generated blob URL as blob:http://localhost/0212cfc1-02ab-417c-b92f-9a7fe613808c

html5-javascript/index.html

function takeScreenshot() { var screenshot = document.documentElement .cloneNode(true); screenshot.style.pointerEvents = 'none'; screenshot.style.overflow = 'hidden'; screenshot.style.webkitUserSelect = 'none'; screenshot.style.mozUserSelect = 'none'; screenshot.style.msUserSelect = 'none'; screenshot.style.oUserSelect = 'none'; screenshot.style.userSelect = 'none'; screenshot.dataset.scrollX = window.scrollX; screenshot.dataset.scrollY = window.scrollY; var blob = new Blob([screenshot.outerHTML], { type: 'text/html' }); return blob;
} function generate() { window.URL = window.URL || window.webkitURL; window.open(window.URL .createObjectURL(takeScreenshot()));
}

3) Using WebRTC’s getDisplayMedia method

This method uses the JavaScript MediaServices class to capture the screenshot from the page content.

This example uses the getDisplayMedia() of this class to return the media stream of the current page content.

Note: It needs to grant permission to get the whole or part of the page content on the display.

It prepares an image source to draw into the canvas with the reference of its context. After writing the media stream object into the context, this script converts the canvas into a data URL.

This data URL is used to see the page screenshot captured on a new page.

After reading the media stream object to a screenshot element object, it should be closed. The JS MediaStreamTrack.stop() is used to close the track if it is not needed.

This JavaScript forEach iterates the MediaStream object array to get the track instance to stop.

webrtc-get-display-media/index.html

<!DOCTYPE html>
<html>
<head>
<title>How to Capture Sceenshot of Page using JavaScript</title>
<link rel='stylesheet' href='form.css' type='text/css' />
</head>
<body> <div class="phppot-container"> <p>This uses the WebRTC standard to take screenshot. WebRTC is popular and has support in all major modern browsers. It is used for audio, video communication.</p> <p>getDisplayMedia() is part of WebRTC and is used for screen sharing. Video is rendered and then page screenshot is captured from the video.</p> <p> <p> <button id="capture-screenshot" onclick="captureScreenshot();">Capture Screenshot</button> </p> </div> <script> const captureScreenshot = async () => { const canvas = document.createElement("canvas"); const context = canvas.getContext("2d"); const screenshot = document.createElement("screenshot"); try { const captureStream = await navigator.mediaDevices.getDisplayMedia(); screenshot.srcObject = captureStream; context.drawImage(screenshot, 0, 0, window.width, window.height); const frame = canvas.toDataURL("image/png"); captureStream.getTracks().forEach(track => track.stop()); window.location.href = frame; } catch (err) { console.error("Error: " + err); } }; </script>
</body>
</html>

Video DemoDownload

↑ Back to Top

Posted on Leave a comment

Python Set to Tuple | Tuple to Set | 3 Easy Ways

5/5 – (1 vote)

💬 Problem Formulation: Given a Python set. How to convert it to a tuple? And how to convert the tuple back to a set?

There are three main ways:

  • Method 1: To convert a Python set to a tuple, use the tuple(my_set) function.
  • Method 2: To convert a Python tuple to a set, use the set(my_tuple) function.
  • Method 3: To convert a Python tuple of mutable elements to a set, use the expression set(tuple(x) for x in my_tuple) to avoid a TypeError.

I’ll also give you a bonus method 4 that shows you what to do to retain the ordering information when converting a tuple to a set—so keep reading! 🙂

Method 1: Convert Set to Tuple with tuple()

To convert a set to a tuple, pass the set into the tuple() function. This is a built-in Python function, so you don’t need to import or install any library to use it. The return value is a new tuple from the values in the set.

👉 Here’s an example where you convert the set {1, 2, 3} to a tuple (1, 2, 3):

my_set = {1, 2, 3}
my_tuple = tuple(my_set)
print(my_tuple)
# (1, 2, 3)

By the way, here’s an explainer video on this function:

YouTube Video

Method 2: Convert Tuple to Set with set()

To convert a tuple to a set, pass the tuple into the set() function. This is a built-in Python function, so you don’t need to import or install any library. The return value is a new set from the values in the tuple.

👉 Here’s an example where you convert the tuple (1, 2, 3) to a set {1, 2, 3}:

my_tuple = (1, 2, 3)
my_set = set(my_tuple)
print(my_set)
# {1, 2, 3}
YouTube Video

⚡ Problem: However, the conversion process from a tuple to set doesn’t always work because if you try to convert a tuple of mutable values, Python will raise the TypeError: unhashable type!

Read on to learn more about this problem—and how to resolve it easily: 👉

Method 3: Convert Tuple to Set with Set Comprehension

💡 A Python set is an unordered collection of unique immutable elements. Each element must define explicitly or implicitly the __hash__() dunder method, i.e., must be hashable.

If you attempt to convert a tuple of mutable elements (e.g., lists) to a set, Python will raise an error such as the TypeError: unhashable type: 'list':

my_tuple = ([1, 2], [3, 4], [5, 6])
my_set = set(my_tuple)
# TypeError: unhashable type: 'list'

In this case, you can use set comprehension to convert each inner tuple element to an immutable type. For example, the expression set(tuple(x) for x in my_tuple) converts each inner list to a tuple. The result is a set of immutable tuples.

Here’s the solution to this problem in a minimal code example:

my_tuple = ([1, 2], [3, 4], [5, 6])
my_set = set(tuple(x) for x in my_tuple)
print(my_set)
# {(1, 2), (3, 4), (5, 6)}

The final “bonus” section introduces another elegant way to retain the ordering information in a set:

Bonus Method 4: Enumerate Elements

Sometimes, you want to associate each set or tuple element with a specific numerical “index” value, i.e., a unique integer identifier. The enumerate() method to the rescue!

YouTube Video
  • Use tuple(enumerate(my_set)) to convert a set to an enumerated tuple.
  • Use set(enumerate(my_tuple)) to convert a tuple to an enumerated set.

The result is the respective container data structure with (identifier, value) tuples:

my_set = {'Alice', 'Bob', 'Carl'} my_tuple = tuple(enumerate(my_set))
print(my_tuple)
# ((0, 'Carl'), (1, 'Bob'), (2, 'Alice')) my_set = set(enumerate(('Alice', 'Bob', 'Carl')))
print(my_set)
# {(2, 'Carl'), (0, 'Alice'), (1, 'Bob')}

Especially in the case where you convert a tuple to a set, this makes a lot of sense because you can retain the information on the ordering of elements that would be otherwise lost after converting to a set.


Thanks for reading the whole article, my friend! You can join us here (we have cheat sheets too):

Posted on Leave a comment

How to Find the Longest String in a NumPy Array?

5/5 – (1 vote)

Python Longest String in NumPy Array

To find the longest string in a given NumPy array, say arr, you can use the max(arr, key=len) function that determines the maximum by comparing the length of the array elements using the len() function as a key for comparison.

import numpy as np arr = np.array(['Alice', 'Bob', 'Carl'])
print(max(arr, key=len))
# Alice

You can find more about the powerful max() function in our detailed blog tutorial:

👉 Recommended Tutorial: Python Maximum Function

Python Length of Longest String in NumPy Array

To find the length of the longest string in a NumPy array arr, use the max(arr, key=len) function to obtain the string with the maximum length and then pass this max string into the len() function to obtain the number of characters of the max string.

len(max(arr, key=len))

Here’s a more detailed code example of a simple 1D NumPy Array:

import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) # Print Longest String:
print(max(arr, key=len))
# Alice # Print Length of Longest String
print(len(max(arr, key=len)))
# 5

Get Longest String from NumPy Axis (2D, Column or Row)

To get the longest string from a certain NumPy array axis (e.g., row or column), first use simple NumPy slicing and indexing to get that axis (e.g., arr[0, :] to get the first row) and pass it into the max() function with the key argument set to the length function like so: max(arr[0, :], key=len).

Here’s an example to get the longest string of the first row of a 2D array:

import numpy as np arr = np.array([['Alice', 'Bob', 'Carl'], ['Ann', 'Zoe', 'Leonard']]) print(max(arr[0, :], key=len))
# Alice

Here’s an example to get the longest string of the third column of a 2D array:

print(max(arr[:, 2], key=len))
# Leonard

You get the idea. 🙂

If you want to get the longest string from the whole NumPy array, not only from a column or row or axis, first flatten it and then pass the flattened array into the max() function using the key=len argument.

👉 Recommended Tutorial: How to Flatten a NumPy Array?

Posted on Leave a comment

Combine Images Using Numpy

Rate this post

Summary: You can combine images represented in the form of Numpy arrays using the concatenate function of the Numpy library as np.concatenate((numpydata_1, numpydata_2), axis=1). This combines the images horizontally. Use syntax: np.concatenate((numpydata_1, numpydata_2), axis=0) to combine the images vertically.

Problem Formulation

Consider you have two images represented as Numpy arrays of pixels. How will you combine the two images represented in the form of Numpy pixel arrays?

Combining two images that are in the form of Numpy arrays will create a new Numpy array having pixels that will represent a new combined image formed by either concatenating the two images horizontally or vertically. Let’s understand this with the help of an example:

Given: Let’s say we have two different images as given below (Both images have similar dimensions)

When you convert them to Numpy arrays this is how you can represent the two images:

numpydata_1 numpydata_2
[[[184 186 201]
[184 186 201]
[184 187 202]

[174 189 218]
[174 189 218]
[173 188 217]]

[[184 186 201]
[184 186 201]
[184 187 202]

[174 189 218]
[173 188 217]
[173 188 217]]

[[183 186 203]
[183 186 203]
[184 187 204]

[173 188 217]
[173 188 217]
[172 187 216]]

[[ 43 64 55]
[ 45 66 57]
[ 48 69 60]

[ 63 84 77]
[ 64 83 77]
[ 64 83 77]]

[[ 49 70 61]
[ 50 71 62]
[ 53 73 64]

[ 58 84 73]
[ 60 83 73]
[ 61 84 74]]

[[ 53 74 65]
[ 52 73 64]
[ 56 73 65]

[ 56 84 72]
[ 57 83 72]
[ 57 83 72]]]

[[[255 255 255]
[255 255 255]
[255 255 255]

[242 245 252]
[240 243 250]
[241 244 251]]

[[255 255 255]
[255 255 255]
[255 255 255]

[242 245 252]
[241 244 251]
[241 244 251]]

[[255 255 255]
[255 255 255]
[255 255 255]

[243 246 253]
[243 246 253]
[241 244 251]]

[[115 152 144]
[111 151 142]
[ 96 142 131]

[ 72 108 106]
[ 73 109 107]
[ 77 113 111]]

[[ 75 118 108]
[ 79 125 114]
[ 82 132 120]

[ 69 104 100]
[ 69 104 100]
[ 71 106 102]]

[[ 42 90 78]
[ 47 97 85]
[ 64 116 103]

[ 65 97 94]
[ 60 92 89]
[ 64 96 93]]]

Challenge: Combine the two images – (i) horizontally (ii) vertically

Expected Output:

Horizontal Combination Vertical Combination
[[[184 186 201]
[184 186 201]
[184 187 202]

[242 245 252]
[240 243 250]
[241 244 251]]
[[184 186 201]
[184 186 201]
[184 187 202]

[242 245 252]
[241 244 251]
[241 244 251]]
[[183 186 203]
[183 186 203]
[184 187 204]

[243 246 253]
[243 246 253]
[241 244 251]]

[[ 43 64 55]
[ 45 66 57]
[ 48 69 60]

[ 72 108 106]
[ 73 109 107]
[ 77 113 111]]
[[ 49 70 61]
[ 50 71 62]
[ 53 73 64]

[ 69 104 100]
[ 69 104 100]
[ 71 106 102]]
[[ 53 74 65]
[ 52 73 64]
[ 56 73 65]

[ 65 97 94]
[ 60 92 89]
[ 64 96 93]]]
[[[184 186 201]
[184 186 201]
[184 187 202]

[174 189 218]
[174 189 218]
[173 188 217]]
[[184 186 201]
[184 186 201]
[184 187 202]

[174 189 218]
[173 188 217]
[173 188 217]]
[[183 186 203]
[183 186 203]
[184 187 204]

[173 188 217]
[173 188 217]
[172 187 216]]

[[115 152 144]
[111 151 142]
[ 96 142 131]

[ 72 108 106]
[ 73 109 107]
[ 77 113 111]]
[[ 75 118 108]
[ 79 125 114]
[ 82 132 120]

[ 69 104 100]
[ 69 104 100]
[ 71 106 102]]
[[ 42 90 78]
[ 47 97 85]
[ 64 116 103]

[ 65 97 94]
[ 60 92 89]
[ 64 96 93]]]

So, are you up for the challenge? Well! If it looks daunting – don’t worry. This tutorial will guide you through the techniques to solve the programming challenge. So, without further delay let us dive into the solution.

Prerequisite: To understand how the solutions to follow work it is essential to understand – “How to concatenate two Numpy arrays in Python.”

NumPy’s concatenate() method joins a sequence of arrays along an existing axis. The first couple of comma-separated array arguments are joined. If you use the axis argument, you can specify along which axis the arrays should be joined. For example, np.concatenate(a, b, axis=0) joins arrays along the first axis and np.concatenate(a, b, axis=None) joins the flattened arrays.

To learn more about concatenating arrays in Python, here’s a wonderful tutorial that will guide you through numerous methods of doing so: How to Concatenate Two NumPy Arrays?

Combine Images “Horizontally” with Numpy

Approach: The concatenate() method of the Numpy library allows you combine matrices of different images along different axes. To combine the two image arrays horizontally, you must specify the axis=1.

Code: Please go through the comments mentioned in the script in order to understand how each line of code works.

from PIL import Image
import numpy as np
# Reading the given images img_1 = Image.open('img_1.JPG')
img_2 = Image.open('img_2.JPG')
# Converting the two images into Numpy Arrays
numpydata_1 = np.asarray(img_1)
numpydata_2 = np.asarray(img_2)
# Combining the two images horizontally
horizontal = np.concatenate((numpydata_1, numpydata_2), axis=1)
# Display the horizontally combined image as a Numpy Array
print(horizontal)
# converting the combined image in the Numpy Array form to an image format
data = Image.fromarray(horizontal)
# Saving the combined image
data.save('combined_pic.png')

Output:

[[[184 186 201] [184 186 201] [184 187 202] ... [242 245 252] [240 243 250] [241 244 251]] [[184 186 201] [184 186 201] [184 187 202] ... [242 245 252] [241 244 251] [241 244 251]] [[183 186 203] [183 186 203] [184 187 204] ... [243 246 253] [243 246 253] [241 244 251]] ... [[ 43 64 55] [ 45 66 57] [ 48 69 60] ... [ 72 108 106] [ 73 109 107] [ 77 113 111]] [[ 49 70 61] [ 50 71 62] [ 53 73 64] ... [ 69 104 100] [ 69 104 100] [ 71 106 102]] [[ 53 74 65] [ 52 73 64] [ 56 73 65] ... [ 65 97 94] [ 60 92 89] [ 64 96 93]]]

Here’s how the horizontally combined image looks like when saved to a file:

Wonderful! Isn’t it?

Combine Images “Vertically” with Numpy

In the previous solution, we combined the images horizontally. In this soution you will learn how to combine two images represented in the form of Numpy arrays vertically.

Approach: The idea is quite similar to the previous solution with the only difference in the axis parameter of the concatenate() method. To combine the two image arrays vertically, you must specify the axis=0.

Code:

from PIL import Image
import numpy as np
# Reading the given images
img_1 = Image.open('img_1.JPG')
img_2 = Image.open('img_2.JPG')
# Converting the two images into Numpy Arrays
numpydata_1 = np.asarray(img_1)
numpydata_2 = np.asarray(img_2)
# Combining the two images horizontally
vertical = np.concatenate((numpydata_1, numpydata_2), axis=0)
# Display the vertically combined image as a Numpy Array
print(vertical)
# converting the combined image in the Numpy Array form to an image format
data = Image.fromarray(vertical)
# Saving the combined image
data.save('combined_pic.png')

Output:

[[[184 186 201] [184 186 201] [184 187 202] ... [174 189 218] [174 189 218] [173 188 217]] [[184 186 201] [184 186 201] [184 187 202] ... [174 189 218] [173 188 217] [173 188 217]] [[183 186 203] [183 186 203] [184 187 204] ... [173 188 217] [173 188 217] [172 187 216]] ... [[115 152 144] [111 151 142] [ 96 142 131] ... [ 72 108 106] [ 73 109 107] [ 77 113 111]] [[ 75 118 108] [ 79 125 114] [ 82 132 120] ... [ 69 104 100] [ 69 104 100] [ 71 106 102]] [[ 42 90 78] [ 47 97 85] [ 64 116 103] ... [ 65 97 94] [ 60 92 89] [ 64 96 93]]]

Here’s how the horizontally combined image looks like when saved to a file:

Hurrah! We have successfully combined the two images vertically.

Exercises

Before we wrap this tutorial, here’s a set of challenges to further enhance your knowledge.

Challenge 1: Consider that you have been given an image. How will you convert this image to a Numpy array?

Given Image

Solution:

from PIL import Image
from numpy import asarray
img = Image.open('img.png')
img_to_array = asarray(img)
print(img_to_array)

Challenge 2: Consider that you have two images of different dimensions. How will you combine the two images horizontally using OpenCV?

Given Images:

Image_1.png
Image_2.png

Solution:

import cv2
import numpy as np
img_1 = cv2.imread('Imgage_1.png')
img_2 = cv2.imread('Image_2.png')
h1, w1 = img_1.shape[:2]
h2, w2 = img_2.shape[:2]
img_3 = np.zeros((max(h1, h2), w1 + w2, 3), dtype=np.uint8)
img_3[:, :] = (255, 255, 255)
img_3[:h1, :w1, :3] = img_1
img_3[:h2, w1:w1 + w2, :3] = img_2
cv2.imwrite('Img_3.png', img_3)

Output:

Img_3.png

Want to learn about OpenCV? Here’s an amazing tutorial to get you started with OpenCV – Python OpenCV Image Processing.

Conclusion

Phew! That was some coding challenge! I hope you can now successfully combine images given as Numpy arrays in both dimensions – horizontally as well as vertically. With that we come to the end of this tutorial. Please subscribe and stay tuned for more interesting tutorials and solutions in the future.

Happy coding! 🙂


Posted on Leave a comment

Solidity Example – Safe Remote Purchase

5/5 – (1 vote)
YouTube Video

This article continues on the Solidity Smart Contract Examples series, which implements a simple, but the useful process of safe remote purchase.

Here, we’re walking through an example of a blind auction (docs).

  • We’ll first lay out the entire smart contract example without the comments for readability and development purposes.
  • Then we’ll dissect it part by part, analyze it and explain it.
  • Following this path, we’ll get a hands-on experience with smart contracts, as well as good practices in coding, understanding, and debugging smart contracts.

Smart Contract – Safe Remote Purchase

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract Purchase { uint public value; address payable public seller; address payable public buyer; enum State { Created, Locked, Release, Inactive } State public state; modifier condition(bool condition_) { require(condition_); _; } error OnlyBuyer(); error OnlySeller(); error InvalidState(); error ValueNotEven(); modifier onlyBuyer() { if (msg.sender != buyer) revert OnlyBuyer(); _; } modifier onlySeller() { if (msg.sender != seller) revert OnlySeller(); _; } modifier inState(State state_) { if (state != state_) revert InvalidState(); _; } event Aborted(); event PurchaseConfirmed(); event ItemReceived(); event SellerRefunded(); constructor() payable { seller = payable(msg.sender); value = msg.value / 2; if ((2 * value) != msg.value) revert ValueNotEven(); } function abort() external onlySeller inState(State.Created) { emit Aborted(); state = State.Inactive; seller.transfer(address(this).balance); } function confirmPurchase() external inState(State.Created) condition(msg.value == (2 * value)) payable { emit PurchaseConfirmed(); buyer = payable(msg.sender); state = State.Locked; } function confirmReceived() external onlyBuyer inState(State.Locked) { emit ItemReceived(); state = State.Release; buyer.transfer(value); } function refundSeller() external onlySeller inState(State.Release) { emit SellerRefunded(); state = State.Inactive; seller.transfer(3 * value); }
}

Code breakdown and analysis

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract Purchase {

The state variables for recording the value, seller, and buyer addresses.

 uint public value; address payable public seller; address payable public buyer;

For the first time, we’re introducing the enum data structure that symbolically defines the four possible states of our contract. The states are internally indexed from 0 to enum_length - 1.

 enum State { Created, Locked, Release, Inactive }

The variable state keeps track of the current state. Our contract starts by default in the created state and can transition to the Locked, Release, and Inactive state.

 State public state;

The condition modifier guards a function against executing without previously satisfying the condition, i.e. an expression given alongside the function definition.

 modifier condition(bool condition_) { require(condition_); _; }

The error definitions are used with the appropriate, equally-named modifiers.

 error OnlyBuyer(); error OnlySeller(); error InvalidState(); error ValueNotEven();

The onlyBuyer modifier guards a function against executing when the function caller is not the buyer.

 modifier onlyBuyer() { if (msg.sender != buyer) revert OnlyBuyer(); _; }

The onlySeller modifier guards a function against executing when the function caller differs from the seller.

 modifier onlySeller() { if (msg.sender != seller) revert OnlySeller(); _; }

The inState modifier guards a function against executing when the contract state differs from the required state_.

 modifier inState(State state_) { if (state != state_) revert InvalidState(); _; }

The events that the contract emits to acknowledge the functions abort(), confirmPurchase(), confirmReceived(), and refundSeller() were executed.

 event Aborted(); event PurchaseConfirmed(); event ItemReceived(); event SellerRefunded();

The constructor is declared as payable, meaning that the contract deployment (synonyms creation, instantiation) requires sending a value (msg.value) with the contract-creating transaction.

 constructor() payable {

The seller state variable is set to msg.sender address, cast (converted) to payable.

 seller = payable(msg.sender);

The value state variable is set to half the msg.value, because both the seller and the buyer have to put twice the value of the item being sold/bought into the contract as an escrow agreement.

💡 Info: “Escrow is a legal arrangement in which a third party temporarily holds money or property until a particular condition has been met (such as the fulfillment of a purchase agreement).” (source)

In our case, our escrow is our smart contract.

 value = msg.value / 2;

If the value is not equally divided, i.e. the msg.value is not an even number, the function will terminate. Since the seller will always

 if ((2 * value) != msg.value) revert ValueNotEven(); }

Aborting the remote safe purchase is allowed only in the Created state and only by the seller.

The external keyword makes the function callable only by other accounts / smart contracts. From the business perspective, only the seller can call the abort() function and only before the buyer decides to purchase, i.e. before the contract enters the Locked state.

 function abort() external onlySeller inState(State.Created) {

Emits the Aborted event, the contract state transitions to inactive, and the balance is transferred to the seller.

 emit Aborted(); state = State.Inactive;

💡 Note: “Prior to version 0.5.0, Solidity allowed address members to be accessed by a contract instance, for example, this.balance. This is now forbidden and an explicit conversion to address must be done: address(this).balance.” (docs).

In other words, this keyword lets us access the contract’s inherited members.

Every contract inherits its members from the address type and can access these members via address(this).<a member> (docs).

 seller.transfer(address(this).balance); }

The confirmPurchase() function is available for execution only in the Created state.

It enforces the rule that a msg.value must be twice the value of the purchase.

The confirmPurchase() function is also declared as payable, meaning the caller, i.e. the buyer has to send the currency (msg.value) with the function call.

 function confirmPurchase() external inState(State.Created) condition(msg.value == (2 * value)) payable {

The event PurchaseConfirmed() is emitted to mark the purchase confirmation.

 emit PurchaseConfirmed();

The msg.sender value is cast to payable and assigned to the buyer variable.

💡 Info: Addresses are non-payable by design to prevent accidental payments; that’s why we have to cast an address to a payable before being able to transfer a payment.

 buyer = payable(msg.sender);

The state is set to Locked as seller and buyer entered the contract, i.e., our digital version of an escrow agreement.

 state = State.Locked; }

The confirmReceived() function is available for execution only in the Locked state, and only to the buyer.

Since the buyer deposited twice the value amount and withdrew only a single value amount, the second value amount remains on the contract balance with the seller’s deposit.

 function confirmReceived() external onlyBuyer inState(State.Locked) {

Emits the ItemReceived() event.

 emit ItemReceived();

Changes the state to Release.

 state = State.Release;

Transfers the deposit to the buyer.

 buyer.transfer(value); }

The refundSeller() function is available for execution only in the Release state, and only to the seller.

Since the seller deposited twice the value amount and earned a single value amount from the purchase, the contract transfers three value amounts from the contract balance to the seller.

 function refundSeller() external onlySeller inState(State.Release) {

Emits the SellerRefunded() event.

 emit SellerRefunded();

Changes the state to Inactive.

 state = State.Inactive;

Transfers the deposit of two value amounts and the one earned value amount to the seller.

 seller.transfer(3 * value); }
}

Our smart contract example of a safe remote purchase is a nice and simple example that demonstrates how a purchase may be conducted on the Ethereum blockchain network.

The safe remote purchase example shows two parties, a seller and a buyer, who both enter a trading relationship with their deposits to the contract balance.

Each deposit amounts to twice the value of the purchase, meaning that the contract balance will hold four times the purchase value at its highest point, i.e. in the Locked state.

The height of deposits is intended to stimulate the resolution of any possible disputes between the parties, because otherwise, their deposits will stay locked and unavailable in the contract balance.

When the buyer confirms that he received the goods he purchased, the contract will transition to the Release state, and the purchase value will be released to the buyer.

The seller can now withdraw his earned purchase value with the deposit, the contract balance drops to 0 Wei, the contract transitions to the Inactive state, and the safe remote purchase concludes with execution.

The Contract Arguments

This section contains additional information for running the contract. We should expect that our example accounts may change with each refresh/reload of Remix.

Our contract creation argument is the deposit (twice the purchase value). We’ll assume the purchase value to be 5 Wei, making the contract creation argument very simple:

10

Contract Test Scenario

  1. Account 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4 deploys the contract with a deposit of 10 Wei, effectively becoming a seller.
  2. Account 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2 confirms the purchase by calling the confirmPurchase() function and enters the trade with a deposit of 10 Wei, effectively becoming a buyer.
  3. The buyer confirms receiving the order by calling the confirmReceived() function.
  4. The seller concludes the trade by calling the refundSeller() function.

Conclusion

We continued our smart contract example series with this article that implements a safe remote purchase.

First, we laid out clean source code (without any comments) for readability purposes.

Second, we dissected the code, analyzed it, and explained each possibly non-trivial segment.


Posted on Leave a comment

PHP YouTube Video Downloader Script

by Vincy. Last modified on September 15th, 2022.

YouTube is almost the numero uno platform for hosting videos. It allows users to publish and share videos, more like a social network.

Downloading YouTube videos is sometimes required. You must read through the YouTube terms and conditions before downloading videos and act according to the permissions given. For example you may wish to download to have a backup of older videos that are going to be replaced or removed.

This quick example provides a YouTube Video downloader script in PHP. It has a video URL defined in a PHP variable. It also establishes a key to access the YouTube video meta via API.

Configure the key and store the video URL to get the video downloader link using this script.

Quick example

<?php
$apiKey = "API_KEY";
$videoUrl = "YOUTUBE_VIDEO_URL";
preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $videoUrl, $match);
$youtubeVideoId = $match[1];
$videoMeta = json_decode(getYoutubeVideoMeta($youtubeVideoId, $apiKey));
$videoTitle = $videoMeta->videoDetails->title;
$videoFormats = $videoMeta->streamingData->formats;
foreach ($videoFormats as $videoFormat) { $url = $videoFormat->url; if ($videoFormat->mimeType) $mimeType = explode(";", explode("/", $videoFormat->mimeType)[1])[0]; else $mimeType = "mp4"; ?>
<a href="video-downloader.php?link=<?php echo urlencode($url)?>&title=<?php echo urlencode($videoTitle)?>&type=<?php echo $mimeType; ?>"> Download Video</a>
<?php
} function getYoutubeVideoMeta($videoId, $key)
{ $ch = curl_init(); $curlUrl = 'https://www.youtube.com/youtubei/v1/player?key=' . $key; curl_setopt($ch, CURLOPT_URL, $curlUrl); curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); $curlOptions = '{"context": {"client": {"hl": "en","clientName": "WEB", "clientVersion": "2.20210721.00.00","clientFormFactor": "UNKNOWN_FORM_FACTOR","clientScreen": "WATCH", "mainAppWebInfo": {"graftUrl": "/watch?v=' . $videoId . '",}},"user": {"lockedSafetyMode": false}, "request": {"useSsl": true,"internalExperimentFlags": [],"consistencyTokenJars": []}}, "videoId": "' . $videoId . '", "playbackContext": {"contentPlaybackContext": {"vis": 0,"splay": false,"autoCaptionsDefaultOn": false, "autonavState": "STATE_NONE","html5Preference": "HTML5_PREF_WANTS","lactMilliseconds": "-1"}}, "racyCheckOk": false, "contentCheckOk": false}'; curl_setopt($ch, CURLOPT_POSTFIELDS, $curlOptions); $headers = array(); $headers[] = 'Content-Type: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $curlResult = curl_exec($ch); if (curl_errno($ch)) { echo 'Error:' . curl_error($ch); } curl_close($ch); return $curlResult;
}
?>

This example code works in the following flow to output the link to download the YouTube video.

  1. Get the unique id of the YouTube video from the input URL.
  2. Request YouTube API via PHP cURL post to access the video metadata.
  3. Get video title, data array in various formats, and MIME type by parsing the cURL response.
  4. Pass the video links, title and mime types to the video downloader script.
  5. Apply PHP readfile() to download the video file by setting the PHP header Content-type.

youtube video downloader links php

The below video downloader script is called by clicking the “Download video” link in the browser.

It receives the video title, and extension to define the output video file name. It also gets the video link from which it reads the video to be downloaded to the browser.

This script sets the content header in PHP to output the YouTube video file.

video-downloader.php

<?php
// this PHP script reads and downloads the video from YouTube
$downloadURL = urldecode($_GET['link']);
$downloadFileName = urldecode($_GET['title']) . '.' . urldecode($_GET['type']);
if (! empty($downloadURL) && substr($downloadURL, 0, 8) === 'https://') { header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment;filename=\"$downloadFileName\""); header("Content-Transfer-Encoding: binary"); readfile($downloadURL);
}
?>

View Demo

Collect YouTube video URL via form and process video downloader script

In the quick example, it has a sample to hardcode the YouTube video URL to a PHP variable.

But, the below code will allow users to enter the video URL instead of the hardcode.

An HTML form will post the entered video URL to process the PHP cURL request to the YouTube API.

After posting the video URL, the PHP flow is the same as the quick example. But, the difference is, that it displays more links to download videos in all the adaptive formats.

index.php

<form method="post" action=""> <h1>PHP YouTube Video Downloader Script</h1> <div class="row"> <input type="text" class="inline-block" name="youtube-video-url"> <button type="submit" name="submit" id="submit">Download Video</button> </div>
</form>
<?php
if (isset($_POST['youtube-video-url'])) { $videoUrl = $_POST['youtube-video-url']; ?>
<p> URL: <a href="<?php echo $videoUrl;?>"><?php echo $videoUrl;?></a>
</p>
<?php
}
if (isset($_POST['submit'])) { preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $videoUrl, $match); $youtubeVideoId = $match[1]; require './youtube-video-meta.php'; $videoMeta = json_decode(getYoutubeVideoMeta($youtubeVideoId, $key)); $videoThumbnails = $videoMeta->videoDetails->thumbnail->thumbnails; $thumbnail = end($videoThumbnails)->url; ?>
<p> <img src="<?php echo $thumbnail; ?>">
</p>
<?php $videoTitle = $videoMeta->videoDetails->title; ?>
<h2>Video title: <?php echo $videoTitle; ?></h2>
<?php $shortDescription = $videoMeta->videoDetails->shortDescription; ?>
<p><?php echo str_split($shortDescription, 100)[0];?></p>
<?php $videoFormats = $videoMeta->streamingData->formats; if (! empty($videoFormats)) { if (@$videoFormats[0]->url == "") { ?>
<p> <strong>This YouTube video cannot be downloaded by the downloader!</strong><?php $signature = "https://example.com?" . $videoFormats[0]->signatureCipher; parse_str(parse_url($signature, PHP_URL_QUERY), $parse_signature); $url = $parse_signature['url'] . "&sig=" . $parse_signature['s']; ?> </p>
<?php die(); } ?>
<h3>With Video & Sound</h3>
<table class="striped"> <tr> <th>Video URL</th> <th>Type</th> <th>Quality</th> <th>Download Video</th> </tr> <?php foreach ($videoFormats as $videoFormat) { if (@$videoFormat->url == "") { $signature = "https://example.com?" . $videoFormat->signatureCipher; parse_str(parse_url($signature, PHP_URL_QUERY), $parse_signature); $url = $parse_signature['url'] . "&sig=" . $parse_signature['s']; } else { $url = $videoFormat->url; } ?> <tr> <td><a href="<?php echo $url; ?>">View Video</a></td> <td><?php if($videoFormat->mimeType) echo explode(";",explode("/",$videoFormat->mimeType)[1])[0]; else echo "Unknown";?></td> <td><?php if($videoFormat->qualityLabel) echo $videoFormat->qualityLabel; else echo "Unknown"; ?></td> <td><a href="video-downloader.php?link=<?php echo urlencode($url)?>&title=<?php echo urlencode($videoTitle)?>&type=<?php if($videoFormat->mimeType) echo explode(";",explode("/",$videoFormat->mimeType)[1])[0]; else echo "mp4";?>"> Download Video</a></td> </tr> <?php } ?> </table>
<?php // if you wish to provide formats based on different formats // then keep the below two lines $adaptiveFormats = $videoMeta->streamingData->adaptiveFormats; include 'adaptive-formats.php'; ?> <?php }
}
?>

This program will output the following once it has the video downloader response.

php youtube video downloader

PHP cURL script to get the video metadata

The PHP cURL script used to access the YouTube endpoint to read the file meta is already seen in the quick example.

The above code snippet has a PHP require_once statement for having the cURL post handler.

The youtube-video-meta.php file has this handler to read the video file meta. It receives the unique id of the video and the key used in the PHP cURL parsing.

In a recently posted article, we have collected file meta to upload to Google Drive.

Display YouTube video downloaders in adaptive formats

The landing page shows another table of downloads to get the video file in the available adaptive formats.

The PHP script accesses the adaptiveFormats property of the Youtube video meta-object to display these downloads.

adaptive-formats.php

<h3>YouTube Videos Adaptive Formats</h3>
<table class="striped"> <tr> <th>Type</th> <th>Quality</th> <th>Download Video</th> </tr> <?php foreach ($adaptiveFormats as $videoFormat) { try { $url = $videoFormat->url; } catch (Exception $e) { $signature = $videoFormat->signatureCipher; parse_str(parse_url($signature, PHP_URL_QUERY), $parse_signature); $url = $parse_signature['url']; } ?> <tr> <td><?php if(@$videoFormat->mimeType) echo explode(";",explode("/",$videoFormat->mimeType)[1])[0]; else echo "Unknown";?></td> <td><?php if(@$videoFormat->qualityLabel) echo $videoFormat->qualityLabel; else echo "Unknown"; ?></td> <td><a href="video-downloader.php?link=<?php print urlencode($url)?>&title=<?php print urlencode($videoTitle)?>&type=<?php if($videoFormat->mimeType) echo explode(";",explode("/",$videoFormat->mimeType)[1])[0]; else echo "mp4";?>">Download Video</a></td> </tr> <?php }?>
</table>

View DemoDownload

↑ Back to Top

Posted on Leave a comment

How to Find All Palindromes in a Python String?

5/5 – (1 vote)

Coding Challenge

💬 Challenge: Given a string. How to find all palindromes in the string?

For comprehensibility, allow me to quickly add a definition of the term palindrome:

💡 Definition: A palindrome is a sequence of characters that reads the same backward as forward such as 'madam', 'anna', or '101'.

This article wants to give you a quick and easy solution in Python. First, we’ll solve the easier but important problem of checking if a substring is a palindrome in the first place:

How to Check If String is Palindrome

You can easily check if a string is a palindrome by using the slicing expression word == word[::-1] that evaluates to True if the word is the same forward and backward, i.e., it is a palindrome.

👉 Recommended Tutorial: Python Palindromes One-Liner

Next, we’ll explore how to find all substrings in a Python string that are also palindromes. You can find our palindrome checker in the code solution (highlighted):

Find All Substrings That Are Palindrome

The brute-force approach to finding all palindromes in a string is to iterate over all substrings in a nested for loop. Then check each substring if it is a palindrome using word == word[::-1]. Keep track of the found palindromes using the list.append() method. Return the final list after traversing all substrings.

Here’s the full solution:

def find_palindromes(s): palindromes = [] n = len(s) for i in range(n): for j in range(i+1,n+1): word = s[i:j] if word == word[::-1]: palindromes.append(word) return palindromes print(find_palindromes('locoannamadam'))
# ['l', 'o', 'oco', 'c', 'o', 'a', 'anna',
# 'n', 'nn', 'n', 'a', 'ama', 'm', 'madam',
# 'a', 'ada', 'd', 'a', 'm'] print(find_palindromes('anna'))
# ['a', 'anna', 'n', 'nn', 'n', 'a'] print(find_palindromes('abc'))
# ['a', 'b', 'c']

Runtime Complexity

This has cubic runtime complexity, i.e., for a string with length n, we need to check O(n*n) different words. Each word may have up to n characters, thus the palindrome check itself is O(n). Together, this yields runtime complexity of O(n*n*n) = O(n³).

Quadratic Runtime Solutions

Is this the best we can do? No! There’s also an O(n²) time solution!

Here’s a quadratic-runtime solution to find all palindromes in a given string that ignores the trivial one-character palindromes (significantly modified from source):

def find_palindromes(s, j, k): ''' Finds palindromes in substring between indices j and k''' palindromes = [] while j >= 0 and k < len(s): if s[j] != s[k]: break palindromes.append(s[j: k + 1]) j -= 1 k += 1 return palindromes def find_all(s): '''Finds all palindromes (non-trivial) in string s''' palindromes = [] for i in range(0, len(s)): palindromes.extend(find_palindromes(s, i-1, i+1)) palindromes.extend(find_palindromes(s, i, i+1)) return palindromes print(find_all('locoannamadam'))
# ['oco', 'nn', 'anna', 'ama', 'ada', 'madam'] print(find_all('anna'))
# ['nn', 'anna'] print(find_all('abc'))
# []

Feel free to join our community of ambitious learners like you (we have cheat sheets too): ❤

Posted on Leave a comment

How to Get a Random Entry from a Python Dictionary

5/5 – (1 vote)

Problem Formulation and Solution Overview

This article will show you how to get a random entry from a Dictionary in Python.

To make it more interesting, we have the following running scenario:

👨‍🏫 The Plot: Mr. Sinclair, an 8th great Science Teacher, is giving his students a quiz on the first 25 Periodic Table elements. He has asked you to write a Python script so that when run, it generates a random key, value, or key:value pair from the Dictionary shown below to ask his students.

els = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li', 'Beryllium': 'Be', 'Boron': 'B', 'Carbon': 'C', 'Nitrogen': 'N', 'Oxygen': 'O', 'Fluorine': 'F', 'Neon': 'Ne', 'Sodium': 'Na', 'Magnesium': 'Mg', 'Aluminum': 'Al', 'Silicon': 'Si', 'Phosphorus': 'P', 'Sulfur': 'S', 'Chlorine': 'Cl', 'Argon': 'Ar', 'Potassium': 'K', 'Calcium': 'Ca', 'Scandium': 'Sc', 'Titanium': 'Ti', 'Vanadium': 'V', 'Chromium': 'Cr', 'Manganese': 'Mn'}

💬 Question: How would we write code to get a random entry from a Dictionary?

We can accomplish this task by one of the following options:


Preparation

This article uses the random library for each example. For these code samples to run error-free, add the following snippet to the top of each example.

import random

Method 1: Use random.choice() and items()

This example uses random.choice() and items() to generate a random Dictionary key:value pair.

el_list = list(els.items())
random_el = random.choice(el_list)
print(random_el)

The above code converts the Dictionary of Periodic Table Elements to a List of Tuples and saves it to el_list. If output to the terminal, the contents of el_list contains the following.

[('Hydrogen', 'H'), ('Helium', 'He'), ('Lithium', 'Li'), ('Beryllium', 'Be'), ('Boron', 'B'), ('Carbon', 'C'), ('Nitrogen', 'N'), ('Oxygen', 'O'), ('Fluorine', 'F'), ('Neon', 'Ne'), ('Sodium', 'Na'), ('Magnesium', 'Mg'), ('Aluminum', 'Al'), ('Silicon', 'Si'), ('Phosphorus', 'P'), ('Sulfur', 'S'), ('Chlorine', 'Cl'), ('Argon', 'Ar'), ('Potassium', 'K'), ('Calcium', 'Ca'), ('Scandium', 'Sc'), ('Titanium', 'Ti'), ('Vanadium', 'V'), ('Chromium', 'Cr'), ('Manganese', 'Mn')]

Next, random.choice() is called and passed one (1) argument: el_list.

The results return a random Tuple from the List of Tuples, saves to random_el and is output to the terminal.

('Oxygen', 'O')

This code can be streamlined down to the following.

random_el = random.choice(list(els.items()))
YouTube Video

Method 2: Use random.choice() and keys()

This example uses random.choice() and keys() to generate a random Dictionary key.

random_el = random.choice(list(els.keys()))
print(random_el)

The above code calls random.choice() and passes it one (1) argument: the keys of the els Dictionary converted to a List of Tuples.

The result returns a random key, saves to random_el and is output to the terminal.

Beryllium
YouTube Video

Method 3: Use random.choice() and dict.values()

This example uses random.choice() and values() to generate a random Dictionary value.

random_el = random.choice(list(els.values()))
print(random_el)

The above code calls random.choice() and passes it one (1) argument: the keys of the els Dictionary converted to a List of Tuples.

The result returns a random value, saves to random_el and is output to the terminal.

Si
YouTube Video

Method 4: Use sample()

This example uses the sample() function to generate a random Dictionary key.

from random import sample
random_el = sample(list(els), 1)
print(random_el)

The above code requires sample to be imported from the random library.

Then, sample() is called and passed two (2) arguments: els converted to a List of Tuples and the number of random keys to return.

The results save to random_el and is output to the terminal.

['Carbon']

Method 5: Use np.random.choice()

This example uses NumPy and np.random.choice() to generate a random Dictionary key.

Before moving forward, please ensure the NumPy library is installed. Click here if you require instructions.

import numpy as np random_el = np.random.choice(list(els), 1)
print(random_el)

This code imports the NumPy library installed above.

Then, np.random.choice() is called and passed two (2) arguments: els converted to a List of Tuples and the number of random keys to return.

The results save to random_el and is output to the terminal.

['Chromium' 'Silicon' 'Oxygen']

💡Note: np.random.choice() has an additional parameter that can be passed. This parameter is a List containing associated probabilities.


Bonus:

This code generates a random key:value pair from a list of tuples. When the teacher runs this code, a random question displays on the screen and waits for a student to answer. Press 1 to display the answer, 2 to quit.

import keyboard
import random
import time els = {'Hydrogen': 'H', 'Helium': 'He', 'Lithium': 'Li', 'Beryllium': 'Be', 'Boron': 'B', 'Carbon': 'C', 'Nitrogen': 'N', 'Oxygen': 'O', 'Fluorine': 'F', 'Neon': 'Ne', 'Sodium': 'Na', 'Magnesium': 'Mg', 'Aluminum': 'Al', 'Silicon': 'Si', 'Phosphorus': 'P', 'Sulfur': 'S', 'Chlorine': 'Cl', 'Argon': 'Ar', 'Potassium': 'K', 'Calcium': 'Ca', 'Scandium': 'Sc', 'Titanium': 'Ti', 'Vanadium': 'V', 'Chromium': 'Cr', 'Manganese': 'Mn'} print('1 Answer 2 quit')
def quiz(): while True: k, v = random.choice(list(els.items())) print(f'\nWhat is the Symbol for {k}?') pressed = keyboard.read_key() if pressed == '1': print(f'The answer is {v}!') elif pressed == '2': print("Exiting\n") exit(0) time.sleep(5)
quiz()

✨Finxter Challenge!
Write code to allow the teacher to enter the answer!


Summary

This article has provided five (5) ways to get a random entry from a Dictionary to select the best fit for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor – Blockchain

“Blockchains are like grappling hooks, in that it’s extremely cool when you encounter a problem for which they’re the right solution, but it happens way too rarely in real life.” source xkcd
Posted on Leave a comment

JavaScript this Keyword

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

JavaScript this keyword is for referring to objects of the current context. If no context around, it points to the window context by default.

There is more context the JavaScript can refer to via this keyword. The below list shows some of them.

  • Global context
  • Method context
  • function context
  • Class context
  • Event context

In these contexts JavaScript this keyword refers to the different objects correspondingly.

The below code uses the ‘this’ keyword to print the main and sub-category breadcrumb in the browser.

Quick Example

This example uses ‘JavaScript this’ in the object’s method to read properties.


<script>
const category = { mainCategory: "Gadgets", subCategory: "Mobile phones", DisplayCategoryTree : function() { return this.mainCategory + " -> " + this.subCategory; }
};
document.write(category.DisplayCategoryTree());
</script>

javascript this

How it works

The behavior of using ‘this’ varies based on several factors. Some of them are listed below.

  1. It differs between dynamic and explicit binding.
  2. It works differently on strict and non-strict modes.
  3. It varies based on the enclosing contexts.
  4. It differs based on how and where they are called or used.

Generally, the ‘this’ will behave with dynamic binding. JavaScript supports explicit binding with the bind() method to change the default.

Without default value, the JavaScript ‘this’ returns ‘undefined’ in a strict mode.

Different usages of ‘this’ in JavaScript

There are different usage practices in JavaScript to use the ‘this’ keyword to refer to a context. Let us see about the following 2 among those practices.

  1. Set default values to the ‘this’.
  2. Arrow function.

By default, the ‘this’ refers to the global context. But, in strict mode, functions need a default value to use ‘this’ as a reference. The JavaScript classes are always in a strict mode and require object reference to use ‘this’.

The JavaScript arrow functions give compact code. So we can choose it for writing a limited code with purposes. But, I prefer to use traditional expressions while coding.

More examples using JavaScript this

This section gives more examples of the ‘JavaScript this’ keyword. It shows how ‘this’ will work in different scenarios and contexts.

It gives code for accessing properties of a class or JavaScript const block.

It accesses the HTML elements on event handling. It helps to manipulate the DOM objects via JavaScript with the reference of the ‘this’ keyword.

Example 1: Accessing object properties via this using JavaScript call() function

This program binds the properties of an object with the method of another object. It uses the JavaScript call() to log the properties with the reference of the ‘this’ object.

bind-objects-and-get-properties-with-this.html


<script>
const category = { DisplayCategoryTree : function() { return this.mainCategory + " -> " + this.subCategory; }
};
const categoryData = { mainCategory: "Gadgets", subCategory: "Mobile phones",
}; console.log(category.DisplayCategoryTree.call(categoryData));
</script>

Example 2: JavaScript this in Strict mode

In strict mode, JavaScript this keyword refers to the global window context. But, within a function, it returns undefined.

javascript-this-in-strict-mode.html


<script> "use strict";
let obj = this;
// 'this' is 'window' object
console.log(obj); function getContext() { return this;
}
// In strict mode, JavaScript 'this' inside a funtion is 'undefined'
console.log(getContext());
</script>

Example 3: Set or get object properties using this keyword

This example sets the properties of an object. Also. it reads them using the JavaScript this keyword. It defines functions to get or set the properties.

javascript-getter-setter-with-this-object-html.php


<script>
const Properties = { color: "Black", size: "Big", type: "2D", getColor: function() { return this.color; }, setColor: function(newColor) { this.color = newColor; }, getSize: function() { return this.size; }, setSize: function(newSize) { this.size = newSize; }, getType: function() { return this.type; }, setType: function(newType) { this.type = newType; }
};
Properties.setColor("White");
Properties.setSize("small");
Properties.setType("3D"); document.write("Color: "+ Properties.getColor()+"<br>");
document.write("Size: "+ Properties.getSize()+"<br>");
document.write("Type: "+ Properties.getType());
</script>

Example 4: JavaScript this object in different contexts

This script logs the ‘JavaScript this’ object in different contexts. The program creates two classes and logs the ‘this’ object from their constructors. It returns the corresponding owner instance and logs it into the developer console.

I have written a similar tutorial on PHP constructors and destructors earlier.

From a jQuery document.ready() function, ‘this’ returns Document:[object HTMLDocument].

this-in-different-context.php


<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
var x = this;
console.log("Default:" + x); class Cart { constructor() { console.log("Class:" + this + " of " + this.constructor.name); }
}
const cart = new Cart(); class Product { constructor() { console.log("Class:" + this + " of " + this.constructor.name); }
}
const product = new Product(); $(document).ready(function(){ var x = this; console.log("Document:" + x);
});
</script>

This program logs the following in the developer console. The ‘this’ object refers to a different context.

javascript this reference

Example 5: JavaScript this keyword in event context

The below code contains HTML button with an on-click event handler. It passes the ‘this’ object to manipulate the button element style. Here, the JavaScript this object refers to the button element.

The on-click event calls the highlight(this) method. It will change the button background color on click.

this-in-event-handler.html


<button onclick="highlight(this)">Button</button>
<script>
function highlight(obj) { obj.style.backgroundColor = '#0099FF';
}
</script>

Example 6: Using the Arrow function

See the below example that creates a compact code to get a global context using ‘this’.

It creates a function consisting of a one-line code to return the global object. This line uses the JavaScript arrow function to use ‘this’.

arrow-function.html


<script>
var getGlobal = (() => this);
console.log(getGlobal());
</script>

Conclusion

I hope you have a good idea of this basic JavaScript concept. The example code guides you on how to use ‘this’ in JavaScript.

The examples with event handlers and arrow functions return relevant object references. Let me know your valuable feedback on this article in the comment section.
Download

↑ Back to Top