code-rag-bench/online-tutorials huggingface dataset:
How to Automatic Refresh a web page in fixed time ?

21 Dec, 2020
Suppose we have given an HTML document and the task is to automatically refresh the webpage after a certain period of time in the web browser. We will predefine a time period and the browser automatically refreshes the webpage.
Example: You are creating an auto refreshing website that needs to be refreshed after a certain smaller period of time. So, in this case, you can use the meta http-equiv tag to refresh the webpage. Another illustration of this http-equiv tag is that it can be used to reload a weather website that needs to be updated after every small interval of time to show the minute weather changes.
Approach 1: One can auto refresh the webpage using the meta tag within the head element of your HTML using the http-equiv property. It is an inbuilt property with HTML 5. One can further add the time period of the refresh using the content attribute within the Meta tag.
The HTTP equiv attribute can be used to simulate an HTTP response header. The attribute is supported by all major web browsers such as Google Chrome, Mozilla Firefox, Microsoft Edge, Safari, Opera Mini, etc.
Syntax:
<meta http-equiv="refresh" content="10">
Example:
<!DOCTYPE html><html>  <head>    <title>Page Title</title>    <meta http-equiv="refresh" content="10"></head>  <body>    <h2>Welcome To GFG</h2>    <p>The code will reload after 10s.</p></body>  </html>
Output:
Approach 2: Using setInterval() method: Another method to access the auto refresh property of webpage is by using the following JavaScript code until ClearInterval() is called, setInterval() will continue to call itself continuously.
Syntax:
<script>
    function autoRefresh() {
        window.location = window.location.href;
    }
    setInterval('autoRefresh()', 5000);
</script>
Example:
<!DOCTYPE html><html>  <head>    <title>        Reloading page after 5 seconds    </title>          <script>        function autoRefresh() {            window.location = window.location.href;        }        setInterval('autoRefresh()', 2000);    </script></head>  <body>    <h1>Welcome to GeeksforGeeks code</h1></body>  </html>
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
Python | Interleaving two strings

07 Jun, 2019
Sometimes, while working with strings, we have the task of combining two strings, i.e interleaving them according to utility. This type of utility is mostly useful while writing codes for games. Let’s discuss certain ways in which this can be performed.
Method #1 : Using join() + zip()This task can be performed using the above functions. In this join function performs the task of joining of each element pair two strings at an index and zip performs the task of interleaving character at each string.
# Python3 code to demonstrate# Interleaving two strings# using join() + zip()  # initializing strings test_string1 = 'geeksforgeeks'test_string2 = 'computerfreak'  # printing original strings  print("The original string 1 : " + test_string1)print("The original string 2 : " + test_string2)  # using join() + zip()# Interleaving two stringsres = "".join(i + j for i, j in zip(test_string1, test_string2))      # print resultprint("The Interleaved string : " + str(res))
 
The original string 1 : geeksforgeeks
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask

 
Method #2 : Using zip() + join() + chain.from_iterable()This task can also be performed using the chain.from_iterable function. The major advantage to use this particular function is that it offers more speed than the above method, about 3 times faster than above method as it converts the string to iterable.
# Python3 code to demonstrate# Interleaving two strings# using join() + zip() + chain.from_iterable()from itertools import chain  # initializing strings test_string1 = 'geeksforgeeks'test_string2 = 'computerfreak'  # printing original strings  print("The original string 1 : " + test_string1)print("The original string 2 : " + test_string2)  # using join() + zip() + chain.from_iterable()# Interleaving two stringsres = "".join(list(chain.from_iterable(zip(test_string1, test_string2))))      # print resultprint("The Interleaved string : " + str(res))
 
The original string 1 : geeksforgeeks
The original string 2 : computerfreak
The Interleaved string : gceoemkpsuftoerrgfereekask

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Kali Linux - Password Cracking Tools

In this chapter, we will learn about the important password cracking tools used in Kali Linux.
Hydra is a login cracker that supports many protocols to attack ( Cisco AAA, Cisco auth, Cisco enable, CVS, FTP, HTTP(S)-FORM-GET, HTTP(S)-FORM-POST, HTTP(S)-GET, HTTP(S)-HEAD, HTTP-Proxy, ICQ, IMAP, IRC, LDAP, MS-SQL, MySQL, NNTP, Oracle Listener, Oracle SID, PC-Anywhere, PC-NFS, POP3, PostgreSQL, RDP, Rexec, Rlogin, Rsh, SIP, SMB(NT), SMTP, SMTP Enum, SNMP v1+v2+v3, SOCKS5, SSH (v1 and v2), SSHKEY, Subversion, Teamspeak (TS2), Telnet, VMware-Auth, VNC and XMPP).
To open it, go to Applications → Password Attacks → Online Attacks → hydra.
It will open the terminal console, as shown in the following screenshot.
In this case, we will brute force FTP service of metasploitable machine, which has IP 192.168.1.101
We have created in Kali a word list with extension ‘lst’ in the path usr\share\wordlist\metasploit.
The command will be as follows −
hydra -l /usr/share/wordlists/metasploit/user -P 
/usr/share/wordlists/metasploit/ passwords ftp://192.168.1.101 –V 

