code-rag-bench/online-tutorials huggingface dataset:
How to delete multiple documents in MongoDB using deleteMany()?

Let us first create a collection with documents −
> db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce00b07bf3115999ed51214")
}
> db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce00b0bbf3115999ed51215")
}
> db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce00b0fbf3115999ed51216")
}
> db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce00b12bf3115999ed51217")
}
> db.deleteMultipleDocumentsDemo.insertOne({"StudentFirstName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce00b18bf3115999ed51218")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.deleteMultipleDocumentsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5ce00b07bf3115999ed51214"), "StudentFirstName" : "Larry" }
{ "_id" : ObjectId("5ce00b0bbf3115999ed51215"), "StudentFirstName" : "Chris" }
{ "_id" : ObjectId("5ce00b0fbf3115999ed51216"), "StudentFirstName" : "David" }
{ "_id" : ObjectId("5ce00b12bf3115999ed51217"), "StudentFirstName" : "Bob" }
{ "_id" : ObjectId("5ce00b18bf3115999ed51218"), "StudentFirstName" : "Carol" }
Following is the query to delete multiple documents in MongoDB −
> db.deleteMultipleDocumentsDemo.deleteMany({StudentFirstName: {$in: ["Larry", "David", "Carol"]}});
{ "acknowledged" : true, "deletedCount" : 3 }
Let us display the document once again −
> db.deleteMultipleDocumentsDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5ce00b0bbf3115999ed51215"), "StudentFirstName" : "Chris" }
{ "_id" : ObjectId("5ce00b12bf3115999ed51217"), "StudentFirstName" : "Bob" }
Python | Boolean List AND and OR operations - GeeksforGeeks

29 Oct, 2019
Sometimes, while working with Python list, we can have a problem in which we have a Boolean list and we need to find Boolean AND or OR of all elements in it. This kind of problem has application in Data Science domain. Let’s discuss an easy way to solve both these tasks.
Method #1 : AND operation – Using all()The solution to this problem is quite straight forward, but application awareness is required. The all() performs the Boolean AND of the list and returns the result.
# Python3 code to demonstrate working of# Boolean List AND and OR operations# AND Operation - Using all()  # initialize listtest_list = [True, True, False, True, False]  # printing original listprint("The original list is : " + str(test_list))  # Boolean List AND and OR operations# AND Operation - Using all()res = all(test_list)  # printing resultprint("Result after performing AND among elements : " + str(res))
The original list is : [True, True, False, True, False]
Result after performing AND among elements : False

 
Method #2 : OR operation – Using any()This task can be performed using any(). This checks for any True element in list and returns True in that case else returns a False.
# Python3 code to demonstrate working of# Boolean List AND and OR operations# OR operation - Using any()  # initialize listtest_list = [True, True, False, True, False]  # printing original listprint("The original list is : " + str(test_list))  # Boolean List AND and OR operations# OR operation - Using any()res = any(test_list)  # printing resultprint("Result after performing OR among elements : " + str(res))
The original list is : [True, True, False, True, False]
Result after performing OR among elements : True

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Lodash _.values() Method - GeeksforGeeks

09 Sep, 2020
The _.values() method is used to return the array of the own enumerable string keyed property values of the object.
Syntax:
_.values(object)

Parameters: This method accepts a single parameter as mentioned above and described below:
object: This parameter holds the object to query.
Return Value: This method returns the array of property values of the object element.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source objectvar obj = {     Name: "GeeksforGeeks",     password: "gfg@1234",     username: "your_geeks"}  // Use of _.values() method console.log(_.values(obj));
Output:
["GeeksforGeeks", "gfg@1234", "your_geeks"]

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // The source functionfunction Fb() {  this.id = 2045;  this.username = 'fb_myself';  this.password = 'fb1234';}    // This will not get included in values arrayFb.prototype.email = 'myself@gmail.com';  // Use of _.values() method console.log(_.values(new Fb)); console.log(_.values('GFG'));
Output:
[2045, "fb_myself", "fb1234"]
['G', 'F', 'G']

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
rmdir command in Linux With Examples - GeeksforGeeks

24 May, 2019
rmdir command is used remove empty directories from the filesystem in Linux. The rmdir command removes each and every directory specified in the command line only if these directories are empty. So if the specified directory has some directories or files in it then this cannot be removed by rmdir command.
Syntax:
rmdir [-p] [-v | –verbose] [–ignore-fail-on-non-empty] directories ...
Options:
–help: It will print the general syntax of the command along with the various options that can be used with the rmdir command as well as give a brief description about each option.
rmdir -p: In this option each of the directory argument is treated as a pathname of which all components will be removed, if they are already empty, starting from the last component.
rmdir -v, –verbose: This option displays verbose information for every directory being processed.
rmdir –ignore-fail-on-non-empty: This option do not report a failure which occurs solely because a directory is non-empty. Normally, when rmdir is being instructed to remove a non-empty directory, it simply reports an error. This option consists of all those error messages.
rmdir –version: This option is used to display the version information and exit.
Example 1: This will first remove the child directory and then remove the parent directory.
rmdir -p mydir/mydir1
Example 2: Remove the directories mydir1, mydir2, and mydir3, if they are empty. If any of these directories are not empty, then an error message will be printed for that directory, and the other directories will be removed.
rmdir mydir1 mydir2 mydir3
Example 3: Remove the directory mydir/mydir1 if it is empty. Then, remove directory mydir, if it is empty after mydir/mydir1 was removed.
rmdir mydir/mydir1 mydir
linux-command
Linux-directory-commands
Linux-file-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Cat command in Linux with examples
touch command in Linux with Examples
echo command in Linux with Examples
scp command in Linux with Examples
ps command in Linux with Examples
How to export to PDF a graph based on a Pandas dataframe in Matplotlib?

To export to PDF a graph based on a Pandas dataframe, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Make a Pandas dataframe with three columns, col1, col2 and col3.
Plot the dataframe using plot() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import pandas as pd

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

df = pd.DataFrame([[2, 1, 4], [5, 2, 1], [4, 0, 1]], columns=['col1', 'col2', 'col3'])
df.plot()

plt.savefig('pd_df.pdf')
When we execute the code, it will save the following plot in a PDF with the name "pd_df.pdf".
Python – How to Multiply all items in Tuple

27 Feb, 2020
Sometimes, while programming, we have a problem in which we might need to perform product among tuple elements. This is an essential utility as we come across product operation many times and tuples are immutable and hence required to be dealt with. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list() + loopThe above functions can be combined to perform this task. We can employ loop to accumulate the result of product logic. The list() function is used to perform interconversions.
# Python3 code to demonstrate working of # Tuple Elements Multiplication# Using list() + loop  # getting Product def prod(val) :     res = 1     for ele in val:         res *= ele     return res    # initializing tup test_tup = (7, 8, 9, 1, 10, 7)   # printing original tuple print("The original tuple is : " + str(test_tup))   # Tuple Elements Multiplication # Using list() + loopres = prod(list(test_tup))   # printing result print("The product of tuple elements are : " + str(res)) 
The original tuple is : (7, 8, 9, 1, 10, 7)
The product of tuple elements are : 35280

 
Method #2 : Using map() + loop + list()The combination of above functions can be used to perform this task. In this, we first convert the tuple to list, flatten it’s each list element using map(), perform product of each using loop and again employ loop for overall product of resultant list.
# Python 3 code to demonstrate working of # Tuple Elements Multiplication# Using map() + list() + loop  # getting Product def prod(val) :     res = 1     for ele in val:         res *= ele     return res    # initializing tup test_tup = ([7, 8], [9, 1], [10, 7])   # printing original tuple print("The original tuple is : " + str(test_tup))   # Tuple Elements Multiplication# Using map() + list() + loop res = prod(list(map(prod, list(test_tup))))   # printing result print("The product of tuple elements are : " + str(res)) 
The original tuple is : (7, 8, 9, 1, 10, 7)
The product of tuple elements are : 35280

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove First Row of DataFrame in R

23 Aug, 2021
In this article, we are going to see how to remove the first row from the dataframe. We can remove first row by indexing the dataframe. 
Syntax:
data[-1,]
where -1 is used to remove the first row which is in row position
Example 1: R program to create a dataframe with 2 columns and delete the first row
R
# create dataframe with names and iddata=data.frame(names=c("sravan","boby","ojaswi","gnanesh",                        "rohith"),id=c(1,2,3,4,5))  # displaydata  # remove first rowdata=data[- 1, ]    print("------")  # displaydata
Output:
Example 2: R program to create dataframe with 4 columns and delete the first row
R
# create dataframe with names ,id,phone and addressdata = data.frame(names=c("sravan", "boby", "ojaswi", "gnanesh",                          "rohith"),                  id=c(1, 2, 3, 4, 5),                  phone=c("91834567450", "2222222222", "333333333333",                          "5555555555555", "333333333333"),                  address=c("hyd", "kol", "patna", "bikat", "guntut"))  # displaydata  # remove first rowdata = data[- 1, ]  print("------")  # displaydata
Output:
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ES6 - Symbol

ES6 introduces a new primitive type called Symbol. They are helpful to implement metaprogramming in JavaScript programs.
const mySymbol = Symbol()
const mySymbol = Symbol(stringDescription)

A symbol is just a piece of memory in which you can store some data. Each symbol will point to a different memory location. Values returned by a Symbol() constructor are unique and immutable.
Let us understand this through an example. Initially, we created two symbols without description followed by symbols with same description. In both the cases the equality operator will return false when the symbols are compared.
<script>
   const s1 = Symbol();
   const s2 = Symbol();
   console.log(typeof s1)
   console.log(s1===s2)
   const s3 = Symbol("hello");//description
   const s4 = Symbol("hello");
   console.log(s3)
   console.log(s4)
   console.log(s3==s4)
</script>
The output of the above code will be as mentioned below −
symbol
false
Symbol(hello)
Symbol(hello)
false

searches for existing symbols in a symbol registry with the given key and returns it, if found. Otherwise, a new symbol gets created in the global symbol registry with this key.
Retrieves a shared symbol key from the global symbol registry for the given symbol.
A symbol can be used with classes to define the properties in the class. The advantage is that if property is a symbol as shown below, the property can be accessed outside the package only if the symbol name is known. So, data is much encapsulated when symbols are used as properties.
<script>
   const COLOR = Symbol()
   const MODEL = Symbol()
   const MAKE = Symbol()
   class Bike {
      constructor(color ,make,model){
      this[COLOR] = color;
      this[MAKE] = make;
      this[MODEL] = model;
   }
}
let bike = new Bike('red','honda','cbr')
console.log(bike)
//property can be accessed ony if symbol name is known
console.log(bike[COLOR])
</script>
The output of the above code will be as stated below −
Bike {Symbol(): "red", Symbol(): "honda", Symbol(): "cbr"}
red


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
C program to print employee details using Structure

Here, we are given a structure containing details of employees. Our task is to create a C program to program to print employee details using structure.
The details of the employee that are in the structure are name, age, phone number, salary, and our program will print these details.
The details of the employees are pre-declared in the program and we will one by one print all the values. For this, we will create a function that will access the object of the structure and then print all the members of the structure using this object.
// C Program to print employee details using structure −
 Live Demo
#include <iostream>
using namespace std;
struct employee {
   int empId;
   string name;
   int age;
   string phone_number;
   int salary;
};
void displayDeitals(struct employee emp[], int n) {
   cout<<"\n\n --- Employee "<<n+1<<" ---- \n";
   cout<<"Employee ID: "<<emp[n].empId<<endl;
   cout<<"Employee name: "<<emp[n].name<<endl;
   cout<<"Employee age:"<<emp[n].age<<endl;
   cout<<"Employee phone number: "<<emp[n].phone_number<<endl;
   cout<<"Employee salary : "<<emp[n].salary<<endl;
}
int main() {
   int n = 3;
   struct employee emp[4];
   emp[0].empId = 0121;
   emp[0].name = "Nupur";
   emp[0].age = 22;
   emp[0].phone_number = "942135439";
   emp[0].salary = 100000;
   emp[1].empId = 0322;
   emp[1].name = "Ramesh";
   emp[1].age = 41;
   emp[1].phone_number = "908564363";
   emp[1].salary = 50000;
   emp[2].empId = 023;
   emp[2].name = "Yash";
   emp[2].age = 45;
   emp[2].phone_number = "943299231";
   emp[2].salary = 250000;
   emp[3].empId = 0112;
   emp[3].name = "Zarin";
   emp[3].age = 35;
   emp[3].phone_number = "796892522";
   emp[3].salary = 300000;
   for(int i= 0; i<=n; i++)
   displayDeitals(emp, i);
   return 0;
}
--- Employee 1 ----
Employee ID: 81
Employee name: Nupur
Employee age: 22
Employee phone number: 942135439
Employee salary: 100000
--- Employee 2 ----
Employee ID: 210
Employee name: Ramesh
Employee age: 41
Employee phone number: 908564363
Employee salary: 50000
--- Employee 3 ----
Employee ID: 19
Employee name: Yash
Employee age: 45
Employee phone number: 943299231
Employee salary: 250000
--- Employee 4 ----
Employee ID: 74
Employee name: Zarin
Employee age: 35
Employee phone number: 796892522
Employee salary: 300000
How to use for loop in Python?

The for loop in Python is used to iterate over a number of elements or some specific integer range. The elements might be of an array, string or any other iterative object in Python.
The for loop is the most frequently used looping statement. Most of the programming questions we encounter make use of the for loop in its solution.
Python has for an range loop. It takes the two integer values which specify the range within which the variable must iterate. If only one integer parameter is specified, then the specified integer is taken as the end of the range and the starting is 0 by default.
for variable in range( starting value, end value)
for variable in range( end value)
Note: The for loop in Python iterates one less than the end value. This means that if the starting and end values are 1 and 5 respectively, then the loop will iterate for 1,2,3,4. The starting value is inclusive but the end value is not inclusive.
 Live Demo
for i in range(1,5):
   print(i,end=" ")
print()
for i in range(5):
   print(i,end=" ")
1 2 3 4
0 1 2 3 4
The for in range loop can take a third parameter -1, which specifies that the for loop will iterate in reverse order. The loop starts from starting value and iterates in decreasing order to the end value(not inclusive).
 Live Demo
for i in range(5,0,-1):
   print(i,end=" ")
5 4 3 2 1
The third parameter in the for loop can be modified to use for loop in different ways. The third parameter, in actual, specifies the steps the variable should jump. If not specified, it is 1 by default.
If the third parameter is negative, it specifies that the loop will iterate in reverse order.
The number of steps (jumps) backwards will be specified by this parameter.
If the parameter is positive, the loop will iterate in forward order. The number of steps forward will be specified by this parameter.
Let’s understand with the help of the below example.
 Live Demo
for i in range(0,11,2):
   print(i,end=" ")
print()
for i in range(10,-1,-2):
   print(i,end=" ")
0 2 4 6 8 10
10 8 6 4 2 0
This loop is used to iterate over a iterable object such as string or array. It cannot be used to iterate over some specific integer range.
for variable in iterable object
This loop iterates over all the elements of the iterable object one by one without taking into account their index. If indexes are needed, use for in range loop.
 Live Demo
st="Tutorials"
for i in st:
   print(i,end=" ")
print()
array=[2,4,6,8,10]
for i in array:
   print(i,end=" ")
print()
for i in range(len(array)):
   print(array[i],end=" ")
T u t o r i a l s
2 4 6 8 10
2 4 6 8 10
Note: As clear from the above example, the variable in for in loop holds the elements of the iterable object one by one, whereas the variable in for in range loop holds the indexes of the elements.
SQLSERVER Tryit Editor v1.0

SELECT FORMAT(123456789, '##-##-#####');
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Difference b/w getText() and getAttribute() in Selenium WebDriver?

The differences between getText() and getAttribute() methods are described below. The getText() method returns the innerText of an element. The text which is visible on the page along with sub elements. It ignores all leading and trailing spaces.
The getAttribute() method fetches the text contained by an attribute in an html document. If a value is not set for an attribute, null value is returned. The attribute is passed as a parameter to the method.
So the getText() method gives the text present between the start and end html tags (which is not hidden by CSS) and the getAttribute() method identifies the key value pairs within the html tags.
In the above html code, style is an attribute whose value can be obtained from getAttribute() method. If we apply the getText() method on that element, we shall get the text.
Code Implementation with getText().
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class GetTextMethd{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://www.tutorialspoint.com/videotutorials/subscription.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElements(By.cssSelector("h2"));
      // extract text with getText()
      System.out.println("getText() method:" + l.getText());
      driver.quit();
   }
}
Code Implementation with getAttribute().
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class GetAttributeMethd{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://www.tutorialspoint.com/videotutorials/subscription.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElements(By.cssSelector("h2"));
      // get style attribute with getAttribute()
      System.out.println("getAttribute() method:" + l.getAttribute("style"));
      driver.quit();
   }
}
UnionWith Method in C#

