code-rag-bench/online-tutorials huggingface dataset:
Delete one row and reorder the others with the correct ID in MySQL?

To understand the concept, let us first create a table. The query to create a table is as follows
mysql> create table ReorderSortDemo
   -> (
   -> UserId int
   -> );
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into ReorderSortDemo values(14);
Query OK, 1 row affected (0.13 sec)
mysql> insert into ReorderSortDemo values(4);
Query OK, 1 row affected (0.10 sec)
mysql> insert into ReorderSortDemo values(6);
Query OK, 1 row affected (0.11 sec)
mysql> insert into ReorderSortDemo values(3);
Query OK, 1 row affected (0.09 sec)
mysql> insert into ReorderSortDemo values(8);
Query OK, 1 row affected (0.11 sec)
mysql> insert into ReorderSortDemo values(18);
Query OK, 1 row affected (0.08 sec)
mysql> insert into ReorderSortDemo values(1);
Query OK, 1 row affected (0.12 sec)
mysql> insert into ReorderSortDemo values(11);
Query OK, 1 row affected (0.08 sec)
mysql> insert into ReorderSortDemo values(16);
Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from ReorderSortDemo;
The following is the output
+--------+
| UserId |
+--------+
|     14 |
|      4 |
|      6 |
|      3 |
|      8 |
|     18 |
|      1 |
|     11 |
|     16 |
+--------+
9 rows in set (0.00 sec)
First delete one row from the table then use update command to reorder the others. The query is as follows −
mysql> delete from ReorderSortDemo where UserId=8;
Query OK, 1 row affected (0.20 sec)
After deleting, let us check the table records once again. The query is as follows −
mysql> select *from ReorderSortDemo;
The output is as follows
+--------+
| UserId |
+--------+
|     14 |
|      4 |
|      6 |
|      3 |
|     18 |
|      1 |
|     11 |
|     16 |
+--------+
8 rows in set (0.00 sec)
Here is the query to reorder the other columns
mysql> update ReorderSortDemo
   -> set UserId=UserId-1
   -> where UserId > 8;
Query OK, 4 rows affected (0.22 sec)
Rows matched: 4 Changed: 4 Warnings: 0
Let us check the table records once again. The query is as follows −
mysql> select *from ReorderSortDemo;
The output is as follows
+--------+
| UserId |
+--------+
|     13 |
|      4 |
|      6 |
|      3 |
|     17 |
|      1 |
|     10 |
|     15 |
+--------+
8 rows in set (0.00 sec)
How to check if a string is alphanumeric in Python?

Python String class has a method called isalnum() which can be called on a string and tells us if the string consists only of alphanumerics or not. You can call it in the following way:
>>> '123abc'.isalnum()
True
>>> '123#$%abc'.isalnum()
False
You can also use regexes for the same result. For matching alpha numerics, we can call the re.match(regex, string) using the regex: "^[a-zA-Z0-9]+$". For example,
>>> bool(re.match('^[a-zA-Z0-9]+$', '123abc'))
True
>>> bool(re.match('^[a-zA-Z0-9]+$', '123#$%abc'))
False
re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().
C++ Variables

Variables are containers for storing data values. 
In C++, there are different types of variables (defined with different keywords), for example:
int - stores integers (whole numbers), without decimals, such as 123 or -123
double - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. 
 Char values are surrounded by single quotes
string - stores text, such as "Hello World". 
 String values are surrounded by double quotes
bool - stores values with two states: 
 true or false
To create a variable, specify the type and assign it a value:
Where type is one of C++ types (such as int), and 
variableName is the name of the variable (such as x or
myName). The equal sign is used to assign values to the variable.
To create a variable that should store a number, look at the following example:
Create a variable called myNum of type int and assign it the value 15:
You can also declare a variable without assigning the value, and assign the value later:
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
A demonstration of other data types:
You will learn more about the individual types in the Data Types chapter.
The cout object is used together with the << 
operator to display variables.
To combine both text and a variable, separate them with the << 
operator:
To add a variable to another variable, you can use the + 
operator:
Create a variable named myNum and assign the value 50 to it.
  = 

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Java Program to format date with System.out.format

System.out.format is used in Java to format output.
Firstly, create a Calendar object −
Calendar calendar = Calendar.getInstance();
Now, use theDate-Time conversion characters to get the date, month and year −
System.out.format("%te %tB, %tY%n", calendar, calendar, calendar);
The following is the complete example −
 Live Demo
import java.util.Locale;
import java.util.Calendar;
public class TestFormat {
   public static void main(String[] args) {
      Calendar calendar = Calendar.getInstance();
      System.out.format("%te %tB, %tY%n", calendar, calendar, calendar);
   }
}
22 November, 2018
Checking HTTP Status Code in Selenium.