where –V is the username and password while trying
As shown in the following screenshot, the username and password are found which are msfadmin:msfadmin
Johnny is a GUI for the John the Ripper password cracking tool. Generally, it is used for weak passwords.
To open it, go to Applications → Password Attacks → johnny.
In this case, we will get the password of Kali machine with the following command and a file will be created on the desktop.
Click “Open Passwd File” → OK and all the files will be shown as in the following screenshot.
Click “Start Attack”.
After the attack is complete, click the left panel at “Passwords” and the password will be unshaded.
john is a command line version of Johnny GUI. To start it, open the Terminal and type “john”.
In case of unshadowing the password, we need to write the following command −
root@kali:~# unshadow passwd shadow > unshadowed.txt 

The RainbowCrack software cracks hashes by rainbow table lookup. Rainbow tables are ordinary files stored on the hard disk. Generally, Rainbow tables are bought online or can be compiled with different tools.
To open it, go to Applications → Password Attacks → click “rainbowcrack”.
The command to crack a hash password is −
rcrack path_to_rainbow_tables -f path_to_password_hash 

It is a dictionary attack tool for SQL server and is very easy and basic to be used. To open it, open the terminal and type “sqldict”. It will open the following view.
Under “Target IP Server”, enter the IP of the server holding the SQL. Under “Target Account”, enter the username. Then load the file with the password and click “start” until it finishes.
It is a tool that is used to identify types of hashes, meaning what they are being used for. For example, if I have a HASH, it can tell me if it is a Linux or windows HASH.
The above screen shows that it can be a MD5 hash and it seems a Domain cached credential.
How to initialize an array in C#?

All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Firstly, declare an array.
int[] rank;

But declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array. For example,
int[] rank = new int[5];

You can assign values to an array at the time of declaration.
int[] rank = { 1, 2, 3,4,5};

With that, you can also create and initialize an array in a single line.
int [] rank = new int[5]  { 1,  2, 3, 4, 5};
How to declare variables in different ways in JavaScript? - GeeksforGeeks

23 Dec, 2021
In JavaScript, we can declare a variable in different ways by using different keywords. Each keyword holds some specific reason or feature in JavaScript. Basically we can declare variables in three different ways by using var, let and const keyword. Each keyword is used in some specific conditions.var: This keyword is used to declare variable globally. If you used this keyword to declare variable then the variable can accessible globally and changeable also. It is good for a short length of codes, if the codes get huge then you will get confused.  
Syntax:  
var variableName = "Variable-Value;"
Code:  
javascript
<script>    var geeks = "GeeksforGeeks";    console.log(geeks);</script>
Output:  
GeeksforGeeks
let: This keyword is used to declare variable locally. If you used this keyword to declare variable then the variable can accessible locally and it is changeable as well. It is good if the code gets huge.  
Syntax:  
let variableName = "Variable-Value;"
Code:  
javascript
<script>if (true) {    let geeks = "GeeksforGeeks";    console.log(geeks);    }          /* This will be error and        show geeks is not defined */    console.log(geeks);</script>
Output:  
GeeksforGeeks
const: This keyword is used to declare variable locally. If you use this keyword to declare a variable then the variable will only be accessible within that block similar to the variable defined by using let and difference between let and const is that the variables declared using const values can’t be reassigned. So we should assign the value while declaring the variable.
Syntax:  
const variableName = "Variable-Value;"
Code:  
javascript
<script>    const geeks = "GeeksforGeeks";    console.log(geeks);</script>
Output:  
GeeksforGeeks
 
bunnyram19
thanoojlingampally
ES6
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Set the value of an input field in JavaScript
Hide or show elements in HTML using display property
How to calculate the number of days between two dates in javascript?
Express.js express.Router() Function
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
How to set input type date in dd-mm-yyyy format using HTML ?
How to create a TableView in JavaFX?

