code-rag-bench/online-tutorials huggingface dataset:
Python Regex – Program to accept string starting with vowel

17 May, 2021
Prerequisite: Regular expression in PythonGiven a string, write a Python program to check whether the given string is starting with Vowel or Not.Examples:  
  
Input: animal
Output: Accepted

Input: zebra
Output: Not Accepted
In this program, we are using search() method of re module.re.search() : This method either returns None (if the pattern doesn’t match), or re.MatchObject that contains information about the matching part of the string. This method stops after the first match, so this is best suited for testing a regular expression more than extracting data. Let’s see the Python program for this :  
Python3
# Python program to accept string starting with a vowel # import re module # re module provides support# for regular expressionsimport re # Make a regular expression# to accept string starting with vowelregex = '^[aeiouAEIOU][A-Za-z0-9_]*'     # Define a function for# accepting string start with voweldef check(string):      # pass the regular expression     # and the string in search() method    if(re.search(regex, string)):        print("Valid")             else:        print("Invalid")      # Driver Codeif __name__ == '__main__' :         # Enter the string    string = "ankit"         # calling run function    check(string)     string = "geeks"    check(string)     string = "sandeep"    check(string)
Valid
Invalid
Invalid
 
varshagumber28
Python Regex-programs
python-regex
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
Python String | replace()
How to Install PIP on Windows ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
GATE | GATE-CS-2015 (Set 2) | Question 56

28 Jun, 2021
Consider a simple checkpointing protocol and the following set of operations in the log.
(start, T4); (write, T4, y, 2, 3); (start, T1); (commit, T4); (write, T1, z, 5, 7);
(checkpoint);
(start, T2); (write, T2, x, 1, 9); (commit, T2); (start, T3); (write, T3, z, 7, 2); 
If a crash happens now and the system tries to recover using both undo and redo operations, what are the contents of the undo list and the redo list
(A) Undo: T3, T1; Redo: T2(B) Undo: T3, T1; Redo: T2, T4(C) Undo: none; Redo: T2, T4, T3; T1(D) Undo: T3, T1, T4; Redo: T2Answer: (A)Explanation: Since T1 and T3 are not committed yet, they must be undone. The transaction T2 must be redone because it is after the latest checkpoint.Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python PIL | ImageOps.postarize() method

11 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.
ImageOps.posterize() Reduce the number of bits for each color channel.In every change of bit change of colour contraction will be seen
Syntax: PIL.ImageOps.posterize(image)
Parameters:image – The image used to posterize.bits – The number of bits to keep for each channel (1-8). Bit 8 is the max bit can be used by the channel.
Returns: An image.
Image Used:
# Importing Image and ImageOps module from PIL package from PIL import Image, ImageOps       # creating a image1 object im1 = Image.open(r"C:\Users\System-Pc\Desktop\a.JPG")   # applying posterize method im2 = ImageOps.posterize(im1, 2)   im2.show()
Output:
bit– Taking bit 4 here to understand the change in colour by changing bits in channel.
# Importing Image and ImageOps module from PIL package from PIL import Image, ImageOps       # creating a image1 object im1 = Image.open(r"C:\Users\System-Pc\Desktop\a.JPG")   # applying posterize method im2 = ImageOps.posterize(im1, 4)   im2.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Python | Percentage similarity of lists

28 Aug, 2019
Sometimes, while working with Python list, we have a problem in which we need to find how much a list is similar to other list. The similarity quotient of both the list is what is required in many scenarios we might have. Let’s discuss a way in which this task can be performed.
Method : Using "|" operator + "&" operator + set()The method which is formally applied to calculate the similarity among lists is finding the distinct elements and also common elements and computing it’s quotient. The result is then multiplied by 100, to get the percentage.
# Python3 code to demonstrate working of# Percentage similarity of lists# using "|" operator + "&" operator + set()  # initialize liststest_list1 = [1, 4, 6, 8, 9, 10, 7]test_list2 = [7, 11, 12, 8, 9]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Percentage similarity of lists# using "|" operator + "&" operator + set()res = len(set(test_list1) & set(test_list2)) / float(len(set(test_list1) | set(test_list2))) * 100  # printing resultprint("Percentage similarity among lists is : " + str(res))
The original list 1 is : [1, 4, 6, 8, 9, 10, 7]
The original list 2 is : [7, 11, 12, 8, 9]
Percentage similarity among lists is : 33.33333333333333

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find Peak Element in Python

