code-rag-bench/online-tutorials huggingface dataset:
Java Connection getClientInfo() method with example

The getClientInfo() method of the Connection interface returns the name and values of the client info properties of the current connection. This method returns a properties object.
To retrieve the values of the client info properties file.
Register the driver using the registerDriver() method of the DriverManager class as −
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Get the connection using the getConnection() method of the DriverManager class as −
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
Create a properties object as −
Properties properties = new Properties();
Add the required key-value pairs to the above created Properties object as −
properties.put("user_name", "new_user");
properties.put("password", "password");
Set the above created properties to the client-info using the setClientInfo() method as −
//Setting the Client Info
con.setClientInfo(properties);
Retrieve the Properties file (object) using the getClientInfo() method and get properties from it by invoking the getProperty() method as −
Properties prop = con.getClientInfo();
prop.getProperty("user_name");
prop.getProperty("password");
You can also directly get the properties as:
con.getClientInfo("user_name");
con.getClientInfo("password");
Following JDBC program establishes connection with the MYSQL database and sets the credentials of a new user to the client info properties file.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class Connection_getClientInfo {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String url = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(url, "root", "password");
      System.out.println("Connection established......");
      //Adding the credentials of another user to the properties file
      Properties properties = new Properties();
      properties.put("user_name", "new_user");
      properties.put("password", "my_password");
      //Setting the ClientInfo
      con.setClientInfo(properties);
      //Retrieving the values in the ClientInfo properties file
      Properties prop = con.getClientInfo();
      System.out.println("user name: "+prop.getProperty("user_name"));
      System.out.println("password: "+prop.getProperty("password"));
   }
}
Connection established......
user name: new_user
password: my_password
Query to find Nth maximum value in MySQL

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Value int
   -> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(40);