TableView is a component that is used to create a table populate it, and remove items from it. You can create a table view by instantiating the javafx.scene.control.TableView class.
The following Example demonstrates the creation of a TableView.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class TableViewExample extends Application {
   public void start(Stage stage) {
      //Label for education
      Label label = new Label("File data:");
      Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
      label.setFont(font);
      //Creating a table view
      TableView<String> table = new TableView<String>();
      //Creating columns
      TableColumn fileNameCol = new TableColumn("File Name");
      TableColumn pathCol = new TableColumn("Path");
      TableColumn imageSizeCol = new TableColumn("Size");
      TableColumn dateCol = new TableColumn("Date Modified");
      dateCol.setPrefWidth(100);
      //Adding data to the table
      ObservableList<String> list = FXCollections.observableArrayList();
      table.setItems(list);
      table.getColumns().addAll(fileNameCol, pathCol, imageSizeCol, dateCol);
      //Setting the size of the table
      table.setMaxSize(350, 200);
      VBox vbox = new VBox();
      vbox.setSpacing(5);
      vbox.setPadding(new Insets(10, 50, 50, 60));
      vbox.getChildren().addAll(label, table);
      //Setting the scene
      Scene scene = new Scene(vbox, 595, 230);
      stage.setTitle("Table View Exmple");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
Escape characters in JavaScript

Escape characters are characters that can be interpreted in some alternate way then what we intended to. To print these characters as it is, include backslash ‘\’ in front of them. Following are the escape characters in JavaScript −
Following is the code implement escape character Backslash in javaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Escape characters in JavaScript</h1>
<div class="result"></div>
<script>
   let str = 'Hello World "This" is some sample \\ Text \' ';
   let resEle = document.querySelector(".result");
   resEle.innerHTML = str;
</script>
</body>
</html>
Difference Between Character Array and String

In this post, we will understand the difference between character array and string.
They are immutable.
They are immutable.
Once they are defined, they can’t be changed.
Once they are defined, they can’t be changed.
It refers to a sequence of characters, which is represented as a single data type.
It refers to a sequence of characters, which is represented as a single data type.
It contains built-in functions such as substring(), charAt().
It contains built-in functions such as substring(), charAt().
The ‘+’ operator can be used to append strings together, which would form a new string.
The ‘+’ operator can be used to append strings together, which would form a new string.
The charAt() method helps access characters at a specific index within a ‘String’.
The charAt() method helps access characters at a specific index within a ‘String’.
These strings are stored in the ‘String Constant Pool’.
These strings are stored in the ‘String Constant Pool’.
It is not preferred to store passwords in strings in Java.
It is not preferred to store passwords in strings in Java.
A string can be converted to a character array using toCharArray() method of ‘String’ class.
A string can be converted to a character array using toCharArray() method of ‘String’ class.
String my_string = "JANE" ;
char [] ch = my_string.toCharArray();
They are mutable.
They are mutable.
This means their values can be changed.
This means their values can be changed.
It is a sequential collection of data type ‘char’.
It is a sequential collection of data type ‘char’.
It doesn’t have built-in methods to perform operations on character arrays in Java.
It doesn’t have built-in methods to perform operations on character arrays in Java.
The ‘+’ operator can’t be used to append two character arrays.
The ‘+’ operator can’t be used to append two character arrays.
The characters in a character array can be accessed using index.
The characters in a character array can be accessed using index.
The values in a character array are stored in contiguous memory locations.
The values in a character array are stored in contiguous memory locations.
All character arrays are stored in Heap.
All character arrays are stored in Heap.
The passwords can be stored in character arrays in Java.
The passwords can be stored in character arrays in Java.
A character array can be converted into a string by passing it to a String Constructor.
A character array can be converted into a string by passing it to a String Constructor.
char[] my_char = {'J','A','N','E'};
String my_str = new String(my_char);
Java Examples - Searching Duplicate Words

How to match duplicate words in a regular expression?
Following example shows how to search duplicate words in a regular expression by using p.matcher() method and m.group() method of regex.Matcher class.
import java.util.Scanner;
import java.io.*;
import java.util.regex.*;
import java.util.ArrayList;

public class dupl {
   public static void main(String[] args) {
      ArrayList <String> manyLines = new ArrayList<String>();
      ArrayList <String> noRepeat = new ArrayList<String>(); 
      try { 
         String s1 = "Hello hello Hello there there past pastures ";
         Scanner myfis = new Scanner(s1);
         while(myfis.hasNext()) { 
            String line = myfis.nextLine();
            String delim = System.getProperty("line.separator");
            String [] lines = line.split(delim);
            
            for(String s: lines) { 
               if(!s.isEmpty() && s != null) { 
                  manyLines.add(s);
               } 
            } 
         }
         if(!manyLines.isEmpty()) { 
            System.out.print("Original text is:\n");
            for(String s: manyLines) { 
               System.out.println(s);
            } 
         } 
         if(!manyLines.isEmpty()) { 
            for(String s: manyLines) { 
               String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1");
               noRepeat.add(result);
            } 
         } 
         if(!noRepeat.isEmpty()) { 
            System.out.print("After Remove duplicates:\n");
            for(String s: noRepeat) { 
               System.out.println(s);
            } 
         } 
      } catch(Exception ex) { 
         System.out.println(ex);
      } 
   }
}
The above code sample will produce the following result.
Original text is:
Hello hello Hello there there past pastures 
After Remove duplicates:
Hello there past pastures 

 Print
 Add Notes
 Bookmark this page
How to save HTML Canvas as an Image with canvas.toDataURL()?

Use toDataURL() method to get the image data URL of the canvas. It converts the drawing (canvas) into a64 bit encoded PNG URL.
You can try to run the following code to save the canvas as an image −
<!DOCTYPE HTML>
<html>
   <head>
   </head>
   <body>
      <canvasid = "newCanvas" width = "450" height = "300"></canvas>
      <script>
         var canvas = document.getElementById('newCanvas');
         var ctx = canvas.getContext('2d');
         // draw any shape
         ctx.beginPath();
         ctx.moveTo(120, 50);
         ctx.bezierCurveTo(130,100, 130, 250, 330, 150);
         ctx.bezierCurveTo(350,180, 320, 180, 240, 150);
         ctx.bezierCurveTo(320,150, 420, 120, 390, 100);
         ctx.bezierCurveTo(130,40, 370, 30, 240, 50);
         ctx.bezierCurveTo(220,7, 350, 20, 150, 50);
         ctx.bezierCurveTo(250,5, 150, 20, 170, 80);
         ctx.closePath();
         ctx.lineWidth = 3;
         ctx.fillStyle ='#F1F1F1';
         ctx.fill();
         ctx.stroke();
         var dataURL =canvas.toDataURL();
      </script>
   </body>
</html>
Playit

#myDIV {  background-color:lightblue;  transform:rotateX(10deg);}
numpy.square() in Python - GeeksforGeeks

29 Nov, 2018
numpy.square(arr, out = None, ufunc ‘square’) : This mathematical function helps user to calculate square value of each element in the array.
Parameters :
arr  : [array_like] Input array or object
          whose elements, we need to square.

Return :
An array with square value of each array.  

 Code #1 : Working
# Python program explaining# square () function  import numpy as np  arr1 = [1, -3, 15, -466]print ("Square Value of arr1 : \n", np.square(arr1))  arr2 = [23 ,-56]print ("\nSquare Value of arr2 : ", np.square(arr2))
Output :
Square Value of arr1 : 
 [     1      9    225 217156]

Square Value of arr2 :  [ 529 3136]

 Code #2 : Working with complex numbers
# Python program explaining# square () function  import numpy as np  a = 4 + 3jprint("Square(4 + 3j) : ", np.square(a))  b = 16 + 13jprint("\nSquare value(16 + 13j) : ", np.square(b))
Output :
Square(4 + 3j) :  (7+24j)

Square value(16 + 13j) :  (87+416j)
 Code #3 : Graphical Representation of numpy.square()
# Python program explaining# square () function  import numpy as npimport matplotlib.pyplot as plt  a = np.linspace(start = -5, stop = 5,                num = 6, endpoint = True)                  print("Graphical Representation : \n", np.square(a))  plt.title("blue : with square\nred : without square")plt.plot(a, np.square(a))  plt.plot(a, a, color = 'red')plt.show()
Output :
Graphical Representation : 
 [ 25.   9.   1.   1.   9.  25.]

References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.absolute.html.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file
Device Drivers in Linux - GeeksforGeeks

25 Jan, 2021
Drivers are used to help the hardware devices interact with the operating system. In windows, all the devices and drivers are grouped together in a single console called device manager. In Linux, even the hardware devices are treated like ordinary files, which makes it easier for the software to interact with the device drivers. When a device is connected to the system, a device file is created in /dev directory. 
Most Common types of devices in Linux:
Character devices – These devices transmit the data character by characters, like a mouse or a keyboard.Block devices – These devices transfer unit of data storage called a block, USB drives, hard drives, and CD ROMs
Character devices – These devices transmit the data character by characters, like a mouse or a keyboard.
Block devices – These devices transfer unit of data storage called a block, USB drives, hard drives, and CD ROMs
To list all the device files use the below command.
ls -l /dev
In the above output, we can see some other types of file types, some of them have B for a block device, C for character device some devices start with /dev/sda or /sdb. In Linux, the disk names are alphabetical. For example, dev/sda is the first hard drive, dev/sdb is the second hard drive, and so on. These devices are mass storage devices like memory sticks, hard drives, etc. Hence, sda means that this device was detected by the computer first. Example of character device is : /dev/consoles or /dev/ttyS0. These devices are accessed as a stream of bytes. Example of block device: /dev/sdxn. Block devices allow the programmer to read and write any size of the block. Pseudo devices act as device drivers without an actual device. Examples of pseudo devices are /dev/null, /dev/zero, /dev/pf etc.
 1. fdisk – It stands for format disk. This command is used to display the partitions on a disk and other details related to the file system.
sudo fdisk -l
2. sfdisk – This command displays the partitions on the disk, the size of each partition in MB, etc.
3. parted – This command helps list and modify the partitions of the disk.
sudo parted -l
4. df – Displays the details of the file system. Using grep we can filter real hard disk files.
df -h | grep ^/dev
5. lsblk – List details about the block devices.
lsblk
6. inxi – Lists details about the hardware components in the file system.
inxi -D -xx
The kernel is a monolithic piece of software, but it is also responsible to provide support to the hardware. Most of the devices have built-in kernel modules, so when they are plugged in, they start working automatically.
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Array Basics in Shell Scripting | Set 1
scp command in Linux with Examples
nohup Command in Linux with Examples
chown command in Linux with Examples
mv command in Linux with examples
Named Pipe or FIFO with example C program
SED command in Linux | Set 2
Basic Operators in Shell Scripting
Start/Stop/Restart Services Using Systemctl in Linux
Create a light-blue alert box that indicates some information with Bootstrap

Use the .alert-info class to create a light-blue alert box indicating some information.
You can try to run the following code to implement .alert-info class in Bootstrap −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <div class = "alert alert-info">
            <p>Information!</p>
            <p>Add information here...</p>
         </div>
      </div>
   </body>
</html>
Construct Binary Tree from Preorder and Postorder Traversal in Python

Suppose we have two traversal sequences Preorder and Postorder, we have to generate the binary tree from these two sequences. So if the sequences are [1,2,4,5,3,6,7], [4,5,2,6,7,3,1], then the output will be
To solve this, we will follow these steps −
ans := make a tree node by taking value pre[0], stack := empty stack, and insert ans
i := 1 and j := 0
while i < length of pre and j < length of postif stack top value = post[j], then increase j by 1, pop from stack, and go for next iterationnode := make a tree node with value pre[i]if left part of stack top node is empty, then set left of stack top node as node, otherwise set right of stack top node as nodeinsert node into stackincrease i by 1
if stack top value = post[j], then increase j by 1, pop from stack, and go for next iteration
node := make a tree node with value pre[i]
if left part of stack top node is empty, then set left of stack top node as node, otherwise set right of stack top node as node
insert node into stack
increase i by 1
return ans
Let us see the following implementation to get better understanding −
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def height(root):
   if root is None:
      return 0
   else :
      # Compute the height of left and right subtree
      l_height = height(root.left)
      r_height = height(root.right)
      #Find the greater one, and return it
      if l_height > r_height :
         return l_height+1
      else:
         return r_height+1
def print_given_level(root, level):
   if root is None:
      return
   if level == 1:
      print(root.data,end = ',')
   elif level > 1 :
      print_given_level(root.left , level-1)
      print_given_level(root.right , level-1)
def level_order(root):
   print('[', end = '')
   h = height(root)
   for i in range(1, h+1):
      print_given_level(root, i)
   print(']')
class Solution(object):
   def constructFromPrePost(self, pre, post):
      """
      :type pre: List[int]
      :type post: List[int]
      :rtype: TreeNode
      """
      ans = TreeNode(pre[0])
      stack = [ans]
      i = 1
      j = 0
      while i < len(pre) and j < len(post):
         if stack[-1].data == post[j]:
            j+=1
            stack.pop(-1)
            continue
         node = TreeNode(pre[i])
         if not stack[-1].left:
            stack[-1].left = node
         else:
            stack[-1].right = node
            stack.append(node)
            i+=1
   return ans
ob = Solution()
pre = [1,2,4,5,3,6,7]
post = [4,5,2,6,7,3,1]
tree = ob.constructFromPrePost(pre, post)
level_order(tree)
[1,2,4,5,3,6,7]
[4,5,2,6,7,3,1]
pre = [1,2,4,5,3,6,7]
post = [4,5,2,6,7,3,1]
[1,2,3,4,5,6,7,]
What is Image Blurring

14 Oct, 2018
What is convolution in 2D?Image is denoted as matrix inside computer. An image contains a lot of features like edge, contrast etc. In image processing features have to be extracted from the image for further study of image.Convolution is a fundamental operation on images in which a mathematical operation is applied to each pixel to get the desired result.For this purpose, another matrix called as kernel is used which is smaller in size of image. This is also called filter. This filter is applied on each pixel of the image and new value obtained is the value of that pixel. The image obtained is called filtered image.In kernel each cell contain some value, that kernel is kept above the pixel and corresponding values are multiplied and then summed up this value obtained is new the value of pixel.
What is BlurringIf a blurred image is observed carefully then a common thing to notice is that image is smooth meaning edges are not observed. A filter used for blurring is also called low pass filter, because it allows low frequency to enter and stop high frequency. Here frequency means the change of pixel value. Around edge pixel value changes rapidly as blur image is smooth so high frequency should be filtered out.For blur purpose a filter with every call having value 1 is used because to blur image a pixel value should be close to neighbor value.In filter it is divided by 9 for normalization otherwise value of a pixel will increase resulting in more contrast which is not the goal.
We can choose the size of the kernel depending on how much we want to smoothen the image. Choosing a bigger size will be averaging over a larger area. This tends to increase the smoothening effect.
# Write Python3 code here  import cv2import numpy as np  image = cv2.imread('geek.jpg')  # making filter of 3 by 3 filled with 1 divide # by 9 for normalizationblur_filter1 = np.ones((3, 3), np.float)/(9.0)  # making filter of 5 by 5 filled with 1 divide# by 25 for normalizationblur_filter2 = np.ones((5, 5), np.float)/(25.0)  # making filter of 7 by 7 filled with 1 divide # by 49 for normalizationblur_filter3 = np.ones((7, 7), np.float)/(49.0)  image_blur1 = cv2.filter2D(image, -1, blur_filter1)image_blur2 = cv2.filter2D(image, -1, blur_filter2)image_blur3 = cv2.filter2D(image, -1, blur_filter3)  cv2.imshow('geek', image)cv2.imshow('geek_blur1', image_blur1)cv2.imshow('geek_blur2', image_blur2)cv2.imshow('geek_blur3', image_blur3)  cv2.waitKey(0)cv2.destroyAllWindows()
Original image
With large filter the images smoothed more.
Image-Processing
Technical Scripter 2018
Advanced Computer Subject
Python Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python 3 - os.rename() Method

The method rename() renames the file or directory src to dst.If dst is a file or directory(already present), OSError will be raised.
Following is the syntax for rename() method −
os.rename(src, dst)

src − This is the actual name of the file or directory.
src − This is the actual name of the file or directory.
dst − This is the new name of the file or directory.
dst − This is the new name of the file or directory.
This method does not return any value.
The following example shows the usage of rename() method.
# !/usr/bin/python3
import os, sys
os.chdir("d:\\tmp")

# listing directories
print ("The dir is: %s"%os.listdir(os.getcwd()))

# renaming directory ''tutorialsdir"
os.rename("python3","python2")

print ("Successfully renamed.")

# listing directories after renaming "python3"
print ("the dir is: %s" %os.listdir(os.getcwd()))
When we run the above program, it produces the following result −
The dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 
   'java.ppt', 'Python3'
]

Successfully renamed.

the dir is: [
   'Applicationdocs.docx', 'book.zip', 'foo.txt', 
   'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files',
Remove all non-alphabetical characters of a String in Java

11 Dec, 2018
Given a string str, consisting of non-alphabetical characters. The task is to remove all those non-alphabetical characters of str and print the words on a new line.
Examples:
Input: str = “Hello, how are you ?”Output:Hellohowareyou
comma(, ), white space and question mark (?) are removed and there are total 4 words in string s.Each token is printed in the same order in which it appears in string s.
Input: “Azad is a good boy, isn’ t he ?”Output:Azadisagoodboyisnthe
Approach: Non-alphabetic characters are basically any character that is not a number or letter. It can be English alphabetic letters, blank spaces, exclamation points (!), commas (, ), question marks (?), periods (.), underscores (_), apostrophes (‘), and at symbols (@). The approach is to use Java String.split method to split the String, s into an array of substrings. Then print each n words on a new line in the same order as it appears in String s.
Below is the implementation of the above approach:
// Java program to split all// non-alphabetical charactersimport java.util.Scanner;  public class Main {      // Function to trim the non-alphabetical characters    static void printwords(String str)    {          // eliminate leading and trailing spaces        str = str.trim();          // split all non-alphabetic characters        String delims = "\\W+"; // split any non word        String[] tokens = str.split(delims);          // print the tokens        for (String item : tokens) {              System.out.println(item + " ");        }    }      public static void main(String[] args)    {          String str = "Hello, how are you  ?";        printwords(str);    }}
Hello 
how 
are 
you

Time Complexity: O(N)
java-basics
Java-String-Programs
Java-Strings
Java
Strings
Java-Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert a JSON to Java Object using the Jackson library in Java?


The ObjectMapper class is the most important class in the Jackson library. We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.
public <T> readValue(String content, JavaType valueType) throws IOException, JsonParseException, JsonMappingException
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
public class JSONToJavaObjectTest {
   public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
      Employee emp1 = new Employee();
      emp1.setFirstName("Raja");
      emp1.setLastName("Ramesh");
      emp1.setId(115);
      emp1.getTechnologies().add("Java");
      emp1.getTechnologies().add("Selenium");
      emp1.getTechnologies().add("Spark");
      ObjectMapper mapper = new ObjectMapper();
      String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp1);
      System.out.println(jsonStr);
      System.out.println("Deserializing JSON to Object:");
      Employee emp2 = mapper.readValue(jsonStr, Employee.class);
      System.out.println(emp2.getId() + " " + emp2.getFirstName() + " " + emp2.getLastName() + " " + emp2.getTechnologies());
   }
}
// Employee class
class Employee {
   private int id;
   private String firstName;
   private String lastName;
   private List technologies = new ArrayList<>();
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }  
   public List getTechnologies() {
      return technologies;
   }
   public void setTechnologies(List technologies) {
      this.technologies = technologies;
   }
}
{
 "id" : 115,
 "firstName" : "Raja",
 "lastName" : "Ramesh",
 "technologies" : [ "Java", "Selenium", "Spark" ]
}
Deserializing JSON to Object:
115 Raja Ramesh [Java, Selenium, Spark]
Difference between Macro and Procedure