We can check HTTP status code in Selenium. As we run tests, we can verify the status code of a response from a resource. Some of the various HTTP status codes are −
5XX – Error in server.
5XX – Error in server.
4XX – Resource not detected.
4XX – Resource not detected.
3XX - Redirected.
3XX - Redirected.
2XX – Ok.
2XX – Ok.
An instance of the class HttpURLConnection is used to get the HTTP status code. To have a connection to an URL, the openConnection method shall be utilized. Then we have to take the help of setRequestMethod and pass HEAD as a parameter to that.
To establish the connection, the connect method is to be applied to the object of the HttpURLConnection class. Finally, the getResponseCode method obtains the HTTP response code.
HttpURLConnection cn= (HttpURLConnection)new URL("https://www.tutorialspoint.com/index.htm")
.openConnection();
cn.setRequestMethod("HEAD");
cn.connect();
int c = cn.getResponseCode();
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class HttpRespCode{
   public static void main(String[] args) throws
   MalformedURLException, IOException {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait of 4 seconds
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // establish and open connection with URL
      HttpURLConnection cn= (HttpURLConnection)new
      URL("https://www.tutorialspoint.com/index.htm")
      .openConnection();
      // set the HEAD request with setRequestMethod
      cn.setRequestMethod("HEAD");
      // connection initiated and obtain status code
      cn.connect();
      int c = cn.getResponseCode();
      System.out.println("Http status code: " + c);
      driver.quit();
   }
}
Python | Using PIL ImageGrab and PyTesseract - GeeksforGeeks

13 Oct, 2019
ImageGrab is a Python module that helps to capture the contents of the screen. PyTesseract is an Optical Character Recognition(OCR) tool for Python. Together they can be used to read the contents of a section of the screen.
Installation –
Pillow (a newer version of PIL)
pip install Pillow
PyTesseract
pip install pytesseract
Apart from this, a tesseract executable needs to be installed.
The following functions were primarily used in the code –
pytesseract.image_to_string(image, lang=**language**) – Takes the image and searches for words of the language in their text.
cv2.cvtColor(image, **colour conversion**) – Used to make the image monochrome(using cv2.COLOR_BGR2GRAY).
ImageGrab.grab(bbox=**Coordinates of the area of the screen to be captured**) – Used to repeatedly(using a loop) capture a specific part of the screen.
The objectives of the code are:
To use a loop to repeatedly capture a part of the screen.To convert the captured image into grayscale.Use PyTesseract to read the text in it.
To use a loop to repeatedly capture a part of the screen.
To convert the captured image into grayscale.
Use PyTesseract to read the text in it.
Code : Python code to use ImageGrab and PyTesseract
# cv2.cvtColor takes a numpy ndarray as an argumentimport numpy as nm  import pytesseract  # importing OpenCVimport cv2  from PIL import ImageGrab    def imToString():      # Path of tesseract executable    pytesseract.pytesseract.tesseract_cmd ='**Path to tesseract executable**'    while(True):          # ImageGrab-To capture the screen image in a loop.         # Bbox used to capture a specific area.        cap = ImageGrab.grab(bbox =(700, 300, 1400, 900))          # Converted the image to monochrome for it to be easily         # read by the OCR and obtained the output String.        tesstr = pytesseract.image_to_string(                cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),                 lang ='eng')        print(tesstr)  # Calling the functionimToString()
The above code can be used to capture a certain section of the screen and read the text contents of it.
NumpyOpenCV(cv2)
Image-Processing
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
POWER() Function in SQL Server - GeeksforGeeks

30 Dec, 2020
POWER() function :This function in SQL Server is used to return a results after raising a specified exponent number to a specified base number. For example if the base is 5 and exponent is 2, this will return a result of 25.
Features :
This function is used to find a results after raising a specified exponent number to a specified base number.
This function accepts two parameters base and exponent.
The base value can be negative but not the exponent value.
The base and exponent value can be in fraction.
This function uses a formula“(base)(exponent) = Returned value”.
Syntax :
POWER(a, b)
Parameter :This method accepts two parameters as given below :
a : Specified base number.
b : Specified exponent number.
Returns :It returns a results after raising a specified exponent number to a specified base number.
Example-1 :Getting a result of 49 for the base value 7 and exponent value 2.
SELECT POWER(7, 2);
Output :
49
Example-2 :Getting a result of 27 for 3 as the base and exponent value.
SELECT POWER(3, 3);
Output :
 27