Use the UnionWith method in C# to get the union of i.e. unique lements from two collections.
Let’s say the following are our Dictionary −
Dictionary < string, int > dict1 = new Dictionary < string, int > ();
dict1.Add("pencil", 1);
dict1.Add("pen", 2);
Dictionary < string, int > dict2 = new Dictionary < string, int > ();
dict2.Add("pen", 3);
Now, use HashSet and UnionWith to get the union −
HashSet < string > hSet = new HashSet < string > (dict1.Keys);
hSet.UnionWith(dict2.Keys);
The following is the complete code −
 Live Demo
using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {
      Dictionary < string, int > dict1 = new Dictionary < string, int > ();
      dict1.Add("pencil", 1);
      dict1.Add("pen", 2);

      Dictionary < string, int > dict2 = new Dictionary < string, int > ();
      dict2.Add("pen", 3);

      HashSet < string > hSet = new HashSet <string > (dict1.Keys);
      hSet.UnionWith(dict2.Keys);

      Console.WriteLine("Merged Dictionary...");
      foreach(string val in hSet) {
         Console.WriteLine(val);
      }
   }
}
Merged Dictionary...
pencil
pen
JavaScript Return an array that contains all the strings appearing in all the subarrays

We have an array of arrays like this −
const arr = [
   ['foo', 'bar', 'hey', 'oi'],
   ['foo', 'bar', 'hey'],
   ['foo', 'bar', 'anything'],
   ['bar', 'anything']
]
We are required to write a JavaScript function that takes in such array and returns an array that
contains all the strings which appears in all the subarrays.
Let's write the code for this function
const arr = [
   ['foo', 'bar', 'hey', 'oi'],
   ['foo', 'bar', 'hey'],
   ['foo', 'bar', 'anything'],
   ['bar', 'anything']
]
const commonArray = arr => {
   return arr.reduce((acc, val, index) => {
      return acc.filter(el => val.indexOf(el) !== -1);
   });
};
console.log(commonArray(arr));
The output in the console will be −
['bar']
How to join two lists in C#?

