code-rag-bench/online-tutorials huggingface dataset:
Method Overloading based on the order of the arguments in Java

In method overloading, the class can have multiple methods with the same name but the parameter list of the methods should not be the same. One way to make sure that the parameter list is different is to change the order of the arguments in the methods.
A program that demonstrates this is given as follows −
 Live Demo
class PrintValues {
   public void print(int val1, char val2) {
      System.out.println("\nThe int value is: " + val1);
      System.out.println("The char value is: " + val2);
   }
   public void print(char val1, int val2) {
      System.out.println("\nThe char value is: " + val1);
      System.out.println("The int value is: " + val2);
   }
}
public class Demo {
   public static void main(String[] args) {
      PrintValues obj = new PrintValues();
      obj.print(15, 'A');
      obj.print('P', 4);
   }
}
The int value is: 15
The char value is: A

The char value is: P
The int value is: 4
Now let us understand the above program.
The PrintValues class is created with two methods print() in the implementation of method overloading. The first of these takes 2 parameters of type int and type char respectively and the other takes 2 parameters of type char and type int respectively. A code snippet which demonstrates this is as follows −
class PrintValues {
   public void print(int val1, char val2) {
      System.out.println("\nThe int value is: " + val1);
      System.out.println("The char value is: " + val2);
   }
   public void print(char val1, int val2) {
      System.out.println("\nThe char value is: " + val1);
      System.out.println("The int value is: " + val2);
   }
}
In the main() method, object obj of class PrintValues is created and the print() method is called two times with parameters (15, ’A’) and (‘P’, 4) respectively. A code snippet which demonstrates this is as follows:
public class Demo {
   public static void main(String[] args) {
      PrintValues obj = new PrintValues();
      obj.print(15, 'A');
      obj.print('P', 4);
   }
}
border-top-0 class in Bootstrap 4

Use the border-top-0 class in Bootstrap 4 to remove the top border.
Set the border-top-0 class −
<div class="mystyle border border-top-0">
  Rectangle is missing the TOP border.
</div>
Let us see an example to implement the border-top-0 class −
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>
    <style>
    .mystyle {
      width: 350px;
      height: 170px;
      margin: 10px;
    }
    </style>
  </head>
<body>
  <div class="container">
    <h2>Heading Two</h2>
    <div class="mystyle border border-top-0">
      Rectangle is missing the TOP border.
    </div>
  </div>
</body>
</html>
Which is better System.String or System.Text.StringBuilder classes in C#?

The main difference is StringBuilder is Mutable whereas String is Immutable.
String is immutable, Immutable means if you create string object then you cannot modify it and It always create new object of string type in memory.
On the other hand, StringBuilder is mutable. Means, if we create a string builder object then we can perform any operation like insert, replace or append without creating new instance for every time. It will update string at one place in memory doesn’t create new space in memory.
 Live Demo
using System;
using System.Text;
class DemoApplication{
   public static void Main(String[] args){
      String systemString = "Hello";
      StringConcat(systemString);
      Console.WriteLine("String Class Result: " + systemString);
      StringBuilder stringBuilderString = new StringBuilder("Hello");
      StringBuilderConcat(stringBuilderString);
      Console.WriteLine("StringBuilder Class Result: " + stringBuilderString);
   }
   public static void StringConcat(String systemString){
      String appendString = " World";
      systemString = String.Concat(systemString, appendString);
   }
   public static void StringBuilderConcat(StringBuilder stringBuilderString){
      stringBuilderString.Append(" World");
   }
}
The output of the above example is as follows −
String Class Result: Hello
StringBuilder Class Result: Hello World
Use of StringConcat Method: In this method, we are passing a string “Hello” and performing “systemString = String.Concat(systemString, appendString);” where appendString is “ World” to be concatenated. The string passed from Main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and systemString in StringConcat() stores reference of the new string. But the references systemString in Main() and StringConcat() refer to different strings.
Use of StringConcat Method: In this method, we are passing a string “Hello” and performing “systemString = String.Concat(systemString, appendString);” where appendString is “ World” to be concatenated. The string passed from Main() is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and systemString in StringConcat() stores reference of the new string. But the references systemString in Main() and StringConcat() refer to different strings.
Use of StringBuilderConcat Method: In this method, we are passing a string “Hello” and performing “stringBuilderString.Append(" World");” which changes the actual value of the string (in Main) to “Hello World”. This is due to the simple fact that StringBuilder is mutable and hence changes its value.
Use of StringBuilderConcat Method: In this method, we are passing a string “Hello” and performing “stringBuilderString.Append(" World");” which changes the actual value of the string (in Main) to “Hello World”. This is due to the simple fact that StringBuilder is mutable and hence changes its value.
Interpolation Search Program in C