Suppose we have to find the peak element in an array. The peak element is an element that is greater than its neighbors. Suppose we have an input array nums, where nums[i] ≠ nums[i+1], search for a peak element and return its index. The array can hold multiple peak elements, in that case return the index to any one of the peak elements. We can imagine that nums[-1] = nums[n] = -∞. So if the array is like [1,2,1,3,5,6,4], the peak elements should be 1 or 5.
To solve this, we will follow these steps −
low := 0 and high := last index of array, n := size of array, ans := infinity
while low <= highmid := low + (high - low)/2if mid – 1 >= 0 and nums[mid – 1] <= nums[mid], then low := mid, otherwise high := mid - 1
mid := low + (high - low)/2
if mid – 1 >= 0 and nums[mid – 1] <= nums[mid], then low := mid, otherwise high := mid - 1
return low
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def findPeakElement(self, nums):
      low = 0
      high = len(nums)-1
      while low<high:
         mid = low + (high - low+1)//2
         if (mid-1>=0 and nums[mid-1]<=nums[mid]):
            low = mid
         else:
            high = mid-1
      return nums[low+1]
ob1 = Solution()
print(ob1.findPeakElement([15,35,85,96,5,6,8,12]))
[15,35,85,96,5,6,8,12]
5
How to get image data url in JavaScript?

To convert image from an Html page tag to a data URI using javascript, you first need to create a canvas element, set its width and height equal to that of the image, draw the image on it and finally call the toDataURL method on it.
This will return the base64 encoded data URI of the image. For example,
if you have an image with id my-image, you can use the following −
function getDataUrl(img) {
   // Create canvas
   const canvas = document.createElement('canvas');
   const ctx = canvas.getContext('2d');
   // Set width and height
   canvas.width = img.width;
   canvas.height = img.height;
   // Draw the image
   ctx.drawImage(img, 0, 0);
   return canvas.toDataURL('image/jpeg');
}
// Select the image
const img = document.querySelector('#my-image');
img.addEventListener('load', function (event) {
   const dataUrl = getDataUrl(event.currentTarget);
   console.log(dataUrl);
});
This will give the output −
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAADSCAMAAABThmYtAAAAXVB
Python | Split string into list of characters

19 Feb, 2021
Given a string, write a Python program to split the characters of the given string into a list. 
Examples:  
Input : geeks
Output : ['g', 'e', 'e', 'k', 's']

Input : Word
Output : ['W', 'o', 'r', 'd']
  Code #1 : Using List ComprehensionThis approach uses list comprehension to convert each character into a list. Using the following syntax you can split the characters of a string into a list. 
Python3
# Python3 program to Split string into charactersdef split(word):    return [char for char in word]     # Driver codeword = 'geeks'print(split(word))
['g', 'e', 'e', 'k', 's']
 
  Code #2 : Typecasting to list Python provides direct typecasting of string into list using list(). 
Python3
# Python3 program to Split string into charactersdef split(word):    return list(word)     # Driver codeword = 'geeks'print(split(word))
['g', 'e', 'e', 'k', 's']
 
willemschipper2
Python string-programs
python-list
python-string
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
ISRO | ISRO CS 2020 | Question 62

09 Sep, 2020
The number of tokens in the following C code segment is
switch(inputvalue)
 {
  case 1 : b = c * d; break;
  default : b = b++; break;
 } 
(A) 27(B) 29(C) 26(D) 24Answer: (C)Explanation:
switch⏐(⏐inputvalue⏐)⏐
{⏐
case⏐1⏐:⏐ b⏐ = ⏐c⏐*⏐d⏐;⏐ break⏐;⏐
default⏐:⏐ b⏐ = ⏐b⏐++⏐;⏐ break⏐;⏐
}⏐ 
Total 26 tokens in the program.
So option (c) is correct.Quiz of this Question
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ISRO | ISRO CS 2011 | Question 56
ISRO | ISRO CS 2015 | Question 14
ISRO | ISRO CS 2011 | Question 70
ISRO | ISRO CS 2018 | Question 44
ISRO | ISRO CS 2008 | Question 1
ISRO | ISRO CS 2013 | Question 21
ISRO | ISRO CS 2018 | Question 74
ISRO | ISRO CS 2007 | Question 12
ISRO | ISRO CS 2009 | Question 30
ISRO | ISRO CS 2017 - May | Question 14
PHP | rawurlencode() function

16 Aug, 2018
The rawurlencode() function is an inbuilt function in PHP which is used to encode the URL(Uniform Resource Locator) according to RFC(Uniform Resource Identifier) 3986.
Syntax:
string rawurlencode( $str )
Parameters: This function accepts single parameters $str which is mandatory. It is used to store the URL which is to be encoded.
Return Value: This function returns a string which contains all non-alphanumeric characters except -_.~ symbols. The symbols or space character replaced with a percent (%) sign followed by two hex digits.
Below programs illustrate the rawurlencode() function in PHP.
Program 1:
<?phpecho '<a href="www.geeksforgeeks.org',  rawurlencode('A computer science portal for geek'), '">';?>
<a href="www.geeksforgeeks.orgA%20computer%20science%20portal%20for%20geek">

Program 2:
<?php  // Store the URL string$str = 'A computer science portal for geek';  // Encode the URL string and print it.echo '<a href="www.geeksforgeeks.org', rawurlencode($str), '">';?>
<a href="www.geeksforgeeks.orgA%20computer%20science%20portal%20for%20geek">

