code-rag-bench/online-tutorials huggingface dataset:
Chef - Libraries

Libraries in Chef provides a place to encapsulate compiled logic so that the cookbook recipes remain neat and clean.
Step 1 − Create a helper method in cookbook’s library.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/libraries/ipaddress.rb 
class Chef::Recipe 
def netmask(ipaddress) 
IPAddress(ipaddress).netmask 
end 
end
Step 2 − Use the helper method.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/recipes/default.rb 
ip = '10.10.0.0/24' 
mask = netmask(ip) # here we use the library method 
Chef::Log.info("Netmask of #{ip}: #{mask}") 
Step 3 − Upload the modified cookbook to the Chef Server.
vipin@laptop:~/chef-repo $ knife cookbook upload my_cookbook 
Uploading my_cookbook [0.1.0] 

user@server $ sudo chef-client 
...TRUNCATED OUTPUT... 
[2013-01-18T14:38:26+00:00] INFO: Netmask of 10.10.0.0/24: 
255.255.255.0 
...TRUNCATED OUTPUT... 

Chef library code can open the chef::Recipe class and add new methods as done in Step 1. This step is not the cleanest but the simplest way of doing it.
class Chef::Recipe 
def netmask(ipaddress) 
... 
end 
end

Once we open the chef::recipe class, there are changes that it gets polluted. As a best practice, it is always a better way to introduce a new sub class inside the library and define a method as class method. This avoids pulling the chef::recipe namespace.
vipin@laptop:~/chef-repo $ subl cookbooks/my_cookbook/libraries/ipaddress.rb 
class Chef::Recipe::IPAddress 
def self.netmask(ipaddress) 
IPAddress(ipaddress).netmask 
end 
end 
We can use the method inside the recipe like
IPAddress.netmask(ip) 

 Print
 Add Notes
 Bookmark this page
How to make a class JSON Serializable in Python?

Serialisation is the process of transforming objects of complex data types to native data types so that they can then be easily converted to JSON notation. 
If you have a JSON string, you can convert it into a JSON string by using the json.dumps() method.
Python pickle module is used for serialising and deserialising a Python object structure. Any object in Python can be pickled so that it can be saved on disk. What pickle does is that it “serialises” the object first before writing it to file. Pickling is a way to convert a python object (i.e) list, dict, etc... into a character stream. 
import json
x = {
   "name": "Archana",
   "age": 30,
   "city": "Hyderabad"
   }
# convert into JSON String by using json.dumps():
y = json.dumps(x)
print(y)
{"name": "Archana", "age": 30, "city": "Hyderabad"}
import json
Emp = {1:"Archana",
       2:"Krishna",
       3:"Vineeth",
       4:"Ramesh"}
jsonString = json.dumps(Emp)
print(jsonString)
Empid = [71,72,73,74]
jsonString = json.dumps(Empid)
print(jsonString)
{"1": "Archana", "2": "Krishna", "3": "Vineeth", "4": "Ramesh"}
[71, 72, 73, 74]
Get or set the element at the specified index in ArrayList in C#

To get or set the element at the specified index in ArrayList, the code is as follows −
 Live Demo
using System;
using System.Collections;
public class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("Laptop");
      arrList.Add("Desktop");
      arrList.Add("Notebook");
      arrList.Add("Ultrabook");
      arrList.Add("Tablet");
      arrList.Add("Headphone");
      arrList.Add("Speaker");
      Console.WriteLine("Elements in ArrayList...");
      foreach(string str in arrList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Element at index 5 = " + arrList[5]);
   }
}
This will produce the following output −
Elements in ArrayList...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 5 = Headphone
Let us see another example −
 Live Demo
using System;
using System.Collections;
public class Demo {
   public static void Main() {
      ArrayList arrList = new ArrayList();
      arrList.Add("Laptop");
      arrList.Add("Desktop");
      arrList.Add("Notebook");
      arrList.Add("Ultrabook");
      arrList.Add("Tablet");
      arrList.Add("Headphone");
      arrList.Add("Speaker");
      Console.WriteLine("Elements in ArrayList...");
      foreach(string str in arrList) {
         Console.WriteLine(str);
      }
      Console.WriteLine("Element at index 5 = " + arrList[5]);
      arrList[5] = "SSD";
      Console.WriteLine("Element at index 5 (Updated) = " + arrList[5]);
   }
}
This will produce the following output −
Elements in ArrayList...
Laptop
Desktop
Notebook
Ultrabook
Tablet
Headphone
Speaker
Element at index 5 = Headphone
Element at index 5 (Updated) = SSD
How to open External Programs using Tkinter? - GeeksforGeeks