To join two lists, use AddRange() method.
Set the first list −
var list1 = new List < string > ();
list1.Add("Keyboard");
list1.Add("Mouse");
Set the second list −
var list2 = new List < string > ();
list2.Add("Hard Disk");
list2.Add("Pen Drive");
To concatenate both the lists −
lists1.AddRange(lists2);
The following is the complete code −
using System.Collections.Generic;
using System;

namespace Demo {
   public static class Program {
      public static void Main() {
         var list1 = new List < string > ();
         list1.Add("Keyboard");
         list1.Add("Mouse");

         Console.WriteLine("Our list1....");
         foreach(var p in list1) {
            Console.WriteLine(p);
         }

         var list2 = new List < string > ();
         list2.Add("Hard Disk");
         list2.Add("Pen Drive");

         Console.WriteLine("Our list2....");
         foreach(var p in list2) {
            Console.WriteLine(p);
         }

         list1.AddRange(list2);

         Console.WriteLine("Concatenated list....");
         foreach(var p in list1) {
            Console.WriteLine(p);
         }
      }
   }
}
Boolean.Equals(Boolean) Method in C#

The Boolean.Equals(Boolean) method in C# returns a value indicating whether this instance is equal to a specified Boolean object.
Following is the syntax −
public bool Equals (bool ob);
Above, ob is a Boolean value to compare to this instance.
Let us now see an example to implement the Boolean.Equals(Boolean) method −
using System;
public class Demo {
   public static void Main(){
      bool b1 = false;
      bool b2 = true;
      bool res = b1.Equals(b2);
      if (res == true)
         Console.Write("b1 equal to b2");
      else
         Console.Write("b1 not equal to b2");
   }
}
This will produce the following output −
b1 not equal to b2
How to sort an array with customized Comparator in Java?