Related Articles:
PHP | base64_encode() Function
PHP | base64_decode() Function
Reference: http://php.net/manual/en/function.rawurlencode.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
How to Compare Two Dictionaries in Python?

15 Mar, 2021
In this article, we will discuss how to compare two dictionaries in Python. As we all know what is a dictionary, but sometimes we may need to compare two dictionaries. Let’s see different methods to do the same.
Method 1: Using == operator.
Python
dict1 = {'Name': 'asif', 'Age': 5}dict2 = {'Name': 'lalita', 'Age': 78}  if dict1 == dict2:    print "dict1 is equal to dict2"else:    print "dict1 is not equal to dict2"
Output:
dict1 is not equal to dict2
Method 2: Using DeepDiff module
This module is used to find the deep differences in dictionaries, iterables, strings, and other objects. To install this module type the below command in the terminal.
pip install deepdiff
Python
from deepdiff import DeepDiff  a = {'Name': 'asif', 'Age': 5}b = {'Name': 'lalita', 'Age': 78}  diff = DeepDiff(a, b)  print(diff)
Output:
{‘values_changed’: {“root[‘Name’]”: {‘new_value’: ‘lalita’, ‘old_value’: ‘asif’}, “root[‘Age’]”: {‘new_value’: 78, ‘old_value’: 5}}}
Picked
Python dictionary-programs
Technical Scripter 2020
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Number of Walks from source to destination

01 Nov, 2020
Given a graph and two vertices src and dest, count the total number of paths from src to dest where the length of the path is k (there should be exactly k edges between them). Note that the graph is represented as an adjacency matrix.For example, consider the following graph: 
The number of paths from vertex 0 to vertex 3 with length 2 is 2 ({0->1->3} and {0->2->3}).We have already discussed a O(V3 K) approach in count all possible walks from a source to a destination with exactly k edges. In this post, a O(V3 Log K) approach is discussed.
Approach: The idea is to compute a resultant matrix where result = (graph)k. The total number of paths from source to the destination of length k will then be simply result[src][dest]. We use this technique to compute the exponentiation of the adjacency matrix of the given graph.The recursion tree of power function used here for exponent = 7 looks like below: 
Below is the implementation of the above approach:
Total number of walks: 2









 
Time Complexity: 
princi singh
amit143katiyar
graph-connectivity
Picked
Technical Scripter 2018
Graph
Technical Scripter
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
Find if there is a path between two vertices in an undirected graph
What is Data Structure: Types, Classifications and Applications
Top 50 Graph Coding Problems for Interviews
Detect Cycle in a Directed Graph using BFS
Minimum steps to reach target by a Knight | Set 1
Bridges in a graph
K Centers Problem | Set 1 (Greedy Approximate Algorithm)
Water Jug problem using BFS
numpy.dot()

This function returns the dot product of two arrays. For 2-D vectors, it is the equivalent to matrix multiplication. For 1-D arrays, it is the inner product of the vectors. For N-dimensional arrays, it is a sum product over the last axis of a and the second-last axis of b.
import numpy.matlib 
import numpy as np 

a = np.array([[1,2],[3,4]]) 
b = np.array([[11,12],[13,14]]) 
np.dot(a,b)
It will produce the following output −
[[37  40] 
 [85  92]] 

Note that the dot product is calculated as −
[[1*11+2*13, 1*12+2*14],[3*11+4*13, 3*12+4*14]]
matBadge in angular-material

19 Jan, 2021
Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. 
The main use of the matBadge and assign a value in order to display numbers or status over text or images or icons. We can relate to them as a notification icon number indicator.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatBadgeModule’ from ‘@angular/material/badge’ in the app.module.ts file.
Then use matBadge and assign a number to display it over any text or image.
We also have other properties like matBadgeOverlap and matBadgeSize in-order to customizes the badge size and position.
If we want to change the theme then we can change it by using the matBadgeColor property. In angular we have 3 themes, they are primary, accent, and warn.
Once done with the above steps then serve or start the project.
Code Implementation:
app.module.ts:
Javascript
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';  import { AppComponent } from './app.component';import { MatBadgeModule} from '@angular/material/badge'; import { MatIconModule} from '@angular/material/icon'; import { MatButtonModule} from '@angular/material/button';   @NgModule({  imports:  [ BrowserModule,     FormsModule,    MatButtonModule,     MatBadgeModule,    MatIconModule ],  declarations: [ AppComponent ],  bootstrap:    [ AppComponent ]})export class AppModule { }
app.component.html:
HTML
<h3> Mat-Badge over a text</h3>  <p>    <span matBadge="8" matBadgeOverlap="false">        Text with a badge    </span></p><hr>  <h3>    Mat-Badge positioned left     and right over a Button</h3>  <p>    <button mat-raised-button color="primary"        matBadge="8" matBadgePosition="before"         matBadgeColor="accent">        Left badge Button with accent theme    </button></p>  <p>    <button mat-raised-button color="accent"         matBadge="8" matBadgePosition="after"         matBadgeColor="primary">        Right badge button with primary theme    </button></p><hr>  <h3> Mat-Badge over a icon</h3>  <p>    <mat-icon matBadge="8" matBadgeColor="warn">        home    </mat-icon></p>
Output:
bunnyram19
AngularJS-Misc
Material-UI
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Comma Separated String to HashSet in Java?

