code-rag-bench/online-tutorials huggingface dataset:
Python Regex Metacharacters - GeeksforGeeks

01 Oct, 2020
Metacharacters are considered as the building blocks of regular expressions. Regular expressions are patterns used to match character combinations in the strings. Metacharacter has special meaning in finding patterns and are mostly used to define the search criteria and any text manipulations.
Some of the mostly used metacharacters along with their uses are as follows:
\w\w\w\w = geek
\w\w\w =! geek
geek[sy] = geeky
geek[sy] != geeki
Regular expressions can be built by metacharacters, and patterns can be processed using a library in Python for Regular Expressions known as “re”.
import re  # used to import regular expressions
The inbuilt library can be used to compile patterns, find patterns, etc. 
Example: In the below code, we will generate all the patterns based on the given regular expression
Python3
import re    '''Meta characters - * - 0 or more+ - 1 or more? - 0 or 1{m} - m times{m,n} - min m and max n'''  test_phrase = 'sddsd..sssddd...sdddsddd...dsds...dsssss...sdddd'test_patterns = [r'sd*',        # s followed by zero or more d's                 r'sd+',          # s followed by one or more d's                 r'sd?',          # s followed by zero or one d's                 r'sd{3}',        # s followed by three d's                 r'sd{2,3}',      # s followed by two to three d's                 ]    def multi_re_find(test_patterns, test_phrase):    for pattern in test_patterns:        compiledPattern = re.compile(pattern)        print('finding {} in test_phrase'.format(pattern))        print(re.findall(compiledPattern, test_phrase))    multi_re_find(test_patterns, test_phrase)
Output:
finding sd* in test_phrase[‘sdd’, ‘sd’, ‘s’, ‘s’, ‘sddd’, ‘sddd’, ‘sddd’, ‘sd’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘sdddd’]finding sd+ in test_phrase[‘sdd’, ‘sd’, ‘sddd’, ‘sddd’, ‘sddd’, ‘sd’, ‘sdddd’]finding sd? in test_phrase[‘sd’, ‘sd’, ‘s’, ‘s’, ‘sd’, ‘sd’, ‘sd’, ‘sd’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘s’, ‘sd’]finding sd{3} in test_phrase[‘sddd’, ‘sddd’, ‘sddd’, ‘sddd’]finding sd{2,3} in test_phrase[‘sdd’, ‘sddd’, ‘sddd’, ‘sddd’, ‘sddd’]
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How to duplicate a div using jQuery?

To duplicate a div in jQuery, use the jQuery clone() method.
You can try to run the following code to learn how to duplicate a div using jQuery:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $("button").click(function(){
      $("div").clone().appendTo("body");
   });
});
</script>
</head>
<body>

<div>This is a text</div>
<button>Clone div and append</button>

</body>
</html>
iOS - Image View

Image view is used for displaying a single image or animated sequence of images.
image
highlightedImage
userInteractionEnabled
animationImages
animationRepeatCount
- (id)initWithImage:(UIImage *)image
- (id)initWithImage:(UIImage *)image highlightedImage: (UIImage *)highlightedImage
- (void)startAnimating
- (void)stopAnimating

-(void)addImageView {
   UIImageView *imgview = [[UIImageView alloc]
   initWithFrame:CGRectMake(10, 10, 300, 400)];
   [imgview setImage:[UIImage imageNamed:@"AppleUSA1.jpg"]];
   [imgview setContentMode:UIViewContentModeScaleAspectFit];
   [self.view addSubview:imgview];
}
This method explains how to animate images in imageView.
-(void)addImageViewWithAnimation {
   UIImageView *imgview = [[UIImageView alloc]
   initWithFrame:CGRectMake(10, 10, 300, 400)];
   
   // set an animation
   imgview.animationImages = [NSArray arrayWithObjects:
   [UIImage imageNamed:@"AppleUSA1.jpg"],
   [UIImage imageNamed:@"AppleUSA2.jpg"], nil];
   imgview.animationDuration = 4.0;
   imgview.contentMode = UIViewContentModeCenter;
   [imgview startAnimating];
   [self.view addSubview:imgview];
}
Note −
We have to add images named as "AppleUSA1.jpg" and "AppleUSA2.jpg" to our project, which can be done by dragging the image to our navigator area where our project files are listed.
Update viewDidLoad in ViewController.m as follows −
(void)viewDidLoad {
   [super viewDidLoad];
   [self addImageView];
}
When we run the application, we'll get the following output −
You can try calling addImageViewWithAnimation instead of addImageView method to see the animation effect of image view.

    23 Lectures 
     1.5 hours 

 Ashish Sharma

    9 Lectures 
     1 hours 

 Abhilash Nelson

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    10 Lectures 
     1 hours 

 Abhilash Nelson

    69 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
RxJS - Working with Subscription

When the observable is created, to execute the observable we need to subscribe to it.
Here, is a simple example of how to subscribe to an observable.
import { of } from 'rxjs';
import { count } from 'rxjs/operators';