Let’s say the following is our string array and we need to sort it:
String[] str = { "Tom", "Jack", "Harry", "Zen", "Tim", "David" };
Within the sort() method, create a customized comparator to sort the above string. Here, two strings are compared with each other and the process goes on:
Arrays.sort(str, new Comparator < String > () {
   public int compare(String one, String two) {
      int val = two.length() - one.length();
      if (val == 0)
      val = one.compareToIgnoreCase(two);
      return val;
   }
});
import java.util.Arrays;
import java.util.Comparator;
public class Demo {
   public static void main(String[] args) {
      String[] str = { "Tom", "Jack", "Harry", "Zen", "Tim", "David" };
      System.out.println("Array...");
      for (String res : str)
         System.out.print(res + " ");
      Arrays.sort(str, new Comparator<String>() {
         public int compare(String one, String two) {
            int val = two.length() - one.length();
            if (val == 0)
               val = one.compareToIgnoreCase(two);
            return val;
         }
      });
      System.out.println("\nSorted array...");
      for (String res : str)
      System.out.print(res + " ");
   }
}
Array...
Tom Jack Harry Zen Tim David
Sorted array...
David Harry Jack Tim Tom Zen
Adding an element in an array using Javascript

Adding an element to an array can be done using different functions for different positions.
This can be accomplished using the push method. For example,
let veggies = ["Onion", "Raddish"];
veggies.push("Cabbage");
console.log(veggies);
This will give the output −
["Onion", "Raddish", "Cabbage"]
You can also use this to push multiple items at the same time as it supports a variable number of
arguments. For example,
let veggies = ["Onion", "Raddish"];
veggies.push("Cabbage", "Carrot", "Broccoli");
console.log(veggies);
This will give the output −
["Onion", "Raddish", "Cabbage", "Carrot", "Broccoli"]
This can be accomplished using the unshift method. For example,
let veggies = ["Onion", "Raddish"];
veggies.unshift("Cabbage");
console.log(veggies);
This will give the output −
["Cabbage", "Onion", "Raddish"]
You can also use this to unshift multiple items at the same time as it supports a variable number of
arguments. For example,
let veggies = ["Onion", "Raddish"];
veggies.unshift("Cabbage", "Carrot", "Broccoli");
console.log(veggies);
This will give the output −
["Cabbage", "Carrot", "Broccoli", "Onion", "Raddish"]
Sometimes you need to add an element to a given position in an array. JavaScript doesn't support it out of the box. So we need to create a function to be able to do that. We can add it to the Array prototype so that we can use it directly on the object.
Array.prototype.insert = function(data, position) {
   if (position >= this.length) {
      this.push(data)
      // Put at the end if position is more than total length of array
   } else if (position <= 0) {
      this.unshift(data)
      // Put at the start if position is less than or equal to 0
   } else {
      // Shift all elements to right
      for (let i = this.length; i >= position; i--) {
         this[i] = this[i - 1];
      }
      this[position] = data;
   }
}