17 Dec, 2020
Given a Set of String, the task is to convert the Set to a comma-separated String in Java.
Examples:
Input: Set<String> = ["Geeks", "ForGeeks", "GeeksForGeeks"]
Output: "Geeks, For, Geeks"

Input: Set<String> = ["G", "e", "e", "k", "s"]
Output: "G, e, e, k, s" 
There are two ways in which we can convert comma separated string to Java HashSet :
Method 1: Using the String split method and Arrays class
First, we will split the string by comma and that will return us an array. 
Once we get an array, we will convert it to the List using the asList() method of the Arrays class. 
The List object then can be converted to the HashSet using the HashSet constructor.
Java
// Java program to convert comma // separated string to HashSet  import java.util.Arrays;import java.util.HashSet;import java.util.List;   public class StringToHashSetExample {          public static void main(String[] args) {                  String str = "1,2,3,4,2,5";                  // split the string by comma        String[] strParts = str.split(",");                  // convert array to the List using asList method        List<String> listParts = Arrays.asList(strParts);                  // create HashSet from the List using constructor        HashSet<String> hsetFromString = new HashSet<String>( listParts );                  System.out.println("HashSet contains: " + hsetFromString);    }}
HashSet contains: [1, 2, 3, 4, 5]
Method 2: Using Java 8 stream
If you are using Java version 8 or later, you can also use the stream to convert comma separated string to Set<String> object as given below.
Java
// Java program to convert comma// separated string to HashSet  import java.util.*;import java.io.*;import java.util.stream.*;  public class StringToHashSetExample {      public static void main(String[] args)    {          String str = "1,2,3,4,2,5";          Set<String> set            = Stream.of(str.trim().split("\\s*,\\s*"))                  .collect(Collectors.toSet());          System.out.println("HashSet contains: " + set);    }}
HashSet contains: [1, 2, 3, 4, 5]
java-hashset
Java-Strings
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Where does npm install the packages ?

14 Jul, 2021
NPM (Node Package Manager) is the default package manager for Node.js and is written entirely in Javascript. In this article, we will see Where does npm install the packages.
When we install a package using npm you can perform two types of installation:
Local InstallationGlobal Installation
Local Installation
Global Installation
Let’s understand each of them in detail.
1. Global Installation of packages: The global installation of dependencies in Node.js is putting global packages in a single place in the system exactly where depends on your setup regardless of where you run the command npm install -g <package-name> to install dependencies.
 
Syntax:
run npm install -g <package-name>
Here g denotes a global mode of a variable.
Example to illustrate How to install package globally in the system.
Write this command in the console.
 npm install -g express
Output:
Path of Global Packages in the system: Global modules are installed in the standard system in root location in system directory  /usr/local/lib/node_modules project directory.
 
Command to print the location on your system where all the global modules are installed.
npm root -g
Output:
C:\Users\Pallavi\AppData\Roaming\npm\node_modules
To List all the Global Packages in the system:
npm list -g --depth 0 
Output:
2. Local Installation of Packages: Local packages are installed in the directory where you run npm install <package-name> and they are put in the node_modules folder under this directory.
Syntax:
npm install <package-name>
Example to illustrate How to install the package locally in the system.
npm install express
Output:
Path of Local Packages in the system: These all are installed in package.json file of the project locally as shown in the below image.
Node-npm
NodeJS-Questions
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.between()

17 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas between() method is used on series to check which values lie between first and second argument.
Syntax: Series.between(left, right, inclusive=True)
Parameters:
left: A scalar value that defines the left boundaryright: A scalar value that defines the right boundaryinclusive: A Boolean value which is True by default. If False, it excludes the two passed arguments while checking.
Return Type: A Boolean series which is True for every element that lies between the argument values.
To download the CSV file used, Click Here.
Example #1:Values of salary column are checked. If they lie between 80000 and 100000, True is returned.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("employees.csv")  # making a bool seriesbool_series = data["Salary"].between(80000, 100000, inclusive = True)  # returning dataframe with salary between above valuesdata[bool_series]
Output:As shown in the output image, the data frame is having rows only with salary between 80000 and 100000.
Error and exceptions:
This method doesn’t work on strings.
This method is only for Series (1D data frame)
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add time onto a DateTime object in Python