Interpolation search is an improved variant of binary search. This search algorithm works on the probing position of the required value. For this algorithm to work properly, the data collection should be in sorted and equally distributed form.
It's runtime complexity is log2(log2 n).
#include<stdio.h>

#define MAX 10

// array of items on which linear search will be conducted. 
int list[MAX] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44 };

int find(int data) {
   int lo = 0;
   int hi = MAX - 1;
   int mid = -1;
   int comparisons = 1;      
   int index = -1;

   while(lo <= hi) {
      printf("\nComparison %d  \n" , comparisons ) ;
      printf("lo : %d, list[%d] = %d\n", lo, lo, list[lo]);
      printf("hi : %d, list[%d] = %d\n", hi, hi, list[hi]);
      
      comparisons++;

      // probe the mid point 
      mid = lo + (((double)(hi - lo) / (list[hi] - list[lo])) * (data - list[lo]));
      printf("mid = %d\n",mid);

      // data found 
      if(list[mid] == data) {
         index = mid;
         break;
      } else {
         if(list[mid] < data) {
            // if data is larger, data is in upper half 
            lo = mid + 1;
         } else {
            // if data is smaller, data is in lower half 
            hi = mid - 1;
         }
      }               
   }
   
   printf("\nTotal comparisons made: %d", --comparisons);
   return index;
}

int main() {
   //find location of 33
   int location = find(33);

   // if element was found 
   if(location != -1)
      printf("\nElement found at location: %d" ,(location+1));
   else
      printf("Element not found.");
   
   return 0;
}
If we compile and run the above program, it will produce the following result −
Comparison 1
lo : 0, list[0] = 10
hi : 9, list[9] = 44
mid = 6

Total comparisons made: 1
Element found at location: 7

You can change the search value and execute the program to test it.

    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Can we define an enum inside a method in Java?

Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax −
enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
We can an enumeration inside a class. But, we cannot define an enum inside a method. If you try to do so it generates a compile time error saying “enum types must not be local”.
public class EnumExample{
   public void sample() {
      enum Vehicles {
         Activa125, Activa5G, Access125, Vespa, TVSJupiter;
      }
   }
}
EnumExample.java:3: error: enum types must not be local
      enum Vehicles {
      ^
1 error
To use the enum constants inside a method declare the required enum inside a class and use its constants inside a method using the values().
Live Demo
public class EnumerationExample {
   enum Enum {
      Mango, Banana, Orange, Grapes, Thursday, Apple
   }
   public void testMethod(){
      Enum constants[] = Enum.values();
      System.out.println("Value of constants: ");  
      for(Enum d: constants) {
         System.out.println(d);
      }
   }
   public static void main(String args[]) {
      EnumerationExample obj = new EnumerationExample();
      obj.testMethod();      
   }
}
Value of constants:
Mango
Banana
Orange
Grapes
Thursday
Apple
What are jQuery events .load(), .ready(), .unload()?

jQuery load() method
The load() method is used to attach event handler to load event.
You can try to run the following code to learn how to work with jQuery load() method.
Note:  The method deprecated in jQuery 1.8. It got finally removed in jQuery 3.0. To run the following code, add jQuery version lesser than 1.8,
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("img").load(function(){
        alert("This is an image.");
    });
});
</script>
</head>
<body>

<img src="/videotutorials/images/coding_ground_home.jpg" alt="Coding Ground" width="310" height="270">

<p>This image will load only in jQuery version lesser than 1.8</p>

</body>
</html>
jQuery ready() method
Easily specify what happens when a ready event occurs, with the ready() function.
You can try to run the following code to learn how to work with ready() method. For an example, we're hiding an element here:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").hide();
    });
});
</script>
</head>
<body>

<p>This is demo text.</p>

<button>Hide</button>

</body>
</html>
jQuery unload() method
If you want to trigger an event while navigate away from the page, use the unload() method.
Note: The jQuery unload() method deprecated in jQuery 1.8. It got finally removed in jQuery 3.0.
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $(window).unload(function(){
        alert("Thanks! Bye!");
    });
});
</script>
</head>
<body>

<p>Event triggers when you leave the page.</p>
</body>
</html>
Python os.write() Method