let arr = [1, 2, 3, 4];
arr.insert(-1, 2);
console.log(arr);
This will give the output −
[1, 2, -1, 3, 4]
Now the insert method is available on every array object you create.
You can also use the splice method to insert elements at given positions. For example,
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
console.log(months);
This will give the output:
['Jan', 'Feb', 'March', 'April', 'June']
The first argument of the method is the index we want to remove elements from or insert elements into. The second argument is the number of elements we want to remove. And the third argument onwards are the values we would like to insert into the array.
What is the usage of zerofill in a MySQL field?

Zerofill pads the displayed value of the field with zeros up to the display width specified in the column definition. For example, if column is set int(8), therefore the width is 8. If the number is let’s say 4376, then zero will be padded on the left for total width i.e. 8 −
00004376
Let us first create a table −
mysql> create table DemoTable
-> (
-> Number int(8) zerofill
-> );
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(10);
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable values(1234);
Query OK, 1 row affected (0.20 sec)

mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.47 sec)

mysql> insert into DemoTable values(678965);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+
| Number   |
+----------+
| 00000010 |
| 00001234 |
| 00000001 |
| 00678965 |
+----------+
4 rows in set (0.00 sec)
How to automate gmail login process using selenium webdriver in java?

We can automate the Gmail login process using Selenium webdriver in Java. To perform this task, first we have to launch the Gmail login page and locate the email, password and other elements with the findElement method and then perform actions on them.
Let us have the look at the Gmail login page −
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
public class GmailLogin{
   public static void main(String[] args) {
      System.setProperty("webdriver.gecko.driver",
      "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
      WebDriver driver = new FirefoxDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://accounts.google.com/signin");
      //identify email
      WebElement l = driver
      .findElement(By.name("identifier"));
      l.sendKeys("abc@gmail.com");
      WebElement b = driver
      .findElement(By.className("VfPpkd-LgbsSe"));
      b.click();
      //identify password
      WebElement p = driver
      .findElement(By.name("password"));
      p.sendKeys("123456");
      b.click();
      //close browser
      driver.close();
   }
}
Does Java support default parameter values for a method?

Java does not support the concept of default parameter however, you can achieve this using
Using method overloading if you define method with no arguments along with parametrized methods. Then you can call a method with zero arguments.
In Java methods parameters accept arguments with three dots. These are known as variable arguments. Once you use variable arguments as a parameter method, while calling you can pass as many number of arguments to this method (variable number of arguments) or, you can simply call this method without passing any arguments.
Live Demo
public class Sample {
   void demoMethod(String... args) {
      for (String arg : args) {
         System.out.println(arg);
      }
   }
   public static void main(String args[] ) {
      new Sample().demoMethod("ram", "rahim", "robert");
      new Sample().demoMethod("krishna", "kasyap");
      new Sample().demoMethod();
   }
}
ram
rahim
robert
krishna
kasyap
Python string | hexdigits - GeeksforGeeks

16 Oct, 2018
In Python3, string.hexdigits is a pre-initialized string used as string constant. In Python, string.hexdigits will give the hexadecimal letters ‘0123456789abcdefABCDEF’.
Syntax : string.hexdigits
Parameters : Doesn’t take any parameter, since it’s not a function.
Returns : Return all hexadecimal digit letters.
Note : Make sure to import string library function inorder to use string.hexdigits
Code #1 :
# import string library function import string     # Storing the value in variable result result = string.hexdigits     # Printing the value print(result) 
Output :
0123456789abcdefABCDEF
 
Code #2 : Given code checks if the string input has only hexadecimal digit letters
# importing string library function import string      # Function checks if input string # has only hexdigits or not def check(value):     for letter in value:                      # If anything other than hexdigit         # letter is present, then return         # False, else return True         if letter not in string.hexdigits:             return False    return True     # Driver Code input1 = "0123456789abcdef"print(input1, "--> ",  check(input1))      input2 = "abcdefABCDEF"print(input2, "--> ", check(input2))      input3 = "abcdefghGEEK"print(input3, "--> ", check(input3)) 
Output:
0123456789abcdef -->  True
abcdefABCDEF -->  True
abcdefghGEEK -->  False
Applications :The string constant hexdigits can be used in many practical applications. Let’s see a code explaining how to use digits to generate strong random passwords of given size.
# Importing random to generate # random string sequence import random     # Importing string library function import string     def rand_pass(size):             # Takes random choices from     # string.hexdigits     generate_pass = ''.join([random.choice(string.hexdigits)                         for n in range(size)])                                 return generate_pass     # Driver Code  password = rand_pass(10) print(password)  
Output:
e497FEe2bC
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Program to find nth term in Look and Say Sequence in Python

Suppose we have a number n we have to generate nth term in “Look and Say” sequence. This is a sequence whose few terms are like below −
1
11
21
1211
111221
The string will be read like
1 (One)
11 (One 1) So read the previous 1, and say “One 1”
21 (Two 1) So read the previous 11, and say “Two 1”
1211 (One 2 one 1) So read the previous 21, and say “One 2 one 1”
111221 (One 1 one 2 two 1) So read the previous 1211, and say “One 1 one 2 two 1”
Suppose we have a number n, 1 <= n < = 30, then we have to generate nth term.
To solve this, we will follow this approach −
set s := “1”
if n = 1, then return s
for i := 2 to n + 1j := 0temp := empty stringcurr = empty string and count := 0while j < length of s, doif curr is empty string, thencurr := s[j], count := 1 and increase j by 1else if curr is s[j], thenincrease count and j by 1otherwise:temp := temp + count as string + currcurr = empty stringcount := 0temp := temp + count as string + curr
j := 0
temp := empty string
curr = empty string and count := 0
while j < length of s, doif curr is empty string, thencurr := s[j], count := 1 and increase j by 1else if curr is s[j], thenincrease count and j by 1otherwise:temp := temp + count as string + currcurr = empty stringcount := 0
if curr is empty string, thencurr := s[j], count := 1 and increase j by 1
curr := s[j], count := 1 and increase j by 1
else if curr is s[j], thenincrease count and j by 1
increase count and j by 1
otherwise:temp := temp + count as string + currcurr = empty stringcount := 0
temp := temp + count as string + curr
curr = empty string
count := 0
temp := temp + count as string + curr
return s
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def solve(self, n):
      s = "1"
      if n == 1:
         return s
      for i in range(2,n+1):
         j = 0
         temp = ""
         curr = ""
         count = 0
         while j <len(s):
            if curr =="":
               curr=s[j]
               count=1
               j+=1
            elif curr == s[j]:
               count+=1
               j+=1
            else:
               temp+= str(count) + curr
               curr=""
               count = 0
               temp+=str(count) + curr
               s=temp
         return s
ob = Solution()
n = 5
print(ob.solve(n))
5
"111221"
Python - Check if frequencies of all characters of a string are different

In this article we will see how to find the frequency of each character in a given string. Then see if two or more characters have the same frequency in the given string or not. We will accomplish this in two steps. In the first program we will just find out the frequency of each character.
Here we find the frequency of each character in the given input screen. We declare a empty dictionary and then add each character as a string. We also assign keys to each of the character to create the key-value pair needed by the dictionary.
 Live Demo
in_string = "She sells sea shells"
dic1 = {}
for k in in_string:
   if k in dic1.keys():
      dic1[k]+=1
   else:
      dic1[k]=1
print(dic1)
for k in dic1.keys():
   print(k, " repeats ",dic1[k]," time's")
Running the above code gives us the following result −
{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}
S repeats 1 time's
h repeats 2 time's
e repeats 4 time's
  repeats 3 time's
s repeats 5 time's
l repeats 4 time's
a repeats 1 time's
Next we extend the above program to find out the frequency for each unique character. If the unique value of the frequency is greater than one, then we conclude that not all characters have same frequency.
 Live Demo
in_string = "She sells sea shells"
dic1 = {}
for k in in_string:
   if k in dic1.keys():
      dic1[k]+=1
   else:
      dic1[k]=1
print(dic1)
u_value = set( val for udic in dic1 for val in (dic1.values()))
print("Number of Unique frequencies: ",len(u_value))
if len(u_value) == 1:
   print("All character have same frequiency")
else:
   print("The characters have different frequencies.")
Running the above code gives us the following result −
{'S': 1, 'h': 2, 'e': 4, ' ': 3, 's': 5, 'l': 4, 'a': 1}
Number of Unique frequencies: 5
The characters have different frequencies.
Check how many rows are in a MySQL database table?

To know how many rows are in a ySQL database table, you need to use aggregate function COUNT(*).
The syntax is as follows
SELECT COUNT(*) FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table CountRowsDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > Name varchar(20)
   - > );