Query OK, 1 row affected (0.26 sec)
mysql> insert into DemoTable values(60);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(45);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(85);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(78);
Query OK, 1 row affected (0.10 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable;
This will produce the following output−
+-------+
| Value |
+-------+
|    40 |
|    60 |
|    45 |
|    85 |
|    78 |
+-------+
5 rows in set (0.00 sec)
Following is the query to find Nth maximum value in MySQL −
mysql> select * from DemoTable order by Value desc limit 2,1;
This will produce the following output −
+-------+
| Value |
+-------+
|    60 |
+-------+
1 row in set (0.00 sec)
Pandas timeseries plot setting X-axis major and minor ticks and labels

Using Pandas, we can create a dataframe with time and speed, and thereafter, we can use the data frame to get the desired plot.
Construct a new Generator with the default BitGenerator (PCG64).
Construct a new Generator with the default BitGenerator (PCG64).
Using Pandas, get a fixed frequency DatetimeIndex. From '2020-01-01' to '2021-01-01'.
Using Pandas, get a fixed frequency DatetimeIndex. From '2020-01-01' to '2021-01-01'.
Draw samples from a log-normal distribution.
Draw samples from a log-normal distribution.
Make a data frame with above data.
Make a data frame with above data.
Using panda dataframe create plot, with figsize = (10, 5).
Using panda dataframe create plot, with figsize = (10, 5).
To show the figure, use the plt.show() method.
To show the figure, use the plt.show() method.
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

rng = np.random.default_rng(seed=1)
date_day = pd.date_range(start='2020-01-01', end='2021-01-01', freq='D')
traffic = rng.lognormal(sigma=2, size=date_day.size)
df_day = pd.DataFrame(dict(speed=[pow(2, -i) for i in range(len(date_day))]),
index=date_day)

df_day.plot(figsize=(10, 5))

plt.show()
Tryit Editor v3.7

Tryit: HTML HEX color values
TypeScript | Array filter() Method - GeeksforGeeks

18 Jun, 2020
The Array.filter() is an inbuilt TypeScript function which is used to creates a new array with all elements that pass the test implemented by the provided function. Syntax:
array.filter(callback[, thisObject])
Parameter: This methods accepts two parameter as mentioned and described below:
callback : This parameter is the Function to test for each element.
thisObject : This parameter is the Object to use as this when executing callback.
Return Value: This method returns created array. Below examples illustrate the Array filter() method in TypeScriptExample 1: 
JavaScript
<script>    // check for positive number     function ispositive(element, index, array)    {        return element > 0;    }             // Driver code    var arr = [ 11, 89, -23, 7, 98 ];           // check for positive number     var value = arr.filter(ispositive);     console.log( value );</script>
Output: 
[11,89,7,98]
Example 2: 
JavaScript
<script>    // check for odd number     function isodd(element, index, array)     {         return (element % 2 == 1);      }       // Driver code    var arr = [ 11, 89, 23, 7, 98 ];            // check for odd number     var value = arr.filter(isodd);     console.log( value );</script>
Output: 
[11,89,23,7]
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Binding mouse double click in Tkinter

Let us suppose that for a particular application, we want to bind the mouse double-click so that it performs some event or operation. We can use the bind(‘<Double-Button-1>’, handler) or bind(‘<Double-Button-2>’, handler) methods to bind the mouse Left or Right Buttons with a handler or a callback function.
In this example, we will create an application that contains a button. When we double click the button, it will open a popup window.
#Import required libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of the window
win.geometry("750x250")
#Define a function
def handler(e):
   top= Toplevel(win)
   top.geometry("600x200")
   Label(top, text= "Hey There!", font= ('Helvetica 15 bold')).pack(pady=30)

#Define a Label in Main window
Label(win, text= "Double Click to Open the Popup",font=('Helvetica 15 underline')).pack(pady=30)

#Create a Button
ttk.Button(win, text= "Click", command=lambda:handler).pack(pady=20)

#Bind the Double Click with the Handler
win.bind('<Double-Button-1>', handler)
win.mainloop()
Now, run the above code to display the window.
Double-click the button "Click" to open a popup window.
Peewee - Delete Records

Running delete_instance() method on a model instance delete corresponding row from the mapped table.
obj=User.get(User.name=="Amar")
obj.delete_instance()
On the other hand, delete() is a class method defined in model class, which generates DELETE query. Executing it effectively deletes rows from the table.
db.create_tables([User])
qry=User.delete().where (User.age==25)
qry.execute()
Concerned table in database shows effect of DELETE query as follows −
('DELETE FROM "User" WHERE ("User"."age" = ?)', [25])

 Print
 Add Notes
 Bookmark this page
Program to print pyramid pattern in C

A pyramid is a polyhedron formed by connecting a polygonal base and a point, called the apex. Each base edge and apex form a triangle, called a lateral face. It is a conic solid with polygonal base. A pyramid with an n-sided base has n + 1 vertices, n + 1 faces, and 2n edges. All pyramids are self-dual.
Accept the number of rows from the user to form pyramid shape
Iterate the loop till the number of rows specified by the user:
Display 1 star in the first row
Increase the number of stars based on the number of rows.
/*Program to print Pyramid Pattern*/
#include<stdio.h>
int main() {
   int r, s, rows=0;
   int t=0;
   clrscr();
   printf("Enter number of rows to print the pyramid: ");
   scanf("%d", &rows);
   printf("\n");
   printf("The Pyramid Pattern for the number of rows are:");
   printf("\n\n");
   for(r=1;r<=rows;++r,t=0) {
      for(s=1; s<=rows-r; ++s){
         printf(" ");
      }
      while (t!=2*r-1) {
         printf("* ");
         ++t;
      }
      printf("\n");
   }
   getch();
   return 0;
}
Python Program to Append, Delete and Display Elements of a List Using Classes

When it is required to append, delete, and display the elements of a list using classes, object oriented method is used. Here, a class is defined, and attributes are defined. Functions are defined within the class that perform certain operations. An instance of the class is created, and the functions are used to add elements to the list, delete elements from the list and display the elements of the list using objects.
Below is a demonstration for the same −
 Live Demo
class list_class():
   def __init__(self):
      self.n=[]
   def add_val(self,a):
      return self.n.append(a)
   def remove_val(self,b):
      self.n.remove(b)
   def display_val(self):
      return (self.n)
my_instance = list_class()
choice_val = 1
while choice_val!=0:
   print("0. Exit")
   print("1. Add elements")
   print("2. Delete element")
   print("3. Display list")
   choice_val=int(input("Enter your choice: "))
   if choice_val==1:
      n=int(input("Enter element to add to the list... "))
      my_instance.add_val(n)
      print("List: ",my_instance.display_val())
   elif choice_val==2:
      n=int(input("Enter number to delete.."))
      my_instance.remove_val(n)
      print("List: ",my_instance.display_val())
   elif choice_val==3:
      print("List: ",my_instance.display_val())
   elif choice_val==0:
      print("Exit")
   else:
      print("Invalid choice!")
print()
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 1
Enter element to add to the list... 34
List: [34]
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 3
List: [34]
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 2
Enter number to delete..34
List: []
0. Exit
1. Add elements
2. Delete element
3. Display list
Enter your choice: 0
Exit
A class named ‘list_class’ class is defined, that has functions like ‘add_val’, ‘remove_val’, and ‘display_val’.
These are used to add elements to the list, remove element from the list and display the list respectively.
An instance of this class is created.
The elements of the list are entered and operations are performed on it.
Relevant messages and output is displayed on the console.
How to format a string to date in as dd-MM-yyyy using java?

The java.text package provides a class named SimpleDateFormat which is used to format and parse dates in required manner (local).
Using the methods of this class you can parse String to Date or, format Date to String.
You can parse a given String to Date object using the parse() method of the SimpleDateFormat class. To this method you need to pass the Date in String format. To parse a String to Date object −
Instantiate the SimpleDateFormat class by passing the required pattern of the date in String format to its constructor.
Instantiate the SimpleDateFormat class by passing the required pattern of the date in String format to its constructor.
//Instantiating the SimpleDateFormat class
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Parse/convert the required String to Date object using the parse() method by passing it as a parameter.
Parse/convert the required String to Date object using the parse() method by passing it as a parameter.
Date date = formatter.parse(dob);
System.out.println("Date object value: "+date);
Following Java program accepts name date of birth from the user in String format, converts/parses the obtained date of birth String to Date object and, calculates the current age and displays the result.
 Live Demo
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Scanner;
public class CalculatingAge {
   public static Date StringToDate(String dob) throws ParseException{
      //Instantiating the SimpleDateFormat class
      SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
      //Parsing the given String to Date object
      Date date = formatter.parse(dob);
      System.out.println("Date object value: "+date);
      return date;
   }
   public static void main(String args[]) throws ParseException {
      //Reading name and date of birth from the user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.next();
      System.out.println("Enter your date of birth (dd-MM-yyyy): ");
      String dob = sc.next();
      //Converting String to Date
      Date date = CalculatingAge.StringToDate(dob);
      //Converting obtained Date object to LocalDate object
      Instant instant = date.toInstant();
      ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
      LocalDate givenDate = zone.toLocalDate();
      //Calculating the difference between given date to current date.
      Period period = Period.between(givenDate, LocalDate.now());
      System.out.print("Hello "+name+" your current age is: ");
      System.out.print(period.getYears()+" years "+period.getMonths()+" and "+period.getDays()+" days");
   }
}
Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-09-1989
Date object value: Tue Sep 26 00:00:00 IST 1989
Hello Krishna your current age is: 29 years 8 and 5 days
Python | os.rmdir() method

29 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.rmdir() method in Python is used to remove or delete a empty directory. OSError will be raised if the specified path is not an empty directory.
Syntax: os.rmdir(path, *, dir_fd = None)
Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional) : A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored.
Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method does not return any value.
# Python program to explain os.rmdir() method     # importing os module import os  # Directory namedirectory = "ihritik"  # Parent Directoryparent = "/home/User/Documents"  # Pathpath = os.path.join(parent, directory)  # Remove the Directory# "ihritik"os.rmdir(path)print("Directory '%s' has been removed successfully" %directory)
Directory 'ihritik' has been removed successfully

