code-rag-bench/online-tutorials huggingface dataset:
Get Standard Deviation of a Column in R dataframe - GeeksforGeeks

07 Apr, 2021
In this article, we are going to find the standard deviation of a column in a dataframe in R Programming Language. 
To select the desired column of a dataframe $ is used.
Syntax:
dataframe$column_name
Formula for variance:
where n is the total number of observations and x bar is the mean
Formula for standard deviation:
In the R programming language, for finding standard deviation on set of data, the method used is sd()
Syntax:
sd(data_values)
Where data-values are a vector input or data frame input.
Given below are some examples to help you understand this better
Example 1:
R
# data1 with vector of elementsdata1=c(1,2,3,4,5)  # data2 with vector of elementsdata2=c("sravan",'bobby','rohith','gnanu','ojaswi')  # give input to the data which is a dataframedata=data.frame(a1=data1,a2=data2)  # finding standard deviation of dataframe# column 1print(sd(data$a1))
Output:
[1] 1.581139
Example 2:
R
# data1 with vector of elementsdata1=c(1,2,3,4,5)  # data2 with vector of elementsdata2=c(10,20,30,40,50)  # give input to the data which is a# dataframedata=data.frame(a1=data1,a2=data2)  # finding standard deviation of dataframe# column 1print(sd(data$a1))  # finding standard deviation of dataframe# column 2print(sd(data$a2))
Output:
[1] 1.581139
[1] 15.81139
Example 3:
R
# data1 with vector of elements (float# values)data1=c(1.0,2,3,4,5,8)  # data2 with vector of elements(float# values)data2=c(10,20.5,30.3,40,50,67.89)  # give input to the data which is a # dataframedata=data.frame(a1=data1,a2=data2)  # finding standard deviation of dataframe # column 1print(sd(data$a1))  # finding standard deviation of dataframe # column 2print(sd(data$a2))
Output:
[1] 2.483277
[1] 20.86387
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
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Logistic Regression in R Programming
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
Java Examples - Format Text in PDF

How to format the text in a PDF using Java.
Following is the program to format the text in a PDF using Java.
import com.itextpdf.io.font.FontConstants; 

import com.itextpdf.kernel.color.Color; 
import com.itextpdf.kernel.font.PdfFontFactory; 
import com.itextpdf.kernel.pdf.PdfDocument; 
import com.itextpdf.kernel.pdf.PdfWriter; 

import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph; 
import com.itextpdf.layout.element.Text;  