Query OK, 0 rows affected (0.78 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.15 sec)
mysql> insert into CountRowsDemo(Name) values('Sam');
Query OK, 1 row affected (0.25 sec)
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountRowsDemo(Name) values('Mike');
Query OK, 1 row affected (0.21 sec)
mysql> insert into CountRowsDemo(Name) values('David');
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.11 sec)
mysql> insert into CountRowsDemo(Name) values(NULL);
Query OK, 1 row affected (0.09 sec)
mysql> insert into CountRowsDemo(Name) values('Carol');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from CountRowsDemo;
The following is the output
+----+-------+
| Id | Name  |
+----+-------+
|  1 | NULL  |
|  2 | Sam   |
|  3 | NULL  |
|  4 | Mike  |
|  5 | David |
|  6 | NULL  |
|  7 | NULL  |
|  8 | Carol |
+----+-------+
8 rows in set (0.00 sec)
Now let us run the following query to count rows from a table
mysql> select count(*) AS TotalRows from CountRowsDemo;
The following is the output
+-----------+
| TotalRows |
+-----------+
|         8 |
+-----------+
1 row in set (0.00 sec)
How to check if a table exists in MySQL and create if it does not already exist?

If you try to create a table and the table name already exist then MySQL will give a warning message. Let us verify the concept.
Here, we are creating a table that already exist −
mysql> CREATE TABLE IF NOT EXISTS DemoTable
   (
   CustomerId int,
   CustomerName varchar(30),
   CustomerAge int
   );