let all_nums = of(1, 7, 5, 10, 10, 20);
let final_val = all_nums.pipe(count());
final_val.subscribe(x => console.log("The count is "+x));
The count is 6

The subscription has one method called unsubscribe(). A call to unsubscribe() method will remove all the resources used for that observable i.e. the observable will get canceled. Here, is a working example of using unsubscribe() method.
import { of } from 'rxjs';
import { count } from 'rxjs/operators';

let all_nums = of(1, 7, 5, 10, 10, 20);
let final_val = all_nums.pipe(count());
let test = final_val.subscribe(x => console.log("The count is "+x));
test.unsubscribe();
The subscription is stored in the variable test. We have used test.unsubscribe() the observable.
The count is 6


    51 Lectures 
     4 hours 

 Daniel Stern
 Print
 Add Notes
 Bookmark this page
How to update parent state in ReactJS?

In this article, we are going to see how to update the parent state from a child component in a React application.
To update the parent state from the children component, either we can use additional dependencies like Redux or we can use this simple method of passing the state of the parent to the children and handling it accordingly.
In this example, we will build a React application which takes the state and the method to update it from the parent component and pass it to the children component and after handling it we will pass the updated state to the parent component.
App.jsx
import React, { useLayoutEffect, useState } from 'react';
const App = () => {
   const [name, setName] = useState('Rahul');
   return (
      <div>
      {name} has email id of rahul@tutorialspoint.com
      <div>
         <Child name={name} change={setName} />
      </div>
      </div>
   );
};

const Child = ({ name, change }) => {
   const [newName, setNewName] = useState(name);
   return (
      <div>
      <input
         placeholder="Enter new name"
         value={newName}
         onChange={(e) => setNewName(e.target.value)}
      />
      <button onClick={() => change(newName )}>Change</button>
      </div>
   );
};
export default App;
In the above example, whenever the user types in the new name, then it changes and updates the state of the child component and when clicked on the change button, then it will update the state of the parent component accordingly.
This will produce the following result.
Find the number of consecutive zero at the end after multiplying n numbers in Python

Suppose we have an array with n numbers, we have to return the number of consecutive zero’s at the end after multiplying all the n numbers.
So, if the input is like [200, 20, 5, 30, 40, 14], then the output will be 6 as 200 * 20 * 5 * 30 * 40 * 14 = 336000000, there are six 0s at the end.
To solve this, we will follow these steps −
Define a function count_fact_two() . This will take n
Define a function count_fact_two() . This will take n
count := 0
count := 0
while n mod 2 is 0, docount := count + 1n := n / 2 (only the quotient as integer)
while n mod 2 is 0, do
count := count + 1
count := count + 1
n := n / 2 (only the quotient as integer)
n := n / 2 (only the quotient as integer)
return count
return count
Define a function count_fact_five() . This will take n
Define a function count_fact_five() . This will take n
count := 0
count := 0
while n mod 5 is 0, docount := count + 1n := n / 5 (only the quotient as integer)
while n mod 5 is 0, do
count := count + 1
count := count + 1
n := n / 5 (only the quotient as integer)
n := n / 5 (only the quotient as integer)
return count
return count
From the main method, do the following −
From the main method, do the following −
n := size of A
n := size of A
twos := 0, fives := 0
twos := 0, fives := 0
for i in range 0 to n, dotwos := twos + count_fact_two(A[i])fives := fives + count_fact_five(A[i])
for i in range 0 to n, do
twos := twos + count_fact_two(A[i])
twos := twos + count_fact_two(A[i])
fives := fives + count_fact_five(A[i])
fives := fives + count_fact_five(A[i])
if twos − fives, thenreturn twos
if twos − fives, then
return twos
return twos
otherwise,return fives
otherwise,
return fives
return fives
Let us see the following implementation to get better understanding −
 Live Demo
def count_fact_two( n ):
   count = 0
   while n % 2 == 0:
      count+=1
      n = n // 2
   return count
def count_fact_five( n ):
   count = 0
   while n % 5 == 0:
      count += 1
      n = n // 5
   return count
def get_consecutive_zeros(A):
   n = len(A)
   twos = 0
   fives = 0
   for i in range(n):
      twos += count_fact_two(A[i])
      fives += count_fact_five(A[i])
   if twos < fives:
      return twos
   else:
      return fives
A = [200, 20, 5, 30, 40, 14]
print(get_consecutive_zeros(A))
[200, 20, 5, 30, 40, 14]
6
Convert string from lowercase to uppercase in R programming - toupper() function - GeeksforGeeks

10 May, 2020
toupper() method in R programming is used to convert the lowercase string to uppercase string.
Syntax: toupper(s)
Return: Returns the uppercase string.
Example 1:
# R program to convert string# from lowercase to uppercase  # Given Stringgfg <- "Geeks For Geeks"  # Using toupper() methodanswer <- toupper(gfg)  print(answer)
Output:
[1] "GEEKS FOR GEEKS"

Example 2:
# R program to convert string# from lowercase to uppercase  # Given Stringgfg <- "The quick brown fox jumps over the lazy dog"  # Using toupper() methodanswer <- toupper(gfg)  print(answer)
Output:
[1] "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG"