07 Jun, 2022
Assembly language is a common intermediate level programming language which is used for microprocessor programming. This macro and procedure are two concepts in assembly by which modular programming is implemented. So now let’s understand how macro and procedure are different from each other. 
1. Macro : Macro is a set of instruction and the programmer can use it anywhere in the program by using its name. It is mainly used to achieve modular programming. So same set of instructions can be used multiple times when ever required by the help of macro. Wherever macro’s identifier is used, it is replaced by the actual defined instructions during compilation thereby no calling and return occurs. 
Syntax of macro : 
%macro macro_name number_of_parameters
<macro body>
%endmacro
2. Procedure : Procedures are also like macro, but they are used for large set of instruction when macro is useful for small set of instructions. It contains a set of instructions which performs a specific task. It contains three main parts i.e Procedure name to identify the procedure, procedure body which contains set of instructions, and RET statement which denotes return statement. Unlike macros, procedures follow call-return method thereby achieving true modularity.
Syntax of Procedure : 
procedure_name :
procedure body
 ..........................
RET
To call a procedure  
CALL procedure_name
After execution of procedure control passes to the calling procedure using RET statement. 
Difference between Macro and Procedure : 
 
 
omkarphansopkar
srkota1951
Computer Organization & Architecture
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set python environment variable PYTHONPATH on Mac?