23 Sep, 2021
In this article, we will discuss the addition of time onto a specified DateTime object in Python. The effect of this will produce a new DateTime object. This addition can be performed by using datetime.timedelta() function. The timedelta() function is used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.
Syntax: datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Return values: This function returns the manipulated date.
Thus by simply passing an appropriate value to the above-given parameters, the required task can be achieved.
Example 1: Adding time to DateTime object
Python3
# Python3 code to illustrate the addition# of time onto the datetime object  # Importing datetimeimport datetime  # Initializing a date and timedate_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)  print("Original time:")print(date_and_time)  # Calling the timedelta() function time_change = datetime.timedelta(minutes=75)new_time = date_and_time + time_change  # Printing the new datetime objectprint("changed time:")print(new_time)
Output:
Original time:
2021-08-22 11:02:05
changed time:
2021-08-22 12:17:05
Example 2: Changing day by adding time to DateTime
Python3
# Python3 code to illustrate the addition# of time onto the datetime object  # Importing datetimeimport datetime  # Initializing a date and timedate_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)  print("Original time:")print(date_and_time)  # Calling the timedelta() functiontime_change = datetime.timedelta(hours=36)new_time = date_and_time + time_change  # Printing the new datetime objectprint("changed time:")print(new_time)
Output:
Original time:
2021-08-22 11:02:05
changed time:
2021-08-23 23:02:05
Example 3: Changing two parameters at the same time
Python3
# Python3 code to illustrate the addition# of time onto the datetime object  # Importing datetimeimport datetime  # Initializing a date and timedate_and_time = datetime.datetime(2021, 8, 22, 11, 2, 5)  print("Original time:")print(date_and_time)  # Calling the timedelta() function and# adding 2 minutes and 10 secondstime_change = datetime.timedelta(minutes=2, seconds=10)new_time = date_and_time + time_change  # Printing the new datetime objectprint("changed time:")print(new_time)
Output:
Original time:
2021-08-22 11:02:05
changed time:
2021-08-22 11:04:15
Picked
Python datetime-program
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install Golang on CentOS 7?

13 Oct, 2021
The Go programming language is an open-source project to make programmers more productive. Go is expressive, concise, clean, and efficient. Its concurrency mechanisms make it easy to write programs that get the most out of multicore and networked machines, while its novel type system enables flexible and modular program construction. Go compiles quickly to machine code yet has the convenience of garbage collection and the power of run-time reflection. It’s a fast, statically typed, compiled language that feels like a dynamically typed, interpreted language.
The user used(Linux user)In this tutorial is root or a user with root power i.e add sudo at the starting of every command.
Follow the below steps to install the Go programming language on Centos 7:
Step 1:First download Wget software using the below command:
yum install wget -y
Then install GO using wget command:
wget https://golang.org/dl/go1.17.2.linux-amd64.tar.gz3
Step 2: Now remove the previous installation (if any ) and unzip the downloaded tar file of GO using the below command:
rm -rf /usr/local/go && tar -C /usr/local -xzf go1.17.2.linux-amd64.tar.gz
Step 3: Now add the path of Go in the PATH variable by  using the below command:
export PATH=$PATH:/usr/local/go/bin
Step 4:  To verify that go is properly installed run this command: 
go version
If this shows up then you are all set to start with go, if not redo all the steps above.
how-to-install
Picked
TrueGeek-2021
Go Language
How To
Installation Guide
TrueGeek
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Constants- Go Language
How to Parse JSON in Golang?
Go Variables
Loops in Go Language
Structures in Golang
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to filter object array based on attributes?
Matrix vs Dataframe in R

26 Nov, 2021
A data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks.The two most important data structures in R are Matrix and Dataframe, they look the same but different in nature.  
It’s a homogeneous collection of data sets which is arranged in a two dimensional rectangular organisation. It’s a m*n array with similar data type. It is created using a vector input. It has a fixed number of rows and columns. You can perform many arithmetic operations on R matrix like – addition, subtraction, multiplication, and divisions.Example: 
Python
# Matrix of two rows# and three columns# boolean value by row is true.# passed as 4th parameterA = matrix (c(11, 22, 33, 44, 55, 66),            nrow = 2, ncol = 3, byrow = 1) # Printing Matrixprint(A)
Output:  
     [, 1] [, 2] [, 3]
[1, ]   11   22   33
[2, ]   44   55   66
Application & Usage  
It has great use in Economics for calculating some data like GDP(Gross Domestic Production) or PI(Price per capita income).  
It is also helpful in the study of electrical and electronics circuits.  
Matrix are used in the study of surveys, i.e. Plotting graphs etc.  
Helpful in probability and statistics.
It is used for storing data tables. It can contain multiple data types in multiple columns called fields. It is a list of vector of equal length. It is a generalized form of a matrix. It is like a table in excel sheets. It has column and row names. The name of rows are unique with no empty columns. The data stored must be numeric, character or factor type. DataFrames are heterogeneous. Example: 
Python
# creating company data framecomp.data <- data.frame( # company ids# data memberscomp_id = c (1:3), # company namescomp_name = c("Geeks", "For", "Geeks"),growth = c(16000, 14000, 12000), # company start dates# data memberscomp_start_date = as.Date(c("02/05/10", "04/04/10", "05/03/10")))print(comp.data)
Output : 
Application & Usage 
Data frames can do lot of works like fit statistics formulas.  
Processing data(Not possible with Matrix, First converting to Data Frame is mandatory).  
Transpose is possible, i.e. changing rows to columns and vice versa which is useful in Data Science.  
clintra
Picked
R-dataStructures
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to find out if a Python object is a string?