R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
K-Means Clustering in R Programming
Remove rows with NA in one column of R DataFrame
Replace Specific Characters in String in R
Python unittest - assertNotEqual() function - GeeksforGeeks

29 Aug, 2020
assertNotEqual() in Python is a unittest library function that is used in unit testing to check the inequality of two values. This function will take three parameters as input and return a boolean value depending upon the assert condition. If both input values are unequal assertNotEqual() will return true else return false.
Syntax:
assertNotEqual(firstValue, secondValue, message)
Parameters: assertNotEqual() accept three parameters which are listed below with explanation:
firstValue: variable of any type which is used in the comparison by function
secondValue: variable of any type which is used in the comparison by function
message: a string sentence as a message which got displayed when the test case got failed.
Listed below are two different examples illustrating the positive and negative test case for given assert function:
Example 1: Negative Test case
Python3
# unit test caseimport unittest  class TestStringMethods(unittest.TestCase):    # test function to test equality of two value    def test_negative(self):        firstValue = "geeks"        secondValue = "geeksg"        # error message in case if test case got failed        message = "First value and second value are not unequal !"        # assertNotEqual() to check unequality of first & second value        self.assertNotEqual(firstValue, secondValue, message)  if __name__ == '__main__':    unittest.main()
Output:
F
======================================================================
FAIL: test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "p1.py", line 12, in test_negative
    self.assertNotEqual(firstValue, secondValue, message)
AssertionError: 'geeks' == 'geeks' : First value and second value are not unequal!

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (failures=1)



Example 2: Positive Test case
Python3
# unit test caseimport unittest  class TestStringMethods(unittest.TestCase):    # test function to test equality of two value    def test_positive(self):        firstValue = "geeks"        secondValue = "geeks"        # error message in case if test case got failed        message = "First value and second value are not unequal !"        # assertNotEqual() to check equality of first & second value        self.assertNotEqual(firstValue, secondValue, message)  if __name__ == '__main__':    unittest.main()
Output:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK


Reference: https://docs.python.org/3/library/unittest.html
Python unittest-library
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
Effect of adding whitespace in the scanf() function in C

19 May, 2021
In this article, we will discuss the scenarios regarding adding white space before or after the format specifier in a scanf() function in C Programming Language.
Adding a whitespace character in a scanf() function causes it to read elements and ignore all the whitespaces as much as it can and search for a non-whitespace character to proceed.
scanf("%d ");
scanf(" %d");