To set the PYTHONPATH on Mac OS to point Python to look in other directories for the module and package imports, export the PYTHONPATH variable as follows:
$ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo
In this case, are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble.
C Program for Radix Sort - GeeksforGeeks

06 Aug, 2018
The Radix Sort Algorithm1) Do following for each digit i where i varies from least significant digit to the most significant digit..............a) Sort input array using counting sort (or any stable sort) according to the i\’th digit.
// C++ implementation of Radix Sort#include<iostream>using namespace std;  // A utility function to get maximum value in arr[]int getMax(int arr[], int n){    int mx = arr[0];    for (int i = 1; i < n; i++)        if (arr[i] > mx)            mx = arr[i];    return mx;}  // A function to do counting sort of arr[] according to// the digit represented by exp.void countSort(int arr[], int n, int exp){    int output[n]; // output array    int i, count[10] = {0};      // Store count of occurrences in count[]    for (i = 0; i < n; i++)        count[ (arr[i]/exp)%10 ]++;      // Change count[i] so that count[i] now contains actual    //  position of this digit in output[]    for (i = 1; i < 10; i++)        count[i] += count[i - 1];      // Build the output array    for (i = n - 1; i >= 0; i--)    {        output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];        count[ (arr[i]/exp)%10 ]--;    }      // Copy the output array to arr[], so that arr[] now    // contains sorted numbers according to current digit    for (i = 0; i < n; i++)        arr[i] = output[i];}  // The main function to that sorts arr[] of size n using // Radix Sortvoid radixsort(int arr[], int n){    // Find the maximum number to know number of digits    int m = getMax(arr, n);      // Do counting sort for every digit. Note that instead    // of passing digit number, exp is passed. exp is 10^i    // where i is current digit number    for (int exp = 1; m/exp > 0; exp *= 10)        countSort(arr, n, exp);}  // A utility function to print an arrayvoid print(int arr[], int n){    for (int i = 0; i < n; i++)        cout << arr[i] << " ";}  // Driver program to test above functionsint main(){    int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};    int n = sizeof(arr)/sizeof(arr[0]);    radixsort(arr, n);    print(arr, n);    return 0;}
Please refer complete article on Radix Sort for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C Program to read contents of Whole File
Header files in C/C++ and its uses
How to Append a Character to a String in C
C program to sort an array in ascending order
Producer Consumer Problem in C
Program to find Prime Numbers Between given Interval
time() function in C
Program to calculate First and Follow sets of given grammar
C Program to Swap two Numbers
Flex (Fast Lexical Analyzer Generator )
Down-sampling in MATLAB - GeeksforGeeks