For Python 2.x
To check if an object obj is a string type or a subclass of a string type −
isinstance(obj, basestring)
because both str and unicode are subclasses of basestring.
To check if obj is an instance of str or any subclass of str −
isinstance(obj, str)
To check if obj is an instance of unicode string −
isinstance(obj, unicode)
For Python 3.x, just
isinstance(obj, str)
works for both str and unicode strings.
What Is Difference Between Del, Remove and Pop on Python Lists?

11 Dec, 2020
In python del is a keyword and remove(), pop() are in-built methods. The purpose of these three are same but the behavior is different remove() method delete values or object from the list using value and del and pop() deletes values or object from the list using an index.
The del keyword delete any variable, list of values from a list. 
Syntax:
del list_name[index]  # To delete single value
del list_name        # To delete whole list
Example:
Python3
# program to demonstrate use of del keyword  # assign listnumbers = [1, 2, 3, 2, 3, 4, 5]  # use deldel numbers[2]  # display listprint(numbers)  # use deldel numbers[-1]  # display listprint(numbers)  # use deldel numbers[0]  # display listprint(numbers)
Output:
[1, 2, 2, 3, 4, 5]
[1, 2, 2, 3, 4]
[2, 2, 3, 4]
The remove() method removes the first matching value from the list.
Syntax:
list_name.remove(value)
Example:
Python3
# program to demonstrate use of remove() method  # assign listnumbers = [1, 2, 3, 2, 3, 4, 5]  # use remove()numbers.remove(3)  # display listprint(numbers)  # use remove()numbers.remove(2)  # display listprint(numbers)  # use remove()numbers.remove(5)  # display listprint(numbers)
Output:
[1, 2, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
The pop() method like del deletes value at a particular index. But pop() method returns deleted value from the list.
Syntax:
list_name.pop(index)
Example:
Python3
# program to demonstrate use of pop() method  # assign listnumbers = [1, 2, 3, 2, 3, 4, 5]  # use remove()numbers.pop(3)  # display listprint(numbers)  # use remove()numbers.pop(-1)  # display listprint(numbers)  # use remove()numbers.pop(0)  # display listprint(numbers)
Output:
[1, 2, 3, 3, 4, 5]
[1, 2, 3, 3, 4]
[2, 3, 3, 4]
                 del                
           remove()          
                 pop()             
python-list
Technical Scripter 2020
Python
Technical Scripter
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Create a Pandas DataFrame from Lists
List all the Microphones connected to System in Python using PyAudio and SpeechRecognition

10 May, 2020
In this article, we are going to get the List ID and index of the microphones attached to the system. One should have knowledge about microphone ID while dealing with microphones in the Python programs. So in order to get the list of microphones attached to the system we need the following Libraries.
Speechrecognition
PyAudio
SpeechRecognition: This module does not comes built-in with Python. There are two ways to install this module.1) Type the below command in the terminal.pip install SpeechRecognition2) Download resources from PyPI and extract it in a folder and then run following command in cmd or terminal.python setup.py install
pip install SpeechRecognition
2) Download resources from PyPI and extract it in a folder and then run following command in cmd or terminal.
python setup.py install
PyAudio:1) Windows: Run the following command in the CMD.pip install pyaudio2) Linux: Run the following command in the terminal.sudo apt-get install python-pyaudio python3-pyaudio
pip install pyaudio
2) Linux: Run the following command in the terminal.
sudo apt-get install python-pyaudio python3-pyaudio
First of all import speechrecognition instance as ‘sr’
import speech_recognition as sr

Now list_microphone_names() method will return a array/list of the connected microphones to the system.
sr.Microphone.list_microphone_names()

Complete Code:
import speechrecognition as sr    print(sr.Microphone.list_microphone_names())
Output:
[‘HDA Intel PCH: ALC255 Analog (hw:0, 0)’, ‘HDA Intel PCH: HDMI 0 (hw:0, 3)’, ‘HDA Intel PCH: HDMI 1 (hw:0, 7)’, ‘HDA Intel PCH: HDMI 2 (hw:0, 8)’, ‘HDA Intel PCH: HDMI 3 (hw:0, 9)’, ‘HDA Intel PCH: HDMI 4 (hw:0, 10)’, ‘sysdefault’, ‘front’, ‘surround40’, ‘surround51’, ‘surround71’, ‘hdmi’, ‘pulse’, ‘dmix’, ‘default’]
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python - Pandas dataframe.append()
Python | datetime.timedelta() function
XSStrike – Hunting for low-hanging fruits in Kali Linux