Example-3 :Using POWER() function with variables and getting a result of 1 for the base value 6 and exponent value 0.
DECLARE @Base_Value INT;
DECLARE @Exponent_Value INT;
SET @Base_Value = 6;
SET @Exponent_Value = 0;
SELECT POWER(@Base_Value, @Exponent_Value);

Output :
1
Example-4 :Getting a result of 0 for the base value 0 and exponent value 4.
SELECT POWER(0, 4);
Output :
0
Example-5 :Getting a result of -64 for the base value -4 and exponent value 3.
SELECT POWER(-4, 3);

Output :
-64
Example-6 :Using POWER() function with variables and getting a result of 28.2 for the base float value 2.1 and exponent float value 4.5.
DECLARE @Base_Value FLOAT;
DECLARE @Exponent_Value FLOAT;
SET @Base_Value = 2.1;
SET @Exponent_Value = 4.5;
SELECT POWER(@Base_Value, @Exponent_Value);

Output :
28.182974409756689
Application :This function is used to return a results after raising a specified exponent number to a specified base number.
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DDL and DML in DBMS
SQL | Views
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL | Subquery
GATE | GATE-CS-2005 | Question 43 - GeeksforGeeks

28 Jun, 2021
Let f: B → C and g: A → B be two functions and let h = f o g. Given that h is an onto function. Which one of the following is TRUE?(A) f and g should both be onto functions.(B) f should be onto but g need not be onto(C) g should be onto but f need not be onto(D) both f and g need not be ontoAnswer: (B)Explanation: A function f: X → Y is called on-to function if for every value in set Y, there is a value in set X.
Given that, f: B → C and g: A → B and h = f o g.  

Note that the sign o represents composition. 

h is basically f(g(x)). So h is a function from set A
to set C.

It is also given that h is an onto function which means
for every value in C there is a value in A. 
We map from C to A using B. So for every value in C, there must be a value in B. It means f must be onto.
But g may or may not be onto as there may be some values in B which don’t map to A.
Example :
Let us consider following sets
A : {a1, a2, a3}
B : {b1, b2}
C : {c1}

And following function values
f(b1) = c1
g(a1) = b1, g(a2) = b1, g(a3) = b1

Values of h() would be,
h(a1) = c1, h(a2) = c1, h(a3) = c1

Here h is onto, therefore f is onto, but g is 
onto as b2 is not mapped to any value in A.
Given that, f: B → C and g: A → B and h = f o g.
Quiz of this Question
GATE-CS-2005
GATE-GATE-CS-2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
numpy.reshape() in Python - GeeksforGeeks

09 Mar, 2022
The numpy.reshape() function shapes an array without changing the data of the array.
Syntax: numpy.reshape(array, shape, order = 'C')
Parameters : 
array : [array_like]Input array
shape : [int or tuples of int] e.g. if we are aranging an array with 10 elements then shaping
        it like numpy.reshape(4, 8) is wrong; we can do numpy.reshape(2, 5) or (5, 2)
order  : [C-contiguous, F-contiguous, A-contiguous; optional]         
         C-contiguous order in memory(last index varies the fastest)
         C order means that operating row-rise on the array will be slightly quicker
         FORTRAN-contiguous order in memory (first index varies the fastest).
         F order means that column-wise operations will be faster. 
         ‘A’ means to read / write the elements in Fortran-like index order if,
         array is Fortran contiguous in memory, C-like order otherwise
Return : 
Array which is reshaped without changing the data.
Python
# Python Program illustrating# numpy.reshape() method import numpy as geek # array = geek.arrange(8)# The 'numpy' module has no attribute 'arrange'array1 = geek.arange(8)print("Original array : \n", array1) # shape array with 2 rows and 4 columnsarray2 = geek.arange(8).reshape(2, 4)print("\narray reshaped with 2 rows and 4 columns : \n",      array2) # shape array with 4 rows and 2 columnsarray3 = geek.arange(8).reshape(4, 2)print("\narray reshaped with 2 rows and 4 columns : \n",      array3) # Constructs 3D arrayarray4 = geek.arange(8).reshape(2, 2, 2)print("\nOriginal array reshaped to 3D : \n",      array4)
Output : 
Original array : 
 [0 1 2 3 4 5 6 7]

array reshaped with 2 rows and 4 columns : 
 [[0 1 2 3]
 [4 5 6 7]]

array reshaped with 4 rows and 2 columns : 
 [[0 1]
 [2 3]
 [4 5]
 [6 7]]

Original array reshaped to 3D : 
 [[[0 1]
  [2 3]]
 [[4 5]
  [6 7]]]
  
 
 [[0 1 2 3]
 [4 5 6 7]]