Query OK, 0 rows affected, 1 warning (0.05 sec)
The table name DemoTable is already present. Let us check the warning message.
Following is the query −
mysql> show warnings;
This will produce the following output i.e. the warning message −
+-------+------+------------------------------------+
| Level | Code | Message                            |
+-------+------+------------------------------------+
| Note  | 1050 | Table 'demotable' already exists   |
+-------+------+------------------------------------+
1 row in set (0.00 sec)
Let us change the table name and create a table that does not already exist −
mysql> CREATE TABLE IF NOT EXISTS DemoTable2
   (
   CustomerId int,
   CustomerName varchar(20),
   CustomerAge int
   );
Query OK, 0 rows affected (0.56 sec)
Table created successfully above since it does not already exist.
Following is the query to insert records in the table using insert command −
mysql> insert into DemoTable2 values(101,'Chris',23);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable2 values(102,'Robert',24);
Query OK, 1 row affected (0.12 sec)
Following is the query to display records from the table using select command −
mysql> select *from DemoTable2;
This will produce the following output
+------------+--------------+-------------+
| CustomerId | CustomerName | CustomerAge |
+------------+--------------+-------------+
| 101        | Chris        | 23          |
| 102        | Robert       | 24          |
+------------+--------------+-------------+
2 rows in set (0.00 sec)
How to find the group-wise correlation coefficient in R?