public class FormatTextInPdf { 
   public static void main(String args[]) throws Exception { 
      String file = "C:/EXAMPLES/itextExamples/formatingTextInPDF.pdf"; 
      
      //Creating a PdfDocument object 
      PdfDocument pdfDoc = new PdfDocument(new PdfWriter(file));     

      //Creating a Document object 
      Document doc = new Document(pdfDoc);        

      //Adding text to the document 
      Text text1 = new Text("Tutorials Point originated from the idea that there exists
         a class of readers who respond better to online content and prefer to
         learn new skills at their own pace from the comforts of their drawing rooms.");

      //Setting color to the text 
      text1.setFontColor(Color.RED); 

      //Setting font to the text  
      text1.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); 
      
      //Creating a paragraph 1 
      Paragraph para1 = new Paragraph(text1); 

      Text text2 = new Text("The journey commenced with a single tutorial on HTML in 2006
         and elated by the response it generated, we worked our way to adding fresh
         tutorials to our repository which now proudly flaunts a wealth of tutorials and
         allied articles on topics ranging from programming languages to web designing to
         academics and much more.");  
      
      //Setting color to the text 
      text2.setFontColor(Color.RED);
      
      //Setting font to the text  
      text2.setFont(PdfFontFactory.createFont(FontConstants.HELVETICA)); 

      //Creating a paragraph 2 
      Paragraph para2 = new Paragraph(text2); 

      //Adding paragraphs to the document 
      doc.add(para1); 
      doc.add(para2); 

      //Closing the document 
      doc.close(); 
      System.out.println("Text added successfully.."); 
   }     
} 
 Print
 Add Notes
 Bookmark this page
Ruby | String insert Method - GeeksforGeeks

09 Dec, 2019
insert is a String class method in Ruby which is used to inserts the specified string before the character at the given index, modifying the given one. Negative indices count from the end of the string, and insert after the given character.
Syntax: str.insert(index, other_str)
Parameters: Here, str is the given string.
Returns: A modified string.
Example 1:
# Ruby program to demonstrate # the insert method        # Taking a string and # using the methodputs "Ruby".insert(0, 'Z')  puts "Program".insert(3, 'Z')   
Output:
ZRuby
ProZgram

Example 2:
# Ruby program to demonstrate # the insert method        # Taking a string and # using the methodputs "Sample".insert(-4, 'Z')  puts "Articles".insert(-5, 'Z')   
Output:
SamZple
ArtiZcles

Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Hash delete() function
Global Variable in Ruby
Ruby | Case Statement
Ruby | String gsub! Method
Include v/s Extend in Ruby
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Enumerable find() function
Ruby | Numeric round() function
How to create a new directory by using File object in Java?

The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
The mkdir() method of this class creates a directory with the path represented by the current object.
Therefore, to create a directory −
Instantiate the File class by passing the path of the directory you need to create, as a parameter (String).
Invoke the mkdir() method using the above created file object.
Following Java example reads the path and name of the directory to be created, from the user, and creates it.
import java.io.File;
import java.util.Scanner;
public class CreateDirectory {
   public static void main(String args[]) {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(System.in);
      String path = sc.next();
      System.out.println("Enter the name of the desired a directory: ");
      path = path+sc.next();
      //Creating a File object
      File file = new File(path);
      //Creating the directory
      boolean bool = file.mkdir();
      if(bool){
         System.out.println("Directory created successfully");
      }else{
         System.out.println("Sorry couldn’t create specified directory");
      }
   }
}
Enter the path to create a directory:
D:\
Enter the name of the desired a directory:
sample_directory
Directory created successfully
If you verify, you can observe see the created directory as −
But, if you specify a path in a drive that doesn’t exist, this method will not create the required directory.
For example, if the D drive of my (windows) system is empty and if I specify the path of the directory to be created as −
D:\test\myDirectories\sample_directory
Where the test and myDirectories folders doesn’t exist, the mkdir() method will not create it.
To create a hierarchy of new directories you can using the method mkdirs() of the same class. This method creates the directory with the path represented by the current object, including non-existing parent directories.
import java.io.File;
import java.util.Scanner;
public class CreateDirectory {
   public static void main(String args[]) {
      System.out.println("Enter the path to create a directory: ");
      Scanner sc = new Scanner(System.in);
      String path = sc.next();
      System.out.println("Enter the name of the desired a directory: ");
      path = path+sc.next();
      //Creating a File object
      File file = new File(path);
      //Creating the directory
      boolean bool = file.mkdirs();
      if(bool){
         System.out.println("Directory created successfully");
      }else{
         System.out.println("Sorry couldnt create specified directory");
      }
   }
}
Enter the path to create a directory:
D:\test\myDirectories\
Enter the name of the desired a directory:
sample_directory
Directory created successfully
If you verify you can observe see the created directory as −
jQuery | hasClass() with Examples - GeeksforGeeks

13 Feb, 2019
The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not.Syntax:
$(selector).hasClass(className);

Parameter: It accepts a “className” parameter which specifies the class name need to search in the selected element.
Return Value: It returns true if the search is successful otherwise false.jQuery code to show the working of this method:
<html>  <head>    <script     src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>    <script>        $(document).ready(function() {            $("button").click(function() {                alert($("p").hasClass("find"));            });        });    </script>    <style>        .find {            font-size: 120%;            color: green;        }                  body {            width: 50%;            height: 200px;            border: 2px solid green;            padding: 20px;        }    </style></head>  <body>      <h1>Heading 1</h1>      <p class="find">Geeks for Geeks !.</p>    <p>This is normal paragraph.</p>      <button>Click me!</button>  </body>  </html>
Output:Before clicking the “Click me!” button-
After clicking the “Click me!” button-
jQuery-HTML/CSS
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to change the background color after clicking the button in JavaScript ?
How to Dynamically Add/Remove Table Rows using jQuery ?
Add a title to any heading element in the Bootstrap 4 card

To add a title to any heading element in Bootstrap card, use the card-title class −
<h4 class="card-title">
  Top Universities
</h4>
The card-title class comes inside the card class in Bootstrap −
<div class="card-body">
  <h4 class="card-title">Top Universities</h4>
  <p class="card-text">Stanford</p>
  <p class="card-text">Oxford</p>
</div>
Live Demo
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
  </head>

<body>
  <div class="container">
    <div class="card">
      <div class="card-body">
        <h4 class="card-title">Top Universities</h4>
        <p class="card-text">Stanford</p>
        <p class="card-text">Oxford</p>
      </div>
    </div>
  </div>

</body>
</html>
NumPy Joining Array

Joining means putting contents of two or more arrays in a single array.
In SQL we join tables based on a key, whereas in NumPy we join arrays by axes.
We pass a sequence of arrays that we want to join to the
concatenate() function, along with the axis. If axis is not explicitly passed, it is taken as 0.
Join two arrays
Join two 2-D arrays along rows (axis=1):
Stacking is same as concatenation, the only difference is that stacking is done along a new axis.
We can concatenate two 1-D arrays along the second axis which would result in putting them one over 
the other, ie. stacking.
We pass a sequence of arrays that we want to join to the
stack() method along with the axis. If axis is not explicitly passed it is taken as 0.
NumPy provides a helper function: hstack() 
to stack along rows.
NumPy provides a helper function: vstack()  to stack along columns.
NumPy provides a helper function: dstack() 
to stack along height, which is the same as depth.
Use a correct NumPy method to join two arrays into a single array.
arr1 = np.array([1, 2, 3])

arr2 = np.array([4, 5, 6])

arr = np.((arr1, arr2))

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.
Python | Pandas DataFrame.where() - GeeksforGeeks

17 Sep, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas where() method is used to check a data frame for one or more condition and return the result accordingly. By default, The rows not satisfying the condition are filled with NaN value.
Syntax:DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors=’raise’, try_cast=False, raise_on_error=None) 
Parameters:
cond: One or more condition to check data frame for.other: Replace rows which don’t satisfy the condition with user defined object, Default is NaNinplace: Boolean value, Makes changes in data frame itself if Trueaxis: axis to check( row or columns)
For link to the CSV file used, Click here.
Example #1: Single Condition operation
In this example, rows having particular Team name will be shown and rest will be replaced by NaN using .where() method.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("nba.csv")  # sorting dataframedata.sort_values("Team", inplace = True)  # making boolean series for a team namefilter = data["Team"]=="Atlanta Hawks"  # filtering datadata.where(filter, inplace = True)  # displaydata
Output:
As shown in the output image, every row which doesn’t have Team = Atlanta Hawks is replaced with NaN.
 
Example #2: Multi-condition Operations
Data is filtered on the basis of both Team and Age. Only the rows having Team name “Atlanta Hawks” and players having age above 24 will be displayed.
# importing pandas packageimport pandas as pd  # making data frame from csv filedata = pd.read_csv("nba.csv")  # sorting dataframedata.sort_values("Team", inplace = True)  # making boolean series for a team namefilter1 = data["Team"]=="Atlanta Hawks"  # making boolean series for agefilter2 = data["Age"]>24  # filtering data on basis of both filtersdata.where(filter1 & filter2, inplace = True)  # displaydata
Output:As shown in the output image, Only the rows having Team name “Atlanta Hawks” and players having age above 24 are displayed.
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Check if element exists in list in Python
Convert integer to string in Python
How To Convert Python Dictionary To JSON?
isupper(), islower(), lower(), upper() in Python and their applications
sum() function in Python
Python - Combinations of sum with tuples in tuple list - GeeksforGeeks

17 Dec, 2019
Sometimes, while working with data, we can have a problem in which we need to perform tuple addition among all the tuples in list. This can have application in many domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using combinations() + list comprehensionThis problem can be solved using combinations of above functions. In this, we use combinations() to generate all possible combination among tuples and list comprehension is used to feed addition logic.
# Python3 code to demonstrate working of# Summation combination in tuple lists# Using list comprehension + combinationsfrom itertools import combinations  # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10)]  # printing original list print("The original list : " + str(test_list))  # Summation combination in tuple lists# Using list comprehension + combinationsres = [(b1 + a1, b2 + a2) for (a1, a2), (b1, b2) in combinations(test_list, 2)]   # printing resultprint("The Summation combinations are : " + str(res))
The original list : [(2, 4), (6, 7), (5, 1), (6, 10)]
The Summation combinations are : [(8, 11), (7, 5), (8, 14), (11, 8), (12, 17), (11, 11)]

 
Method #2 : Using list comprehension + zip() + operator.add + combinations()The combinations of above methods can also solve this problem. In this, we perform the task of addition using add() and the like indexed elements are linked using zip().
# Python3 code to demonstrate working of# Summation combination in tuple lists# Using list comprehension + zip() + operator.add + combinations()from itertools import combinationsimport operator  # initialize list test_list = [(2, 4), (6, 7), (5, 1), (6, 10)]  # printing original list print("The original list : " + str(test_list))  # Summation combination in tuple lists# Using list comprehension + zip() + operator.add + combinations()res = [(operator.add(*a), operator.add(*b))\    for a, b in (zip(y, x) for x, y in combinations(test_list, 2))]  # printing resultprint("The Summation combinations are : " + str(res))
The original list : [(2, 4), (6, 7), (5, 1), (6, 10)]
The Summation combinations are : [(8, 11), (7, 5), (8, 14), (11, 8), (12, 17), (11, 11)]

Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
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
as_integer_ratio() in Python for reduced fraction of a given rational - GeeksforGeeks

30 Nov, 2021
Given a rational number d, print the reduced fraction which gives d.Examples: 
Input : d = 2.5 
Output : 5/2
Explanation: 5/2 gives 2.5 which is the reduced form
             of any fraction that gives 2.5 

Input : d = 1.5 
Output : 3/2 
 
as_integer_ratio() function Python: Returns a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. 
Syntax: float. as_integer_ratio() Return Value: Tuple (a pair of integers) Errors: Raises OverflowError on infinities and a ValueError on NaNs.
In Python we have an inbuilt function as_integer_ratio() which prints the reduced fraction form of any given rational number d. We need to store that in any variable and then print the 0th index and 1st index of the stored fraction.
Python3
# function to print the fraction of# a given rational numberdef reducedfraction(d):     # function that converts a rational number    # to the reduced fraction    b = d.as_integer_ratio()     # reduced the list that contains the fraction    return b     # driver codeb = reducedfraction(2.5)print (b[0], "/", b[1])
Output: 
5 / 2 
simmytarika5
Fraction
Python-Library
rational-numbers
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
Tryit Editor v3.7

CSS Image Reflection
Tryit: Image reflection - add gradient
LocalDate getMonth() method in Java

The month name for a particular LocalDate can be obtained using the getMonth() method in the LocalDate class in Java. This method requires no parameters and it returns the month name in the year.
A program that demonstrates this is given as follows
 Live Demo
import java.time.*;
public class Demo {
   public static void main(String[] args) {
      LocalDate ld = LocalDate.parse("2019-02-14");
      System.out.println("The LocalDate is: " + ld);
      System.out.println("The month is: " + ld.getMonth());
   }
}
The LocalDate is: 2019-02-14
The month is: FEBRUARY
Now let us understand the above program.
First the LocalDate is displayed. Then the month name for the LocalDate is displayed using the getMonth() method. A code snippet that demonstrates this is as follows:
LocalDate ld = LocalDate.parse("2019-02-14");
System.out.println("The LocalDate is: " + ld);
System.out.println("The month is: " + ld.getMonth());
Python | Reverse an array upto a given position - GeeksforGeeks

21 Nov, 2018
Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. Extra space used should be O(1) and time complexity should be O(k).
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6}
       k = 4

Output:  arr[] = {4, 3, 2, 1, 5, 6} 

This problem has existing solution please refer Reverse an array upto a given position link. We will solve this problem quickly in Python.
# Program to Reverse an array # upto a given position   def reverseArrayUptoK(input, k):      # reverse list starting from k-1 position     # and split remaining list after k    # concat both parts and print    # input[k-1::-1] --> generate list starting    # from k-1 position element till first     # element in reverse order    print (input[k-1::-1] + input[k:])  # Driver programif __name__ == "__main__":    input = [1, 2, 3, 4, 5, 6]    k = 4    reverseArrayUptoK(input, k)
Output:
[4, 3, 2, 1, 5, 6]

Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
JavaScript Switch Statement

The switch statement is used to perform different actions based on different conditions.
Use the switch statement to select one of many code blocks to be executed.
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
If there is no match, the default code block is executed.
The getDay() method returns the weekday as a number between 
 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
The result of day will be:
When JavaScript reaches a break 
keyword, it breaks out of the switch block.
This will stop the execution inside the switch block.
It is not necessary to break the last case in a switch block. The block breaks (ends) there anyway.
Note: If you omit the break statement, the next case will be executed even if 
the evaluation does not match the case.
The default keyword specifies the code to run if there is no 
case match:
The getDay() method returns the weekday as a number between 
 0 and 6.
If today is neither Saturday (6) nor Sunday (0), write a default message:
The result of text will be:
The default case does not have to be the last case in a switch 
block:
If default is not the last case in the switch block, remember to end the default case with a break.

Sometimes you will want different 
switch cases to use the same 
code.

In this example case 4 and 5 share the same code block, and 0 and 6 share 
another code block:

If multiple cases matches a case value, the first case is selected.

If no matching cases are found, the program continues to the default label.

If no default label is found, the program continues to the statement(s) after the switch.
Switch cases use strict comparison (===).
The values must be of the same type to match.
A strict comparison can only be true if the operands are of the same type.
In this example there will be no match for x: 
Create a switch statement that will alert "Hello" if fruits is "banana", and "Welcome" if fruits is "apple".
(fruits) {
  "Banana":
    alert("Hello")
    break;
  "Apple":
    alert("Welcome")
    break;    
}

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.
ipcalc - Unix, Linux Command

Erik Troan <ewt@redhat.com>
Preston Brown <pbrown@redhat.com>





Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How do I plot only a table in Matplotlib?

To plot only a table, we can take the following steps−
Create fig and axs, using subplots. Create a figure and a set of subplots.
Create random data for 10 rows and 3 columns.
Create a tuple for columns name.
axis('tight') − Set the limits, just large enough to show all the data, then disable further autoscaling.
axis('off') − Turn off axis lines and labels. Same as ''False''.
To add a table on the axis, use table() instance, with column text, column labels, columns, and location=center.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig, axs = plt.subplots(1, 1)
data = np.random.random((10, 3))
columns = ("Column I", "Column II", "Column III")
axs.axis('tight')
axs.axis('off')
the_table = axs.table(cellText=data, colLabels=columns, loc='center')
plt.show()
Count Odd and Even numbers in a range from L to R in C++

We are given a range starting from L to R of integer values and the task is to calculate the count of odd numbers and the even numbers in the range.
Input − L = 7, R = 17
Output − Count of Even numbers in a range from L to R are − 5
Count of Odd numbers in a range from L to R are − 6
Input − L = 1, R = 10
Output − Count of Even numbers in a range from L to R are − 5
Count of Odd numbers in a range from L to R are − 5
Input the range starting from L to R
Input the range starting from L to R
Pass the L and R values to the function to find out the even values and then we will calculate the odd values depending upon the return value.
Pass the L and R values to the function to find out the even values and then we will calculate the odd values depending upon the return value.
Start loop FOR from i to L till R
Start loop FOR from i to L till R
Inside the loop, check IF i%2==0 then increment the even count by 1
Inside the loop, check IF i%2==0 then increment the even count by 1
Return the even count
Return the even count
Now to calculate the odd count set odd as (R - L + 1) - even
Now to calculate the odd count set odd as (R - L + 1) - even
 Live Demo
#include <iostream>
using namespace std;
int Odd_Even(int L, int R){
   int even = 0;
   for(int i = L ;i < R ;i++){
      if(i%2==0){
         even++;
      }
   }
   return even;
}
int main(){
   int L = 7, R = 17;
   int even = Odd_Even(L, R);
   int odd = (R - L + 1) - even;
   cout<<"Count of Even numbers in a range from L to R are: "<<even<<endl;
   cout<<"Count of Odd numbers in a range from L to R are: "<<odd;
   return 0;
}
If we run the above code it will generate the following output −
Count of Even numbers in a range from L to R are: 5
Count of Odd numbers in a range from L to R are: 6
How to exclude a field from JSON using @Expose annotation in Java?

The Gson @Expose annotation can be used to mark a field to be exposed or not (included or not) for serialized or deserialized. The @Expose annotation can take two parameters and each parameter is a boolean which can take either the value true or false. In order to get GSON to react to the @Expose annotations we must create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, it configures Gson to exclude all fields from consideration for serialization or deserialization that do not have the Expose annotation.
public GsonBuilder excludeFieldsWithoutExposeAnnotation()
import com.google.gson.*;
import com.google.gson.annotations.*;
public class JsonExcludeAnnotationTest {
   public static void main(String args[]) {
      Employee emp = new Employee("Raja", 28, 40000.00);
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      String jsonStr = gson.toJson(emp);
      System.out.println(jsonStr);
      gson = new GsonBuilder().setPrettyPrinting().excludeFieldsWithoutExposeAnnotation().create();
      jsonStr = gson.toJson(emp);
      System.out.println(jsonStr);
   }
}
// Employee class
class Employee {
   @Expose(serialize = true, deserialize = true)
   public String name;
   @Expose(serialize = true, deserialize = true)
   public int age;
   @Expose(serialize = false, deserialize = false)
   public double salary;
   public Employee(String name, int age, double salary) {
      this.name = name;
      this.age = age;
      this.salary = salary;
   }
}
{
 "name": "Raja",
 "age": 28,
 "salary": 40000.0
}
{
 "name": "Raja",
 "age": 28
}
CSS Background Properties

CSS background properties help us style the background of elements. The CSS background property is a shorthand for specifying the background of an element. background-color, background-image, background-repeat, background-position, background-clip, background-size, background-origin and background-attachment together comprise the CSS background properties.
The syntax of CSS background property is as follows−
Selector {
   background: /*value*/
}
The following examples illustrate CSS background property −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#main {
   margin: auto;
   width: 300px;
   background-image: url("https://www.tutorialspoint.com/hadoop/images/hadoop-mini-logo.jpg");
   background-repeat: no-repeat;
   background-size: cover;
}
#im {
   height: 200px;
   width: 200px;
   background-image: url("https://www.tutorialspoint.com/images/css.png");
   background-repeat: no-repeat;
   background-position: center;
}
</style>
</head>
<body>
<div id="main">
<div id="im"></div>
</div>
</body>
</html>
This gives the following output −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
   background-image: url("https://www.tutorialspoint.com/hcatalog/images/hcatalog-mini-   logo.jpg"),url("https://www.tutorialspoint.com/hbase/images/hbase-mini-logo.jpg"),url("https://www.tutorialspoint.com/hadoop/images/hadoop-mini-logo.jpg");
   background-repeat: no-repeat;
   background-attachment: fixed;
   background-position: 10% 10%, 40% 40%, 90% 10%;
}
</style>
</head>
<body>
</body>
</html>
This gives the following output
How to create digital clock with textview in android?

This example demonstrates How to create digital clock with textview in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/textview"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent"
      android:gravity = "center"
      android:textStyle = "bold"
      android:textSize = "50sp"
      app:fontFamily = "@font/orbitron" />
</LinearLayout>
In the above code, we have taken textview. It will show clock with blink animation as we see in normal digital clock.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
public class MainActivity extends AppCompatActivity {
   TextView textview;
   @Override
   protected void onCreate(Bundle readdInstanceState) {
      super.onCreate(readdInstanceState);
      setContentView(R.layout.activity_main);
      textview = findViewById(R.id.textview);
      Date today = new Date();
      SimpleDateFormat formatter = new SimpleDateFormat("HH:MM");
      textview.setText(formatter.format(today));
      blink();
   }
   private void blink() {
      final Handler hander = new Handler();
      new Thread(new Runnable() {
         @Override
         public void run() {
            try {
               Thread.sleep(550);
            } catch (InterruptedException e) {
               e.printStackTrace();
            }
            hander.post(new Runnable() {
               @Override
               public void run() {
                  if(textview.getVisibility() = = View.VISIBLE) {
                     textview.setVisibility(View.INVISIBLE);
                  } else {
                     textview.setVisibility(View.VISIBLE);
                  }
                  blink();
               }
            });
         }
      }).start();
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
In the above time textview will blink for forever
Click here to download the project code
How to find the median for factor levels in R?

The second most used measure of central tendency median is calculated when we have ordinal data or the continuous data has outliers, also if there are factors data then we might need to find the median for levels to compare them with each other. The easiest way to do this is finding summary with aggregate function.
Consider the below data frame that contains one factor column −
 Live Demo
set.seed(191)
x1<-as.factor(sample(LETTERS[1:3],20,replace=TRUE))
x2<-sample(1:10,20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
  x1 x2
1  B 6
2  C 5
3  B 4
4  C 8
5  B 5
6  B 5
7  A 4
8  C 8
9  C 3
10 C 4
11 B 9
12 A 10
13 C 6
14 C 1
15 A 10
16 A 3
17 A 5
18 C 7
19 B 3
20 C 1
> str(df1)
'data.frame': 20 obs. of 2 variables:
$ x1: Factor w/ 3 levels "A","B","C": 2 3 2 3 2 2 1 3 3 3 ...
$ x2: int 6 5 4 8 5 5 4 8 3 4 ...
Finding the median of x2 for the categories in x1 −
aggregate(x2~x1,data=df1,summary)
  x1 x2.Min. x2.1st Qu.x2.Median x2.Mean x2.3rd Qu.   x2.Max.
1 A 3.000000 4.000000 5.000000   6.400000 10.000000 10.000000
2 B 3.000000 4.250000 5.000000   5.333333 5.750000  9.000000
3 C 1.000000 3.000000 5.000000   4.777778 7.000000  8.000000
Let’s have a look at another example −
 Live Demo
Temperature<-as.factor(sample(c("Cold","Hot"),20,replace=TRUE))
Sales<-sample(50000:80000,20)
df2<-data.frame(Temperature,Sales)
df2
   Temperature Sales
1    Cold    72210
2    Cold    56758
3    Hot     53809
4    Hot     79977
5    Hot     77135
6    Cold    56932
7    Hot     51104
8    Cold    67742
9    Hot     75402
10   Hot     62546
11   Cold    68520
12   Hot     54575
13   Cold    51591
14   Hot    55232
15   Hot    77742
16   Hot    62507
17   Hot    62156
18   Cold   73853
19   Cold   69807
20   Hot    53930
Finding the median of Sales for the categories in Temperature −
aggregate(Sales~Temperature,data=df2,summary)
 Temperature Sales.Min. Sales.1st Qu. Sales.Median Sales.Mean Sales.3rd Qu.
1    Cold    51591.00    56888.50    68131.00       64676.62    70407.75
2    Hot     51104.00    54413.75    62331.50       63842.92    75835.25
 Sales.Max.
1 73853.00
2 79977.00
Python program to find the factorial of a number using recursion - GeeksforGeeks

12 Nov, 2020
A factorial is positive integer n, and denoted by n!. Then the product of all positive integers less than or equal to n.
For example:
In this article, we are going to calculate the factorial of a number using recursion.
Examples:
Input: 5
Output: 120

Input: 6
Output: 720

Implementation:
If fact(5) is called, it will call fact(4), fact(3), fact(2) and fact(1). So it means keeps calling itself by reducing value by one till it reaches 1.
Python3
# Python 3 program to find  # factorial of given number def factorial(n):           # Checking the number    # is 1 or 0 then    # return 1    # other wise return    # factorial    if (n==1 or n==0):                  return 1          else:                  return (n * factorial(n - 1))   # Driver Code num = 5; print("number : ",num)print("Factorial : ",factorial(num))
Output:
Number :  5
Factorial :  120

factorial
Python
Python Programs
factorial
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 dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Filter list of strings based on the substring list - GeeksforGeeks

29 May, 2019
Given two lists of strings string and substr, write a Python program to filter out all the strings in string that contains string in substr.
Examples:
Input : string = ['city1', 'class5', 'room2', 'city2']
        substr = ['class', 'city']
Output : ['city1', 'class5', 'city2']

Input : string = ['coordinates', 'xyCoord', '123abc']
        substr = ['abc', 'xy']
Output : ['xyCoord', '123abc']

 Method #1 : Using List comprehension
We can Use list comprehension along with in operator to check if the string in ‘substr’ is contained in ‘string’ or not.
# Python3 program to Filter list of # strings based on another listimport re  def Filter(string, substr):    return [str for str in string if             any(sub in str for sub in substr)]      # Driver codestring = ['city1', 'class5', 'room2', 'city2']substr = ['class', 'city']print(Filter(string, substr))
['city1', 'class5', 'city2']

 Method #2 : Python Regex
# Python3 program to Filter list of # strings based on another listimport re  def Filter(string, substr):    return [str for str in string     if re.match(r'[^\d]+|^', str).group(0) in substr]      # Driver codestring = ['city1', 'class5', 'room2', 'city2']substr = ['class', 'city']print(Filter(string, substr))
['city1', 'class5', 'city2']

Python string-programs
Python
Python Programs
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
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Apache Presto - HIVE Connector

The Hive connector allows querying data stored in a Hive data warehouse.
Hadoop
Hive
Hopefully you have installed Hadoop and Hive on your machine. Start all the services one by one in the new terminal. Then, start hive metastore using the following command,
hive --service metastore

Presto uses Hive metastore service to get the hive table’s details.
Create a file “hive.properties” under “etc/catalog” directory. Use the following command.
$ cd etc 
$ cd catalog 
$ vi hive.properties  

connector.name = hive-cdh4 
hive.metastore.uri = thrift://localhost:9083

After making all the changes, save the file and quit the terminal.
Create a database in Hive using the following query −
hive> CREATE SCHEMA tutorials; 
After the database is created, you can verify it using the “show databases” command.
Create Table is a statement used to create a table in Hive. For example, use the following query.
hive> create table author(auth_id int, auth_name varchar(50), 
topic varchar(100) STORED AS SEQUENCEFILE;
Following query is used to insert records in hive’s table.
hive> insert into table author values (1,’ Doug Cutting’,Hadoop),
(2,’ James Gosling’,java),(3,’ Dennis Ritchie’,C);
You can start Presto CLI to connect Hive storage plugin using the following command.
$ ./presto --server localhost:8080 --catalog hive —schema tutorials; 

You will receive the following response.
presto:tutorials >

To list out all the schemas in Hive connector, type the following command.
presto:tutorials > show schemas from hive;
default  

tutorials 

To list out all the tables in “tutorials” schema, use the following query.
presto:tutorials > show tables from hive.tutorials; 
author

Following query is used to fetch all the records from hive’s table.
presto:tutorials > select * from hive.tutorials.author; 
auth_id  |   auth_name    | topic 
---------+----------------+-------- 
       1 | Doug Cutting   | Hadoop 
       2 | James Gosling  | java 
       3 | Dennis Ritchie | C


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
Convert datetime string to YYYY-MM-DD-HH:MM:SS format in Python - GeeksforGeeks

23 Aug, 2021
In this article, we are going to convert the DateTime string into the %Y-%m-%d-%H:%M:%S format. For this  task strptime() and strftime() function is used.
strptime() is used to convert the DateTime string to DateTime in the format of year-month-day hours minutes and seconds
Syntax:
datetime.strptime(my_date, “%d-%b-%Y-%H:%M:%S”)
strftime() is used to convert DateTime into required timestamp format
Syntax:
datetime.strftime(“%Y-%m-%d-%H:%M:%S”)
Here,
&Y means year
%m  means month
%d means day
%H means hours
%M means minutes
%S means seconds.
First the take DateTime timestamp as a String. Then, convert it into DateTime using strptime(). Now, convert into the necessary format of DateTime using strftime
Example 1: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format
Python3
# import datetime modulefrom datetime import datetime  # consider date in string formatmy_date = "30-May-2020-15:59:02"  # convert datetime string into date,month,day and# hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")  # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S"))
Output
'2020-05-30-15:59:02'
Example 2: Python program to convert DateTime string into %Y-%m-%d-%H:%M:%S format
Python3
# import datetime modulefrom datetime import datetime  # consider date in string formatmy_date = "30-May-2020-15:59:02"  # convert datetime string into date,month,day # and hours:minutes:and seconds format using# strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")  # convert datetime format into %Y-%m-%d-%H:%M:%S# format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S"))  # consider date in string formatmy_date = "04-Jan-2021-02:45:12"  # convert datetime string into date,month,day # and hours:minutes:and seconds format using # strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")  # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S"))  # consider date in string formatmy_date = "23-May-2020-15:59:02"  # convert datetime string into date,month,day and # hours:minutes:and seconds format using strptimed = datetime.strptime(my_date, "%d-%b-%Y-%H:%M:%S")  # convert datetime format into %Y-%m-%d-%H:%M:%S # format using strftimeprint(d.strftime("%Y-%m-%d-%H:%M:%S"))
2020-05-30-15:59:02
2021-01-04-02:45:12
2020-05-23-15:59:02

Picked
Python-datetime
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()
*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?
Why can C++ templates only be implemented in the header file?

When you instantiate a template in C++, the compiler creates a new class. This class has all the places where you placed the template arguments replaced with the actual argument you pass to it when using it. For example −
template<typename T> class MyClass {
   T foo;
   T myMethod(T arg1, T arg2) {
      // Impl
   }
};
And somewhere in your program use this class,
MyClass<int> x;
The compiler creates a new class upon encountering this for every type argument you pass it. For example, if you created 3 objects with different template arguments you'll get 3 classes, which would be equivalent to −
class MyClassInt {
   int foo;
   int myMethod(int arg1, int arg2) {
      // Impl
   }
};
In order to do so, the compiler needs to have access to the implementation of the class and the methods before it encounters such statements, to instantiate them with the template argument (in this case int). If these template class implementations were not in the header, they wouldn't be accessible and hence won't compile.
When to use fillInStackTrace() method in Java?

The fillInStackTrace() is an important method of Throwable class in Java. The stack trace can be useful to determine where exactly the exception is thrown. There may be some situations where we need to rethrow an exception and find out where it is rethrown, we can use the fillInStackTrace() method in such scenarios.
public Throwable fillInStackTrace()
public class FillInStackTraceTest {
   public static void method1() throws Exception {
      throw new Exception("This is thrown from method1()");
   }
   public static void method2() throws Throwable {
      try {
         method1();
      } catch(Exception e) {
         System.err.println("Inside method2():");
            e.printStackTrace();
            throw e.fillInStackTrace(); // calling fillInStackTrace() method
      }
   }
   public static void main(String[] args) throws Throwable {
      try {
         method2();
      } catch (Exception e) {
         System.err.println("Caught Inside Main method()");
         e.printStackTrace();
      }
   }
}
Inside method2():
java.lang.Exception: This is thrown from method1()
        at FillInStackTraceTest.method1(FillInStackTraceTest.java:3)
        at FillInStackTraceTest.method2(FillInStackTraceTest.java:7)
        at FillInStackTraceTest.main(FillInStackTraceTest.java:18)
Caught Inside Main method()
java.lang.Exception: This is thrown from method1()
        at FillInStackTraceTest.method2(FillInStackTraceTest.java:12)
        at FillInStackTraceTest.main(FillInStackTraceTest.java:18)