# Python program to explain os.rmdir() method     # importing os module import os  # Directory namedirectory = "ihritik"  # Parent Directoryparent = "/home/User/Documents"  # Pathpath = os.path.join(parent, directory)    # Remove the Directory# "ihritik"try:    os.rmdir(path)    print("Directory '%s' has been removed successfully" %directory)except OSError as error:    print(error)    print("Directory '%s' can not be removed" %directory)    # if the specified path # is not an empty directory# then permission error will# be raised  # similarly if specified path# is invalid or is not a # directory then corresponding# OSError will be raised
[Errno 13] Permission denied: '/home/User/Documents/ihritik'
Directory 'ihritik' can not be removed

Reference: https://docs.python.org/3/library/os.html
Python OS-path-module
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Add leading Zeros to string

25 Jun, 2022
Sometimes, during the string manipulation, we are into a problem where we need to pad or add leading zeroes to the string as per the requirements. This problem can occur in web development. Having shorthands to solve this problem turns out to be handy in many situations. Let’s discuss certain ways in which this problem can be solved. 
Method #1: Using rjust() function offers a single-line way to perform this particular task. Hence can easily be employed on any string whose padding we need to be done. We can specify the amount of padding required. 
Python3
# Python3 code to demonstrate# adding leading zeros# using rjust() # initializing stringtest_string = 'GFG' # printing original stringprint(& quot       The original string : & quot       + str(test_string)) # No. of zeros requiredN = 4 # using rjust()# adding leading zerores = test_string.rjust(N + len(test_string), '0') # print resultprint(& quot       The string after adding leading zeros : & quot       + str(res))
The original string : GFG
The string after adding leading zeros : 0000GFG
Method #2: Using zfill() This is yet another way to perform this particular task, in this function we don’t need to specify the letter that we need to pad, this function is exclusively made to pad zeros internally and hence recommended. 
Python3
# Python3 code to demonstrate# adding leading zeros# using zfill() # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4 # using zfill()# adding leading zerores = test_string.zfill(N + len(test_string)) # print resultprint("The string after adding leading zeros : " + str(res))
The original string : GFG
The string after adding leading zeros : 0000GFG
Method #3: Without any built-in methods.
Python3
# Python3 code to demonstrate# adding leading zeros # initializing stringtest_string = 'GFG' # printing original stringprint("The original string : " + str(test_string)) # No. of zeros requiredN = 4  # adding leading zerox = '0'*Nres = x+test_string # print resultprint("The string after adding leading zeros : " + str(res))
The original string : GFG
The string after adding leading zeros : 0000GFG
kogantibhavya
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
D3.js axis.ticks() Function