Python method write() writes the string str to file descriptor fd. Return the number of bytes actually written.
Following is the syntax for write() method −
os.write(fd, str)

fd − This is the file descriptor.
fd − This is the file descriptor.
str − This is the string to be written.
str − This is the string to be written.
This method returns the number of bytes actually written.
Python following example shows the usage of write() method.
# !/usr/bin/python

import os, sys

# Open file
fd = os.open("f1.txt",os.O_RDWR|os.CREAT)

# Writing text
ret = os.write(fd,"This is test")

# ret consists of number of bytes written to f1.txt
print "the number of bytes written: "
print  ret

print "written successfully"

# Close opened file
os.close(fd)
print "Closed the file successfully!!"
When we run above program, it produces following result −
the number of bytes written:
12
written successfully 
Closed the file successfully!!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to detect a mobile device in jQuery? - GeeksforGeeks

16 Apr, 2019
We can use JavaScript window.matchMedia() method to detect a mobile device based on the CSS media query. This is the best and easiest way to detect mobile devices.
Syntax:
window.matchMedia();
Example-1: Program run on desktop.
<!DOCTYPE html><html lang="en">  <head>    <title>      jQuery Detect Mobile Device  </title></head>  <body>    <script>        if (window.matchMedia("(max-width: 767px)").matches)         {                        // The viewport is less than 768 pixels wide            document.write("This is a mobile device.");        } else {                        // The viewport is at least 768 pixels wide            document.write("This is a tablet or desktop.");        }    </script></body>  </html>
Output:
Example-2: Program run on mobile device.
<!DOCTYPE html><html lang="en">  <head>    <title>      jQuery Detect Mobile Device  </title></head>  <body>    <script>        if (window.matchMedia("(max-width: 767px)").matches)        {                        // The viewport is less than 768 pixels wide            document.write("This is a mobile device.");        } else {                        // The viewport is at least 768 pixels wide            document.write("This is a tablet or desktop.");        }    </script></body>  </html>
Output:
Supported Browsers:
Google Chrome
Mozilla Firefox
Opera
Edge
Safari
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Scroll to the top of the page using JavaScript/jQuery
How to get the ID of the clicked button using JavaScript / jQuery ?
jQuery | children() with Examples
Express.js express.Router() Function
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
Top 10 Angular Libraries For Web Developers
Console.Clear Method in C# - GeeksforGeeks

29 Jan, 2019
This method is used to clear the console buffer and corresponding console window of display information.
Syntax: public static void Clear ();
Exceptions: This method throws IOException if an I/O error occurred.
Below programs show the use of Console.Clear() method:
Program 1: To display the contents before the use of Clear method
// C# program to illustrate the use// of Console.Clear Method using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {          // Print the statements        Console.WriteLine("GeeksForGeeks");        Console.WriteLine("A Computer Science Portal");        Console.WriteLine("For Geeks");    }}}
GeeksForGeeks
A Computer Science Portal
For Geeks

Program 2: Use clear() method to clear the console
// C# program to illustrate the use// of Console.Clear Method using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading;using System.Threading.Tasks;  namespace GFG {  class Program {      static void Main(string[] args)    {        // Print the statements        Console.WriteLine("GeeksForGeeks");        Console.WriteLine("A Computer Science Portal");        Console.WriteLine("For Geeks");          // Clear the Console        Console.Clear();    }}}
CSharp-Console-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
How to create JavaScript alert with 3 buttons (Yes, No and Cancel)?

The standard JavaScript alert box won’t work if you want to customize it. For that, we have a custom alert box, which we’re creating using jQuery and styled with CSS.
You can try to run the following code to create an alert box with 3 buttons i.e Yes, No and Cancel.
<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         function functionConfirm(msg, myYes, myNo, cancel) {
            var confirmBox = $("#confirm");
            confirmBox.find(".message").text(msg);
            confirmBox.find(".yes,.no,.cancel").unbind().click(function() {
               confirmBox.hide();
            });
            confirmBox.find(".yes").click(myYes);
            confirmBox.find(".no").click(myNo);
            confirmBox.find(".no").click(cancel);
            confirmBox.show();
         }
      </script>
      <style>
         #confirm {
            display: none;
            background-color: #91FF00;
            border: 1px solid #aaa;
            position: fixed;
            width: 250px;
            left: 50%;
            margin-left: -100px;
            padding: 6px 8px 8px;
            box-sizing: border-box;
            text-align: center;
         }
         #confirm button {
            background-color: #48E5DA;
            display: inline-block;
            border-radius: 5px;
            border: 1px solid #aaa;
            padding: 5px;
            text-align: center;
            width: 80px;
            cursor: pointer;
         }
         #confirm .message {
            text-align: left;
         }
      </style>
   </head>
   <body>
      <div id="confirm">
         <div class="message"></div>
         <button class="yes">Yes</button>
         <button class="no">No</button>
         <button class="cancel">Cancel</button>
      </div>
      <button onclick='functionConfirm("Do you like Football?", function yes() {
         alert("Yes")
      }, function no() {
      alert("no")
      }
      );'>submit</button>
   </body>