References : 
https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.reshape.html
Note: These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
AditiGoyal1
saurabh1990aror
jeetasitsarkar
sooda367
knspavankumar
subhajitghosh1997
vinayedula
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
Enumerate() in Python
sum() function in Python
Python String | replace()
How to Install PIP on Windows ?
Deque in Python
Different ways to create Pandas Dataframe
Stack in Python
*args and **kwargs in Python
Convert integer to string in Python
matplotlib.pyplot.axhline() in Python - GeeksforGeeks

12 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The axhline() function in pyplot module of matplotlib library is used to add a horizontal line across the axis.
Syntax: matplotlib.pyplot.axhline(y=0, xmin=0, xmax=1, **kwargs)
Parameters: This method accept the following parameters that are described below:
y: This parameter is an optional and it is position in data coordinates of the horizontal line.
xmin: This parameter is a scalar and optional. Its default value is 0.
xmax: This parameter is a scalar and optional. Its default value is 1.
Returns: This returns the following:
line : This returns the line created by this function.
Below examples illustrate the matplotlib.pyplot.axhline() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib.pyplot.annotate() function  import numpy as npimport matplotlib.pyplot as plt  t = np.linspace(-10, 10, 100)sig = 1 / t  plt.axhline(y = 0, color ="green", linestyle ="--")plt.axhline(y = 0.5, color ="green", linestyle =":")plt.axhline(y = 1.0, color ="green", linestyle ="--")  plt.axvline(color ="black")  plt.plot(t, sig, linewidth = 2,          label = r"$\sigma(t) = \frac{1}{x}$")  plt.xlim(-10, 10)plt.xlabel("t")plt.title("Graph of 1 / x")plt.legend(fontsize = 14)  plt.show()
Output:
Example #2:
# Implementation of matplotlib.pyplot.annotate() # function  import numpy as npimport matplotlib.pyplot as plt  x = np.linspace(0, 13, 100)  plt.rcParams['lines.linewidth'] = 2plt.figure()  plt.plot(x, np.sin(x), label ='Line1',          color ='green', linestyle ="--")  plt.plot(x, np.sin(x + 0.5), label ='Line2',         color ='black', linestyle =":")  plt.axhline(0, label ='Line3', color ='black')    plt.title('Axhline() Example')l = plt.legend(loc ='upper right')  # legend between blue and orange # linel.set_zorder(2.5)  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Graph Plotting in Python | Set 1
Python | Get unique values from a list
Python - Convert Flat dictionaries to Nested dictionary - GeeksforGeeks

14 May, 2020
Sometimes, while working with records, we can have problem in which we need to perform the task of conversion of multiple flat dictionaries to a single nested dictionary. This can have application in many domains in which data is used extensively. Lets discuss certain ways in which this task can be performed.
Method #1 : Using dict() + key accessThis is one of the way in which this task can be performed. In this, we construct empty dictionary using dict and assign a new level to dictionary using manual brute key access.
# Python3 code to demonstrate working of # Convert Flat dictionaries to Nested dictionary# Using key access + dict()  # initializing dictionariestest_dict1 = {'gfg' : 1, 'best' : 2}test_dict2 = {'for' : 3, 'geeks' : 5}  # printing original dictionariesprint("The original dictionary 1 is : " + str(test_dict1))print("The original dictionary 2 is : " + str(test_dict2))  # Convert Flat dictionaries to Nested dictionary# Using key access + dict()res = dict()res["level1"] = test_dict1res['level2'] = test_dict2  # printing result print("The nested dictionary is : " + str(res)) 
The original dictionary 1 is : {‘gfg’: 1, ‘best’: 2}The original dictionary 2 is : {‘geeks’: 5, ‘for’: 3}The nested dictionary is : {‘level2’: {‘geeks’: 5, ‘for’: 3}, ‘level1’: {‘gfg’: 1, ‘best’: 2}}
 
Method #2 : Using zip()This is another way in which this task can be performed. In this we link inner keys to outer keys using zip().
# Python3 code to demonstrate working of # Convert Flat dictionaries to Nested dictionary# Using zip()  # initializing dictionariestest_dict1 = {'gfg' : 1, 'best' : 2}test_dict2 = {'for' : 3, 'geeks' : 5}  # printing original dictionariesprint("The original dictionary 1 is : " + str(test_dict1))print("The original dictionary 2 is : " + str(test_dict2))  # Convert Flat dictionaries to Nested dictionary# Using zip()key_dict = ['level1', 'level2']dict_list = [test_dict1, test_dict2]res = dict(zip(key_dict, dict_list))  # printing result print("The nested dictionary is : " + str(res)) 
The original dictionary 1 is : {‘gfg’: 1, ‘best’: 2}The original dictionary 2 is : {‘geeks’: 5, ‘for’: 3}The nested dictionary is : {‘level2’: {‘geeks’: 5, ‘for’: 3}, ‘level1’: {‘gfg’: 1, ‘best’: 2}}
Python dictionary-programs
Python-nested-dictionary
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Find next greater number with same set of digits in C++

