code-rag-bench/online-tutorials huggingface dataset:
How to select specific columns in MongoDB query?

To select specific columns, you can ignore the rest of them i.e. to hide those columns, set them to 0. Let us first create a collection with documents −
> db.demo415.insertOne({"ClientName":"Robert","ClientCountryName":"US"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e72329db912067e57771adc")
}
> db.demo415.insertOne({"ClientName":"David","ClientCountryName":"UK"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7232acb912067e57771add")
}
> db.demo415.insertOne({"ClientName":"Bob","ClientCountryName":"AUS"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e7232b4b912067e57771ade")
}
Display all documents from a collection with the help of find() method −
> db.demo415.find();
This will produce the following output −
{ "_id" : ObjectId("5e72329db912067e57771adc"), "ClientName" : "Robert", "ClientCountryName" : "US" }
{ "_id" : ObjectId("5e7232acb912067e57771add"), "ClientName" : "David", "ClientCountryName" : "UK" }
{ "_id" : ObjectId("5e7232b4b912067e57771ade"), "ClientName" : "Bob", "ClientCountryName" : "AUS" }
Following is the query to select specific columns. Here, we have ignored rest of the columns to display the column “ClientCountryName” −
> db.demo415.find({},{_id:0,ClientName:0});
This will produce the following output −
{ "ClientCountryName" : "US" }
{ "ClientCountryName" : "UK" }
{ "ClientCountryName" : "AUS" }
How to find the percentage of missing values in an R data frame?

To find the percentage of missing values in an R data frame, we can use sum function with the prod function. For example, if we have a data frame called df that contains some missing values then the percentage of missing values can be calculated by using the command: (sum(is.na(df))/prod(dim(df)))*100
 Live Demo
Consider the below data frame −
x1<−sample(c(NA,1,5,10,15),20,replace=TRUE)
x2<−sample(c(NA,rnorm(5)),20,replace=TRUE)
x3<−sample(c(NA,100,200),20,replace=TRUE)
x4<−sample(c(NA,0,1),20,replace=TRUE)
df1<−data.frame(x1,x2,x3,x4)
df1
x1 x2 x3 x4
1 10 −0.7734719 NA 1
2 10 −1.8581538 200 0
3 10 −0.7734719 100 1
4 1 NA 200 1
5 5 −1.8581538 100 NA
6 10 −0.7734719 100 0
7 5 −1.8581538 200 0
8 10 −0.3188769 NA NA
9 5 −0.7734719 NA 1
10 NA 1.0589124 200 0
11 NA −0.7734719 200 0
12 15 −1.8581538 NA 1
13 5 −0.7734719 200 NA
14 5 −0.7734719 200 0
15 10 −0.3188769 200 1
16 15 −1.8581538 NA 1
17 NA −1.8581538 200 0
18 15 1.0589124 NA 1
19 10 −0.7734719 NA 1
20 5 −1.8581538 100 NA
Finding the percentage of missing values in df1 −
(sum(is.na(df1))/prod(dim(df1)))*100
[1] 18.75
 Live Demo
y1<−sample(c(NA,rpois(2,1)),20,replace=TRUE)
y2<−sample(c(NA,rpois(2,1)),20,replace=TRUE)
y3<−sample(c(NA,rpois(2,5)),20,replace=TRUE)
y4<−sample(c(NA,rpois(2,3)),20,replace=TRUE)
y5<−sample(c(NA,rpois(2,2)),20,replace=TRUE)
y6<−sample(c(NA,rpois(2,5)),20,replace=TRUE)
df2<−data.frame(y1,y2,y3,y4,y5,y6)
df2
y1 y2 y3 y4 y5 y6
1 2 NA NA 2 NA 5
2 1 NA 9 NA 2 5
3 1 1 9 NA 3 5
4 NA 0 6 3 3 5
5 2 1 NA 3 2 NA
6 2 NA 6 NA 3 NA
7 NA 0 6 2 3 NA
8 2 NA NA 3 NA 5
9 1 1 9 NA 3 NA
10 2 NA NA 3 NA 2
11 NA 1 6 3 3 NA
12 2 NA 6 3 2 2
13 NA NA 6 2 2 NA
14 2 0 6 NA NA NA
15 2 0 6 3 NA 5
16 NA 1 9 3 2 2
17 2 NA 6 3 2 NA
18 2 1 6 3 NA 2
19 NA 1 NA NA 3 2
20 2 NA 6 3 NA 5
Finding the percentage of missing values in df2 −
(sum(is.na(df2))/prod(dim(df2)))*100
[1] 34.16667
How to Use str_replace in R? - GeeksforGeeks

02 Dec, 2021
str_replace() is used to replace the given string with a particular value in R Programming Language. It is available in stringr library, so we have to load this library.
Syntax:
str_replace( "replacing string", "replaced string")
where,
replacing string is the string to be replaced
replaced string is the final string
We will use str_replace in dataframe. We can replace particular string in dataframe column by using the following syntax
str_replace(dataframe$column_name, "replacing string", "replaced string")
where,
dataframe is the input dataframe
column_name is the column in the dataframe
Example:
R
# load the librarylibrary(stringr) # create a dataframe with 3 columnsdata = data.frame(name1=c('java', 'python', 'php'),                  name2=c('html', 'css', 'jsp'),                  marks=c(78, 89, 77)) # replace the java with oops in name1 columnprint(str_replace(data$name1, "java", "oops")) # replace the htmlwith oops in name2 columnprint(str_replace(data$name2, "html", "HTML5"))
Output:
[1] "oops"   "python" "php"   
[1] "HTML5" "css"   "jsp"  
We can replace the string with “” empty.
Syntax:
str_replace(dataframe$column_name, "replacing string", "")
Example :
R
# load the librarylibrary(stringr) # create a dataframe with 3 columnsdata = data.frame(name1=c('java', 'python', 'php'),                  name2=c('html', 'css', 'jsp'),                  marks=c(78, 89, 77)) # replace the java with nothing in name1 columnprint(str_replace(data$name1, "java", "")) # replace the html with nothing in name2 columnprint(str_replace(data$name2, "html", ""))
Output:
[1] ""       "python" "php"   
[1] ""    "css" "jsp"
We can replace multiple string in a particular column by using str_replace_all method.
Syntax:
str_replace_all(dataframe$column_name, c(“string1” = “new string”,.................,”stringn” = “new string”))
Example:
R
# load the librarylibrary(stringr) # create a dataframe with 3 columnsdata = data.frame(name1=c('java', 'python', 'php'),                  name2=c('html', 'css', 'jsp'),                  marks=c(78, 89, 77)) # replace the java with oops and php with sql in name1 columnprint(str_replace_all(data$name1, c("java"="oops", "php"="sql"))) # replace the html with r  and jsp with servletsin name2 columnprint(str_replace_all(data$name2, c("html"="R", "jsp"="servlets")))
Output:
[1] "oops"   "python" "sql"   
[1] "R"        "css"      "servlets"
kapoorsagar226
sumitgumber28
Picked
R-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
How to change the order of bars in bar chart in R ?
Class and Static Variables in C#

Static variables are used for defining constants because their values can be retrieved by invoking the
class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.
 Live Demo
using System;

namespace StaticVarApplication {
   class StaticVar {
      public static int num;

      public void count() {
         num++;
      }
      public int getNum() {
         return num;
      }
   }
   class StaticTester {
      static void Main(string[] args) {
         StaticVar s1 = new StaticVar();
         StaticVar s2 = new StaticVar();

         s1.count();
         s1.count();
         s1.count();

         s2.count();
         s2.count();
         s2.count();

         Console.WriteLine("Variable num for s1: {0}", s1.getNum());
         Console.WriteLine("Variable num for s2: {0}", s2.getNum());
         Console.ReadKey();
      }
   }
}
Variable num for s1: 6
Variable num for s2: 6
Class variables are the attributes of an object (from design perspective) and they are kept private to
implement encapsulation. These variables can only be accessed using the public member functions.
Let us see an example −
 Live Demo
using System;

namespace BoxApplication {
   class Box {
      private double length; // Length of a box
      private double breadth; // Breadth of a box
      private double height; // Height of a box

      public void setLength( double len ) {
         length = len;
      }
      public void setBreadth( double bre ) {
         breadth = bre;
      }
      public void setHeight( double hei ) {
         height = hei;
      }
      public double getVolume() {
         return length * breadth * height;
      }
   }
   class Boxtester {
      static void Main(string[] args) {
         Box Box1 = new Box(); // Declare Box1 of type Box
         Box Box2 = new Box();
         double volume;

         // Declare Box2 of type Box
         // box 1 specification
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);

         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}" ,volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);
         Console.ReadKey();
      }
   }
}
Volume of Box1 : 210
Volume of Box2 : 1560
MySQL query to count rows with mutual relation using JOIN?

For this, use aggregate function COUNT(*). Let us first create a table −
mysql> create table DemoTable1543
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (1.36 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1543 values(57,60);
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable1543 values(60,68);
Query OK, 1 row affected (0.38 sec)
mysql> insert into DemoTable1543 values(90,98);
Query OK, 1 row affected (0.36 sec)
mysql> insert into DemoTable1543 values(98,90);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1543;
This will produce the following output −
+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     57 |     60 |
|     60 |     68 |
|     90 |     98 |
|     98 |     90 |
+--------+--------+
4 rows in set (0.00 sec)
Here is the query to count rows with mutual relation like the number 90 in both the columns −
mysql> select count(*) from DemoTable1543 tbl1
   -> join DemoTable1543 tbl2
   -> on tbl1.Value2=tbl2.Value1
   -> where tbl1.Value1=90 and tbl2.Value2=90;
This will produce the following output −
+----------+
| count(*) |
+----------+
|        1 |
+----------+
1 row in set (0.00 sec)
How to convert a color integer to a hex String in Android?

This example demonstrates how do I in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/textView"
      android:textSize="24sp"
      android:textStyle="bold"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextView textView = findViewById(R.id.textView);
      int intColor = -16895234;
      String hexColor = Integer.toHexString(intColor).substring(2);
      textView.setText("#"+hexColor);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code
Bootstrap .has-error class

The has-error class allows you to set error for input.
You can try to run the following code to implement the has-error class
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <form class = "form-horizontal" role = "form">
         <div class = "form-group has-error">
            <label class = "col-sm-2 control-label" for = "inputError">
               Input with error
            </label>
            <div class = "col-sm-10">
               <input type = "text" class = "form-control" id = "inputError">
            </div>
         </div>
      </form>
   </body>
</html>
bits.Sub() Function in Golang with Examples - GeeksforGeeks

28 Apr, 2020
The bits.Sub() Function in Golang is used to find the difference of a, b and borrow, i.e. diff = a – b – borrow. Here the borrow must be 0 or 1; otherwise, the behavior is undefined. To access this function, one needs to imports the math/bits package in the program. The return value of the borrowOutput will be always 0 or 1 in any case.
Syntax:
func Sub(a, b, borrow uint) (diff, borrowOut uint)

Parameters: This function takes three parameters of uint type, i.e., a, b, and borrow. The value of borrow parameter is either 1 or 0
Return Value: This function return two values of uint type, i.e., diff and borrowOut. Here diff contains the result of a – b – borrow and borrowOut is either 1 or 0.
Example 1:
// Golang program to illustrate bits.Sub() Function package main     import (     "fmt"    "math/bits")     // Main function func main() {         // Finding diff and borrowOu     // of the specified numbers     // Using Sub() function     nvalue_1, borrowOut := bits.Sub(4, 3, 0)     fmt.Println("Diff:", nvalue_1)     fmt.Println("BorrowOut :", borrowOut )     } 
Output:
Diff: 1
BorrowOut : 0

Example 2:
// Golang program to illustrate bits.Sub() Functionpackage main  import (    "fmt"    "math/bits")  // Main functionfunc main() {      // Finding diff and borrowOut    // of the specified numbers    // Using Sub() function      var a, b, borrow uint = 10, 5, 1    Diff, borrowOut := bits.Sub(a, b, borrow)    fmt.Println("Number 1:", a)    fmt.Println("Number 2:", b)    fmt.Println("Borrow :", borrow)    fmt.Println("Diff:", Diff)    fmt.Println("BorrowOut :", borrowOut)  }
Output:
Number 1: 10
Number 2: 5
Borrow : 1
Diff: 4
BorrowOut : 0

Golang-bits
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
How to Split a String in Golang?
Arrays in Go
How to Trim a String in Golang?
How to convert a string in lower case in Golang?
Golang Maps
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
Slices in Golang
Inheritance in GoLang
Erlang - list_to_tuple

This method is to convert a list to a tuple.
list_to_tuple(list)

list − This is the list which needs to be converted to a tuple.
list − This is the list which needs to be converted to a tuple.
Returns a tuple based on the list provided.
-module(helloworld). 
-export([start/0]). 

start() -> 
   io:fwrite("~w",[list_to_tuple([1,2,3])]).
The output of the above program is as follows
{1,2,3}

 Print
 Add Notes
 Bookmark this page
How to display the JList items from top to bottom and left to right in Java?

For this, set the layout orientation to the following −
setLayoutOrientation(JList.VERTICAL_WRAP);
The following is an example to display the JList items from top to bottom and left to right −
package my;
import java.awt.BorderLayout;
import java.util.ArrayList ;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel(new BorderLayout());
      List<String> myList = new ArrayList<>(10);
      for (int index = 0; index < 20; index++) {
         myList.add("List Item " + index);
      }
      final JList<String> list = new JList<String>(myList.toArray(new String[myList.size()]));
      JScrollPane scrollPane = new JScrollPane();
      scrollPane.setViewportView(list);
      list.setLayoutOrientation(JList.VERTICAL_WRAP);
      panel.add(scrollPane);
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.setSize(500, 250);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }
}
GATE | GATE CS 2020 | Question 49 - GeeksforGeeks