</html>
Using class to implement Vector Quantities in C++

In this tutorial, we will be discussing a program to understand how to use class to implement vector quantities in C++.
Vector quantities are the ones which have both magnitude and direction. Here we will be implementing them using classes and then performing basic operations on them.
 Live Demo
#include <cmath>
#include <iostream>
using namespace std;
class Vector {
   private:
   int x, y, z;
   //components of the Vector
   public:
   Vector(int x, int y, int z){
      this->x = x;
      this->y = y;
      this->z = z;
   }
   Vector operator+(Vector v);
   Vector operator-(Vector v);
   int operator^(Vector v);
   Vector operator*(Vector v);
   float magnitude(){
      return sqrt(pow(x, 2) + pow(y, 2) + pow(z, 2));
   }
   friend ostream& operator<<(ostream& out, const Vector& v);
   //outputting the vector
};
// Addition of vectors
Vector Vector::operator+(Vector v){
   int x1, y1, z1;
   x1 = x + v.x;
   y1 = y + v.y;
   z1 = z + v.z;
   return Vector(x1, y1, z1);
}
// Subtraction of vectors
Vector Vector::operator-(Vector v){
   int x1, y1, z1;
   x1 = x - v.x;
   y1 = y - v.y;
   z1 = z - v.z;
   return Vector(x1, y1, z1);
}
// Dot product of vectors
int Vector::operator^(Vector v){
   int x1, y1, z1;
   x1 = x * v.x;
   y1 = y * v.y;
   z1 = z * v.z;
   return (x1 + y1 + z1);
}
// Cross product of vectors
Vector Vector::operator*(Vector v){
   int x1, y1, z1;
   x1 = y * v.z - z * v.y;
   y1 = z * v.x - x * v.z;
   z1 = x * v.y - y * v.x;
   return Vector(x1, y1, z1);
}
ostream& operator<<(ostream& out, const Vector& v){
   out << v.x << "i ";
   if (v.y >= 0)
      out << "+ ";
   out << v.y << "j ";
   if (v.z >= 0)
      out << "+ ";
   out << v.z << "k" << endl;
   return out;
}
int main(){
   Vector V1(3, 4, 2), V2(6, 3, 9);
   cout << "V1 = " << V1;
   cout << "V2 = " << V2;
   cout << "V1 + V2 = " << (V1 + V2);
   cout << "Dot Product is : " << (V1 ^ V2);
   cout << "Cross Product is : " << (V1 * V2);
   return 0;
}
V1 = 3i + 4j + 2k
V2 = 6i + 3j + 9k
V1 + V2 = 9i + 7j + 11k
Dot Product is : 48 Cross Product is : 30i -15j -15k
Python | Indices of sorted list of list elements - GeeksforGeeks

11 May, 2020
Sorting is a common construct and there have been many variations of it being discussed. But sometimes, we need to perform the sorting on the list of list and moreover just require to find the order in which element occurs before getting sorted. Let’s find out how to get indices of sorted order in list of lists.
Method #1 : Using List comprehension + enumerate() + sort()
The combination of above 3 functions can be used to perform this particular task. In this, we perform the sorting taking triplets consisting of element and row and column coordinates and return them in 2nd step.
# Python3 code to demonstrate# Indices of sorted list of list elements# using List comprehension + enumerate() + sort()  # initializing listtest_list = [[4, 5, 1],             [9, 3, 2],             [8, 6]]  # printing original listprint("The original list : " + str(test_list))  # using List comprehension + enumerate() + sort()# Indices of sorted list of list elementsres = [(i, j) for i, x in enumerate(test_list)                     for j, k in enumerate(x)]  res.sort(key = lambda ij: test_list[ij[0]][ij[1]])   # print resultprint("The indices of sorted order are : " + str(res))
The original list : [[4, 5, 1], [9, 3, 2], [8, 6]]The indices of sorted order are : [(0, 2), (1, 2), (1, 1), (0, 0), (0, 1), (2, 1), (2, 0), (1, 0)]
 