23 Aug, 2021
XSStrike is a free and open-source tool available on GitHub. This tool is specially designed to find cross-site scripting. This tool is written in Python. You must have python 3.7 installed in your Kali Linux. There are lots of websites on the internet which are vulnerable of cross-site scripting(XSS). This tool makes finding cross-site scripting easy. This tool works like a scanner. The Internet has millions of websites and webapps a question comes into mind whether your website is safe or not. The security of our websites plays an important role. Cross-site scripting or XSS is a vulnerability that can be used to hack websites. This tool helps to find such vulnerabilities easily.
It’s an open-source tool just download it and run it to find cross-site scripting vulnerabilities.
This tool is available on GitHub to install and start scanning websites.
It has a feature of error handling. If any error occurred during scanning it can handle easily.
It is a free and open-source tool.
It is written in python language.
It makes it easy to scan websites for xss.
This tool works like  scanner. XSStrike  is a multiprocessing support tool,.
It is a customizable tool, You can customize it.
It supports all types of request POST and GET.
It is used to find cross site scripting vulnerability in websites and webapps.
Step 1: Open your terminal of our kali linux operating system and use the following command to clone the tool. Use the second command to move into the directory of the tool.
git clone https://github.com/s0md3v/XSStrike.git
cd XSStrike
Step 2: Now you are in the directory of the tool. Use the following command to install the requirements of the tool.
pip3 install -r requirements.txt
Step 3: Now use the following command to run the tool.
python3 xsstrike.py -h
The tool is running successfully now we will see some example to use the tool.
Example 1: Use the XSStrike tool to find reflective xss on a domain.
python3 xsstrike.py -u "http://<URL>/faq.php?lang=q"
Example 2: Use the XSStrike tool to crawling a domain.
./xsstrike.py -u "http://<URL>/" --crawl
You can see that the tool found a vulnerable webpage in the domain after crawling. This is how you can also perform crawling
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check whether a string is palindrome or not in PL/SQL

12 Jul, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given a string and the task is to find whether it is Palindrome or not.Examples:
Input: str = geeksskeeg
Output: geeksskeeg is palindrome

Input: str = geeks
Output: geeks is not palindrome

Approach is to take the string, reverse it and check whether the reversed string is equal to the original string or not. If it is equal, then it will be palindrome otherwise not.
Below is the required implementation:
DECLARE       -- Declared variables are s, l, t .     -- These variables are of same data type VARCHAR.     s VARCHAR2(10) := 'abccba';     l VARCHAR2(20);     t VARCHAR2(10); BEGIN     FOR i IN REVERSE 1..Length(s) LOOP         l := Substr(s, i, 1);           -- here || are used for concatenation of string.         t := t              ||''              ||l;     END LOOP;       IF t = s THEN       dbms_output.Put_line(t                            ||''                            ||' is palindrome');     ELSE       dbms_output.Put_line(t                            ||''                            ||' is not palindrome');     END IF; END;   -- Program End 
Output:
abccba is palindrome

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Prototype - Object isString() Method

This method returns true if obj is of type string, false otherwise.
Object.isString(obj);

Returns true if obj is of type string, false otherwise.
<html>
   <head>
      <title>Prototype examples</title>
      <script type = "text/javascript" src = "/javascript/prototype.js"></script>
      
      <script>
         function showResult() {
            var myString = "This is string";
            alert( "test 1: " + Object.isString("foo") );
            alert( "test 3: " + Object.isString(123) );
            alert( "test 4: " + Object.isString(myString) );
         }
      </script>
   </head>

   <body>
      <p>Click the button to see the result.</p>
      <br />
      <br />
      <input type = "button" value = "Result" onclick = "showResult();"/>
   </body>
</html>
Click the button to see the result.

    127 Lectures 
     11.5 hours 

 Aleksandar Cucukovic
 Print
 Add Notes
 Bookmark this page
How to catch IOError Exception in Python?

IOError Exception
It is an error raised when an input/output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. It is also raised for operating system-related errors.
If the given code is written in a try block, it raises an input/output exception, which is handled in the except block as shown given below
import sys
def whatever():
try:
f = open ( "foo.txt", 'r' )
except IOError, e:
print e
print sys.exc_type
whatever()

[Errno 2] No such file or directory: 'foo.txt'
<type 'exceptions.IOError'>
Machine Learning - Box and Whisker Plots