01 Oct, 2020
The two basic operations in a multi-rate system are decreasing/down-sampling (decimation) and increasing (interpolation) the sampling rate of a signal.
In down-sampling we start with a constant time signal x(t) and convert it into a succession of tests x[n], in decimation we start with a discrete-time signal x[n] and convert it into another discrete-time signal y[n], which comprises of sub-tests of x[n].
We will be using the decimate() and stem() function.The decimate() function is used to decrease a sample rate by an integer factor.
Syntax: a = decimate(x, r)Parameters:
x: input signal,
r: decimation factor
Return Value: Decimated Signal
The stem() function is used to plot a discrete sequence data.
Syntax: stem(y)Parameter:
y: data sequence
Return Value: Plot of data sequence in discrete time
MATLAB code for down-sampling:
% Time vectort = 0 : .00025 : 1;  % Original signalx = sin(2 * pi * 50 * t) + sin(2 * pi * 100 * t);  % Reduces the sample rate of original signal by factor of 4y = decimate(x, 4);   figure()subplot(2, 2, 1);  % Plot few samples of the Original signalstem(x(1:75)) title('Original Signal');  subplot(2, 2, 2);  % Plots few samples of the Decimated signalstem(y(1:75)); title('Decimated Signal');
Output
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Fuzzy Logic | Introduction
Basics of API Testing Using Postman
Principal Component Analysis with Python
Markov Decision Process
ML | What is Machine Learning ?
How to create a REST API using Java Spring Boot
Q-Learning in Python
OpenCV - Overview
Getting Started with System Design
How to use the Glyphicons icons in Bootstrap