Method #2 : Using sorted() + lambda
The task performed above can be performed as arguments to the sorted function and lambda function performs the task of list comprehension function as above.
# Python3 code to demonstrate# Indices of sorted list of list elements# using sorted() + lambda  # initializing listtest_list = [[4, 5, 1],             [9, 3, 2],             [8, 6]]  # printing original listprint("The original list : " + str(test_list))  # using sorted() + lambda# Indices of sorted list of list elementsres = sorted([(i, j) for i, x in enumerate(test_list)                            for j, k in enumerate(x)],             key = lambda ij: test_list[ij[0]][ij[1]])  # print resultprint("The indices of sorted order are : " + str(res))
The original list : [[4, 5, 1], [9, 3, 2], [8, 6]]The indices of sorted order are : [(0, 2), (1, 2), (1, 1), (0, 0), (0, 1), (2, 1), (2, 0), (1, 0)]
Python list-programs
Python-list-of-lists
Python-Sorted
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Defaultdict in Python
Python program to convert a list to string
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Python – Get all numbers combinations in list

03 Jul, 2020
Sometimes, while working with Python lists, we can have a problem in which we need to concatenate each number with other create new number. This kind of problem is peculiar but can have application in many domains such as day-day programming and gaming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [7, 3, 4, 5]Output : [73, 74, 75, 34, 35, 45]
Input : test_list = [2, 5]Output : [25]
Method #1 : Using list comprehension + combination()The combination of above functions can be used to solve this problem. In this, we perform the task of finding all combination using combination() and f-strings can be used to perform concatenation.
# Python3 code to demonstrate working of # All numbers combinations# Using list comprehension + combinationsfrom itertools import combinations  # initializing listtest_list = [59, 236, 31, 38, 23]  # printing original list print("The original list : " + str(test_list))  # All numbers combinations# Using list comprehension + combinationsres = [int(f"{x}{y}") for x, y in combinations(test_list, 2)]          # printing result print("All numbers combinations : " + str(res))
The original list : [59, 236, 31, 38, 23]All numbers combinations : [59236, 5931, 5938, 5923, 23631, 23638, 23623, 3138, 3123, 3823]
 
Method #2 : Using loop + str() + int()The combination of above functions can be used to solve this problem. In this we perform the task of forming combinations using brute force and type conversions in nested loop. This also outputs reverse combinations.
# Python3 code to demonstrate working of # All numbers combinations# Using loop + str() + int()from itertools import combinations  # initializing listtest_list = [59, 236, 31, 38, 23]  # printing original list print("The original list : " + str(test_list))  # All numbers combinations# Using loop + str() + int()res = []for i in test_list:    for j in test_list:        if j != i:           res.append(int(str(i) + str(j)))          # printing result print("All numbers combinations : " + str(res))
The original list : [59, 236, 31, 38, 23]All numbers combinations : [59236, 5931, 5938, 5923, 23659, 23631, 23638, 23623, 3159, 31236, 3138, 3123, 3859, 38236, 3831, 3823, 2359, 23236, 2331, 2338]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Clean the string data in the given Pandas Dataframe

26 Jan, 2019
As we know, In today’s world data analytics is being used by all sorts of companies out there. While working with data, we can come across any sort of problem which requires an out of the box approach for evaluation. Most of the Data in real life contains the name of entities or other nouns. It might be possible that the names are not in proper format. In this post, we are going to discuss the approaches to clean such data.
Suppose we are dealing with the data of an e-commerce based website. The name of the products is not in the proper format. Properly format the data such that the there are no leading and trailing whitespaces as well as the first letters of all products are capital letter.
Solution #1: Many times we will come across a situation where we are required to write our own customized function suited for the task at hand.
# importing pandas as pdimport pandas as pd  # Create the dataframedf = pd.DataFrame({'Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],                   'Product':[' UMbreLla', '  maTress', 'BaDmintoN ', 'Shuttle'],                   'Updated_Price':[1250, 1450, 1550, 400],                   'Discount':[10, 8, 15, 10]})  # Print the dataframeprint(df)
Output :
Now we will writer our own customized function to solve this problem.
def Format_data(df):    # iterate over all the rows    for i in range(df.shape[0]):          # reassign the values to the product column        # we first strip the whitespaces using strip() function        # then we capitalize the first letter using capitalize() function        df.iat[i, 1]= df.iat[i, 1].strip().capitalize()  # Let's call the functionFormat_data(df)  # Print the Dataframeprint(df)
Output :
 Solution #2 : Now we will see a better and efficient approach using Pandas DataFrame.apply() function.