scanf("%d\n"); This is different
from scanf("%d"); function.
Example 1: The scanf function after reading the number starts reading further until it finds a non-whitespace character on the input and prints the first number that was typed.
Adding whitespace or “\n” after format specifier in scanf functionscanf(“%d “);          or scanf(“%d\n”, );
Below is the C program to implement the above approach:
C
// C program to demonstrate the// above approach  #include <stdio.h>  // Driver Codeint main(){    // Declaring integer variable a    int a;      // Reading value in "a" using scanf    // and adding whitespace after    // format specifier    scanf("%d ", &a);      // Or scanf("%d\n", &a);      // Both work the same and    // print the same value    printf("%d", a);      return 0;}
Output:
Explanation: In the above example, when the program is executed, first the program will ask for the first input.
In this case, 2 is entered, after that whitespace is given and still there is no output rather waiting for the next input.
When 3 is entered, the output is printed which is the first number that is entered i.e., 2.
Similarly, is the case when after entering the first input i.e., 2 in the above case, if the user presses enter button and goes to the next line, the program is still waiting for the input and after entering the second input the result is printed.
Example 2: The scanf function ignores the whitespace character and reads the element only once.
Adding whitespace before format specifier in scanf functionscanf(” %d”);
Below is the C program to implement the above approach:
C
// C program to demonstrate the// above approach#include <stdio.h>  // Driver Codeint main(){    // Declaring integer variable    int a;      // Reading value in a using scanf    // and adding whitespace before    // format specifier    scanf(" %d", &a);      // Printing value of a    printf("%d", a);      return 0;}
Output:
Explanation: In this code, there is an output as soon as the number is entered because almost all the whitespaces before format specifier are ignored by scanf %-conversions except for “%c”, “%n”, and “%[“. Hence, it is advised to avoid whitespaces in scanf function as much as possible unless one is confident of its use and necessity.
C Basics
C Language
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How can I loop through all rows of a table in MySQL?

To loop through all rows of a table, use stored procedure in MySQL. The syntax is as follows −
delimiter //
CREATE PROCEDURE yourProcedureName()
BEGIN
DECLARE anyVariableName1 INT DEFAULT 0;
DECLARE anyVariableName2 INT DEFAULT 0;
SELECT COUNT(*) FROM yourTableName1 INTO anyVariableName1;
SET anyVariableName2 =0;
WHILE anyVariableName2 < anyVariableName1 DO
   INSERT INTO yourTableName2(yourColumnName,...N) SELECT (yourColumnName1,...N)
FROM yourTableName1 LIMIT anyVariableName2,1;
   SET anyVariableName2 = anyVariableName2+1;
END WHILE;
End;
//
To understand the above syntax, let us create two tables i.e. one has records and the second table will have records from the loop using stored procedures.
The following is the query to create first table −
mysql> create table AllRows
   -> (
   -> Id int,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.46 sec)
Insert some records in the first table using insert command. The query is as follows −
mysql> insert into AllRows values(1,'John');
Query OK, 1 row affected (0.12 sec)

mysql> insert into AllRows values(100,'Carol');
Query OK, 1 row affected (0.13 sec)

mysql> insert into AllRows values(300,'Sam');
Query OK, 1 row affected (0.15 sec)

mysql> insert into AllRows values(400,'Mike');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from AllRows;
+------+-------+
| Id   | Name  |
+------+-------+
|    1 | John  |
|  100 | Carol |
|  300 | Sam   |
|  400 | Mike  | 
+------+-------+
4 rows in set (0.00 sec)
Here is the query to create a second table. The query to create a table is as follows −
mysql> create table SecondTableRows
   -> (
   -> StudentId int,
   -> StudentName varchar(100)
   -> );
Query OK, 0 rows affected (0.54 sec)
Now you can loop through all rows of a table using stored procedure. The stored procedure is as follows −
mysql> delimiter //
mysql> CREATE PROCEDURE Sp_AllRowsOfATable()
   -> BEGIN
   -> DECLARE lastRows INT DEFAULT 0;
   -> DECLARE startRows INT DEFAULT 0;
   -> SELECT COUNT(*) FROM AllRows INTO lastRows;
   -> SET startRows=0;
   -> WHILE startRows <lastRows DO
   -> INSERT INTO SecondTableRows(StudentId) SELECT (Id) FROM AllRows LIMIT
startRows ,1;
   -> SET startRows= startRows+1;
   -> END WHILE;
   -> End;
   -> //
Query OK, 0 rows affected (0.22 sec)
mysql> delimiter ;
Call stored procedure using CALL command. The syntax is as follows −
CALL yourStoredProcedureName;
Call the above stored procedure to loop through all rows of the first table. The query is as follows −
mysql> call Sp_AllRowsOfATable();
Query OK, 1 row affected (0.61 sec)
After calling the stored procedure, let us check what happened with the second table. The query is as follows −
mysql> select StudentId from SecondTableRows;
+-----------+
| StudentId |
+-----------+
|         1 |
|       100 |
|       300 |
|       400 |
+-----------+
4 rows in set (0.00 sec)
How Can We Calculate Age Without DATEDIF Function?

09 May, 2021
In this article, we’ll explore different ways of finding age in Excel, other than the usual way of finding age using DATEDIF function. For this we can use one of the two ways:
Using simple mathematics
Using the YEAR function
We can easily find age of a person using simple Math. All we need to do is, subtract the DOB from current date and divide it by 365.25
So, the formula would be:
= (TODAY()-date_of_birth)/365.25
Example:
In this case, the formula to calculate age would be:
=(TODAY()-A2)/365.25
With the current date of 26.04.2021, the age of above person is 16 years.
Remarks:
1. This formula returns the age in decimal form. In order to get age in integer form, we can wrap the formula in INT function. The syntax would be:
= INT((TODAY()- date_of_birth)/365.25)
2. This formula will produce wrong result if you try to find age of someone who hasn’t lived through a leap year.
YEARFRAC function in Excel returns a decimal value that represents fractional years between two dates. We can use this function to calculate age.
Syntax:
= INT(YEARFRAC(date_of_birth, TODAY()))
Example:
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Delete Blank Columns in Excel?
How to Get Length of Array in Excel VBA?
How to Normalize Data in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Use Solver in Excel?
How to Show Percentages in Stacked Column Chart in Excel?
Introduction to Excel Spreadsheet
How to make a 3 Axis Graph using Excel?
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
Drop login in SQL Server

18 Aug, 2020
The DROP LOGIN statement could be used to delete an user or login that used to connect to a SQL Server instance.
Syntax –
DROP LOGIN loginname;
GO 
Permissions :The user which is deleting the login must have ALTER ANY LOGIN permission on the server.
Note –A login which is currently logged into SQL Server cannot be dropped.
If you try to drop login which is currently using SQL Server, the DROP LOGIN statement will raise below error.
Drop failed for Login “loginname”
Let us assume, we have created below login:
CREATE LOGIN geeks  
WITH PASSWORD = ‘gEe@kF0rG##ks’; 
Below example shows how to use DROP LOGIN statement in SQL Server.
Example –
DROP LOGIN geeks; 
DROP LOGIN used in above example would delete the login called geeks from SQL server. This DROP LOGIN statement will only run if geeks is not the current user.
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is MIPS(Million of Instructions Per Second)?

07 Jul, 2022
It may be a strategy for measuring the raw speed of a computer’s processor. Since the MIPS estimation doesn’t take into consideration other components such as the computer’s I/O speed or processor engineering, it isn’t continuously a reasonable way to degree the execution of a computer. For this case, a computer evaluated at 100 MIPS may be able to compute certain capacities quicker than another computer evaluated at 120 MIPS. 
The MIPS estimation has been utilized by computer producers like IBM to degree the “cost of computing.” The value of computers is decided in MIPS per dollar. Interests, the esteem of computers in MIPS per dollar has consistently multiplied on a yearly premise for a final couple of decades.
Required inputs for calculating MIPS are the
 Number of instructions per second can be performed by a processor 
 CPU processor speed (cycles per second), Ex (1 GHz, 2 GHz).
 CPI (average clock cycles per instruction).
 Execution time. 
Step 1: Perform the Divide operation between no. of instructions and Execution time and store the value (Let X)  in a variable. 
Step 2: Perform the Divide operation between that variable (X) and 1 million for finding millions of instructions per second. Example:
if a computer completed 2 million instructions in 0.10 seconds .
X = 2 million/0.10 = 20 million. 
No of MISP = X/1 million (as the name tells about it)
No of MISP=20 million/1 million =20.
Step 1: Perform the Divide operation between the number of cycles per second (CPU) and the number of cycles per instruction (CPI) and store the value (X) in a variable. 
Step 2: Perform a Divide operation between that variable and 1 million for finding millions of instructions per second. Example:
If a computer with a CPU of 400 megahertz had a CPI of 2.
X =  400/2=200 
No of MISP=X/1 million
No of MISP =  0.0002
Advantages of MIPS:
It is easy to understand and measure
It helps in the calculation of CPU processor speed (cycles per second), CPI (average clock cycles per instruction) and Execution time.
It handles when the amount of work is large.
Disadvantages of MIPS:
It may not reflect real execution, since simple instructions do way better.
It is an older, obsolete measure of a computer’s speed and power.
rakeshdhariwal61
Picked
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Least Frequent Character in String

30 Jun, 2022
This article gives us the methods to find the frequency of minimum occurring character in a python string. This is quite important utility nowadays and knowledge of it is always useful. Let’s discuss certain ways in which this task can be performed. 
Method 1 : Naive method + min() 
In this method, we simply iterate through the string and form a key in a dictionary of newly occurred element or if element is already occurred, we increase its value by 1. We find minimum occurring character by using min() on values. 
Python3
# Python 3 code to demonstrate# Least Frequent Character in String# naive method # initializing stringtest_str = "GeeksforGeeks" # printing original stringprint ("The original string is : " + test_str) # using naive method to get# Least Frequent Character in Stringall_freq = {}for i in test_str:    if i in all_freq:        all_freq[i] += 1    else:        all_freq[i] = 1res = min(all_freq, key = all_freq.get) # printing resultprint ("The minimum of all characters in GeeksforGeeks is : " + str(res))
The original string is : GeeksforGeeks
The minimum of all characters in GeeksforGeeks is : f
 Method 2 : Using collections.Counter() + min() 
The most suggested method that could be used to find all occurrences is this method, this actually gets all element frequency and could also be used to print single element frequency if required. We find minimum occurring character by using min() on values. 
Python3
# Python 3 code to demonstrate# Least Frequent Character in String# collections.Counter() + min()from collections import Counter # initializing stringtest_str = "GeeksforGeeks" # printing original stringprint ("The original string is : " + test_str) # using collections.Counter() + min() to get# Least Frequent Character in Stringres = Counter(test_str)res = min(res, key = res.get) # printing resultprint ("The minimum of all characters in GeeksforGeeks is : " + str(res))
The original string is : GeeksforGeeks
The minimum of all characters in GeeksforGeeks is : f
nidhi_biet
vinayedula
Python string-programs
Python
Python Programs
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
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
Path toString() method in Java with Examples

16 Jul, 2019
The Java Path interface was added to Java NIO in Java 7. toString() method of java.nio.file.Path used to return the string representation of this path. If this path was created by converting a path string using the getPath method then the path string returned by this method may differ from the original String used to create the path. The returned path by this method uses the default name-separator to separate names in the path.
Syntax:
String toString()

Parameters: This method accepts nothing.
Return value: This method returns the string representation of this path.
Below programs illustrate toString() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.toAbsolute() method  import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;public class GFG {    public static void main(String[] args)        throws IOException    {          // create object of Path        Path path            = Paths.get("C:\\Program Files\\"                        + "Java\\jre1.8.0_211");          // print path        System.out.println("Path: "                           + path.toString());    }}
Path: C:\Program Files\Java\jre1.8.0_211

Program 2:
// Java program to demonstrate// java.nio.file.Path.toString() method  import java.io.IOException;import java.nio.file.Path;import java.nio.file.Paths;  public class GFG {    public static void main(String[] args)        throws IOException    {          // create object of Path        Path path            = Paths.get("C:\\Users\\"                        + "asingh.one\\Documents");          // print path        System.out.println("Path: "                           + path.toString());    }}
Path: C:\Users\asingh.one\Documents

References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#toString()
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python Number pow() Method

Python number  method pow() returns x to the power of y. If the third argument (z) is given, it returns x to the power of y modulus z, i.e. pow(x, y) % z.
Following is the syntax for pow() method −
import math

math.pow( x, y[, z] )
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − number which is to be powered.
x − number which is to be powered.
y − number which is to be powered with x
y − number which is to be powered with x
z − (Optional) number which is to be used for modulus operation
z − (Optional) number which is to be used for modulus operation
This method returns value of xy.
The following example shows the usage of pow() method.
#!/usr/bin/python
import math   # This will import math module

print "math.pow(100, 2) : ", math.pow(100, 2)
print "math.pow(100, -2) : ", math.pow(100, -2)
print "math.pow(2, 4) : ", math.pow(2, 4)
print "math.pow(3, 0) : ", math.pow(3, 0)
When we run above program, it produces following result −
math.pow(100, 2) :  10000.0
math.pow(100, -2) :  0.0001
math.pow(2, 4) :  16.0
math.pow(3, 0) :  1.0
How to create a character vector from data frame values in R?

To create a character vector in R we can enclose the vector values in double quotation marks but if we want to use a data frame values to create a character vector then as.character function can be used. For example, if we have a data frame df then all the values in the df can form a character vector using as.character(df[]).
 Live Demo
x1<−letters[1:10]
x2<−letters[11:20]
df1<−data.frame(x1,x2)
df1
x1 x2
1 a k
2 b l
3 c m
4 d n
5 e o
6 f p
7 g q
8 h r
9 i s
10 j t
as.character(df1[])
[1] "c(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\")"
[2] "c(\"k\", \"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\", \"t\")"
is.vector(as.character(df1[]))
[1] TRUE
 Live Demo
set.seed(3232)
y1<−sample(LETTERS[1:5],20,replace=TRUE)
y2<−sample(LETTERS[6:15],20,replace=TRUE)
y3<−sample(LETTERS[16:26],20,replace=TRUE)
df2<−data.frame(y1,y2,y3)
df2
y1 y2 y3
1 E O U
2 B N U
3 C L P
4 A N Q
5 A I W
6 E M Y
7 E N P
8 B I Z
9 A G Z
10 B J W
11 D L R
12 D G R
13 B M U
14 D K W
15 B F S
16 A O Y
17 D K Z
18 A N Y
19 A O U
20 D K W
as.character(df2[])
[1] "c(\"E\", \"B\", \"C\", \"A\", \"A\", \"E\", \"E\", \"B\", \"A\", \"B\", \"D\", \"D\", \"B\", \"D\", \"B\", \"A\", \"D\", \"A\", \"A\", \"D\")"
[2] "c(\"O\", \"N\", \"L\", \"N\", \"I\", \"M\", \"N\", \"I\", \"G\", \"J\", \"L\", \"G\", \"M\", \"K\", \"F\", \"O\", \"K\", \"N\", \"O\", \"K\")"
[3] "c(\"U\", \"U\", \"P\", \"Q\", \"W\", \"Y\", \"P\", \"Z\", \"Z\", \"W\", \"R\", \"R\", \"U\", \"W\", \"S\", \"Y\", \"Z\", \"Y\", \"U\", \"W\")"
is.vector(as.character(df2[]))
[1] TRUE
 Live Demo
z1<−sample(c("Purity","Impurity","Crystal"),20,replace=TRUE)
z2<−sample(c("Chain Reaction","Odorless","Reactive"),20,replace=TRUE)
df3<−data.frame(z1,z2)
df3
z1 z2
1 Impurity Reactive
2 Crystal Reactive
3 Impurity Chain Reaction
4 Purity Chain Reaction
5 Impurity Chain Reaction
6 Crystal Reactive
7 Crystal Chain Reaction
8 Impurity Reactive
9 Purity Odorless
10 Impurity Chain Reaction
11 Purity Odorless
12 Purity Chain Reaction
13 Impurity Odorless
14 Impurity Chain Reaction
15 Impurity Odorless
16 Purity Odorless
17 Impurity Chain Reaction
18 Crystal Reactive
19 Impurity Chain Reaction
20 Crystal Reactive
as.character(df3[])
[1] "c(\"Impurity\", \"Crystal\", \"Impurity\", \"Purity\", \"Impurity\", \"Crystal\", \"Crystal\", \"Impurity\", \"Purity\", \"Impurity\", \"Purity\", \"Purity\", \"Impurity\", \"Impurity\", \"Impurity\", \"Purity\", \"Impurity\", \"Crystal\", \"Impurity\", \"Crystal\")"
[2] "c(\"Reactive\", \"Reactive\", \"Chain Reaction\", \"Chain Reaction\", \"Chain Reaction\", \"Reactive\", \"Chain Reaction\", \"Reactive\", \"Odorless\", \"Chain Reaction\", \"Odorless\", \"Chain Reaction\", \"Odorless\", \"Chain Reaction\", \"Odorless\", \"Odorless\", \"Chain Reaction\", \"Reactive\", \"Chain Reaction\", \"Reactive\")"
is.vector(as.character(df3[]))
[1] TRUE
fillellipse() function in C

05 Dec, 2019
The header file graphics.h contains fillellipse() function which draws and fills an ellipse with center at (x, y) and (x_radius, y_radius) as x and y radius of ellipse.Syntax :
void fillellipse(int x, int y, int x_radius,
                              int y_radius);

where,
(x, y) is center of the ellipse.
(x_radius, y_radius) are x and y 
radius of ellipse.

Examples :
Input : x = 200, y = 200,
        x_radius = 50, y_radius = 90
Output : 

Input : x = 300, y = 250,
        x_radius = 100, y_radius = 70
Output : 

Below is the implementation of fillellipse() function :
// C Implementation for fillellipse()#include <graphics.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // fillellipse function    fillellipse(200, 200, 50, 90);      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output :


Akanksha_Rai
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if a string is palindrome in C using pointers

25 May, 2022
Given a string. The task is to check if the string is a palindrome or not using pointers. You are not allowed to use any built-in string functions. A string is said to be a palindrome if the reverse of the string is same as the original string. For example, “madam” is palindrome because when the string is reversed same string is achieved, but “Madam” is not a palindrome.
Input: str = "Madam"
Output: String is not a Palindrome.

Input: str = "madam"
Output: String is Palindrome.

Input: str = "radar"
Output: String is Palindrome.
Algorithm:
Take two pointers say, ptr and rev.Initialize ptr to the base address of the string and move it forward to point to the last character of the string.Now, initialize rev to the base address of the string and start moving rev in forward direction and ptr in backward direction simultaneously until middle of the string is reached.If at any point the character pointed by ptr and rev does not match, then break from the loop.Check if ptr and rev crossed each other, i.e. rev > ptr. If so, then the string is palindrome otherwise not.
Take two pointers say, ptr and rev.
Initialize ptr to the base address of the string and move it forward to point to the last character of the string.
Now, initialize rev to the base address of the string and start moving rev in forward direction and ptr in backward direction simultaneously until middle of the string is reached.
If at any point the character pointed by ptr and rev does not match, then break from the loop.
Check if ptr and rev crossed each other, i.e. rev > ptr. If so, then the string is palindrome otherwise not.
Below is the implementation of the above approach: 
C
// C program to check if a string is palindrome// using pointers #include <stdio.h> // Function to check if the string is palindrome// using pointersvoid isPalindrome(char* string){    char *ptr, *rev;     ptr = string;     while (*ptr != '\0') {        ++ptr;    }    --ptr;     for (rev = string; ptr >= rev;) {        if (*ptr == *rev) {            --ptr;            rev++;        }        else            break;    }     if (rev > ptr)        printf("String is Palindrome");    else        printf("String is not a Palindrome");} // Driver codeint main(){    char str[1000] = "madam";     isPalindrome(str);     return 0;}
String is Palindrome
Time Complexity: O(N), where N represents the length of the given string.Auxiliary Space: O(1), no extra space is required, so it is a constant.
samim2000
C-Pointer Basics
C-Pointers
palindrome
C Programs
School Programming
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
SelectionSort - GeeksforGeeks

28 Jun, 2021
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array ... More on Selection Sort 
Selection sort makes O(n) swaps which is minimum among all sorting algorithms mentioned above.
In best case, 

Quick sort: O (nlogn) 
Merge sort: O (nlogn)
Insertion sort: O (n)
Selection sort: O (n^2)  
 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Tejas Networks Interview Experience for R&D Engineer
TCS NQT Coding Sheet
A Freshers Guide To Programming
Different Ways to Initialize an Set in C++
How to Merge all CSV Files into a single dataframe – Python Pandas?

To merge all CSV files, use the GLOB module. The os.path.join() method is used inside the concat() to merge the CSV files together.
At first, import the required libraries. We have set pd as an alias for the pandas library −
import pandas as pd
import glob
import os
Now, let’s say we have the following 3 CSV Files −
Sales1.csv
Sales2.csv
Sales3.csv
At first, set the path for joining multiple files. We have all the CSV files to be merged on the Desktop −
files = os.path.join("C:\\Users\\amit_\\Desktop\\", "sales*.csv")

Next, use glob to return the list of merged files −
files = glob.glob(files)
Following is the code −
import pandas as pd
import glob
import os

# setting the path for joining multiple files
files = os.path.join("C:\\Users\\amit_\\Desktop\\", "sales*.csv")

# list of merged files returned
files = glob.glob(files)

print("Resultant CSV after joining all CSV files at a particular location...");

# joining files with concat and read_csv
df = pd.concat(map(pd.read_csv, files), ignore_index=True)
print(df)
This will produce the following −
Resultant CSV after joining all CSV files at a particular location...
           Car      Place   UnitsSold
0         Audi  Bangalore          80
1      Porsche     Mumbai         110
2   RollsRoyce       Pune         100
3          BMW      Delhi          95
4     Mercedes  Hyderabad          80
5  Lamborghini Chandigarh          80
6        Volvo  Rajasthan         150
7      Hyundai    Manipur         120
8       Toyota         HP          70
Difference between sequence and identity in Hibernate

Hibernate or JPA support 4 different types of  primary key generator. These generators are used to generate primary key while inserting rows in the database. Below are the primary key generator   −
GenerationType.AUTO
GenerationType. IDENTITY
GenerationType.SEQUENCE 
GenerationType.TABLE
GenerationType. IDENTITY − In identity , database is responsible to auto generate the primary key. Insert a row without specifying a value for the ID and after inserting the row, ask the database for the last generated ID.  Oracle 11g does not support identity key generator. This feature is supported in Oracle 12c. 
GenerationType. SEQUENCE − In sequence, we first ask database for the next set of the sequence then we insert row with return sequence id. 
1
Basic 
 Database is responsible to auto generate the primary key
we first ask database for the next set of the sequence then we insert row with return sequence id.
2
Performance 
It is faster than sequence key generator 
It is bit slower than identity key generator
3
Database Support 
Oracle 11g does not support identity key generator
Oracle 11g does support SEQUENCE key generator
@Entity
public class User {
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   Integer id;
   String name;
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
@Entity
public class User {
   @Id
   @GeneratedValue(strategy = GenerationType.SEQUENCE)
   Integer id;
   String name;  
   public Integer getId() {
      return id;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}
Perl gethostbyname Function

This function contacts the system's name-resolving service, returning a list of information for the host ADDR of type ADDRTYPE, as follows − ($name, $aliases, $addrtype, $length, @addrs)
The @addrs array contains a list of packed binary addresses. In a scalar context, returns the host address.
Following is the simple syntax for this function −
gethostbyname NAME

This function returns undef on error and otherwise host name in scalr context and empty list on error otherwise host record in list context.
Following is the example code showing its basic usage −
#!/usr/bin/perl
use Socket;

   ($name, $aliases, $addrtype, 
      $length, @addrs) = gethostbyname "amrood.com";
   print "Host name is $name\n";
   print "Aliases is $aliases\n";
When above code is executed, it produces the following result −
Host name is amrood.com
Aliases is


    46 Lectures 
     4.5 hours 

 Devi Killada

    11 Lectures 
     1.5 hours 

 Harshit Srivastava

    30 Lectures 
     6 hours 

 TELCOMA Global

    24 Lectures 
     2 hours 

 Mohammad Nauman

    68 Lectures 
     7 hours 

 Stone River ELearning

    58 Lectures 
     6.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Scikit Learn - Linear Regression

It is one of the best statistical models that studies the relationship between a dependent variable (Y) with a given set of independent variables (X). The relationship can be established with the help of fitting a best line.
sklearn.linear_model.LinearRegression is the module used to implement linear regression.
Following table consists the parameters used by Linear Regression module −
fit_intercept − Boolean, optional, default True
Used to calculate the intercept for the model. No intercept will be used in the calculation if this set to false.
normalize − Boolean, optional, default False
If this parameter is set to True, the regressor X will be normalized before regression. The normalization will be done by subtracting the mean and dividing it by L2 norm. If fit_intercept = False, this parameter will be ignored.
copy_X − Boolean, optional, default True
By default, it is true which means X will be copied. But if it is set to false, X may be overwritten.
n_jobs − int or None, optional(default = None)
It represents the number of jobs to use for the computation.
Following table consists the attributes used by Linear Regression module −
coef_ − array, shape(n_features,) or (n_targets, n_features)
It is used to estimate the coefficients for the linear regression problem. It would be a 2D array of shape (n_targets, n_features) if multiple targets are passed during fit. Ex. (y 2D). On the other hand, it would be a 1D array of length (n_features) if only one target is passed during fit.
Intercept_ − array
This is an independent term in this linear model.
First, import the required packages −
import numpy as np
from sklearn.linear_model import LinearRegression
Now, provide the values for independent variable X −
X = np.array([[1,1],[1,2],[2,2],[2,3]])
Next, the value of dependent variable y can be calculated as follows −
y = np.dot(X, np.array([1,2])) + 3
Now, create a linear regression object as follows −
regr = LinearRegression(
   fit_intercept = True, normalize = True, copy_X = True, n_jobs = 2
)
.fit(X,y)
Use predict() method to predict using this linear model as follows −
regr.predict(np.array([[3,5]]))
array([16.])

To get the coefficient of determination of the prediction we can use Score() method as follows −
regr.score(X,y)

1.0

We can estimate the coefficients by using attribute named ‘coef’ as follows −
regr.coef_

array([1., 2.])

We can calculate the intercept i.e. the expected mean value of Y when all X = 0 by using attribute named ‘intercept’ as follows −
In [24]: regr.intercept_
Output
3.0000000000000018

import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1,1],[1,2],[2,2],[2,3]])
y = np.dot(X, np.array([1,2])) + 3
regr = LinearRegression(
   fit_intercept = True, normalize = True, copy_X = True, n_jobs = 2
).fit(X,y)
regr.predict(np.array([[3,5]]))
regr.score(X,y)
regr.coef_
regr.intercept_

    11 Lectures 
     2 hours 

 PARTHA MAJUMDAR
 Print
 Add Notes
 Bookmark this page