In this problem, we are given an element N. We need to find the next greater
number with the same set of digits. We need to find the smallest number with the same digit which is greater than N.
Let’s take an example to understand the problem,
N = "92534"
92543
A simple solution to the problem to find the next greater element is by the
following approach −
Traverse the number from least significant bit to most significant bit. And stop when the current element is smaller than the last element.
Traverse the number from least significant bit to most significant bit. And stop when the current element is smaller than the last element.
After this search for the smallest element in the remaining array. And find the smallest number and swap it with the number.
After this search for the smallest element in the remaining array. And find the smallest number and swap it with the number.
Then sort the remaining subarray and return the output.
Then sort the remaining subarray and return the output.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
void findNextGreater(char number[], int n) {
   int i, j;
   for (i = n-1; i > 0; i--)
      if (number[i] > number[i-1])
         break;
   if (i==0) {
      cout<<"Next number is not possible";
      return;
   }
   int x = number[i-1], smallest = i;
   for (j = i+1; j < n; j++)
      if (number[j] > x && number[j] < number[smallest])
         smallest = j;
   char temp = number[smallest];
   number[smallest] = number[i-1];
   number[i-1] = temp;
   sort(number + i, number + n);
   cout<<number;
   return;
}
int main(){
   char number[] = "92534";
   int n = strlen(number);
   cout<<"The next number with same set of digits is ";
   findNextGreater(number, n);
   return 0;
}
The next number with same set of digits is 92543
C Program for Number of elements with odd factors in given range - GeeksforGeeks

05 Dec, 2018
Given a range [n, m], find the number of elements that have odd number of factors in the given range (n and m inclusive).
Examples:
Input  : n = 5, m = 100
Output : 8
The numbers with odd factors are 9, 16, 25, 
36, 49, 64, 81 and 100

Input  : n = 8, m = 65
Output : 6

Input  : n = 10, m = 23500
Output : 150

A Simple Solution is to loop through all numbers starting from n. For every number, check if it has an even number of factors. If it has an even number of factors then increment count of such numbers and finally print the number of such elements. To find all divisors of a natural number efficiently, refer All divisors of a natural number
An Efficient Solution is to observe the pattern. Only those numbers, which are perfect Squares have an odd number of factors. Let us analyze this pattern through an example.
For example, 9 has odd number of factors, 1, 3 and 9. 16 also has odd number of factors, 1, 2, 4, 8, 16. The reason for this is, for numbers other than perfect squares, all factors are in the form of pairs, but for perfect squares, one factor is single and makes the total as odd.
How to find number of perfect squares in a range?The answer is difference between square root of m and n-1 (not n)There is a little caveat. As both n and m are inclusive, if n is a perfect square, we will get an answer which is less than one the actual answer. To understand this, consider range [4, 36]. Answer is 5 i.e., numbers 4, 9, 16, 25 and 36.But if we do (36**0.5) – (4**0.5) we get 4. So to avoid this semantic error, we take n-1.
// C++ program to count number of odd squares// in given range [n, m]#include <bits/stdc++.h>using namespace std;  int countOddSquares(int n, int m){    return (int)pow(m, 0.5) - (int)pow(n - 1, 0.5);}  // Driver codeint main(){    int n = 5, m = 100;    cout << "Count is " << countOddSquares(n, m);    return 0;}
Count is 8

Time Complexity: O(1)
Please refer complete article on Number of elements with odd factors in given range for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
C program to find the length of a string
Exit codes in C/C++ with Examples
Regular expressions in C
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Conditional wait and signal in multi-threading
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C Hello World Program
Difference between break and continue statement in C
Python | math.floor() function - GeeksforGeeks

11 Mar, 2019
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.floor() function returns the largest integer not greater than x. If number is already integer, same number is returned.
Syntax: math.floor(x)

Parameter:
x: This is a numeric expression.

Returns:  largest integer not greater than x.
Code #1:
# Python code to demonstrate the working of floor()    # importing "math" for mathematical operations import math     x = 33.7    # returning the floor of 33.7print ("The floor of 33.7 is : ", end ="") print (math.floor(x))
The floor of 33.7 is : 33

 Code #2:
# Python code to demonstrate the working of floor()    # importing "math" for mathematical operations import math     # prints the floor using floor() method print ("math.floor(-13.1) : ", math.floor(-13.1))print ("math.floor(101.96) : ", math.floor(101.96))
math.floor(-13.1) :  -14
math.floor(101.96) :  101

Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Tryit Editor v3.7