# importing pandas as pdimport pandas as pd  # Create the dataframedf = pd.DataFrame({''Date':['10/2/2011', '11/2/2011', '12/2/2011', '13/2/2011'],                   'Product':[' UMbreLla', '  maTress', 'BaDmintoN ', 'Shuttle'],                   'Updated_Price':[1250, 1450, 1550, 400],                   'Discount':[10, 8, 15, 10]})  # Print the dataframeprint(df)
Output :
Let’s use the Pandas DataFrame.apply() function to format the Product names in the right format. Inside the Pandas DataFrame.apply() function we will use lambda function.
# Using the df.apply() function on product columndf['Product'] = df['Product'].apply(lambda x : x.strip().capitalize())  # Print the Dataframeprint(df)
Output :
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
HTML | DOM Dialog show() Method

31 May, 2019
The DOM Dialog show() method is used to show the dialog. The Dialog element is accessed by getElementById(). It is used in HTML5.While using this method, the user can interact with other elements on the page.
Syntax:
dialogObject.show()
Example: This example shows the working of Dialog show() Method:
<!DOCTYPE html><html><body>  <h3> HTML | DOM Dialog show() Method</h3><p>Click on the below buttons to show or close the dialog window.</p>  <button onclick="showDialog()">Show dialog box</button>    <dialog id="showDialog" style= "color:green">            Welcome to GeeksforGeeks</dialog>  <script>var gfg = document.getElementById("showDialog");   function showDialog() { gfg.show(); } </script>  </body></html>                                        
Output:Before Clicking on Button:
After Clicking on Button:
Supported Browsers:
Google Chrome 37.0
Opera 24.0
Safari 6.0
HTML-DOM
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Design a Tribute Page using HTML & CSS
How to Insert Form Data into Database using PHP ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Form validation using HTML and JavaScript
Difference between Primary Key and Foreign Key

28 Mar, 2020
Primary Key:A primary key is used to ensure data in the specific column is unique. It is a column cannot have NULL values. It is either an existing table column or a column that is specifically generated by the database according to a defined sequence.
Example: Refer the figure –STUD_NO, as well as STUD_PHONE both, are candidate keys for relation STUDENT but STUD_NO can be chosen as the primary key (only one out of many candidate keys).
Foreign Key:A foreign key is a column or group of columns in a relational database table that provides a link between data in two tables. It is a column (or columns) that references a column (most often the primary key) of another table.
Example: Refer the figure –STUD_NO in STUDENT_COURSE is a foreign key to STUD_NO in STUDENT relation.
Figure:
Let’s see the difference between Primary Key and Foreign Key:
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.tri() in Python

09 Mar, 2022
numpy.tri(R, C = None, k = 0, dtype = ‘float’) : Creates an array with 1’s at and below the given diagonal(about k) and 0’s elsewhere.Parameters :
R     : Number of rows
C     : [optional] Number of columns; By default R = C
k     : [int, optional, 0 by default]
               Diagonal we require; k>0 means diagonal above main diagonal or vice versa.
dtype : [optional, float(byDefault)] Data type of returned array.  

# Python Program illustrating# numpy.tri method  import numpy as geek  print("tri with k = 1 : \n",geek.tri(2, 3, 1, dtype = float), "\n")  print("tri with main diagonal : \n",geek.tri(3, 5, 0), "\n")  print("tri with k = -1 : \n",geek.tri(3, 5, -1), "\n")
Output :
tri with k = 1 : 
 [[ 1.  1.  0.]
 [ 1.  1.  1.]] 

tri with main diagonal : 
 [[ 1.  0.  0.  0.  0.]
 [ 1.  1.  0.  0.  0.]
 [ 1.  1.  1.  0.  0.]] 

tri with k = -1 : 
 [[ 0.  0.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.]
 [ 1.  1.  0.  0.  0.]]  

References :https://docs.scipy.org/doc/numpy/reference/generated/numpy.tri.htmlNote :These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore them.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vinayedula
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fmt.Scan() Function in Golang With Examples