24 Jan, 2021
Prerequisite: Tkinter, os
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications.  In this article, we will learn how to open an external program using Tkinter. Here we will use the system() method in the os module.
Approach:
First, we will import the required library
Then we create an object, which will ask for a file that you want to open
To open that file we will use the system() method from the os Module.
Syntax:
os.system(‘”%s”‘ % File Path)
Below is the Implementation:
Python3
# Import Libraryfrom tkinter import *import osfrom tkinter.filedialog import askopenfilename   # Create Object root = Tk()   # Set geometryroot.geometry('200x200')   def open_file():     file = askopenfilename()    os.system('"%s"' % file)  Button(root, text ='Open',        command = open_file).pack(side = TOP,                                  pady = 10)   # Execute Tkinterroot.mainloop()
Output:
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Reverse a String (Recursive) C++

Recursion is simply the way toward rehashing things in a self-comparative way. In programming dialects, if a program enables you to call a capacity inside a similar capacity, at that point, it is known as a recursive call of the capacity. You can switch a string utilizing the recursive capacity as appeared in the accompanying project.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void reverse(string str){
   if(str.size() == 0){
      return;
   }
   reverse(str.substr(1));
   cout << str[0];
}
int main(){
   string a = "Arnold";
   cout<<"recursive reverse (Arnold) ::";
   reverse(a);
   return 0;
}
The above C++ program accepts a string "Arnold" as an input then it yields results as "dlonrA" by applying recursion as;
Recursive reverse (Arnold):: dlonrA
Fortran - Arithmetic Operators

Following table shows all the arithmetic operators supported by Fortran. Assume variable A holds 5 and variable B holds 3 then −
Try the following example to understand all the arithmetic operators available in Fortran −
program arithmeticOp

! this program performs arithmetic calculation
implicit none  

   ! variable declaration
   integer :: a, b, c
   
   ! assigning values 
   a = 5   
   b = 3  
   
   ! Exponentiation 
   c = a ** b 
   
   ! output 
   print *, "c = ", c
   
   ! Multiplication  
   c = a * b 
   
   ! output 
   print *, "c = ", c
   
   ! Division  
   c = a / b 
   
   ! output 
   print *, "c = ", c
   
   ! Addition
   c = a + b 
   
   ! output 
   print *, "c = ", c
   
   ! Subtraction 
   c = a - b 
   
   ! output 
   print *, "c = ", c
   
end program arithmeticOp
When you compile and execute the above program, it produces the following result −
c = 125
c = 15
c = 1
c = 8
c = 2

 Print
 Add Notes
 Bookmark this page
MySQL query to select all entries from a particular month

To select all entries from a particular month in MySQL, use the monthname() or month() function.
The syntax is as follows.
select *from yourTableName where monthname(yourColumnName)='yourMonthName';
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table selectAllEntriesDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> ShippingDate datetime
   -> );