To use the Glyphicons icon in Bootstrap, use the following code just about anywhere in your code. Leave a space between the icon and text for proper padding like −
Live Demo
<!DOCTYPE html>
<html>
  <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <span class = "glyphicon glyphicon-user"></span>
   </body>
</html>
You can try to run the following code to implement the Glyphicons icons:
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>The following are the icons:</p>
      <p>
         <button type = "button" class = "btn btn-default">
            <span class = "glyphicon glyphicon-print"></span>
         </button>
         <button type = "button" class = "btn btn-default">
            <span class = "glyphicon glyphicon-search"></span>
         </button>
         <button type = "button" class = "btn btn-default">
            <span class = "glyphicon glyphicon-download"></span>
         </button>
      </p>
   </body>
</html>
\hline - Tex Command

\hline - Used to draw horizontal line.
{ \hline }
\hline command draws horizontal line.

\begin{matrix}
x_{11} & x_{12} \\
x_{21} & x_{22} \\
x_{31} & x_{32} \\
\hline
\end{matrix}

x11x12x21x22x31x32



\begin{matrix}
x_{11} & x_{12} \\
x_{21} & x_{22} \\
x_{31} & x_{32} \\
\hline
\end{matrix}

x11x12x21x22x31x32


\begin{matrix}
x_{11} & x_{12} \\
x_{21} & x_{22} \\
x_{31} & x_{32} \\
\hline
\end{matrix}

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page