Tryit: Keep getting coordinates when you move
Python : __delete__ vs __del__

27 Dec, 2019
Both __delete__ and __del__ are dunder or magic methods in Python. Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. Dunder here means “Double Under (Underscores)”. These are commonly used for operator overloading.
__del__ is a destructor method which is called as soon as all references of the object are deleted i.e when an object is garbage collected.
Syntax:
def __del__(self):
    body of destructor
    .
    .

Example: Here is the simple example of destructor. By using del keyword we deleted the all references of object ‘obj’, therefore destructor invoked automatically.
# Python program to demonstrate# __del__    class Example:         # Initializing    def __init__(self):         print("Example Instance.")      # Calling destructor    def __del__(self):         print("Destructor called, Example deleted.")     obj = Example() del obj 
Example Instance.
Destructor called, Example deleted.

Note : The destructor was called after the program ended or when all the references to object are deleted i.e when the reference count becomes zero, not when object went out of scope.
__delete__ is used to delete the attribute of an instance i.e removing the value of attribute present in the owner class for an instance.
Note: This method only deletes the attribute which is a descriptor.
Syntax:
def __delete__(self, instance):
    body of delete
    .
    .

Example:
# Python program to demonstrate# __delete__    class Example(object):      # Initializing    def __init__(self):        print("Example Instance.")      # Calling __delete__    def __delete__(self, instance):        print ("Deleted in Example object.")    # Creating object of Example# class as an descriptor attribute# of this classclass Foo(object):    exp = Example()  # Driver's codef = Foo()del f.exp
Example Instance.
Deleted in Example object.

Example: A combine example of __del__ and __delete__.
# Python program to demonstrate# __del__ and __delete__    class Example(object):      # Initializing    def __init__(self):        self.value = ''      # deletes an attribute    def __delete__(self, instance):        print ("Inside __delete__")              # Destructor    def __del__(self):        print("Inside __del__")            class Foo(object):    exp = Example()  # Driver's codef = Foo()del f.exp
Output:
Inside __delete__
Inside __del__

python-oop-concepts
Python
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
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 | Get unique values from a list
Python | datetime.timedelta() function
Lodash _.keyBy() Method

07 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.
The _.keyBy() method creates an object that composed of keys generated from the results of running an each element of collection through iteratee. Corresponding value of each key is the last element that responsible for generating the key.
Syntax:
_.keyBy( collection, iteratee )
Parameters: This method accepts two parameters as mentioned above and described below:
collection: This parameter holds the collection to iterate over.
iteratee: This parameter holds the iteratee to transform keys.
Return Value: This method returns the composed aggregate object.
Example 1:
// Requiring the lodash library const _ = require("lodash");        // Original array var array = [  { 'dir': 'left', 'code': 89 },  { 'dir': 'right', 'code': 71 }];   // Use of _.keyBy() methodlet keyby_array = _.keyBy(array, 'dir');  // Printing the output console.log(keyby_array);
Output:
{ 'left': { 'dir': 'left', 'code': 89 }, 
'right': { 'dir': 'right', 'code': 71 } }
Example 2:
// Requiring the lodash library const _ = require("lodash");        // Original array var array = [  { 'dir': 'left', 'code': 89 },  { 'dir': 'right', 'code': 71 }];   // Use of _.keyBy() methodlet keyby_array = _.keyBy(array, function(o) {  return String.fromCharCode(o.code);});  // Printing the output console.log(keyby_array);
Output:
{ 'Y': { 'dir': 'left', 'code': 89 }, 
'G': { 'dir': 'right', 'code': 71 } }
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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 ?
Pandas – GroupBy One Column and Get Mean, Min, and Max values