26 Feb, 2021
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Scan() function in Go language scans the input texts which is given in the standard input, reads from there and stores the successive space-separated values into successive arguments. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions. 
Syntax:  
func Scan(a ...interface{}) (n int, err error)
Here, “a ...interface{}” receives each type of the given texts.Returns: It returns the number of items successfully scanned. 
Example 1: 
C
// Golang program to illustrate the usage of// fmt.Scan() function // Including the main packagepackage main // Importing fmtimport (    "fmt") // Calling mainfunc main() {     // Declaring some variables    var name string    var alphabet_count int     // Calling Scan() function for    // scanning and reading the input    // texts given in standard input    fmt.Scan(&name)    fmt.Scan(&alphabet_count)     // Printing the given texts    fmt.Printf("The word %s containing %d number of alphabets.",               name, alphabet_count) }
Input:  
GFG 3
Output:  
The word GFG containing 3 number of alphabets.
Example 2: 
C
// Golang program to illustrate the usage of// fmt.Scan() function // Including the main packagepackage main // Importing fmtimport (    "fmt") // Calling mainfunc main() {     // Declaring some variables    var name string    var alphabet_count int    var float_value float32    var bool_value bool     // Calling Scan() function for    // scanning and reading the input    // texts given in standard input    fmt.Scan(&name)    fmt.Scan(&alphabet_count)    fmt.Scan(&float_value)    fmt.Scan(&bool_value)     // Printing the given texts    fmt.Printf("%s %d %g %t", name,     alphabet_count, float_value, bool_value) }
Input:  
GeeksforGeeks 13 6.789 true
Output:  
GeeksforGeeks 13 6.789 true
 
arorakashish0911
Golang-fmt
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to convert a string in lower case in Golang?
How to Trim a String in Golang?
install command in Linux with examples

22 May, 2019
install command is used to copy files and set attributes. It is used to copy files to a destination of the user’s choice, If the user want to download and install a ready to use package on GNU/Linux system then he should use apt-get, apt, yum, etc depending on their distribution.
Syntax:
install [OPTION]... [-T] SOURCE DEST
install [OPTION]... SOURCE... DIRECTORY
install [OPTION]... -t DIRECTORY SOURCE...
install [OPTION]... -d DIRECTORY...

Here, the first three forms are used to copy the SOURCE to DEST or multiple SOURCE(s) to the existing DIRECTORY while setting permission modes and owner/group. But the fourth form is used to create all components of the given DIRECTORY.
Options:
–backup[=CONTROL] : This option is used to create a backup of each existing destination file.
-b : Like –backup but It will not accept an argument.
-C, –compare : Used to compare each pair of source and destination files. But in some cases it does not modify the destination.
-d, –directory : It will act as directory names towards all arguments. And create all components of the specified directories.
-g, –group=GROUP : Used to set group ownership, instead of processing the current group.
-m, –mode=MODE : Set permission mode (as in chmod).
-o, –owner=OWNER : Set ownership (super-user only).
-p, –preserve-timestamps : Apply access/modification times of SOURCE files to corresponding destination files
-t, –target-directory=DIRECTORY : Copy all SOURCE arguments into DIRECTORY.
-T, –no-target-directory : Treat DEST as a normal file.
-v, –verbose : Used to show the name of each directory as it is created.
–help : Display the help message and exit.
–version : Shows the version information and exit.
Examples:
Copies two files rocket.c and rocket to directory demo.
Compare and copies files(observe the difference).
Using -T option(observe that it makes a file instead of directory).
Changing owner and permissions.
Printing version information.
linux-command
Linux-system-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
tar command in Linux with examples
Compiling with g++
UDP Server-Client implementation in C
Head command in Linux with examples
nohup Command in Linux with Examples
ZIP command in Linux with examples
'dd' command in Linux
Tail command in Linux with examples
Conditional Statements | Shell Script
Python | time.time_ns() method

05 Sep, 2019
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules.
time.time_ns() method of Time module is used to get the time in nanoseconds since the epoch. To get the time in seconds since the epoch, we can use time.time() method.
The epoch is the point where the time starts and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0).
Note: time.time_ns() method is new in Python version 3.7
Syntax:time.time_ns()
Parameter:No parameter is required.
Return type:This method returns an integer value whichrepresents the time in nanoseconds since the epoch.
Code: Use of time.time_ns() method
# Python program to explain time.time_ns() method     # importing time module import time     # Get the epoch obj = time.gmtime(0) epoch = time.asctime(obj) print("epoch is:", epoch)     # Get the time in seconds # since the epoch # using time.time() methodtime_sec = time.time()   # Get the time in nanoseconds# since the epoch# using time.time_ns() methodtime_nanosec = time.time_ns()    # Print the time # in seconds since the epoch print("Time in seconds since the epoch:", time_sec)   # Print the time # in nanoseconds since the epoch print("Time in nanoseconds since the epoch:", time_nanosec) 
epoch is: Thu Jan  1 00:00:00 1970
Time in seconds since the epoch: 1567451658.4676464
Time in nanoseconds since the epoch: 1567451658467647709