Box and Whisker plots, also called boxplots in short, is another useful technique to review the distribution of each attribute’s distribution. The following are the characteristics of this technique −
It is univariate in nature and summarizes the distribution of each attribute.
It is univariate in nature and summarizes the distribution of each attribute.
It draws a line for the middle value i.e. for median.
It draws a line for the middle value i.e. for median.
It draws a box around the 25% and 75%.
It draws a box around the 25% and 75%.
It also draws whiskers which will give us an idea about the spread of the data.
It also draws whiskers which will give us an idea about the spread of the data.
The dots outside the whiskers signifies the outlier values. Outlier values would be 1.5 times greater than the size of the spread of the middle data.
The dots outside the whiskers signifies the outlier values. Outlier values would be 1.5 times greater than the size of the spread of the middle data.
In the following example, Python script will generate Density Plots for the distribution of attributes of Pima Indian Diabetes dataset.
from matplotlib import pyplot
from pandas import read_csv
path = r"C:\pima-indians-diabetes.csv"
names = ['preg', 'plas', 'pres', 'skin', 'test', 'mass', 'pedi', 'age', 'class']
data = read_csv(path, names = names)
data.plot(kind = 'box', subplots = True, layout = (3,3), sharex = False,sharey = False)
pyplot.show()
From the above plot of attribute’s distribution, it can be observed that age, test and skin appear skewed towards smaller values.

    168 Lectures 
     13.5 hours 

 Er. Himanshu Vasishta

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions

    91 Lectures 
     10 hours 

 Abhilash Nelson

    54 Lectures 
     6 hours 

 Abhishek And Pukhraj

    49 Lectures 
     5 hours 

 Abhishek And Pukhraj

    35 Lectures 
     4 hours 

 Abhishek And Pukhraj
 Print
 Add Notes
 Bookmark this page
Lowest Common Ancestor of a Binary Tree in Python

Suppose we have a binary tree. we have to find the Lowest common ancestor nodes of two given nodes. The LCA of two nodes p and q is actually as the lowest node in tree that has both p and q as decedent. So if the binary tree is like [3,5,1,6,2,0,8,null,null,7,4]. The tree will be like −
Here LCA of 5 and 1 is 3
To solve this, we will follow these steps −
If the tree is empty, then return null
if p and q both are same as root, then return root
left := LCA of left subtree of the root using p and q
right := LCA of right subtree of the root using p and q
if left and right both are non-zero, then return root
return left OR right
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, data, left = None, right = None):
      self.data = data
      self.left = left
      self.right = right
def insert(temp,data):
   que = []
   que.append(temp)
   while (len(que)):
      temp = que[0]
      que.pop(0)
      if (not temp.left):
         if data is not None:
            temp.left = TreeNode(data)
         else:
            temp.left = TreeNode(0)
         break
      else:
         que.append(temp.left)
         if (not temp.right):
            if data is not None:
               temp.right = TreeNode(data)
            else:
               temp.right = TreeNode(0)
            break
         else:
            que.append(temp.right)
def make_tree(elements):
   Tree = TreeNode(elements[0])
   for element in elements[1:]:
      insert(Tree, element)
   return Tree
class Solution(object):
   def lowestCommonAncestor(self, root, p, q):
      if not root:
         return None
      if root.data == p or root.data ==q:
         return root
      left = self.lowestCommonAncestor(root.left, p, q)
      right = self.lowestCommonAncestor(root.right, p, q)
      if right and left:
         return root
      return right or left
ob1 = Solution()
tree = make_tree([3,5,1,6,2,0,8,None,None,7,4])
print(ob1.lowestCommonAncestor(tree, 5, 1).data)
[3,5,1,6,2,0,8,null,null,7,4]
5
1
3
Sorting an array of literals using quick sort in JavaScript

We are required to write a JavaScript function that takes in an array of numbers and uses the
quick sort algorithm to sort it.
This algorithm is basically a divide and conquer algorithm where we pick a pivot in every pass of loop and put all the elements smaller than pivot to its left and all greater than pivot to its right (if its ascending sort otherwise opposite)
The code for this will be −
const arr = [43, 3, 34, 34, 23, 232, 3434, 4, 23, 2, 54, 6, 54];
// Find a "pivot" element in the array to compare all other
// elements against and then shift elements before or after
// pivot depending on their values
const quickSort = (arr, left = 0, right = arr.length - 1) => {
   let len = arr.length, index;
   if(len > 1) {
      index = partition(arr, left, right)
         if(left < index - 1) {
            quickSort(arr, left, index - 1)
         }
         if(index < right) {
            quickSort(arr, index, right)
      }
   }
   return arr
}
const partition = (arr, left, right) => {
   let middle = Math.floor((right + left) / 2),
   pivot = arr[middle],
   i = left, // Start pointer at the first item in the
   array
   j = right // Start pointer at the last item in the
   array
   while(i <= j) {
      // Move left pointer to the right until the value at the
      // left is greater than the pivot value
      while(arr[i] < pivot) {
         i++
      }
      // Move right pointer to the left until the value at the
      // right is less than the pivot value
      while(arr[j] > pivot) {
         j--
      }
      // If the left pointer is less than or equal to the
      // right pointer, then swap values
      if(i <= j) {
         [arr[i], arr[j]] = [arr[j], arr[i]] // ES6 destructuring swap
         i++
         j--
      }
   }
   return i
}
console.log(quickSort(arr));
The output in the console −
[
   2, 3, 4, 6, 23,
   23, 34, 34, 43, 54,
   54, 232, 3434
]