If we have two continuous and one categorical column in an R data frame then we can find the correlation coefficient between continuous values for the categories in the categorical column. For this purpose, we can use by function and pass the cor function with the spearman method as shown in the below examples.
Consider the below data frame:
Live Demo
> x1<-sample(c("A","B","C"),20,replace=TRUE)
> y1<-rnorm(20,1,0.24)
> z1<-rpois(20,2)
> df1<-data.frame(x1,y1,z1)
> df1
  x1   y1    z1
1 A 1.1155324 2
2 C 0.9801564 3
3 B 0.9116162 1
4 A 0.8406772 3
5 C 0.8009355 2
6 A 0.9331637 2
7 B 1.0642089 1
8 B 1.1633515 0
9 B 1.1599037 5
10 B 1.0509981 2
11 B 0.7574267 1
12 B 0.8456225 1
13 B 0.8926751 2
14 B 0.6074419 3
15 C 0.7999792 0
16 A 1.0685236 2
17 B 0.9756677 3
18 A 0.9495342 0
19 C 1.0109747 2
20 A 0.9090985 4
Finding the correlation between y1 and z1 for categories in x1:
> by(df1,df1$x1,FUN=function(x) cor(df1$y1,df1$z1,method="spearman"))
df1$x1: A
[1] 0.03567607
df1$x1: B
[1] 0.03567607

df1$x1: C
[1] 0.03567607
Live Demo
> x2<-sample(c("India","China","France"),20,replace=TRUE)
> y2<-rexp(20,0.335)
> z2<-runif(20,2,10)
> df2<-data.frame(x2,y2,z2)
> df2
    x2      y2         z2
1 France 2.31790394 2.649538
2 China 10.61012173 8.340615
3 France 5.00085220 6.602884
4 France 1.67707140 7.722530
5 India 9.60663732 9.837268
6 France 1.46030289 5.370930
7 France 10.44614704 9.035748
8 India 0.39506766 6.318701
9 China 1.83071453 7.282782
10 China 0.23080001 7.210144
11 India 2.27763766 9.233019
12 China 18.21276888 9.928614
13 France 1.72085517 9.176826
14 India 4.77786071 8.899026
15 China 8.55501571 7.240147
16 China 0.19832026 5.641800
17 India 0.03113389 6.928705
18 China 0.56958471 3.496314
19 China 0.72728737 6.903436
20 India 8.73571474 5.286486
Finding the correlation between y2 and z2 for categories in x2:
> by(df2,df2$x2,FUN=function(x) cor(df2$y2,df2$z2,method="spearman"))
df2$x2: China
[1] 0.487218
df2$x2: France
[1] 0.487218

df2$x2: India
[1] 0.487218