26 May, 2021
Which one of the following predicate formulae is NOT logically valid ?
Note that W is a predicate formula without any free occurrence of x.(A) ∀x(p(x) ∨ W) ≡ ∀x(px) ∨ W(B) ∃x(p(x) ∧ W) ≡ ∃xp(x) ∧ W(C) ∀x(p(x) → W) ≡ ∀xp(x) → W(D) ∃x(p(x) → W) ≡ ∀xp(x) → WAnswer: (C)Explanation: ∀x (p(x) → W) ≡ ∀x p(x) → W is wrong.
Since ∀x [p(x) → W]
≡ ∀x [¬p(x) ∨ W]
≡ ∀x (¬p(x) ∨ W
≡ ¬(∃x p(x)) ∨ W
≡ ∃x p(x) → W 
Option (C) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2015 (Set 1) | Question 42
Add a temporary column with a value in MySQL?

You can add a temporary column with value with the help of the following syntax −
select yourColumnName1,yourColumnName2,.....N ,yourTemporaryColumnValue as yourTemporaryColumnName from yourTableName;
To add a temporary column with a value, let us create a table. The following is the query −
mysql> create table TemporaryColumnWithValueDemo
   −> (
      −> StudentId int,
      −> StudentName varchar(100)
   −> );
Query OK, 0 rows affected (0.59 sec)
Inserting some records in the table. The query to insert records are as follows −
mysql> insert into TemporaryColumnWithValueDemo values(101,'John');
Query OK, 1 row affected (0.13 sec)

mysql> insert into TemporaryColumnWithValueDemo values(102,'Johnson');
Query OK, 1 row affected (0.15 sec)

mysql> insert into TemporaryColumnWithValueDemo values(103,'Carol');
Query OK, 1 row affected (0.14 sec)

mysql> insert into TemporaryColumnWithValueDemo values(104,'Sam');
Query OK, 1 row affected (0.16 sec)
Display all records inserted above. The query to display all records is as follows −
mysql> select *from TemporaryColumnWithValueDemo;
The following is the output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       101 | John        |
|       102 | Johnson     |
|       103 | Carol       |
|       104 | Sam         |
+-----------+-------------+
4 rows in set (0.00 sec)
Now here is the query to add a column with a t.emporary value. The query is as follows −
mysql> select StudentId,StudentName,'M.I.T.' as TempCollegeName from TemporaryColumnWithValueDemo;
The following is the output. The temporary column added successfully −
+-----------+-------------+-----------------+
| StudentId | StudentName | TempCollegeName |
+-----------+-------------+-----------------+
|       101 | John        | M.I.T.          |
|       102 | Johnson     | M.I.T.          |
|       103 | Carol       | M.I.T.          |
|       104 | Sam         | M.I.T.          |
+-----------+-------------+-----------------+
4 rows in set (0.00 sec)
Python - Convert 1D list to 2D list of variable length

A list in python is normally a 1D list where the elements are listed one after another. But in a 2D list we have list nested inside the outer list. In this article we will see how to create a 2D list from a given 1D list. We also supply the values for the number of elements inside the 2D list to the program.
In this approach we will create a for loop to loop through each element in the 2D list and use it as an index for the new list to be created. We keep incrementing the index value by starting it at zero and adding it to the the element we receive from the 2D list.
# Given list
listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

# Length of 2D lists needed
len_2d = [ 2, 4]

#Declare empty new list
res = []
def convert(listA, len_2d):
   idx = 0
   for var_len in len_2d:
      res.append(listA[idx: idx + var_len])
      idx += var_len
convert(listA, len_2d)
print("The new 2D lis is: \n",res)
Running the above code gives us the following result −
The new 2D lis is:
[[1, 2], [3, 4, 5, 6]]
The islice function can be used to slice a given list with certain number of elements as required by the 2D list. So here week looked through each element of the 2D list and use that value 2 slice the original list. We need itertools package to use the islice function.
from itertools import islice
# Given list
listA = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat']

# Length of 2D lists needed
len_2d = [ 3, 2]

# Use islice
def convert(listA, len_2d):
   res = iter(listA)
   return [list(islice(res,i)) for i in len_2d]
res = [convert(listA, len_2d)]
print("The new 2D lis is: \n",res)
Running the above code gives us the following result −
The new 2D lis is:
[[['Sun', 'Mon', 'Tue'], ['Wed', 'Thu']]]
How to measure time taken by a function in java ?

08 Jan, 2018
We can measure the time taken by a function in Java with the help of java.lang.System.currentTimeMillis() method. This method returns the current time in millisecond. We can call this method at the beginning and at the end of function and by the difference we measure the time taken by the function.
import java.io.*;  public class Time {    public static void main(String[] args)    {        // starting time        long start = System.currentTimeMillis();               // start of function          count_function(10000000);          // end of function          // ending time        long end = System.currentTimeMillis();        System.out.println("Counting to 10000000 takes " +                                    (end - start) + "ms");    }      // A dummy function that runs a loop x times    public static void count_function(long x)    {        System.out.println("Loop starts");        for (long i = 0; i < x; i++)            ;        System.out.println("Loop ends");    }}
Output:
Loop starts
Loop ends
Counting to 10000000 takes 8ms

How to measure time taken by a program in C?
java-puzzle
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Fill an empty matrix in R

21 Apr, 2021
In this article, we will discuss how to fill the empty matrix with values in R Programming Language. First, let’s create an empty matrix.
Syntax:
matrix_name[row,column]=value.
Where, row and column are the numbers in which the value is occupied.
Example:
R
# create empty matrix.a<-matrix(nrow=4,ncol=4)  # display matrixprint(a)  # filling empty matrix with value at # 2nd row and 4 th columna[2,4]=4print(a)  # create empty matrix.a<-matrix(nrow=4,ncol=4)  # filling empty matrix with value at # 4th columna[,4]=4print(a)  # create empty matrix.a<-matrix(nrow=4,ncol=4)  # filling empty matrix with value at # 4th rowa[4,]=4print(a)
Output:
We can replace with same value for all empty value in a matrix, by using [,].
Example
R
# create empty matrix.a<-matrix(nrow=4,ncol=4)  # display matrixprint(a)  # replace empty matrix with 5 valuea[,]=5print(a)
Output:
Even a range can be inserted.
Example
R
# create empty matrix.a<-matrix(nrow=4,ncol=4)  # display matrixprint(a)  # replace empty matrix with  # 1 to 16 valuesa[,]=1:16print(a)
Output:
Picked
R Matrix-Programs
R-Matrix
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Get total keys in dictionary

02 Aug, 2019
Sometimes, while working with Python dictionaries, one can come in a problem in which one needs to get the exact number of keys that are present in whole of dictionaries including ones that are nested. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using recursion + items() + sum() + len()This task can be performed using the combination of above functions. In this, we check if a nested is a dictionary of not and then extract it’s keys using items() and then sum of find length of it using respective functions.
# Python3 code to demonstrate working of# Get total keys in dictionary# Using recursion + items() + sum() + len()  # Utility function to perform task def total_keys(test_dict):    return (0 if not isinstance(test_dict, dict)     else len(test_dict) + sum(total_keys(val) for val in test_dict.values()))  # Initialize dictionarytest_dict = { 'gfg' : { 'is'  : 1, 'best' : { 'for' : {'geeks' :4}}}}  # Printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using recursion + items() + sum() + len()# Get total keys in dictionaryres = total_keys(test_dict)  # printing result print("Number of keys in dictionary is : " + str(res))
The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}Number of keys in dictionary is : 5
 
Method #2 : Using yield() + recursionThis task can also be performed using the combination of above functions. This is just another way to perform this task. The intermediate result is returned, and hence this is a more efficient method of the 2.
# Python3 code to demonstrate working of# Get total keys in dictionaryfrom collections import Mapping  # Utility function to perform taskdef total_keys(test_dict):     for key, value in test_dict.items():         if isinstance(value, Mapping):             yield from total_keys(value)     yield len(test_dict)  # Initialize dictionarytest_dict = { 'gfg' : { 'is'  : 1, 'best' : { 'for' : {'geeks' :4}}}}  # Printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Using yield() + recursion# Get total keys in dictionaryres = sum(total_keys(test_dict))  # printing result print("Number of keys in dictionary is : " + str(res))
The original dictionary is : {‘gfg’: {‘best’: {‘for’: {‘geeks’: 4}}, ‘is’: 1}}Number of keys in dictionary is : 5
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery | dblclick() with Examples

12 Feb, 2019
The dblclick() is an inbuilt method in jQuery which is used to trigger the double-click event to occur. This method occurs when the selected element will be double clicked.Syntax:
$(selector).dblclick(args);

Here “selector” is the selected element.Parameter: It accepts an optional parameter “args” which specifies a function that do a specific task after double clicking.Return Value: It returns some function when the selected element is double-clicked.
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/                  jquery/3.3.1/jquery.min.js"></script>    <script>        <!-- jQuery code to show dbclick method -->        $(document).ready(function() {                    $("div").click(function() {                        $("div").dblclick();                    });    </script>    <style>        div {            display: block;            width: 370px;            padding: 10px;            font-size: 25px;            border: 2px solid green;        }    </style></head>  <body>    <!-- click on this div and a pop will appear -->    <div ondblclick="alert('dblclick event has been triggered')                 ">Click me to trigger dblclick event</div></body>  </html>
Output:Before double clicking the “Click me to trigger dblclick event” button-After double clicking the “Click me to trigger dblclick event” button-
Code #2:In the below code, function is passed to dblclick() method.
<html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/    jquery/3.3.1/jquery.min.js"></script>    <script>        <!-- jQuery code to show dbclick method -->        $(document).ready(function() {            $("button").dblclick(function() {                $("p").fadeOut();            });        });    </script>    <style>        p {            display: block;            padding: 20px;            color: gree;            width: 300px;            border: 2px solid green;            font-size: 25px;        }    </style></head>  <body>    <p>Welcome to GeeksforGeeks !</p>    <!-- click on this button and above paragraph             will disappear -->    <button> Click Me! </button></body>  </html>
Output:Before double clicking the “Click Me” button-
After double clicking the “Click Me” button-
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert epoch Date to meaningful JavaScript date?

Dates in JavaScript take milliseconds since epoch. If the epoch in milliseconds is 1514789449605, then let us convert it into a meaningful JavaScript date.
Live Demo
<html>
   <head>
      <title>JavaScript Dates</title>
   </head>
   <body>
      <script>
         var val ="/Date(1514789449605)/";
         var myDate = new Date( parseFloat( val.substr(6 )));
         document.write("Converted Date:"+ (myDate.getMonth() + 1) + "/" +
                      myDate.getDate() + "/" + myDate.getFullYear() + " " +
                      myDate.getHours() + ":" + myDate.getMinutes() + ":" +
                      myDate.getSeconds()
         );
      </script>
   </body>
</html>
Converted Date:1/1/2018 12:20:49
Java single line comments.

// is used for single line comments.
Live Demo
public class MyFirstJavaProgram {
   public static void main(String[] args) {
      // This is a single line comment.
      System.out.println("Hello World");
   }
}
How to Create Dummy Variables in Python with Pandas? - GeeksforGeeks

16 Jan, 2022
A dataset may contain various type of values, sometimes it consists of categorical values. So, in-order to use those categorical value for programming efficiently we create dummy variables. A dummy variable is a binary variable that indicates whether a separate categorical variable takes on a specific value. 
Explanation:
As you can see three dummy variables are created for the three categorical values of the temperature attribute. We can create dummy variables in python using get_dummies() method.
Syntax: pandas.get_dummies(data, prefix=None, prefix_sep=’_’,)
Parameters:
data= input data i.e. it includes pandas data frame. list . set . numpy arrays etc.
prefix= Initial value
prefix_sep= Data values separation.
Return Type: Dummy variables.
Step-by-step Approach:
Import necessary modules
Consider the data
Perform operations on data to get dummies
Example 1: 
Python3
# import required modulesimport pandas as pdimport numpy as np # create datasetdf = pd.DataFrame({'Temperature': ['Hot', 'Cold', 'Warm', 'Cold'],                   }) # display datasetprint(df) # create dummy variablespd.get_dummies(df)
Output:
Example 2:
Consider List arrays to get dummies
Python3
# import required modulesimport pandas as pdimport numpy as np # create datasets = pd.Series(list('abca')) # display datasetprint(s) # create dummy variablespd.get_dummies(s)
Output:
Example 3: 
Here is another example, to get dummy variables.
Python3
# import required modulesimport pandas as pdimport numpy as np # create datasetdf = pd.DataFrame({'A': ['hello', 'vignan', 'geeks'],                   'B': ['vignan', 'hello', 'hello'],                   'C': [1, 2, 3]}) # display datasetprint(df) # create dummy variablespd.get_dummies(df)
Output:
sooda367
saurabh1990aror
Python-numpy
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
GATE | GATE CS 2008 | Question 50 - GeeksforGeeks

28 Jun, 2021
Which of the following statements are true?
I. Every left-recursive grammar can be converted to a 
   right-recursive grammar and vice-versa
II. All  productions can be removed from any context-free 
    grammar by suitable transformations
III. The language generated by a context-free grammar all of whose 
     productions are of the form X --> w or X --> wY (where, w is a string of 
     terminals and Y is a non-terminal), is always regular
IV. The derivation trees of strings generated by a context-free grammar 
    in Chomsky Normal Form are always binary trees 
(A) I, II, III and IV(B) II, III and IV only(C) I, III and IV only(D) I, II and IV onlyAnswer: (C)Explanation:  I is true as we can always remove left recursion from any given grammar.(For better understanding, see this.) II is false as we can remove all epsilon productions only if grammar doesn’t contain epsilon in the language. III is true as it is the definition of regular grammar.(For better understanding, see type-3 languages in this article.) IV is true because in chomsky normal form, all the productions are of type X -> YZ or X -> t, where X, Y, Z are variables and ‘t’ is terminal string. When we draw the derivation tree for every node there are at most 2 children. That’s why Derivation trees of grammars in chomsky normal form are Binary trees.(For better understanding, see this.) Thus, C is the correct choice.Quiz of this Question
GATE-CS-2008
GATE-GATE CS 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Ruby | String delete() Method - GeeksforGeeks

13 Dec, 2019
delete is a String class method in Ruby which is used to return a copy of the given string with all characters in the intersection of its arguments deleted.
Syntax: str.delete(parameter_list)
Parameters: Here, str is the given string and parameter_list are the specified characters.
Returns: A new copy of the string with all characters in the intersection of its arguments deleted.
Example 1:
# Ruby program to demonstrate # the delete method        # Taking a string and # using the methodstr = "String Counting"puts str.delete "ing"
Output:
Str Cout

Example 2:
# Ruby program to demonstrate # the delete method        # Taking a string and # using the methodstr = "String Counting"puts str.delete "ing", "^n"  str2 = "Ruby Method\\r\\n"  puts str2.delete "\\"
Output:
Strn Countn
Ruby Methodrn

Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
Ruby | String capitalize() Method
How to create dynamic length array with numbers and sum the numbers using JavaScript ? - GeeksforGeeks

25 Aug, 2021
In JavaScript, array is a single variable that is used to store different elements. It is often used when we want to store list of elements and access them by a single variable. Unlike most languages where array is a reference to the multiple variable, in JavaScript array is a single variable that stores multiple elements.
JavaScript Arrays are Dynamic in nature it means, the length of array can be modified at run time (when necessary). Array length can be specified after declaring array as shown in the following example.
Example:
Javascript
// Declare an array of undefined sizevar arr = []; // Set array length to 10arr.length = 10; // Print the length to consoleconsole.log(arr);
Output: 
Array(10) [ <10 empty slots> ]
As you can see, this method explain the array with 10 empty slots. The following example declares an array and take input elements using prompt dynamically and print the sum of all elements and display the result sing alert.
Example:
Javascript
(function () {         // Declare an array of undefined size    var arr = [];     // Notice how the size of array    // is not dot defined     // Initiating loop to iterate    // for inputs    for (var i = 0; i < 10; i++) {         // Feeding integer inputs to array        arr[i] = +prompt('Enter number');                 // Calculate sum of array elements        var sum = arr.reduce(function (a, b) {            return a + b;        }, 0)    }    alert(sum);})();
Output:
Input : 1 2 3 4 5 6 7 8 9 10
Output :55
kk773572498
JavaScript-Misc
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Python | Pandas Index.values - GeeksforGeeks

20 Feb, 2019
Pandas Index is an immutable ndarray implementing an ordered, sliceable set. It is the basic object which stores the axis labels for all pandas objects.
Pandas Index.values attribute return an array representing the data in the given Index object.
Syntax: Index.values
Parameter : None
Returns : an array
Example #1: Use Index.values attribute to return an array representing the data in the given Index object.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index(['Melbourne', 'Sanghai', 'Lisbon', 'Doha', 'Moscow', 'Rio'])  # Print the indexprint(idx)
Output :
Now we will use Index.values attribute to return an array representing the data in the given Index object.
# return an arrayresult = idx.values  # Print the resultprint(result)
Output :As we can see in the output, the Index.values attribute has successfully returned an array representing the data of the given Index object. Example #2 : Use Index.values attribute to return an array representing the data in the given Index object.
# importing pandas as pdimport pandas as pd  # Creating the indexidx = pd.Index([900 + 3j, 700 + 25j, 620 + 10j, 388 + 44j, 900])  # Print the indexprint(idx)
Output :
Now we will use Index.values attribute to return an array representing the data in the given Index object.
# return an arrayresult = idx.values  # Print the resultprint(result)
Output :As we can see in the output, the Index.values attribute has successfully returned an array representing the data of the given Index object.
Python pandas-indexing
Python-pandas
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Year plus(TemporalAmount) method in Java with Examples - GeeksforGeeks

25 Feb, 2019
The plus(TemporalAmount) method of Year class is used to return a copy of this year after adding the specified amount of TemporalAmount to this Year object. An exception is thrown, If the specified unit cannot be added to Year. The TemporalAmount passed is created from the Period object. This instance is immutable and unaffected by this method call.
Syntax:
public Year plus(TemporalAmount amountToadd)

Parameters: This method accepts only one parameter TemporalAmount which represents the amount to add to Year object.
Return Value: This method returns a Year based on this year with the specified amount added.
Exception: This method throws following Exceptions:
DateTimeException – This exception is thrown if the addition cannot be made.
ArithmeticException – This exception is thrown if numeric overflow occurs.
Below programs illustrate the plus(TemporalAmount amountToadd) method:
Program 1:
// Java program to demonstrate// Year.plus(TemporalAmount amountToadd) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {        // create a Year object        Year year = Year.of(2019);          // print instance        System.out.println("Year :"                           + year);          // create temporalAmount object from period class        // passing temporalAmount to        // plus() method        Year value            = year.plus(                Period.ofYears(12));          // print result        System.out.println("Value after addition: "                           + value);    }}
Year :2019
Value after addition: 2031

Program 2:
// Java program to demonstrate// Year.plus(TemporalAmount amountToadd) method  import java.time.*;import java.time.temporal.*;  public class GFG {    public static void main(String[] args)    {        // create a Year object        Year year = Year.of(2019);          // print instance        System.out.println("Year :"                           + year);          // create temporalAmount object from period class        // passing temporalAmount to        // plus() method        Year value            = year.plus(                Period.ofYears(120));          // print result        System.out.println("Value after addition: "                           + value);    }}
Year :2019
Value after addition: 2139

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

02 Jun, 2021
Pandas have an options system that lets you customize some aspects of its behavior, display-related options being those the user is most likely to adjust. Let us see how to see the value of a specified option.
Syntax : pandas.get_option(pat)Parameters : 
pat : Regexp which should match a single option.
Returns : Value of the option Raises : OptionError if no such option exists  
Example 1 : Fetching the value of maximum and minimum number of columns and rows that can be displayed.  
Python3
# importing the moduleimport pandas as pd # fetching maximum number of# columns that can be displayedprint("The value of max_columns : " +      str(pd.get_option("display.max_columns"))) # fetching maximum number of# rows that can be displayedprint("The value of max_rows : " +      str(pd.get_option("display.max_rows"))) # fetching minimum number of# rows that can be displayedprint("The value of min_rows : " +      str(pd.get_option("display.min_rows")))
Output :  
Output may vary.
Example 2 : Fetching the attributes related to Excel files. 
Python3
# importing the moduleimport pandas as pd # default Excel reader engine for ‘ods’ filesprint("The default Excel reader engine for ‘ods’ files : " +      str(pd.get_option("io.excel.ods.reader"))) # default Excel reader engine for ‘xls’ filesprint("The default Excel reader engine for ‘xls’ files : " +      str(pd.get_option("io.excel.xls.reader"))) # default Excel writer engine for ‘xls’ filesprint("The default Excel writer engine for ‘xls’ files : " +      str(pd.get_option("io.excel.xls.writer"))) # default Excel reader engine for ‘xlsb’ filesprint("The default Excel reader engine for ‘xlsb’ files : " +      str(pd.get_option("io.excel.xlsb.reader"))) # default Excel reader engine for ‘xlsm’ filesprint("The default Excel reader engine for ‘xlsm’ files : " +      str(pd.get_option("io.excel.xlsm.reader"))) # default Excel writer engine for ‘xlsm’ filesprint("The default Excel writer engine for ‘xlsm’ files : " +      str(pd.get_option("io.excel.xlsm.writer"))) # default Excel reader engine for ‘xlsm’ filesprint("The default Excel reader engine for ‘xlsx’ files : " +      str(pd.get_option("io.excel.xlsx.reader"))) # default Excel writer engine for ‘xlsx’ filesprint("The default Excel writer engine for ‘xlsx’ files : " +      str(pd.get_option("io.excel.xlsx.writer")))
Output :  
 
anikaseth98
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python Remove Duplicates from a List - GeeksforGeeks

19 Dec, 2020
The job is simple. We need to take a list, with duplicate elements in it and generate another list which only contains the element without the duplicates in them.
Examples:  
Input : [2, 4, 10, 20, 5, 2, 20, 4]
Output : [2, 4, 10, 20, 5]

Input : [28, 42, 28, 16, 90, 42, 42, 28]
Output : [28, 42, 16, 90]
We can use not in on list to find out the duplicate items. We create a result list and insert only those that are not already not in. 
Python3
# Python code to remove duplicate elementsdef Remove(duplicate):    final_list = []    for num in duplicate:        if num not in final_list:            final_list.append(num)    return final_list     # Driver Codeduplicate = [2, 4, 10, 20, 5, 2, 20, 4]print(Remove(duplicate))
Output:  
[2, 4, 10, 20, 5]
Easy Implementation:
A quick way to do the above using set data structure from the python standard library (Python 3.x implementation is given below)  
Python3
duplicate = [2, 4, 10, 20, 5, 2, 20, 4]print(list(set(duplicate)))
Output:  
[2, 4, 10, 20, 5] 
codeslord
sathiya1622
Python list-programs
python-list
Python
python-list
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
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists