code-rag-bench/online-tutorials huggingface dataset:
How to make an HTML link to open a folder? - GeeksforGeeks

14 Apr, 2020
HTML can be used to open a folder from our local storage. In order to open a folder from our local storage, use ‘HREF’ attribute of HTML. In the HREF attribute, we specify the path of our folder.
Syntax:
<a href="Path"></a>
Example 1:
<!DOCTYPE html><html><head>    <title>Sample Code</title></head> <body>    <h1>Opening a folder from HTML code</h1>    <a href="D:\Series\Breaking Bad">Click to open a folder</a></body></html>
Output:
On clicking the link:
Example 2:
<!DOCTYPE html><html><head>    <title>Sample Code</title></head> <body>    <h1>Opening a folder from HTML code</h1>    <a href="C:\Users\ABC\Desktop\cpp">        Click to open a folder    </a></body></html>
Output:
On clicking the link:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Spring Boot CLI - Testing Application

In this chapter, we will test the sample project created in Hello World Example Chapter to demonstrate the testing capabilities of Spring CLI. Follow the steps listed in the table below to test the sample project −
@RestController
class FirstApplication {
   @RequestMapping("/")
   
   String welcome() {
      "Welcome to TutorialsPoint.Com"
   }
} 
class TestFirstApplication {
   @Test
   void welcomeTest() {
      assertEquals("Welcome to TutorialsPoint.Com", new FirstApplication().welcome())
   }
} 
To run the application, type the following command −
E:/Test/FirstApplication/> spring test FirstApplication.groovy TestFirstApplication.groovy

Now Spring Boot CLI will come into action, download the required dependencies, compile the source and test file and unit test the code. The following output will be generated on console −
Resolving dependencies........................................................
.
Time: 0.457

OK (1 test)

Consider the following points to understand the actions taken by Spring CLI −
The @Test annotation directs CLI to download JUnit 4.12 version.
The @Test annotation directs CLI to download JUnit 4.12 version.
Spring CLI automatically detects the version using its metadata, as we have not specified any dependency.
Spring CLI automatically detects the version using its metadata, as we have not specified any dependency.
Finally, after code compilation, test the application.
Finally, after code compilation, test the application.
 Print
 Add Notes
 Bookmark this page
Fabric.js | Rect skewX Property - GeeksforGeeks

29 May, 2020
In this article, we are going to see how to set horizontal skew of a canvas rectangle using FabricJS. The canvas rectangle means rectangle is movable and can be stretched according to requirement. Further, the rectangle can be customized when it comes to initial stroke color, height, width, fill color, or stroke width.
To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library, we will create a canvas block in the body tag which will contain the rectangle. After this, we will initialize instances of Canvas and Rect provided by FabricJS and set horizontal skew of the rectangle using skewX property and render the Rect on the Canvas as given in the example below.
Syntax:
fabric.Rect({
    width: number,
    height: number,
    skewX: number
});
Parameters: This function accepts three parameters as mentioned above and described below:
width: It specifies the width of rectangle.
height: It specifies the height of rectangle.
skewX: It specifies the horizontal skew.
Example: This example uses FabricJS to set horizontal skew of a canvas rectangle.
<!DOCTYPE html> <html>   <head>     <title>         Fabric.js | Rect skewX Property    </title>           <!-- Adding the FabricJS library -->    <script src= "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js">     </script> </head>   <body>     <center>       <h1 style="color: green;">        GeeksforGeeks       </h1>       <b>        Fabric.js | Rect skewX Property       </b>    </center>    <canvas id="canvas" width="600" height="200"        style="border:1px solid #000000">     </canvas>           <script>               // Initiate a Canvas instance         var canvas = new fabric.Canvas("canvas");           // Initiate a Rect instance         var rectangle = new fabric.Rect({             width: 200,            height: 100,            fill: '',             stroke: 'green',            strokeWidth: 3,            skewX: 45        });           // Render the Rect in canvas         canvas.add(rectangle);         canvas.centerObject(rectangle);    </script> </body>   </html>
Output:
Fabric.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
How to get character array from string in JavaScript?
How to filter object array based on attributes?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
jQuery css() Method

The css() method sets or returns one or more style properties for the selected elements.
To return the value of a specified CSS property, use the following syntax:
The following example will return the background-color value of the FIRST matched element:
To set a specified CSS property, use the following syntax:
The following example will set the background-color value for ALL matched elements:
To set multiple CSS properties, use the following syntax:
The following example will set a background-color and a font-size for ALL 
matched elements:
Use the css() method to add a pink background color to a <p> element.
$("p").("", "");

Start the Exercise
For a complete overview of all jQuery CSS methods, please go to our jQuery HTML/CSS Reference.
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.
Groovy - max()

The method gives the maximum of the two arguments. The argument can be int, float, long, double.
double max(double arg1, double arg2) 
float max(float arg1, float arg2) 
int max(int arg1, int arg2) 
long max(long arg1, long arg2) 

Parameters − This method accepts any primitive data type as parameter.
Return Value − This method Returns the maximum of the two arguments.
Following is an example of the usage of this method −
class Example { 
   static void main(String[] args) { 
      System.out.println(Math.max(12.123, 12.456)); 
      System.out.println(Math.max(23.12, 23.0)); 
   } 
}
When we run the above program, we will get the following result −
12.456 
23.12


    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Python – scipy.linalg.norm

The norm() function of the scipy.linalg package is used to return one of eight different matrix norms or one of an infinite number of vector norms.
scipy.linalg.norm(x)
Where x is an input array or a square matrix.
Let us consider the following example −
# Importing the required libraries from scipy
from scipy import linalg
import numpy as np

# Define the input array
x = np.array([7 , 4])
print("Input array:\n", x)

# Calculate the L2 norm
r = linalg.norm(x)

# Calculate the L1 norm
s = linalg.norm(x, 3)

# Display the norm values
print("Norm Value of r :", r)
print("Norm Value of s :", s)
The above program will generate the following output −
Input array:
[7 4]
Norm Value of r : 8.06225774829855
Norm Value of s : 7.410795055420619
Let us take another example −
# Importing the required libraries from scipy
from scipy import linalg
import numpy as np

# Define the input array
x = np.array([[ 6, 7, 8], [9, -1, -2]])
print("Input Array :\n", x)

# Calculate the L2 norm
p = linalg.norm(x)

# Calculate the L1 norm
q = linalg.norm(x, axis=1)

# Display the norm values
print("Norm Values of P :", p)
print("Norm Values of Q :", q)
It will produce the following output −
Input Array :
[[ 6 7 8]
[ 9 -1 -2]]
Norm Values of P : 15.329709716755891
Norm Values of Q : [12.20655562 9.2736185 ]
Optimal Binary Search Tree

A set of integers are given in the sorted order and another array freq to frequency count. Our task is to create a binary search tree with those data to find the minimum cost for all searches.
An auxiliary array cost[n, n] is created to solve and store the solution of subproblems. Cost matrix will hold the data to solve the problem in a bottom-up manner.
Input:
The key values as node and the frequency.
Keys = {10, 12, 20}
Frequency = {34, 8, 50}
Output:
The minimum cost is 142.
These are possible BST from the given values.
For case 1, the cost is: (34*1) + (8*2) + (50*3) = 200
For case 2, the cost is: (8*1) + (34*2) + (50*2) = 176.
Similarly for case 5, the cost is: (50*1) + (34 * 2) + (8 * 3) = 142 (Minimum)
optCostBst(keys, freq, n)
Input: Keys to insert in BST, the frequency for each key, number of keys.
Output: Minimum cost to make optimal BST.
Begin
   define cost matrix of size n x n
   for i in range 0 to n-1, do
      cost[i, i] := freq[i]
   done

   for length in range 2 to n, do
      for i in range 0 to (n-length+1), do
         j := i + length – 1
         cost[i, j] := ∞
         for r in range i to j, done
            if r > i, then
               c := cost[i, r-1]
            else
               c := 0
            if r < j, then
               c := c + cost[r+1, j]
            c := c + sum of frequency from i to j
            if c < cost[i, j], then
               cost[i, j] := c
         done
      done
   done
   return cost[0, n-1]
End
#include <iostream>
using namespace std;

int sum(int freq[], int low, int high) {    //sum of frequency from low to high range
   int sum = 0;
   for (int k = low; k <=high; k++)
      sum += freq[k];
   return sum;
}

int minCostBST(int keys[], int freq[], int n) {
   int cost[n][n];

   for (int i = 0; i < n; i++)    //when only one key, move along diagonal elements
      cost[i][i] = freq[i];

   for (int length=2; length<=n; length++) {
      for (int i=0; i<=n-length+1; i++) {    //from 0th row to n-length+1 row as i
         int j = i+length-1;
         cost[i][j] = INT_MAX;    //initially store to infinity

         for (int r=i; r<=j; r++) {
            //find cost when r is root of subtree
            int c = ((r > i)?cost[i][r-1]:0)+((r < j)?cost[r+1][j]:0)+sum(freq, i, j);
            if (c < cost[i][j])
               cost[i][j] = c;
         }
      }
   }
   return cost[0][n-1];
}

int main() {
   int keys[] = {10, 12, 20};
   int freq[] = {34, 8, 50};
   int n = 3;
   cout << "Cost of Optimal BST is: "<< minCostBST(keys, freq, n);
}
Cost of Optimal BST is: 142
F# - Enumerations

An enumeration is a set of named integer constants.
In F#, enumerations, also known as enums, are integral types where labels are assigned to a subset of the values. You can use them in place of literals to make code more readable and maintainable.
The general syntax for declaring an enumeration is −
type enum-name =
   | value1 = integer-literal1
   | value2 = integer-literal2
...

The following example demonstrates the use of enumerations −
// Declaration of an enumeration.
type Days =
   | Sun = 0
   | Mon = 1
   | Tues = 2
   | Wed = 3
   | Thurs = 4
   | Fri = 5
   | Sat = 6

// Use of an enumeration.
let weekend1 : Days = Days.Sat
let weekend2 : Days = Days.Sun
let weekDay1 : Days = Days.Mon

printfn "Monday: %A" weekDay1
printfn "Saturday: %A" weekend1
printfn "Sunday: %A" weekend2
When you compile and execute the program, it yields the following output −
Monday: Mon
Saturday: Sat
Sunday: Sun

 Print
 Add Notes
 Bookmark this page
How to create a responsive header with CSS?

Following is the code to create a responsive header with CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box;}
nav {
   overflow: hidden;
   background-color: #330b7c;
   padding: 10px;
}
.links {
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   font-weight: bold;
   float: left;
   color:white;
   text-align: center;
   padding: 12px;
   text-decoration: none;
   font-size: 18px;
   line-height: 25px;
   border-radius: 4px;
}
nav .logo {
   font-size: 25px;
   font-weight: bold;
}
nav .links:hover {
   background-color: rgb(214, 238, 77);
   color: rgb(42, 10, 94);
}
nav .selected {
   background-color: dodgerblue;
   color: white;
}
.rightSection {
   float: right;
}
@media screen and (max-width: 870px) {
   nav .links {
      float: none;
      display: block;
      text-align: left;
   }
   .rightSection {
      float: none;
   }
}
</style>
</head>
<body>
<nav>
<a class="links logo" href="#">Company Logo/Image</a>
<div class="rightSection">
<a class="selected links" href="h">Home</a>
<a class="links" href="#">Contact Us</a>
<a class="links" href="#">About Us</a>
<a class="links" href="#">More Info</a>
<a class="links" href="#">Register</a>
</nav>
</body>
</html>
The above code will produce the following output −
On resizing the screen the navigation menu resizes as follows −
How to get the file extension using PowerShell?

We can retrieve the file extension using multiple ways. First, using the [System.IO.Path] class.
PS C:\> [System.IO.Path]::GetExtension("C:\temp\25Aug2020.txt")
.txt
PS C:\> [System.IO.Path]::GetExtension("C:\temp\azcopy.zip")
.zip
This is the easiest way to get the file extension. Otherways,
Using programmatically,
PS C:\> ((Split-Path "C:\Temp\azcopy.zip" -Leaf).Split('.'))[1]
zip
PS C:\> ((Split-Path "C:\Temp\25Aug2020.txt" -Leaf).Split('.'))[1]
txt
Using Get-ChildItem,
PS C:\> (Get-ChildItem C:\Temp\azcopy.zip).Extension
.zip
PS C:\> (Get-ChildItem C:\Temp\25Aug2020.txt).Extension
.txt
Using Get-Item,
PS C:\> (Get-Item C:\Temp\azcopy.zip).Extension
.zip
Compare Println vs Printf in Golang with Examples - GeeksforGeeks

10 May, 2020
Println and Printf are the functions to print the output in Golang. Both are present inside the package “fmt“. However, both these functions provide output differently as follows:
Means “Print Line”. It helps us to print integers, strings, etc but inserts a new line at the end i.e. a line break is inserted. It formats the string using the default formats for its operands. Println also inserts spaces between arguments.
Syntax:
func Println(a ...interface{}) (n int, err error)

Example 1:
// Golang program to show the uses of Println functionpackage main  import "fmt"  func main() {      // The Println prints and    // adds a new line    s := "Sam"    age := 25    fmt.Println("His name is", s)      fmt.Println("His age is", age, "years")}
Output:
His name is Sam
His age is 25 years

Example 2:
// Golang program to show the uses of Println functionpackage main  import "fmt"  func main() {    a, b := 10, 20      fmt.Println("a * b: ")    fmt.Println(a, "*", b, "=", a*b)}
Output:
a * b: 
10 * 20 = 200

Means “Print Formatter”. It prints formatted strings. It contains symbols in the string which you want to print and then arguments after it will replace those symbol points. It does not insert a new line at the end like Println. For that, you’ll have to add “\n” in the end. It formats the string according to a format specifier.
Syntax:
func Printf(format string, a ...interface{}) (n int, err error)

Example 1:
// Golang program to show the uses of Printf functionpackage main  import "fmt"  func main() {      // The Printf prints but    // doesn't add a new line    s := "Sam"    age := 25      fmt.Printf("His name is %s", s)      fmt.Printf("His age is %d ", age)    fmt.Printf("years")}
Output:
His name is SamHis age is 25 years

To be more clear, see the below example. Here Printf formats according to a specified format specifier but Println uses the default formats for its operands.
// Golang program to show the uses// of Printf and Println functionpackage main  import "fmt"  func main() {    m, n, p := 15, 25, 40      fmt.Println(        "(m + n = p) :", m, "+", n, "=", p,    )      fmt.Printf(        "(m + n = p) : %d + %d = %d\n", m, n, p,    )}
Output:
(m + n = p) : 15 + 25 = 40
(m + n = p) : 15 + 25 = 40

Golang-fmt
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
Interfaces in Golang
How to Trim a String in Golang?
How to compare times in Golang?
Beeply module in Python - GeeksforGeeks

03 Jun, 2021
The beeply module in python will helps you produce musical notes using your computer’s characteristic beep sounds. It’s completely written in python ( using winsound and time module to be precise )
As this module is written using winsound, it will work only on Windows. This module contains only one class and a single method i.e beeply class and head() method.
Installation:
pip install beeply
Below are some examples which depicts the use of beeply module:
Example 1
A scale is the tonal basis of music. It is a set of tones from which one can generate melodies. The underscore _ is used for scale of sound If _ is given, it’s scale will be 1
Syntax:
obj = notes.beeps(duration in ms)
beeps is class, it’s constructor takes an  arg ( optional ) of time duration if not given it will take it as 900 ms
If given make sure it’s in ms.
obj.hear(self,duration in ms)
Python3
# import required modulefrom beeply.notes import * # Creating obj of beeply# It's has another arg of duration# By default it's 900 msa = beeps() # It's has another arg of duration# By default it's 900 msa.hear('A_')  print("Done ") # To acknowledge usa.hear("A")
Output:
It will produce tone of A at scale 1 and the at scale 0, you can head 2 beeps for 0.9 sec each.
Example 2
Python3
# import modulefrom beeply.notes import * # create object with duration as argumenta = beeps(1154) # It will sound for 1154 msa.hear('A_') # But if it isa.head('A_', 5000) # Then it is for 5 sec i.e. 5000msprint("Done")
Output:
If you will give duration as argument while making object ( i.e. while instantiating ) then it will be default duration for hear function too if not given specifically. 
clintra
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
LocalDate isLeapYear() method in Java with Examples - GeeksforGeeks

29 Nov, 2018
The isLeapYear() method of LocalDate class in Java checks if the year is leap year or not.
Syntax:
public boolean isLeapYear()

Parameter: This method does not accept parameters.
Return Value: The function returns true if the year is leap, false otherwise.
Below programs illustrate the isLeapYear() method of LocalDate in Java:
Program 1:
// Program to illustrate the isLeapYear() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the first date        LocalDate dt1 = LocalDate.parse("2018-11-27");          // Checks        System.out.println(dt1.isLeapYear());    }}
false

Program 2:
// Program to illustrate the isLeapYear() method  import java.util.*;import java.time.*;  public class GfG {    public static void main(String[] args)    {        // Parses the first date        LocalDate dt1 = LocalDate.parse("2012-11-27");          // Checks        System.out.println(dt1.isLeapYear());    }}
true

Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#isLeapYear()
Java-Functions
Java-LocalDate
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Python | Pandas Series.mean() - GeeksforGeeks

11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.mean() function return the mean of the underlying data in the given Series object.
Syntax: Series.mean(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameter :axis : Axis for the function to be applied on.skipna : Exclude NA/null values when computing the result.level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a scalar.numeric_only : Include only float, int, boolean columns.**kwargs : Additional keyword arguments to be passed to the function.
Returns : mean : scalar or Series (if level specified)
Example #1: Use Series.mean() function to find the mean of the underlying data in the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 25, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.mean() function to find the mean of the given series object.
# return the meanresult = sr.mean()  # Print the resultprint(result)
Output :As we can see in the output, the Series.mean() function has successfully returned the mean of the given series object. Example #2: Use Series.mean() function to find the mean of the underlying data in the given series object. The given series object also contains some missing values.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, 16.8, 20.124, None, 18.1002, 19.5])  # Print the seriesprint(sr)
Output :
Now we will use Series.mean() function to find the mean of the given series object. we are going to skip all the missing values while calculating the mean.
# return the mean# skip all the missing valuesresult = sr.mean(skipna = True)  # Print the resultprint(result)
Output :As we can see in the output, the Series.mean() function has successfully returned the mean of the given series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
HashSet hashCode() method in Java with Example - GeeksforGeeks

24 Dec, 2018
The hashCode() method of HashSet in Java is used to get the hashCode value for this instance of the HashSet. It returns an integer value which is the hashCode value for this instance of the HashSet.
Syntax:
public int hashCode()
Parameters: This function has no parameters.
Returns: The method returns an integer value which is the hashCode value for this instance of the HashSet.
Below examples illustrates the HashSet.hashCode() method:
Example 1:
// Java code to demonstrate the working of// hashCode() method in HashSet  import java.util.*;  public class GFG {    public static void main(String[] args)    {        // creating an HashSet        HashSet<Integer> arr            = new HashSet<Integer>();          // using add() to initialize values        // [1, 2, 3, 4]        arr.add(1);        arr.add(2);        arr.add(3);        arr.add(4);          // print HashSet        System.out.println("HashSet: "                           + arr);          // Get the hashCode value        // using hashCode() value        System.out.println("HashCode value: "                           + arr.hashCode());    }}
HashSet: [1, 2, 3, 4]
HashCode value: 10

Example 2:
// Java code to demonstrate the working of// hashCode() method in HashSet  import java.util.*;  public class GFG {    public static void main(String[] args)    {        // creating an HashSet        HashSet<String> arr            = new HashSet<String>();          // using add() to initialize values        // [Geeks, For, ForGeeks, GeeksForGeeks]        arr.add("Geeks");        arr.add("For");        arr.add("ForGeeks");        arr.add("GeeksForGeeks");          // print HashSet        System.out.println("HashSet: "                           + arr);          // Get the hashCode value        // using hashCode() value        System.out.println("HashCode value: "                           + arr.hashCode());    }}
HashSet: [ForGeeks, Geeks, For, GeeksForGeeks]
HashCode value: -482506029

Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Multithreading in Java
Collections in Java
Initializing a List in Java
How to convert datetime to date in Python - GeeksforGeeks

23 Aug, 2021
In this article, we are going to see how to convert DateTime to date in Python. For this, we will use the strptime() method. This method is used to create a DateTime object from a string. Then we will extract the date from the DateTime object using the date() function.
Syntax: datetime.strptime()
Parameters : 
arg: It can be integer, float, tuple, Series, Dataframe to convert into datetime as its datatype
format: This will be str, but the default is None. The strftime to parse time, eg “%d/%m/%Y”, note that “%f” will parse all the way up to nanoseconds.
Example 1: Convert datetime to date.
In this example, We have created a datetime_str which is “24AUG2001101010”, and its format is “%d%b%Y%H%M%S”.
Python3
# import important moduleimport datetimefrom datetime import datetime  # Create datetime stringdatetime_str = "24AUG2001101010"print("datetime string : {}".format(datetime_str))  # call datetime.strptime to convert# it into datetime datatypedatetime_obj = datetime.strptime(datetime_str,                                  "%d%b%Y%H%M%S")  # It will print the datetime objectprint(datetime_obj)  # extract the time from datetime_objdate = datetime_obj.date()print(date)
Output : 
datetime string : 24AUG2001101010
2001-08-24 10:10:10
2001-08-24
Example 2: Convert datetime with numeric date.
In this example, We have created a datetime_str which is “100201095407”, and its format is “%d%m%y%H%M%S”.
Python3
# import important moduleimport datetimefrom datetime import datetime  # Create datetime stringdatetime_str = "100201095407"print("datetime string : {}".format(datetime_str))  # call datetime.strptime to convert# it into datetime datatypedatetime_obj = datetime.strptime(datetime_str,                                 "%d%m%y%H%M%S")  # It will print the datetime objectprint(datetime_obj)  # extract the time from datetime_objdate = datetime_obj.date()  # it will print date that we have# extracted from datetime objprint(date)
Output: 
datetime string : 100201095407
2001-02-10 09:54:07
2001-02-10
Example 3: Convert datetime with current date.
In this example, we take present date and time, and extracted its date from the object.
Python3
# import important modulefrom datetime import datetime  # call datetime.strptime to# convert it into datetime datatypedatetime_obj = datetime.now()  # It will print the datetime objectprint(datetime_obj)  # extract the time from datetime_objdate = datetime_obj.date()print(date) 
Output: 
2021-08-07 06:30:20.227879
2021-08-07
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
Scala Collections - Partition Method

partition() method is a member of TraversableLike trait, it is used to run a predicate method on each elements of a collection. It returns two collections, one collection is of elements which satisfiles a given predicate function and another collection is of elements which do not satisfy the given predicate function.
The following is the syntax of map method.
def partition(p: (A) ? Boolean): (Repr, Repr)

Here, partition method takes a prediate function as a parameter. This method returns the collections.
Below is an example program of showing how to use partition method −
object Demo {
   def main(args: Array[String]) = {
      val list = List(1, 2, 3, 4, 5, 6, 7)
      //apply operation to get twice of each element.
      val (result1, result2) = list.partition(x=>{x % 3 == 0})
      //print result
      println(result1)
      println(result2)      
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

List(3, 6)
List(1, 2, 4, 5, 7)


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
random.getrandbits() in Python - GeeksforGeeks

17 May, 2020
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined.
The getrandbits() method of the random module is used to return an integer with a specified number of bits. The number of bits required in the result is passed as an parameter in the method.
Examples :
Input : getrandbits(4)
Output : 14
(the binary equivalent of 14 is 1110 which has 4 bits)

Input : getrandbits(16)
Output : 60431
(the binary equivalent of 14 is 1110110000001111 
which has 16 bits)

Example 1:
# import the random moduleimport random  # a random number with 4 bitsprint(random.getrandbits(4))  # a random number with 16 bitsprint(random.getrandbits(16))
Output :
10
49195
Example 2:
# import the random moduleimport random  # 5 random number with 4 bitsfor i in range(4):    print(random.getrandbits(4))
Output:
10
0
1
14
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
How to use a return statement in lambda expression in Java?

A return statement is not an expression in a lambda expression. We must enclose statements in braces ({}). However, we do not have to enclose a void method invocation in braces. The return type of a method in which lambda expression used in a return statement must be a functional interface.
public class LambdaReturnTest1 {
   interface Addition {
      int add(int a, int b);
   }
   public static Addition getAddition() {
      return (a, b) -> a + b; // lambda expression return statement
   }
   public static void main(String args[]) {
      System.out.println("The addition of a and b is: " + getAddition().add(20, 50));
   }
}
The addition of a and b is: 70

public class LambdaReturnTest2 {
   public static void main(String args[]) {
      Thread th = new Thread(getRunnable());
      th.run();
   }
   public static Runnable getRunnable() {
      return() -> {    // lambda expression return statement
         System.out.println("Lambda Expression Return Statement");
      };
   }
}
Lambda Expression Return Statement
Alter login in SQL Server - GeeksforGeeks

19 Aug, 2020
Alter login statements can be used to changes the properties of a SQL Server login account.
Syntax:
ALTER LOGIN loginname;
GO

Enable a disabled login –
Syntax :
ALTER LOGIN loginname ENABLE;

Example –
ALTER LOGIN geeks ENABLE;
Change password of a loginSyntax :
ALTER LOGIN geeks WITH PASSWORD = 'newpassword';

Example –
ALTER LOGIN geeks WITH PASSWORD = ‘G9h$fm@1LZe’;

Change the password for a login when logged in using the same login
Syntax:
ALTER LOGIN loginname 
WITH PASSWORD = 'newpassword' OLD_PASSWORD = 'oldpassword';

Example –
ALTER LOGIN geeks 
WITH PASSWORD = ‘G9h$fm@1LZe’ OLD_PASSWORD = ‘Ge@@k$s12’;

Change name of a login
Syntax:
ALTER LOGIN loginnmae WITH NAME = newname;

Example –
ALTER LOGIN geeks WITH NAME = geek;

Unlock a login
Syntax:
ALTER LOGIN loginnmae WITH PASSWORD = 'password' UNLOCK ;

Example –
ALTER LOGIN geeks WITH PASSWORD = ‘G9h$fm@1LZe’ UNLOCK ;

Unlock a login without changing the password
Syntax:
ALTER LOGIN [loginname] WITH CHECK_POLICY = OFF;
ALTER LOGIN [loginnmae] WITH CHECK_POLICY = ON;

Example –
ALTER LOGIN geeks WITH CHECK_POLICY = OFF;

ALTER LOGIN geeks WITH CHECK_POLICY = ON;

DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Alter Multiple Columns at Once in SQL Server?
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL using Python
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL | Subquery
SQL | Date functions
SQL Query for Matching Multiple Values in the Same Column
SQL Query to Convert VARCHAR to INT
SQL | DROP, TRUNCATE
Logistic Regression in Python - Splitting Data

We have about forty-one thousand and odd records. If we use the entire data for model building, we will not be left with any data for testing. So generally, we split the entire data set into two parts, say 70/30 percentage. We use 70% of the data for model building and the rest for testing the accuracy in prediction of our created model. You may use a different splitting ratio as per your requirement.
Before we split the data, we separate out the data into two arrays X and Y. The X array contains all the features (data columns) that we want to analyze and Y array is a single dimensional array of boolean values that is the output of the prediction. To understand this, let us run some code.
Firstly, execute the following Python statement to create the X array −
In [17]: X = data.iloc[:,1:]

To examine the contents of X use head to print a few initial records. The following screen shows the contents of the X array.
In [18]: X.head ()

The array has several rows and 23 columns.
Next, we will create output array containing “y” values.
To create an array for the predicted value column, use the following Python statement −
In [19]: Y = data.iloc[:,0]

Examine its contents by calling head. The screen output below shows the result −
In [20]: Y.head()
Out[20]: 0   0
1    0
2    1
3    0
4    1
Name: y, dtype: int64

Now, split the data using the following command −
In [21]: X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=0)

This will create the four arrays called X_train, Y_train, X_test, and Y_test. As before, you may examine the contents of these arrays by using the head command. We will use X_train and Y_train arrays for training our model and X_test and Y_test arrays for testing and validating.
Now, we are ready to build our classifier. We will look into it in the next chapter.

    15 Lectures 
     1 hours 

 Ajay

    53 Lectures 
     6 hours 

 Abhishek And Pukhraj

    49 Lectures 
     5 hours 

 Abhishek And Pukhraj
 Print
 Add Notes
 Bookmark this page
Changing the Default Font for all the widgets in Tkinter

Let us consider a case where we want to change the default font of a Tkinter application. To apply the font and setting it as the default font for a particular application, we have to use option_add(**options) method where we specify a property such as background color, font, etc. The changes made after defining the method will force all the widgets to inherit the same property.
In the given script, we have set a default font for the application such that it can be used for all the widgets defined in the application.
#Import the required libraries
from tkinter import *

#Create an instance of Tkinter frame
win = Tk()

win.geometry("700x350")
#Add fonts for all the widgets
win.option_add("*Font", "aerial")

#Set the font for the Label widget
win.option_add("*Label.Font", "aerial 18 bold")

# Define the backround color for all the idgets
win.option_add("*Background", "bisque")

#Display bunch of widgets
Label(win, text="Label").pack()
Button(win, text="Button").pack()

#Create a Listbox widget
w = Listbox(win)
for i in range(5):
   w.insert(i, "item %d" % (i+1))
w.pack()

w = Text(win, width=20, height=10)
w.insert(1.0, "a text widget")
w.pack()

win.mainloop()
Running the above code will display a window with a Label widget, a Button, a Listbox, and a Text Widget. In the given output, all widgets inherit the same properties.
Python | Arithmetic operations in excel file using openpyxl

19 May, 2021
Prerequisite: Reading & Writing to excel sheet using openpyxlOpenpyxl is a Python library using which one can perform multiple operations on excel files like reading, writing, arithmetic operations and plotting graphs. Let’s see how to perform different arithmetic operations using openpyxl.  
=SUM(cell1:cell2) : Adds all the numbers in a range of cells.  
Python3
# import openpyxl moduleimport openpyxl # Call a Workbook() function of openpyxl# to create a new blank Workbook objectwb = openpyxl.Workbook() # Get workbook active sheet # from the active attribute.sheet = wb.active # writing to the cell of an excel sheetsheet['A1'] = 200sheet['A2'] = 300sheet['A3'] = 400sheet['A4'] = 500sheet['A5'] = 600 # The value in cell A7 is set to a formula# that sums the values in A1, A2, A3, A4, A5 .sheet['A7'] = '= SUM(A1:A5)' # save the filewb.save("sum.xlsx")
Output:  
=PRODUCT(cell1:cell2) : Multiplies all the numbers in the range of cells. 
Python3
import openpyxl wb = openpyxl.Workbook()sheet = wb.active sheet['A1'] = 2sheet['A2'] = 3sheet['A3'] = 4sheet['A4'] = 5sheet['A5'] = 6 # The value in cell A7 is set to a formula# that multiplies the values in A1, A2, A3, A4, A5 .sheet['A7'] = '= PRODUCT(A1:A5)' wb.save("product.xlsx")
Output:  
=AVERAGE(cell1:cell2) : It gives the average (arithmetical mean) of all the numbers which is present in the given cell range. 
Python3
import openpyxl wb = openpyxl.Workbook()sheet = wb.active sheet['A1'] = 200sheet['A2'] = 300sheet['A3'] = 400sheet['A4'] = 500sheet['A5'] = 600 # The value in cell A7 is set to a formula# that return average of the values in A1, A2, A3, A4, A5 .sheet['A7'] = '= AVERAGE(A1:A5)' wb.save("average.xlsx")
Output:  
=QUOTIENT(num1, num2) : It returns the integer portion of a division. 
Python3
import openpyxl wb = openpyxl.Workbook()sheet = wb.active # The value in cell is set to a formula# that gives quotient value .sheet['A1'] = '= QUOTIENT(64, 8)'sheet['A2'] = '= QUOTIENT(25, 4)' wb.save("quotient.xlsx")
Output:  
=MOD(num1, num2) : Returns the remainder after a number is divided by the divisor. 
Python3
import openpyxl wb = openpyxl.Workbook()sheet = wb.active # The value in cell is set to a formula# that gives remainder or modulus value.sheet['A1'] = '= MOD(64, 8)'sheet['A2'] = '= MOD(25, 4)' wb.save("modulus.xlsx")
Output:  
=COUNT(cell1:cell2) : It counts the number of cells in a range that contain the number. 
Python3
import openpyxl wb = openpyxl.Workbook()sheet = wb.active sheet['A1'] = 200sheet['A2'] = 300sheet['A3'] = 400sheet['A4'] = 500sheet['A5'] = 600 # The value in cell A7 is set to a formula# that gives counting of number present in the cells.sheet['A7'] = '= COUNT(A1:A6)' wb.save("count.xlsx")
Output:  
 
anikaseth98
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Multiple Choice Questions - GeeksforGeeks

28 Jun, 2021
Mcq / Quizzes
Outputs
Mcq / Quizzes :
FunctionsOperatorsMiscellaneousData TypeOutput
Functions
Operators
Miscellaneous
Data Type
Output
Outputs :
Output of Python Program | Set 1Output of python program | Set 2Output of python program | Set 3Output of python program | Set 4Output of python program | Set 5Output of python program | Set 6(Lists)Output of python program | Set 7Output of python program | Set 8Output of python program | Set 9(Dictionary)Output of python program | Set 10(Exception Handling)Output of python program | Set 11(Lists)Output of python program | Set 12(Lists and Tuples)Output of python program | Set 13(Lists and Tuples)Output of python program | Set 14 (Dictionary)
Output of Python Program | Set 1
Output of python program | Set 2
Output of python program | Set 3
Output of python program | Set 4
Output of python program | Set 5
Output of python program | Set 6(Lists)
Output of python program | Set 7
Output of python program | Set 8
Output of python program | Set 9(Dictionary)
Output of python program | Set 10(Exception Handling)
Output of python program | Set 11(Lists)
Output of python program | Set 12(Lists and Tuples)
Output of python program | Set 13(Lists and Tuples)
Output of python program | Set 14 (Dictionary)
Output of python program | Set 15 (Modules)Output of Python program | Set 15 (Loops)Output of Python program | Set 16 (Threads)Output of Python program | Set 17Output of Python Programs | Set 18 (List and Tuples)Output of Python Programs | Set 19 (Strings)Output of Python Programs | Set 20 (Tuples)Output of Python Programs | Set 21 (Bool)Output of Python Programs | Set 22 (Loops)Output of Python Programs | Set 23 (String in loops)Output of Python Programs | Set 24 (Sets)
Output of python program | Set 15 (Modules)
Output of Python program | Set 15 (Loops)
Output of Python program | Set 16 (Threads)
Output of Python program | Set 17
Output of Python Programs | Set 18 (List and Tuples)
Output of Python Programs | Set 19 (Strings)
Output of Python Programs | Set 20 (Tuples)
Output of Python Programs | Set 21 (Bool)
Output of Python Programs | Set 22 (Loops)
Output of Python Programs | Set 23 (String in loops)
Output of Python Programs | Set 24 (Sets)
    
All Articles of Python
Java Multiple Choice Questions
C Multiple Choice Questions
C++ Multiple Choice Questions
Multiple Choice Questions on all CS topics
 
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
XSD - Attribute

Attribute represents the attribute of an XML element. XSD defines it as a simple type.
<xs:attribute name = "attribute-name" type = "attribute-type"/>

<xs:attribute name = "rollno" type = "xs:integer"/> 

defines following rollno attribute which can be used in an XML element. For example
<student rollno = "393" />

<xs:attribute name = "rollno" type = "xs:integer"/> 

defines type of attribute as integer, rollno should have value of type int.
<student rollno = "393" />

Consider the following XML Element
<student rollno = "393" />

XSD declarations for rollno attribute will be as follows − 
<xs:attribute name = "rollno" type = "xs:integer"/>

Attribute can have a default value assigned to it. Default value is used in case the attribute has no value.
<xs:attribute name = "grade" type = "xs:string" default = "NA" /> 

Attribute can have a fix value assigned. In case a fixed value is assigned, then the element can not have any value.
<xs:attribute name = "class" type = "xs:string" fixed = "1" /> 

Attributes are by default optional. But to make an attribute mandatory, "use" attribute can be used.
<xs:attribute name = "rollno" type = "xs:integer" use = "required"/>

 Print
 Add Notes
 Bookmark this page
GATE | GATE-CS-2003 | Question 90 - GeeksforGeeks

28 Jun, 2021
Consider the following recurrence relationThe value of T(m2) for m ≥ 1 is(A) (m/6) (21m – 39) + 4(B) (m/6) (4m2 – 3m + 5)(C) (m/2) (m2.5 – 11m + 20) – 5(D) (m/6) (5m3 – 34m2 + 137m – 104) + (5/6)Answer: (B)Explanation:
One easy way to solve this is to try putting different 
values of m.

For example, we know T(1) = 1. If we put m = 1, only A
and B satisfy the result.

m = 2

T(2) = T(1) + 1 = 2
T(3) = T(2) + 1 = 3
T(4) = T(3) + 2 = 5

Both A & B produce 5

m = 3
T(9) = T(4) + 2*5 + 1 = 5 + 10 + 1 = 16
Both A & B produce 16

m = 4
T(16) = T(9) + 3*7 + 1 = 16 + 21 + 1 = 38
Only B produces 38, A produces 34 which doesn't match 
Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-CS-2016 (Set 1) | Question 56
GATE | GATE-CS-2014-(Set-1) | Question 51