07 Aug, 2020
The d3.axis.ticks() Function in D3.js is used to control which ticks are displayed by the axis. This function returns the axis generator
Syntax:
axis.ticks(arguments...)
axis.ticks([count[, specifier]])
axis.ticks([interval[, specifier]])
Parameters: This function accepts the following parameters.
count/interval: This parameter is used to display the number of ticks.
specifier: This parameter is an optional format specifier to customize how the tick values are formatted.
Return Value: This function returns the axis generator.
Below programs illustrate the d3.axis.ticks() function in D3.js:
Example 1:
<!DOCTYPE html> <html>   <head>     <title>         D3.js | D3.axis.ticks() Function     </title>     <script type="text/javascript"        src="https://d3js.org/d3.v4.min.js">     </script>           <style>         svg text {             fill: green;             font: 15px sans-serif;             text-anchor: center;         }     </style> </head>   <body>     <script>         var width = 400, height = 400;         var svg = d3.select("body")             .append("svg")             .attr("width", width)             .attr("height", height);           var xscale = d3.scaleLinear()             .domain([0, 10])             .range([0, width - 60]);           var x_axis = d3.axisBottom().scale(xscale).ticks(5);           var xAxisTranslate = height / 2;           svg.append("g")             .attr("transform", "translate(50, "             + xAxisTranslate + ")")             .call(x_axis)     </script> </body> </html>
Output:
Example 2:
<!DOCTYPE html> <html>   <head>     <title>         D3.js | d3.axis.ticks() Function     </title>     <script type="text/javascript"        src="https://d3js.org/d3.v4.min.js">     </script>           <style>         svg text {             fill: green;             font: 15px sans-serif;             text-anchor: end;         }     </style> </head>   <body>     <script>         var width = 400, height = 400;         var svg = d3.select("body")             .append("svg")             .attr("width", width)             .attr("height", height);           var yscale = d3.scaleLinear()             .domain([0, 1])             .range([height - 50, 0]);           var y_axis = d3.axisLeft().scale(yscale).ticks(3, "$.2f");             svg.append("g")             .attr("transform", "translate(100, 20)")             .call(y_axis)     </script> </body> </html>
Output:
D3.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
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
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 ?
How to use JavaScript Fetch API to Get Data ?