References: https://docs.python.org/3/library/time.html#time.time_ns
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Int32.Parse(String) Method in C# with Examples

12 Jun, 2019
Int32.Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent.
Syntax:
public static int Parse (string str);
Here, str is a string that contains a number to convert. The format of str will be [optional white space][optional sign]digits[optional white space].
Return Value: It is a 32-bit signed integer equivalent to the number contained in str.
Exceptions:
ArgumentNullException: If str is null.
FormatException: If str is not in the correct format.
OverflowException: If str represents a number less than MinValue or greater than MaxValue.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# program to demonstrate// Int32.Parse(String) Methodusing System;  class GFG {      // Main Method    public static void Main()    {          // passing different values        // to the method to check        checkParse("2147483647");        checkParse("214,7483,647");        checkParse("-2147483");        checkParse(" 2183647 ");    }      // Defining checkParse method    public static void checkParse(string input)    {          try {              // declaring Int32 variable            int val;              // getting parsed value            val = Int32.Parse(input);            Console.WriteLine("'{0}' parsed as {1}", input, val);        }          catch (FormatException) {            Console.WriteLine("Can't Parsed '{0}'", input);        }    }}
'2147483647' parsed as 2147483647
Can't Parsed '214,7483,647'
'-2147483' parsed as -2147483
' 2183647 ' parsed as 2183647

Example 2: For ArgumentNullException
// C# program to demonstrate// Int32.Parse(String) Method// for ArgumentNullExceptionusing System;  class GFG {      // Main Method    public static void Main()    {          try {              // passing null value as a input            checkParse(null);        }        catch (ArgumentNullException e) {              Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }        catch (FormatException e) {              Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }      // Defining checkparse method    public static void checkParse(string input)    {          // declaring Int32 variable        int val;          // getting parsed value        val = Int32.Parse(input);        Console.WriteLine("'{0}' parsed as {1}", input, val);    }}
Exception Thrown: System.ArgumentNullException

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.int32.parse?view=netframework-4.7.2#System_Int32_Parse_System_String_
CSharp-Int32-Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
PHP | strftime() Function

06 Jul, 2021
The strftime() function is an inbuilt function in PHP that formats local time or date according to locale settings i.e. it formats local time or date for location set for it of a place.
Syntax: 
strftime( $format, $timestamp ) 
Parameters: This function accept two parameters as mentioned above and described below:  
$format: This parameter defines the format for the date and time it is a must required parameter.
$timestamp: The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().
Return Values: It returns a string formatted to $format using the given $timestamp(if mentioned explicitly, otherwise takes default time). Month and weekday names and other language-dependent strings respect the current locale set with setlocale().
Example:  
PHP
<?php // This program prints the current daysetlocale(LC_TIME, "C");echo strftime("%A");?>
Output: 
Thursday
Format: Following are the values that can be added to $format for a desired output.  
Hour formatting: 
Time and Date stamps formatting: 
Day formatting: 
Week formatting: 
Month formatting: 
Year formatting: 
Miscellaneous formatting:  
Below examples illustrate the application of strftime() in php: 
Example 1: A simple program to display the date and time provided to it.  
PHP
<?php // Displays the dateecho strftime("%d, %B, %Y", strtotime("01/03/2004")); // Displays the timeecho strftime("   %I:%M  %p", strtotime("21:34"));?>
Output: 
03, January, 2004 09:34 PM
Example 2: This example display the time at a specific region (an additional function, setlocale() is employed for this. For setlocale() to work, locales should be supported by your server.) 
PHP
<?php // Setting locale to germansetlocale(LC_ALL, "de");echo strftime("The current german time is %r"); // Setting locale to englishsetlocale(LC_ALL, "en");echo strftime(" and the current english time is %r");?>
Output: 
The current german time is 22:14:20 and the current english time is 10:14:20 PM
Reference: https://www.php.net/manual/en/function.strftime.php 
Akanksha_Rai
varshagumber28
PHP-date-time
PHP-function
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
How to create admin login page using PHP?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?