Query OK, 0 rows affected (0.63 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2019-01-21');
Query OK, 1 row affected (0.24 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2018-02-24');
Query OK, 1 row affected (0.15 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2010-10-22');
Query OK, 1 row affected (0.20 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2011-04-12');
Query OK, 1 row affected (0.12 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2013-02-10');
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2014-02-15');
Query OK, 1 row affected (0.16 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2016-06-14');
Query OK, 1 row affected (0.18 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2017-02-14');
Query OK, 1 row affected (0.51 sec)
mysql> insert into selectAllEntriesDemo(ShippingDate) values('2015-03-29');
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement.
The query is as follows.
mysql> select *from selectAllEntriesDemo;
The following is the output.
+----+---------------------+
| Id | ShippingDate        |
+----+---------------------+
| 1  | 2019-01-21 00:00:00 |
| 2  | 2018-02-24 00:00:00 |
| 3  | 2010-10-22 00:00:00 |
| 4  | 2011-04-12 00:00:00 |
| 5  | 2013-02-10 00:00:00 |
| 6  | 2014-02-15 00:00:00 |
| 7  | 2016-06-14 00:00:00 |
| 8  | 2017-02-14 00:00:00 |
| 9  | 2015-03-29 00:00:00 |
+----+---------------------+
9 rows in set (0.00 sec)
The following is the query to select all entries from a particular month:
mysql> select *from selectAllEntriesDemo where monthname(ShippingDate)='February';
Here is the output.
+----+---------------------+
| Id | ShippingDate        |
+----+---------------------+
| 2  | 2018-02-24 00:00:00 |
| 5  | 2013-02-10 00:00:00 |
| 6  | 2014-02-15 00:00:00 |
| 8  | 2017-02-14 00:00:00 |
+----+---------------------+
4 rows in set (0.00 sec)
Here is an alternate query.
mysql> select *from selectAllEntriesDemo where month(ShippingDate)=2;
The following is the output.
+----+---------------------+
| Id | ShippingDate        |
+----+---------------------+
| 2  | 2018-02-24 00:00:00 |
| 5  | 2013-02-10 00:00:00 |
| 6  | 2014-02-15 00:00:00 |
| 8  | 2017-02-14 00:00:00 |
+----+---------------------+
4 rows in set (0.04 sec)
Difference Between CrudRepository and JPARepository in Java

CrudRepository and JPA repository both are the interface of the spring data repository library. Spring data repository reduces the boilerplate code by providing some predefined finders to access the data layer for various persistence layers.
JPA repository extends CrudRepository and PagingAndSorting repository. It inherits some finders from crud repository such as findOne, gets and removes an entity. It also provides some extra methods related to JPA such as delete records in batch, flushing data directly to a database base and methods related to pagination and sorting.
We need to extend this repository in our application and then we can access all methods which are available in these repositories. We can also add new methods using named or native queries based on business requirements.
@Repository
public interface BookDAO extends JpaRepository {
   Book findByAuthor(@Param("id") Integer id);
}
@Repository
public interface BookDAO extends CrudRepository {
   Book Event findById(@Param("id") Integer id);
}
Getting hash of a file using CMD - GeeksforGeeks

23 Oct, 2020
A cryptographic hash is a fixed size string (or text) that is used as an identifier/fingerprint of some data. These are particularly useful in determining the integrity of files after they are transferred over a communication channel. Hashes are even utilized by certain OS-level processes for their working. The command processor of Windows OS (cmd.exe) provides the user with the ability to compute hashes on files/Directories via an utility command named Certutil. In this article we would learn about computing hashes on command prompt (cmd).
Description of command :The command Certutil is primarily used for working with digital certificates and not hashes. The ability to hash files is due to the presence of a -hashfile switch in it.
> Certutil -hashfile
-hashfile  -- Generate and display cryptographic hash over a file

Where certutil is the command, and -hashfile is a switch provided to it.Syntax :The -hashfile switch takes in two arguments. Firstly, the path to the file in which we are interested in getting the hash. And then the hash algorithm that we are interested in.
Creating a syntax :
Certutil -hashfile (Path_to_file) [HashAlgo]

Where Path_to_file is mandatory(should be provided) argument and HashAlgo is optional argument (If not provided, defaults to SHA1). If HashAlgo is provided it should either be from SHA (Secure Hash Algorithms) or from MD (Message Digest) Cryptographic Hash families. Some of the hash algorithms allowed in the command are MD4, MD5, SHA1, SHA256, SHA512.
Usage of the command :To demonstrate the usage of the command, we would be running the command on a file. Our example file will be at the location “C:\Users\Public\spars.txt” .
That contains some text data. So to get the MD5 (Message Digest 5) hash of the file, we would have to execute the command.
certutil -hashfile "C:\Users\Public\spars.txt" MD5
The command upon execution would produce an output similar to this.
MD5 hash of spars.txt:
cb21e6741817a2d3020e02bb94301ae4
CertUtil: -hashfile command completed successfully.

To get SHA512 hash of the above file the command and the output would appear as following :
Hash
Operating Systems
Operating Systems
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
Difference between Internal and External fragmentation
Program for Least Recently Used (LRU) Page Replacement algorithm
Mutex lock for Linux Thread Synchronization
Logical and Physical Address in Operating System
File Allocation Methods
States of a Process in Operating Systems
Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm
Dining Philosopher Problem Using Semaphores
Producer Consumer Problem using Semaphores | Set 1
How to select a radio button by default in JavaScript?

To select a radio button by default we have to check it as true. If it is checked as true then by default it will be autofocused. 
In the following example, we have only radio buttons and none of them is autofocused.
Live Demo
<html>
   <form id="radiobuttons" name="radiobutton">
      <input id="rad1" value="a" type="radio" name="check"/>male
      <input id="rad2" value="b" type="radio" name="check"/>female
      <input id="rad3" value="c" type="radio" name="check"/>other
   </form>
<body>
</body>
</html>
When the above code is executed we will get radio buttons and none of them is autofocused as shown in the following image.
To autofocus any of the above buttons we have to check them initially. This can be done by using pure javascript as shown in the following example.
Live Demo
<html>
   <form id="radiobuttons" name="radiobutton">
      <input id="rad1" value="a" type="radio" name="check"/>male
      <input id="rad2" value="b" type="radio" name="check"/>female
      <input id="rad3" value="c" type="radio" name="check"/>other
   </form>
<body>
<script>
   radiobtn = document.getElementById("rad1");
   radiobtn.checked = true;
</script>
</body>
</html>
After executing the above code, we will get the following output.
How to check if a column is categorical in R data frame?

To check if a column is categorical in R data frame, we can follow the below steps −
First of all, create a data frame.
Use class function to check the class of the column.
Let's create a data frame as shown below −
 Live Demo
x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) −
   x y  z
1  4 D High
2  1 B High
3  1 C High
4  2 A Medium
5  3 B High
6  2 D Medium
7  2 C Low
8  1 A Low
9  5 D Medium
10 3 D Low
11 1 B Medium
12 3 B High
13 5 C Medium
14 4 C Medium
15 1 B High
16 1 C Low
17 3 A Medium
18 1 D Low
19 1 B High
20 1 D Medium
21 3 B High
22 4 A Low
23 2 C High
24 2 A Medium
25 5 B High
Use class function to find whether column x is categorical or not −
 Live Demo
x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
class(df$x)
[1] "integer"
Use class function to find whether column y is categorical or not −
 Live Demo
x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
class(df$y)
[1] "character"
Use class function to find whether column z is categorical or not −
 Live Demo
x<-rpois(25,2)
y<-sample(LETTERS[1:4],25,replace=TRUE)
z<-factor(sample(c("Low","Medium","High"),25,replace=TRUE))
df<-data.frame(x,y,z)
class(df$z)
[1] "factor"
C++ Program to Remove all Characters in a String Except Alphabets

A string is a one-dimensional character array that is terminated by a null character. It may contain characters, digits, special symbols etc.
A program to remove all characters in a string except alphabets is given as follows.
#include <iostream>
using namespace std;
int main() {
   char str[100] = "String@123!!";
   int i, j;
   cout<<"String before modification: "<<str<<endl;
   for(i = 0; str[i] != '\0'; ++i) {
      while(!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] ==          '\0') {
         for(j = i; str[j] != '\0'; ++j) {
            str[j] = str[j+1];
         }
      }
   }
   cout<<"String after modification: "<<str;
   return 0;
}
String before modification: String@123!!
String after modification: String
In the above program, the string modification is done in a for loop. If the character in the string is not an alphabet or null, then all the characters to the right of that character are shifted towards the left by 1. This is done using j in the inner for loop. This leads to the removal of the non alphabetic character. A code snippet that demonstrates this is as follows −
for(i = 0; str[i] != '\0'; ++i) {
   while(!( (str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z') || str[i] == '\0') )    {
      for(j = i; str[j] != '\0'; ++j) {
         str[j] = str[j+1];
      }
   }
}
After modification, the string is displayed. This is shown below −
cout<<"String after modification: "<<str;
MongoDB query for exact match

For exact match, you can use $exists that checks for a match. Let us create a collection with documents −
> db.demo290.insertOne({"ListOfName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c0c9e5d93261e4bc9ea2d")
}
> db.demo290.insertOne({"ListOfName":["Chris","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e4c0cb05d93261e4bc9ea2e")
}
Display all documents from a collection with the help of find() method −
> db.demo290.find();
This will produce the following output −
{ "_id" : ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName" : "Chris" }
{ "_id" : ObjectId("5e4c0cb05d93261e4bc9ea2e"), "ListOfName" : [ "Chris", "David" ] }
Here is the query for exact match of a value −
> db.demo290.find({$and: [{'ListOfName.0': {$exists: false}}, {"ListOfName": 'Chris'}]});
This will produce the following output −
{ "_id" : ObjectId("5e4c0c9e5d93261e4bc9ea2d"), "ListOfName" : "Chris" }
HTML | size Attribute

09 Dec, 2021
The size attribute in HTML is used to specify the initial width for the input field and a number of visible rows for the select element.The size attribute can be used with the following elements:  
<input>
<hr>
<select>
<font> 
Attribute Values: It contains a numeric value that specify the number of visible options in the drop-down list. It has a default value which is 4.
<input> size Attribute: This attribute specifies the visible width of input element.Syntax:  
<input size = "value">
Example:  
html
<!DOCTYPE html><html> <head>    <title>HTML size Attribute</title>    <style>        h1,        h2 {            text-align: center;        }    </style></head> <body>    <center>        <h1 style="color: green;">            GeeksforGeeks        </h1>         <h2>            HTML size Attribute        </h2>         <!-- It is the default size -->        Name:        <input type="text">        <br>        <br>        <!-- It's user specified size with value 50 -->        Email-id:        <input type="text" size="50">    </center></body> </html>
Output:  
<select> size Attribute: This attribute specifies the number of visible options in a drop-down list. Syntax:  
<select size = "value"> option values...</select>
Example:  
html
<!DOCTYPE html><html>    <head>        <title>HTML size Attribute</title>        <style>            h1, h2 {                text-align: center;            }        </style>    </head>    <body>        <h1 style = "color: green;">            GeeksforGeeks        </h1>                 <h2>            HTML size Attribute        </h2>           <p>Sorting Algorithms</p>           <select size="3">            <option value="merge">              merge sort            </option>            <option value="bubble">              bubble sort            </option>            <option value="selection">              selection sort</option>            <option value="quick">quick sort</option>            <option value="insertion">insertion sort</option>        </select>    </body></html>
Output:  
<hr> size Attribute: This attribute specifies the height of the horizontal line. Syntax:  
<hr size = "value">
Example:  
html
<!DOCTYPE html><html>    <head>        <title>HTML size Attribute</title>        <style>            h1, h2 {                text-align: center;            }            hr {                background: green;            }        </style>    </head>    <body>        <h1 style = "color: green;">            GeeksforGeeks        </h1>                 <h2>            HTML size Attribute        </h2>        <hr size = "26">    </body></html>
Output:  
Supported Browsers: The browsers supported by size attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
nidhi_biet
ManasChhabra2
HTML-Attributes
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Remove square brackets from list

05 Sep, 2019
Sometimes, while working with displaying the contents of list, the square brackets, both opening and closing are undesired. For this when we need to print whole list without accessing the elements for loops, we require a method to perform this. Let’s discuss a shorthand by which this task can be performed.
Method : Using str() + list slicingThe shorthand that can be applied, without having need to access each element of list is to convert the entire list to string and then strip the initial and last character of list using list slicing. This won’t work if list contains a string. In that case, each element can be joined using join(), as discussed in many other articles.
# Python3 code to demonstrate working of# Remove square brackets from list# using str() + list slicing  # initialize listtest_list = [5, 6, 8, 9, 10, 21]  # printing original listprint("The original list is : " + str(test_list))  # Remove square brackets from list# using str() + list slicingres = str(test_list)[1:-1]  # printing resultprint("List after removing square brackets : " + res)
The original list is : [5, 6, 8, 9, 10, 21]
List after removing square brackets : 5, 6, 8, 9, 10, 21

Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
String rjust() and ljust() in python()

08 Jan, 2018
1. String rjust() The string rjust() method returns a new string of given length after substituting a given character in left side of original string.
Syntax:
string.rjust(length, fillchar)
Parameters:
length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned.fillchar: (optional) characters which needs to be padded. If it’s not provided, space is taken as a default argument.
Returns:
Returns a new string of given length after substituting a given character in left side of original string.
Example
# Python program to demonstrate working of # rjust()string = 'geeks'length = 8  # If no fill character is provided, space# is used as fill characterprint(string.rjust(length))
Output:
   geeks
Example
# example stringstring = 'geeks'length = 8fillchar = '*'  print(string.rjust(length, fillchar))
Output:
***geeks  

 
2. String ljust()The string ljust() method returns a new string of given length after substituting a given character in right side of original string.
Syntax:
string.ljust(length, fillchar)
Parameters:
length: length of the modified string. If length is less than or equal to the length of the original string then original string is returned.fillchar: (optional) characters which needs to be padded. If it’s not provided, space is taken as a default argument.
Returns:
Returns a new string of given length after substituting a given character in right side of original string.
Example 1
# example stringstring = 'geeks'length = 8  # If no fill character is provided, space# is used as fill character.print(string.ljust(length))
Output: (Three spaces are printed after geeks)
geeks   

Example 2
# example stringstring = 'geeks'length = 8fillchar = '*'  # print left justified stringprint(string.ljust(length, fillchar))
Output:
geeks***  

python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove SVG content?

30 Jun, 2022
In order to remove SVG content, you can use the remove() function provided by D3.js. The remove() function is used along with two methods which are also provided by D3.js. Following methods are:
Using select() Method with remove() Method: The d3.select() method is used to select the first element that need to remove. 
Syntax:
d3.select("element").remove()
Example: In this example, first paragraph (p) element is removed. 
html
<!DOCTYPE html><html> <head>    <title>        How can I remove SVG content?    </title>         <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body style="text-align:center">            <h1 style="color:green">GeeksforGeeks</h1>  <h3> How can I remove SVG content?</h3>  <p>Geeks1</p>  <p>Geeks2</p>  <p>Geeks3</p>    <script>                 // Calling the selectAll() function        d3.select("p").remove();    </script></body> </html>                    
Output:
 
Using selectAll() Method with remove() Method: The d3.selectAll() method is used to select all the element that matched and remove it. Syntax:
d3.selectAll("element").remove()
Example: In this example, all paragraph (p) elements are removed. 
html
<!DOCTYPE html><html> <head>    <title>        How can I remove SVG content?    </title>         <script src = "https://d3js.org/d3.v4.min.js"></script></head> <body style="text-align:center">            <h1 style="color:green">GeeksforGeeks</h1>  <h3> How can I remove SVG content?</h3>  <p>Geeks1</p>  <p>Geeks2</p>  <p>Geeks3</p>    <script>                 // Calling the selectAll() function        d3.selectAll("p").remove();    </script></body> </html>                    
Output:
 
sidhanthnandansaaho
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PLSQL | ADD_MONTHS Function

24 Oct, 2019
The PLSQL ADD_MONTHS function is used to return a date with a specified number of months added to it. The ADD_MONTHS function accepts two parameters which are the initial date and the number of months to be added to it.The ADD_MONTHS function returns a value of the date data type.
The date argument can be a datetime value or any value that can be implicitly converted to DATE. The integer argument to be added can be an integer or any value that can be implicitly converted to an integer. The return type is always DATE, regardless of the data type of date. If the date specified in the argument is the last day of the month or if the resulting month has fewer days than the day component of date, then the result is the last day of the resulting month.
Syntax:
ADD_MONTHS( init_date, add_months )
Parameters Used
init_date – It is used to specify the initial date.add_months – It is used to specify the number of months to be added to the initial date.
init_date – It is used to specify the initial date.
add_months – It is used to specify the number of months to be added to the initial date.
Return Value:The ADD_MONTHS function returns a value of the date data type.
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example-1: Using positive numeric value in the add_months argument of the ADD_MONTHS function.
DECLARE 
   Test_Date date := '01-Aug-18';
   Add_Month number := 3;
   
BEGIN 
   dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month)); 
   
END; 
Output:
01.12.18 
Example-2: Using negative numeric value in the add_months argument of the ADD_MONTHS function.
DECLARE 
   Test_Date date := '01-Aug-18';
   Add_Month number := -3;
   
BEGIN 
   dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month)); 
   
END; 
Output:
01.05.03 
Example-3: Using negative numeric value in the add_months argument of the ADD_MONTHS function.
DECLARE 
   Test_Date date := '31-Aug-18';
   Add_Month number := -4;
   
BEGIN 
   dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month)); 
   
END; 
Output:
30.04.18 
Since April has 30 days, the ADD_MONTHS returns 30.04.18 as the last day.
Example-4: Using a positive numeric value in the add_months argument of the ADD_MONTHS function.
DECLARE 
   Test_Date date := '31-Aug-18';
   Add_Month number := 3;
   
BEGIN 
   dbms_output.put_line(ADD_MONTHS(Test_Date, Add_Month)); 
   
END; 
Output:
30.11.18 
Since November has 30 days, the ADD_MONTHS returns 30.11.18 as the last day.
Example-5: Using select query with the ADD_MONTHS function.
SELECT
  ADD_MONTHS( DATE '2016-02-29', 1 )
FROM
  dual; 
Output:
31-MAR-16 
Advantages:The integer argument to be added can be an integer or any value that can be implicitly converted to an integer.
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Timestamp.isoformat

14 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.isoformat() function is used to convert the given Timestamp object into the ISO format.
Syntax :Timestamp.isoformat()
Parameters : None
Return : date time as a string
Example #1: Use Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2011,  month = 11, day = 21,                  hour = 10, second = 49, tz = 'US/Central')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format.
# convert to ISO formatts.isoformat()
Output :
As we can see in the output, the Timestamp.isoformat() function has returned the date in the ISO format.
Example #2: Use Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format.
# importing pandas as pdimport pandas as pd  # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31,                  hour = 4, second = 49, tz = 'Europe/Berlin')  # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.isoformat() function to convert the date in the given Timestamp object to ISO format.
# convert to ISO formatts.isoformat()
Output :
As we can see in the output, the Timestamp.isoformat() function has returned the date in the ISO format.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Program to Find Binary Equivalent of an Integer using Recursion - GeeksforGeeks

18 Oct, 2021
Given an integer number, now we convert the given integer number into a binary number using recursion. Recursion is a method in which a function calls itself directly or indirectly and such type of function is known as a recursive function. It solves the problem very efficiently like we find the binary equivalent of an integer.
Examples:
Input : 10
Output: 1010

Input : 11
Output: 1011
Approach: 
To display the binary equivalent of an integer we use the following steps:
If condition is used to check if the given value is not equal to zero.
If the given condition is true then perform the modulus of the val by 2, then add the modulus result to 10 and then multiply the value of the result with the value of decimaltobinary() function.
Now repeat step 2 until the value of val variable is greater than zero.
Print the array in reverse order now.
And if the condition is false then it will execute the else section, i.e., return 0
The below image can help you better understand the approach.
Let us considered the integer number is 10. Now we find the binary equivalent of 10 so,
10 % 2 + 10 * (10 / 2) % 2 will return 0
5 % 2 + 10 * (5 / 2) % 2 will return 1
2 % 2 + 10 * (2 / 2) % 2 will return 0
1 % 2 + 10 * (1 / 2) % 2 will return 1
So the final result is 1010.
Example 1:
C#
// C# program to display the binary equivalent// of an integerusing System;  class GFG{  // Driver codepublic static void Main(string[] args){          // Input    int num = 15;          decimaltobinary(num);}  // Function to display the binary equivalent // of an integerpublic static int decimaltobinary(int val){    int binary;          if (val != 0)    {        binary = (val % 2) + 10 * decimaltobinary(val / 2);        Console.Write(binary);        return 0;    }    else    {        return 0;    }}}
1111
Example 2:
C#
// C# program to display the binary equivalent// of an integerusing System;  class GFG{    // Function to display the binary equivalent // of an integerpublic static int decimaltobinary(int val){    int binary;          if (val != 0)    {        binary = (val % 2) + 10 * decimaltobinary(val / 2);        Console.Write(binary);        return 0;    }    else    {        return 0;    }}    // Driver codepublic static void Main(string[] args){    int num;          // Reading input from user    Console.Write("Hi! Enter the number:");    num = int.Parse(Console.ReadLine());    decimaltobinary(num);  }}
Output:
Hi! Enter the number:10
1010
CSharp LINQ
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
C# | Generics - Introduction
Switch Statement in C#
Top 50 C# Interview Questions & Answers
Lambda Expressions in C#
C# | How to insert an element in an Array?
Convert String to Character Array in C#
Python | Pandas dataframe.applymap()

16 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Dataframe.applymap() method applies a function that accepts and returns a scalar to every element of a DataFrame.
Syntax: DataFrame.applymap(func)

Parameters:
func: Python function, returns a single value from a single value.

Returns: Transformed DataFrame.

For link to CSV file Used in Code, click here
Example #1: Apply the applymap() function on the dataframe to find the no. of characters in all cells.
# importing pandas as pdimport pandas as pd  # Making data frame from the csv filedf = pd.read_csv("nba.csv")  # Printing the first 10 rows of # the data frame for visualizationdf[:10]
# Using lambda function we first convert all # the cell to a string value and then find# its length using len() functiondf.applymap(lambda x: len(str(x)))
Output:Notice how all nan value has been converted to string nan and their length is evaluated to be 3.
 Example #2: Append _X in each cell using applymap() function.
In order to append _X in each cell, first convert each cell into a string.
# importing pandas as pdimport pandas as pd  # Making data frame from the csv filedf = pd.read_csv("nba.csv")  # Using applymap() to append '_X'# in each cell of the dataframedf.applymap(lambda x: str(x) + '_X')
Output:
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Locale getDefault() method in Java - GeeksforGeeks

07 Sep, 2018
This method returns default Locale set by the Java Virtual Machine. This is static method so it can be called without creating object of the class Locale.
Syntax:
public static Locale getDefault()
Return Value: The method returns default Locale set by the Java Virtual Machine.
Below is the code to illustrate getDefault() method:
Program 1:
// Java code to demonstrate// getLocale() method in Locale  import java.util.Locale;public class GfG {      // main method    public static void main(String[] args)    {        // declaring object of Locale        Locale locale;          // calling the getDefault method        locale = Locale.getDefault();          // printing the locale        System.out.println(locale);    }}
en_US

This method returns default Locale set by the Java Virtual Machine for the specified category. This is static method so it can be called without creating object of the class Locale.
Syntax:
Locale.getDefault(Locale.Category category)
Parameters: It takes a mandatory parameter category of type Locale.Category.
Return Value: The method returns default Locale set of type Locale, for the specified category.
Exceptions: If the category passed in the parameter is null, the getDefault() method will throw NullPointerException.
Below is the code to illustrate getDefault(Locale.Category category):
Program 1:
// Java code to demonstrate// getLocale() method in Locale  import java.util.Locale;  public class GfG {      // main method    public static void main(String[] args)    {        // declaring object of Locale        Locale locale;          // Specified category.        Locale.Category category = Locale.Category.DISPLAY;          // calling the getDefault method        locale = Locale.getDefault(category);          // printing the locale        System.out.println(locale);    }}
en_US

Program 2: To demonstrate NullPointerException
// Java code to demonstrate// getLocale() method in Locale  import java.util.*;  public class GfG {      // main method    public static void main(String[] args)    {        // declaring object of Locale        Locale locale;          try {            // Specified category = null            Locale.Category category = null;              // calling the getDefault method            // This will throw exception            // as the category passed is null            locale = Locale.getDefault(category);              // printing the locale            System.out.println(locale);        }        catch (Exception e) {            System.out.println("Exception: " + e);        }    }}
Exception: java.lang.NullPointerException

Java - util package
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Interfaces in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
Overriding in Java
Stack Class in Java
Collections in Java
Delete elements in range in Python

Deleting a single element from a python is straight forward by using the index of the element and the del function. But there may be scenarios when we need to delete elements for a group of indices. This article explores the approaches to delete only those elements form the list which are specified in the index list.
In this approach we create a list containing the index values where deletion has to happen. The we sort and reverse them to preserve the original order of the elements of the list. Finally we apply the del function to the original given list for those specific index points.
 Live Demo
Alist = [11,6, 8, 3, 2]

# The indices list
idx_list = [1, 3, 0]

# printing the original list
print("Given list is : ", Alist)

# printing the indices list
print("The indices list is : ", idx_list)

# Use del and sorted()
for i in sorted(idx_list, reverse=True):
del Alist[i]

# Print result
print("List after deleted elements : " ,Alist)
Running the above code gives us the following result −
Given list is : [11, 6, 8, 3, 2]
The indices list is : [1, 3, 0]
List after deleted elements : [8, 2]
idx_list after sorting and reverse becomes [0,1,3]. So only the elements from these positions get deleted.
We can also approach the above program by using enumerate and a not in clause inside a for loop. The result is same as above.
 Live Demo
Alist = [11,6, 8, 3, 2]

# The indices list
idx_list = [1, 3, 0]

# printing the original list
print("Given list is : ", Alist)

# printing the indices list
print("The indices list is : ", idx_list)

# Use slicing and not in
Alist[:] = [ j for i, j in enumerate(Alist)
if i not in idx_list ]

# Print result
print("List after deleted elements : " ,Alist)
Running the above code gives us the following result −
Given list is : [11, 6, 8, 3, 2]
The indices list is : [1, 3, 0]
List after deleted elements : [8, 2]
Python Tuple len() Method

Python tuple method len() returns the number of elements in the tuple.
Following is the syntax for len() method −
len(tuple)
tuple − This is a tuple for which number of elements to be counted.
tuple − This is a tuple for which number of elements to be counted.
This method returns the number of elements in the tuple.
The following example shows the usage of len() method.
#!/usr/bin/python

tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc')
print "First tuple length : ", len(tuple1)
print "Second tuple length : ", len(tuple2)
When we run above program, it produces following result −
First tuple length :  3
Second tuple length :  2


    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
time.Ticker.Stop() Function in Golang With Examples - GeeksforGeeks

21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The NewTicker() function in Go language is used to disable a ticker. So, after calling Stop() method no further ticks will be transmitted. And it doesn’t close the channel, in order to avoid a concurrent go-routine reading from the channel from viewing an inaccurate “tick”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t *Ticker) Stop()

Here, “t” is a pointer to the Ticker. Where Ticker is used to hold a channel that supplies `ticks’ of a clock at intervals.
Return Value: It returns the output of the stated operation before calling the Stop() method because after calling it ticker is turned off.
Example:
// Golang program to illustrate the usage of// time.Ticker.Stop() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Calling NewTicker method    Ticker := time.NewTicker(2 * time.Second)      // Creating channel using make    // keyword    mychannel := make(chan bool)      // Go function    go func() {          // Using for loop        for {              // Select statement            select {              // Case statement            case <-mychannel:                return              // Case to print current time            case tm := <-Ticker.C:                fmt.Println("The Current time is: ", tm)            }        }    }()      // Calling Sleep() method    time.Sleep(7 * time.Second)      // Calling Stop() method    Ticker.Stop()      // Setting the value of channel    mychannel <- true      // Printed when the ticker is turned off    fmt.Println("Ticker is turned off!")}
Output:
The Current time is:  2020-04-09 07:26:05.374436607 +0000 UTC m=+2.000213251
The Current time is:  2020-04-09 07:26:07.374442201 +0000 UTC m=+4.000218858
The Current time is:  2020-04-09 07:26:09.374511648 +0000 UTC m=+6.000288424
Ticker is turned off!

Here, at first a Ticker is created then a channel is created that transmits time. After that for loop is used in order to print the current time then Ticker.Stop() method is called and the ticker is turned off.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
strings.Replace() Function in Golang With Examples
Arrays in Go
How to Split a String in Golang?
Slices in Golang
Golang Maps
How to convert a string in lower case in Golang?
Different Ways to Find the Type of Variable in Golang
Inheritance in GoLang
How to compare times in Golang?
Interfaces in Golang
Write a program in Python to merge two dataframes based on matching data in a column

Assume, you have two dataframe,
first dataframe is
 id country
0 1 India
1 2 UK
2 3 US
3 4 China

second dataframe is

 id City
0 1 Chennai
1 11 Cambridge
2 22 Chicago
3 4 Chengdu
And the result for merging based on same column is,
Merging data based on same column - id
 id    country    City
0 1    India    Chennai
1 4    China    Chengdu
To solve this, we will follow the steps given below −
Define a two dataframes
Define a two dataframes
Merge two dataframes based on the same column id is defined below,
Merge two dataframes based on the same column id is defined below,
pd.merge(first_df,second_df,how='inner',on='id')
Let us see the following implementation to get a better understanding −
import pandas as pd
import numpy as np
first_df = pd.DataFrame({'id':[1,2,3,4], 'country':['India','UK','US','China']
                        })
print("first dataframe is\n", first_df)
second_df = pd.DataFrame({'id':[1,11,22,4], 'City' : ['Chennai','Cambridge','Chicago','Chengdu']
                        })
print("second dataframe is\n", second_df)
print("Merging data based on same column - id")
print(pd.merge(first_df,second_df,how='inner',on='id'))
first dataframe is
 id country
0 1 India
1 2 UK
2 3 US
3 4 China

second dataframe is
  id  City
0 1 Chennai
1 11 Cambridge
2 22 Chicago
3 4 Chengdu

Merging data based on same column - id
 id country City
0 1 India Chennai
1 4 China Chengdu