08 Jan, 2021
The Fetch API provides a JavaScript interface that enables users to manipulate and access parts of the HTTP pipeline such as responses and requests. 
Fetch API has so many rich and exciting options like method, headers, body, referrer, mode, credentials, cache, redirect, integrity and few more. However, the most prominent ones we use are method, headers and body.
Method are used to create, read, update and delete data, and hence we have methods like GET, POST, PUT and DELETE.
As an example we would use the API: https://reqres.in/arpi/users which would give us random data about a person, our goal here is to see what is presented in this data. 
Syntax: 
fetch(URL, options)
Parameters: This method accepts two parameters as shown above and described below:
URL: This is the endpoint of the resource from where you want to fetch data.Options: This is an optional parameter, it is an options object that can have the following values:Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc.Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc.  Body: In this part, we actually pass the data as a JSON.
URL: This is the endpoint of the resource from where you want to fetch data.
Options: This is an optional parameter, it is an options object that can have the following values:Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc.Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc.  Body: In this part, we actually pass the data as a JSON.
Method: This denotes the method type, it can be of any HTTP request type, like GET, POST, PUT, DELETE, etc.
Headers: In case we are passing data to the server, we need to additionally tell fetch that we are going to pass data in form of json/text, etc.  
Body: In this part, we actually pass the data as a JSON.
Example 1: GET Request demonstration.
Javascript
fetch("https://reqres.in/api/users").then(res => res.json()).then(data => console.log(data))
Output: This is what the API is returning to us, some random data about people.
Example 2: POST Request demonstration. We will, now post some random data by our self, with the help of POST method. 
Javascript
fetch("https://reqres.in/api/users", {  // Defining method type as POST  method: 'POST',   // Fetch knows, what type of data are we dealing with  headers: {    'Content-Type': 'application/json'   },  // Data needs to be parsed into JSON  body: JSON.stringify({     name: 'Geeks For Geeks',    website: 'https://www.geeksforgeeks.org/',  })}).then(res => {  return res.json()}).then(data => console.log(data));
Output: Here, we see that we have successfully made a POST request using fetch API. 
JavaScript-Misc
Picked
Technical Scripter 2020
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Split heterogeneous type list

16 Sep, 2021
Sometimes, we might be working with many data types and in these instances, we can have a problem in which list that we receive might be having elements from different data types. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + isinstance() The combination of above both functionalities can be used to perform this task. In this, we just extract the similar element types using different list comprehensions and detect the type using isinstance().
Python3
# Python3 code to demonstrate working of# Split heterogeneous type list# using list comprehension + isinstance # initialize listtest_list = ['gfg', 1, 2, 'is', 'best'] # printing original listprint("The original list : " + str(test_list)) # Split heterogeneous type list# using list comprehension + isinstanceres_str = [ele for ele in test_list if isinstance(ele, str)]res_int = [ele for ele in test_list if isinstance(ele, int)] # printing resultprint("Integer list : " + str(res_int))print("String list : " + str(res_str))
The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']
 
 Method #2 : Using defaultdict() + loop This is yet another way in which this problem can be solved. In this, we initialize the list as data type for defaultdict() and loop through each element and save each datatype list in defaultdict.
Python3
# Python3 code to demonstrate working of# Split heterogeneous type list# using defaultdict() + loopfrom collections import defaultdict # initialize listtest_list = ['gfg', 1, 2, 'is', 'best'] # printing original listprint("The original list : " + str(test_list)) # Split heterogeneous type list# using defaultdict() + loopres = defaultdict(list)for ele in test_list:   res[type(ele)].append(ele) # printing resultprint("Integer list : " + str(res[int]))print("String list : " + str(res[str]))
The original list : ['gfg', 1, 2, 'is', 'best']
Integer list : [1, 2]
String list : ['gfg', 'is', 'best']
 
akshaysingh98088
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 | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How to add Key Value Pair to List in R ?

01 Oct, 2021
A key-value pair can be explained as a set of two linked data items where a key uniquely identifies a value or a set of values in the data. Since a list can hold multiple data-types data, we can have a key-value pair stored in the list
We can assign variables to each key and value. Store each key-value pair after building the list using square brackets.
R
rm(list = ls()) # create key value variableskey1 <- "Age"value1 <- 21 key2 <- "Name"value2 <- "Pulkit" # create the listmylist <- list() # Build up key value pairsmylist[[ key1 ]] <- value1mylist[[ key2 ]] <- value2 # Access value using the keyprint(mylist$Age)print(mylist$Name)
Output:
21
Pulkit 
Another way of doing this without using any additional variables is to specify the key and the value in the list() function while creating the list.
Example
R
rm(list = ls()) # Creating the listmylist<-list("Name"="Pulkit","Age"=21,             "Gender"="Male") # Access value using the keyprint(mylist$Age)print(mylist$Gender)
Output:
21
Male
Another approach we can take to add a key-value pair in the list is to setNames() function and inside it, we use as.list(). Basically what we will have here is a syntax like given below, which will create a list and assign all the keys with their respective values. 
Syntax:
variable<-setNames(as.list(values), keys)
Example:
R
rm(list = ls()) # initialize keys and respected valuesstudents <- c("Pulkit", "Ritika", "Parth",              "Vishesh", "Dharvik", "krishav",              "Reshav") marks <- c(75, 92, 97, 80, 85, 87, 52) # make the listresults <- setNames(as.list(marks), students) # Access value using the keyprint(results$Pulkit)
Output:
 75
simmytarika5
Picked
R List-Programs
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use sub-package in Java?

Subpackages are similar to sub-directories. Consider an example. The company had a com.apple.computers package that contained a Dell.java source file, it would be contained in a series of subdirectories like this −
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class, interface, and enumeration defined in it. The base name of the output file is the name of the type, and its extension is .class.
For example −
// File Name:Dell.java
package com.apple.computers;
public class Dell {
}
class Ups {
}
Now, compile this file as follows using -d option −
$javac -d.Dell.java
The files will be compiled as follows −
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
You can import all the classes or interfaces defined in \com\apple\computers\ as follows −
import com.apple.computers.*;
Go - Maps

Go provides another important data type named map which maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.
You must use make function to create a map.
/* declare a variable, by default map will be nil*/
var map_variable map[key_data_type]value_data_type

/* define the map as nil map can not be assigned any value*/
map_variable = make(map[key_data_type]value_data_type)

The following example illustrates how to create and use a map −
package main

import "fmt"

func main() {
   var countryCapitalMap map[string]string
   /* create a map*/
   countryCapitalMap = make(map[string]string)
   
   /* insert key-value pairs in the map*/
   countryCapitalMap["France"] = "Paris"
   countryCapitalMap["Italy"] = "Rome"
   countryCapitalMap["Japan"] = "Tokyo"
   countryCapitalMap["India"] = "New Delhi"
   
   /* print map using keys*/
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   /* test if entry is present in the map or not*/
   capital, ok := countryCapitalMap["United States"]
   
   /* if ok is true, entry is present otherwise entry is absent*/
   if(ok){
      fmt.Println("Capital of United States is", capital)  
   } else {
      fmt.Println("Capital of United States is not present") 
   }
}
When the above code is compiled and executed, it produces the following result −
Capital of India is New Delhi
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of United States is not present

delete() function is used to delete an entry from a map. It requires the map and the corresponding key which is to be deleted. For example −
package main

import "fmt"

func main() {   
   /* create a map*/
   countryCapitalMap := map[string] string {"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
   
   fmt.Println("Original map")   
   
   /* print map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
   
   /* delete an entry */
   delete(countryCapitalMap,"France");
   fmt.Println("Entry for France is deleted")  
   
   fmt.Println("Updated map")   
   
   /* print map */
   for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
   }
}
When the above code is compiled and executed, it produces the following result −
Original Map
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Entry for France is deleted
Updated Map
Capital of India is New Delhi
Capital of Italy is Rome
Capital of Japan is Tokyo
Tailwind CSS Box Sizing - GeeksforGeeks

23 Mar, 2022
This class accepts more than one value in tailwind CSS all the properties are covered as in class form. It is the alternative to the CSS box-sizing property. This class is used to defines how the user should calculate the total width and height of an element i.e. padding and borders, are to be included or not.
Box Sizing:
box-border 
box-content 
box-border: In this mode, the width and height properties include content, padding, and borders i.e. if we set an element’s width to 200 pixels, that 200 pixels will include any border or padding we added, and the content box will shrink to absorb that extra width. This typically makes it much easier to size elements.
Syntax:
<element class="box-border">..</element>
Example:
HTML
<!DOCTYPE html> <head>     <title>Tailwind box-border Class</title>     <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"           rel="stylesheet"> </head>   <body class="text-center"> <center>    <h1 class="text-green-600 text-5xl font-bold">        GeeksforGeeks    </h1>     <b>Tailwind CSS box-border Class</b>     <div class="box-border h-28 w-32 p-4                 border-4 bg-green-500 m4">        A Computer Science Portal    </div> </center></body>   </html>
Output:
box-content: This is the default value of the box-sizing class. In this mode, the width and height class include only the content. Border and padding are not included in it i.e if we set an element’s width to 200 pixels, then the element’s content box will be 200 pixels wide, and the width of any border or padding will be added to the final rendered width.
Syntax:
<element class="box-content">..</element>
Example: 
HTML
<!DOCTYPE html> <head>     <title>Tailwind box-content Class</title>     <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css"           rel="stylesheet"> </head>   <body class="text-center"> <center>    <h1 class="text-green-600 text-5xl font-bold">        GeeksforGeeks    </h1>     <b>Tailwind CSS box-content Class</b>     <div class="box-content h-28 w-32 p-4                 border-4 bg-green-500 m4">        A Computer Science Portal    </div> </center></body>   </html>
Output:
Tailwind CSS
Tailwind-Layout
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Compute Cumulative Chi Square Density in R Programming - pchisq() Function - GeeksforGeeks

25 Jun, 2020
pchisq() function in R Language is used to compute cumulative chi square density for a vector of elements. It also creates a density plot for chi square cumulative distribution.
Syntax: pchisq(vec, df)
Parameters:vec: Vector of x-valuesdf: Degree of Freedom
Example 1:
# R program to compute # Cumulative Chi Square Density  # Create a vector of x-valuesx <- seq(0, 10, by = 1)  # Calling pchisq() Functiony <- pchisq(x, df = 5)y
Output:
 [1] 0.00000000 0.03743423 0.15085496 0.30001416 0.45058405 0.58411981
 [7] 0.69378108 0.77935969 0.84376437 0.89093584 0.92476475

Example 2:
# R program to compute # Cumulative Chi Square Density  # Create a vector of x-valuesx <- seq(0, 10, by = 0.1)  # Calling pchisq() Functiony <- pchisq(x, df = 5)  # Plot a graph plot(y)
Output:
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ?
How to get the first and last elements of Deque in Python? - GeeksforGeeks

01 Oct, 2020
Deque is a Double Ended Queue which is implemented using the collections module in Python. Let us see how can we get the first and the last value in a Deque.
Method 1: Accessing the elements by their index. 
The deque data structure from the collections module does not have a peek method, but similar results can be achieved by fetching the elements with square brackets. The first element can be accessed using [0] and the last element can be accessed using [-1].
Python3
# importing the modulefrom collections import deque          # creating a deque  dq = deque(['Geeks','for','Geeks', 'is', 'good'])     # displaying the dequeprint(dq)  # fetching the first elementprint(dq[0])  # fetching the last elementprint(dq[-1])
Output:
deque(['Geeks', 'for', 'Geeks', 'is', 'good'])
Geeks
good

Method 2: Using the popleft() and pop() method
popleft() method is used to pop the first element or the element from the left side of the queue and the pop() method to pop the last element or the element form the right side of the queue. It should be noted that these methods also delete the elements from the deque, so they should not be preferred when only fetching the first and the last element is the objective.
Python3
# importing the modulefrom collections import deque          # creating a deque  dq = deque(['Geeks','for','Geeks', 'is', 'good'])     # displaying the dequeprint(dq)  # fetching and deleting the first elementprint(dq.popleft())  # fetching and deleting the last elementprint(dq.pop())  # displaying the dequeprint(dq)
Output:
deque(['Geeks', 'for', 'Geeks', 'is', 'good'])
Geeks
good
deque(['for', 'Geeks', 'is'])

deque
Python collections-module
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Astsu - Network Scanner Tool - GeeksforGeeks

04 Jan, 2022
Astsu is a free and open-source tool available on GitHub. Astsu is written in python language. You must have python language installed in your kali Linux operating system in order to use this tool. Astsu works as a scanner on the network. Astsu is used to scan a network using the IP address. Astsu can be used to scan common ports in which a TCP syn Packet to the destination port and the Nmap will check the services running on the port. Astsu can be used to discover open and closed ports on the network. Astsu can be used to scan the Operating system on the host. Astsu works as a scanner using an IP address.
Astsu sends the TCP Syn packet to the target port. During the TCP Syn if the port is open then perform Nmap scanning to check what service running on the port. Astsu shows all the open and closed ports during the scanning.
Astsu discovers all the hosts on the IP address of the domain. After discovering all possible IP’s astsu sends an ICMP packet to each IP. Astsu then waits for a response from each IP. After receiving all the responses from each IP the astsu prints all hosts.
Astsu sends an ICMP packet to the port destination and waits for a response from the domain. After receiving the response astsu extracts the TTL and finds the possible operating system of the host.
Astsu can perform simple network scanning.
Astsu can be used to scan all the target ports.
Astsu can be used to find which port is open and which is closed.
Astsu is used to discover hosts in a network.
Astsu can be used to perform reconnaissance in the early stages of penetration testing.
Step 1: Open your kali Linux operating system and use the following command to install the tool from GitHub.
git clone https://github.com/ReddyyZ/astsu.git
Step 2: Now use the following command to install the requirements of the tool.
python3 -m pip install -r requirements.txt
Step 3: The tool has been downloaded and installed in your kali linux operating system. Now Use the following command to run the tool.
python3 astsu.py -h
The tool is running successfully. Now we will see examples to use the tool.
Example 1: Use the astsu tool to find to scan common ports on the network.
python3 astsu.py -sC <ip address>
The astsu tool is filtering common ports.
Example 2: Use the astsu tool to find to scan common ports on the network.
python3 astsu.py -sA <ip address>
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scp command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
SED command in Linux | Set 2
chown command in Linux with Examples
nohup Command in Linux with Examples
Named Pipe or FIFO with example C program
Thread functions in C/C++
uniq Command in LINUX with examples
Start/Stop/Restart Services Using Systemctl in Linux
Python | os.getloadavg() method - GeeksforGeeks

25 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.getloadavg() method in Python is used to get the load average over the last 1, 5, and 15 minutes. The load average is the average of the number of processes in the system run queue over a given period of time over 1, 5 and 15 minutes. This method raises OSError if the load average is unobtainable.
Note: This method is available on UNIX platforms only.
Syntax: os.getloadavg()
Parameter: No parameter is required.
Return Type: This method returns a tuple object consisting of float values which denotes the load average over the last 1, 5, and 15 minutes.
# Python program to explain os.getloadavg() method    # importing os module import os  # Get the load average over# the last 1, 5, and 15 minutes # using os.getloadavg() methodload1, load5, load15 = os.getloadavg()  # Print the load average over# the last 1, 5, and 15 minutes print("Load average over the last 1 minute:", load1)print("Load average over the last 5 minute:", load5)print("Load average over the last 15 minute:", load15)
Load average over the last 1 minute: 0.34
Load average over the last 5 minute: 0.42
Load average over the last 15 minute: 0.46

python-os-module
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?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Convert an Iterable to Stream in Java - GeeksforGeeks

11 Dec, 2018
Given an Iterable, the task is to convert it into Stream in Java.
Examples:
Input: Iterable = [1, 2, 3, 4, 5]
Output: {1, 2, 3, 4, 5}

Input: Iterable = ['G', 'e', 'e', 'k', 's']
Output: {'G', 'e', 'e', 'k', 's'}

Approach:
Get the Iterable.Convert the Iterable to Spliterator using Iterable.spliterator() method.Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.Return the stream.
Get the Iterable.
Convert the Iterable to Spliterator using Iterable.spliterator() method.
Convert the formed Spliterator into Sequential Stream using StreamSupport.stream() method.
Return the stream.
Below is the implementation of the above approach:
// Java program to get a Stream// from a given Iterable  import java.util.*;import java.util.stream.*;  class GFG {      // Function to get the Stream    public static <T> Stream<T>    getStreamFromIterable(Iterable<T> iterable)    {          // Convert the Iterable to Spliterator        Spliterator<T>            spliterator = iterable.spliterator();          // Get a Sequential Stream from spliterator        return StreamSupport.stream(spliterator, false);    }      // Driver code    public static void main(String[] args)    {          // Get the Iterator        Iterable<Integer>            iterable = Arrays.asList(1, 2, 3, 4, 5);          // Get the Stream from the Iterable        Stream<Integer>            stream = getStreamFromIterable(iterable);          // Print the elements of stream        stream.forEach(s -> System.out.println(s));    }}
1
2
3
4
5

Java - util package
Java-Iterable
java-stream
Java-Stream-programs
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java