25 Aug, 2020
We can use Groupby function to split dataframe into groups and apply different operations on it. One of them is Aggregation. Aggregation i.e. computing statistical parameters for each group created example – mean, min, max, or sums.
Let’s have a look at how we can group a dataframe by one column and get their mean, min, and max values.
Example 1:
import pandas as pd    # creating a dataframedf = pd.DataFrame([('Bike', 'Kawasaki', 186),                   ('Bike', 'Ducati Panigale', 202),                   ('Car', 'Bugatti Chiron', 304),                    ('Car', 'Jaguar XJ220', 210),                   ('Bike', 'Lightning LS-218', 218),                    ('Car', 'Hennessey Venom GT', 270),                   ('Bike', 'BMW S1000RR', 188)],                  columns =('Type', 'Name', 'top_speed(mph)'))  df
Output :
Finding mean, min and max values.
# using groupby function with aggregation# to get mean, min and max valuesresult = df.groupby('Type').agg({'top_speed(mph)': ['mean', 'min', 'max']})  print("Mean, min, and max values of Top Speed grouped by Vehicle Type")print(result)
Output :
Example 2:
import pandas as pd    # creating a dataframesales_data = pd.DataFrame({'customer_id':[3005, 3001, 3002, 3009, 3005, 3007,               3002, 3004, 3009, 3008, 3003, 3002],      'salesman_id': [102, 105, 101, 103, 102, 101, 101,                106, 103, 102, 107, 101],  'purchase_amt':[1500, 2700, 1525, 1100, 948, 2400,                5700, 2000, 1280, 2500, 750, 5050]})  sales_data
Output :
Finding mean, min and max values.
# using groupby function with aggregation # to get mean, min and max valuesresult = sales_data.groupby('salesman_id').agg({'purchase_amt': ['mean', 'min', 'max']})  print("Mean, min, and max values of Purchase Amount grouped by Salesman id")print(result)
Output :
Example 3:
import pandas as pd    # creating a dataframedf = pd.DataFrame({"Team": ["Radisson", "Radisson", "Gladiators",                            "Blues", "Gladiators", "Blues",                             "Gladiators", "Gladiators", "Blues",                             "Blues", "Radisson", "Radisson"],                             "Position": ["Player", "Extras", "Player", "Extras",                     "Extras", "Player", "Player", "Player",                     "Extras", "Player", "Player", "Extras"],                             "Age": [22, 24, 21, 29, 32, 20, 21, 23, 30, 26, 20, 31]})df
Output :
Finding mean, min and max values.
# using groupby function with aggregation # to get mean, min and max valuesresult = df.groupby('Team').agg({'Age': ['mean', 'min', 'max']})  print("Mean, min, and max values of Age grouped by Team")print(result)
Output :
Python Pandas-exercise
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Opening | Morphological Transformations in OpenCV in C++

10 Feb, 2021
In this article, a Morphological operation called Opening is discussed.
Opening operation is similar to erosion in the sense that it also removes foreground pixels from the edges of the image. Opening operation is erosion operation followed by dilation. It is usually used for removing internal noise present inside an image. This operator safeguards the foreground region that has similarity with the structuring component or the one that fits inside the structuring element while removing everything else.
Syntax:
morphologyEx (src, dst, op, kernel, anchor, iterations, borderType, borderValue)
Parameters:
src: It is the input image.
dst: It is the output image.
op: Type of morphological operation.
kernel: Structuring element used for Closing.
anchor: Anchor position inside the structuring element. The default value is [-1, -1} signifying position as the center of the structuring element.
iterations: Number of times Closing is applied.
borderType: Type of border ( BORDER_CONSTANT, BORDER_REPLICATE, etc.)
borderValue: Border value
Return: Output Image (Mat Object)
The opening operator is given by the expression:
The expression represents that AoB is a subset (sub-image of A). The opening operator removes internal noise and thin protrusions present inside an image.
Below is the C++ program to demonstrate the Opening Morphological Operation:
C++
// C++ program to demonstrate the// opening morphological transformation#include <iostream>#include <opencv2/core/core.hpp>  // Library include for drawing shapes#include <opencv2/highgui/highgui.hpp>#include <opencv2/imgproc.hpp>using namespace cv;using namespace std;  // Function to demonstrate the// opening morphological operatorint openingMorphological(){    // Reading the Image    Mat image = imread(        "C:/Users/harsh/Downloads/geeks.png",        IMREAD_GRAYSCALE);      // Check if the image is    // created successfully or not    if (!image.data) {        cout << "Could not open or"             << " find the image\n";          return 0;    }      // Create a structuring element    int morph_size = 2;    Mat element = getStructuringElement(        MORPH_RECT,        Size(2 * morph_size + 1,             2 * morph_size + 1),        Point(morph_size,              morph_size));    Mat output;      // Opening    morphologyEx(image, output,                 MORPH_OPEN, element,                 Point(-1, -1), 2);      // Display the image    imshow("source", image);    imshow("Opening", output);    waitKey();      return 0;}  // Driver Codeint main(){      openingMorphological();      return 0;}
Output:
OpenCV
Advanced Computer Subject
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Reinforcement learning
Docker - COPY Instruction
Supervised and Unsupervised learning
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Python | Find all triplets in a list with given sum

30 Jul, 2019
Given a list of integers, write a Python program to find all triplets that sum up to given integer ‘k’.
Examples:
Input : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 10
Output : [(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)]

Input : [12, 3, 6, 1, 6, 9], k = 24
Output : [(12, 6, 6), (12, 9, 3)]

Approach #1 : Naive (Using set)In this approach, we use two for loops. The first loop sets first element, another to check whether other two elements including first sums up to k or not. This approach takes O(n2) time complexity.
# Python3 program to Find total number # of triplets in a temp_list with given k  def findTriplets(lst, k):    triplet_count = 0    final_temp_list =[]          for i in range(0, len(lst)-1):                   s = set()         temp_list = []          # Adding first element        temp_list.append(lst[i])          curr_k = k - lst[i]                   for j in range(i + 1, len(lst)):                           if (curr_k - lst[j]) in s:                 triplet_count += 1                                  # Adding second element                temp_list.append(lst[j])                  # Adding third element                temp_list.append(curr_k - lst[j])                                  # Appending tuple to the final list                final_temp_list.append(tuple(temp_list))                temp_list.pop(2)                temp_list.pop(1)            s.add(lst[j])                  return final_temp_list      # Driver Codelst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]k = 10print(findTriplets(lst, k))
[(1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 5, 3)]

 Approach #2 : Using itertoolsPython itertools module provide combination(iterable, r) function. This tool returns the r length subsequences of elements from the input iterable. Every time we make a combination of 3 elements and check if they sums up to k or not.
# Python3 program to Find total number # of  triplets in a list with given sumfrom itertools import combinations  def findTriplets(lst, key):          def valid(val):        return sum(val) == key              return list(filter(valid, list(combinations(lst, 3))))  # Driver Codelst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]print(findTriplets(lst, 10))
[(1, 2, 7), (1, 3, 6), (1, 4, 5), (2, 3, 5)]

ManasChhabra2
Python list-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
Python String | replace()
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 | Convert string dictionary to dictionary
What are the differences between get() and navigate() method?

The differences between get() and navigate() methods are listed below.
With get().
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class LaunchBrw {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      driver.close();
   }
}
With navigate().
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class BrowserNavigation {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      // new browser will launch and navigate to the URL
      driver.navigate().to(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // refresh the current browser
      driver.navigate().refresh();
      //Using id tagname attribute combination for css expression
      driver.findElement(By.cssSelector("input[name=’search’]")). sendKeys("Selenium");
      //browser will go back to the previous page
      driver.navigate().back();
      //browser will go move to the next page
      driver.navigate().forward();
      driver.close();
   }
}
Python math function | copysign()

01 Jan, 2019
math.copysign() is a function exists in Standard math Library of Python. This function returns a float value consisting of magnitude from parameter x and the sign (+ve or -ve) from parameter y.
Syntax : math.copysign(x, y)
Parameters :x : Integer value to be convertedy : Integer whose sign is required
Returns : float value consisting of magnitude from parameter x and the sign from parameter y.
Code #1:
# Python code to demonstrate copy.sign() functionimport math  def func():    a = 5    b = -7            # implementation of copysign    c = math.copysign(a, b)          return c      print (func())
Output :
-5.0
 Code #2:
# Python code to demonstrate copy.sign() functionimport math  def func():    a = 10    b = 10            # implementation of copysign    c = math.copysign(a, b)          return c      print (func())
Output :
10
Python math-library-functions
Python-Built-in-functions
Python
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Convert Matrix to Dataframe in R - GeeksforGeeks

09 May, 2021
In this article, we will discuss how to convert the matrix into DataFrame, or we can also say that we will discuss how to create a DataFrame from a matrix in R Programming Language.
A matrix can be converted to a dataframe by using a function called as.data.frame(). It will take each column from the matrix and convert it to each column in the dataframe.
Syntax:
as.data.frame(matrix_data)
Where, matrix_data is the input matrix.
Example 1:
R
# create the matrix with 4 rows # with numeric elementsmatrix_data=matrix(c(1,2,3,4,5,6,7,8),nrow=4)  # display the dataprint(matrix_data)  # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data)  # print dataframe dataprint(dataframe_data)
Output:
Example 2:
R
# create the matrix with 8 rows # with numeric elementsmatrix_data=matrix(c(1,2,3,4,5,6,7,8,11:18),nrow=8)  # display the dataprint(matrix_data)  # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data)  # print dataframe dataprint(dataframe_data)
Output:
Example 3:
R
# create the matrix with 8 rows # with different elementsmatrix_data=matrix(c(  "bobby","pinkey","rohith","gnanesh",5.3,6.6,7,8,11:18),nrow=8)  # display the dataprint(matrix_data)  # convert the matrix into dataframedataframe_data=as.data.frame(matrix_data)  # print dataframe dataprint(dataframe_data)
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Loops in R (for, while, repeat)
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Remove rows with NA in one column of R DataFrame
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R