code-rag-bench/online-tutorials huggingface dataset:
How to add a vector to each row of a matrix in R?

To add a vector to reach row of a matrix, we can use addition sign (+) and create the repetition of the vector up to the number of rows in the matrix. For example, if we have a matrix called M then a vector say v can be added to each row of M by using the command −
M+rep(v,each=nrow(M))
Consider the below matrix and the vector −
Live Demo
> M1<-matrix(rpois(40,2),nrow=20)
> M1
      [,1] [,2]
 [1,]    3    2
 [2,]    3    3
 [3,]    4    2
 [4,]    5    1
 [5,]    3    1
 [6,]    2    2
 [7,]    1    2
 [8,]    2    1
 [9,]    3    2
[10,]    0    1
[11,]    3    4
[12,]    2    6
[13,]    3    1
[14,]    4    0
[15,]    1    3
[16,]    1    0
[17,]    1    1
[18,]    0    1
[19,]    1    3
[20,]    2    0
Adding v1 to rows in M1 −
> M1+rep(v1,each=nrow(M1))
      [,1] [,2]
 [1,]    4    3
 [2,]    4    4
 [3,]    5    3
 [4,]    6    2
 [5,]    4    2
 [6,]    3    3
 [7,]    2    3
 [8,]    3    2
 [9,]    4    3
[10,]    1    2
[11,]    4    5
[12,]    3    7
[13,]    4    2
[14,]    5    1
[15,]    2    4
[16,]    2    1
[17,]    2    2
[18,]    1    2
[19,]    2    4
[20,]    3    1
Live Demo
> M2<-matrix(rnorm(60),ncol=3)
> M2
             [,1]        [,2]        [,3]
 [1,] -1.16459899  0.04276452 -0.38747561
 [2,]  0.50198231  1.40818681  1.34047754
 [3,] -0.83571273  0.15311835 -0.66026732
 [4,] -1.04751005  0.68401101  0.36614494
 [5,] -0.13906013 -0.08104307  1.58938567
 [6,]  0.79923477  0.13871823  1.19483957
 [7,] -0.70957734 -1.22610985  0.79431236
 [8,] -0.61919335 -1.67900016  0.75673298
 [9,]  0.02131366  0.59198453 -0.51860397
[10,] -0.92114971 -0.94043054 -0.66674705
[11,] -0.26933585  0.61537773  1.18988144
[12,]  2.11994998 -0.62014441 -0.97012363
[13,] -0.45798423  0.92096389  0.74603167
[14,] -0.51599135 -0.01450992 -1.84365984
[15,] -0.29866554  0.99900886 -0.55598877
[16,] -0.91226758 -1.63915166 -0.20200339
[17,]  0.40107684  1.79162856 -0.02759807
[18,]  0.44712300 -0.07322323 -0.15221520
[19,]  0.15838286 -1.50611267 -0.07117655
[20,]  0.53166819 -0.99748658 -0.54070065
> v2<-c(100,100,100)
Adding v2 to rows in M2 −
> M2+rep(v2,each=nrow(M2))
           [,1]      [,2]      [,3]
 [1,]  98.83540 100.04276  99.61252
 [2,] 100.50198 101.40819 101.34048
 [3,]  99.16429 100.15312  99.33973
 [4,]  98.95249 100.68401 100.36614
 [5,]  99.86094  99.91896 101.58939
 [6,] 100.79923 100.13872 101.19484
 [7,]  99.29042  98.77389 100.79431
 [8,]  99.38081  98.32100 100.75673
 [9,] 100.02131 100.59198  99.48140
[10,]  99.07885  99.05957  99.33325
[11,]  99.73066 100.61538 101.18988
[12,] 102.11995  99.37986  99.02988
[13,]  99.54202 100.92096 100.74603
[14,]  99.48401  99.98549  98.15634
[15,]  99.70133 100.99901  99.44401
[16,]  99.08773  98.36085  99.79800
[17,] 100.40108 101.79163  99.97240
[18,] 100.44712  99.92678  99.84778
[19,] 100.15838  98.49389  99.92882
[20,] 100.53167  99.00251  99.45930
Count of n digit numbers whose sum of digits equals to given sum in C++

Given a positive number as the number of digits and a sum. The goal is to find all d digit numbers that have sum of digits equal to the input sum. The numbers having leading zeros will not be considered as d digit numbers.
The ranges are digits between 1 to 100 and sum between 1 and 500.
For Example
Input - digits = 3, digi_sum = 3
Output - Count of n digit numbers whose sum of digits equals to given sum are: 6
Explanation - Three digit numbers having sum of digits as 3 are:
102, 111, 120, 201, 210, and 300. 
Input -  digits = 4  digi_sum = 2
Output - Count of n digit numbers whose sum of digits equals to given sum are: 4
Explanation - Four digit numbers having sum of digits as 2 are :
1001, 1010, 1100, and 2000.
In this approach we will traverse from the first d digit number and find the first number whose sum of digits is equal to the given sum. Then increment numbers by 9 until we find the sum of digits more than the given sum. Once a number having digit sum greater than input sum is found then increment the number by 1 and find the next number with sum as input sum. Repeat this process till the last d digit number.
Take the number of digits and sum of digits as input.
Function digits_sum(int digits, int digi_sum) takes both input values and returns the count of n digit numbers whose sum of digits equals a given sum.
Take the initial count as 0.
Take the first number as Left = pow(10, digits - 1). And the last number of the range as right = pow(10, digits) - 1 ( i.e  10 and 99 for digits=2 ).
Using a while loop traverse from left to right.
Take first=0 and last=i.
For each i ( last ), take the rightmost digit ( last % 10 ) and add to first. Reduce last by 10 for the next iteration.
If first becomes equal to digi_sum then increment count and update i by 9 for next iteration.
Otherwise increment i by 1.
At the end of all loops we will have count as numbers that have digit sum equal to digi_sum.
Return count as result.
Live Demo
#include <bits/stdc++.h>
using namespace std;

int digits_sum(int digits, int digi_sum) {
   int count = 0;
   int Left = pow(10, digits - 1);
   int right = pow(10, digits) - 1;
   int i = Left;
   while (i <= right) {
      int first = 0;
      int last = i;
      while (last != 0) {
         first = first + last % 10;
         last = last / 10;
      }
      if (first == digi_sum) {
         count++;
         i = i + 9;
      } else {
         i++;
      }
   }
   return count;
}
int main() {
   int digits = 5;
   int digi_sum = 7;
   cout << "Count of n digit numbers whose sum of digits equals to given sum are: " << digits_sum(digits, digi_sum);
   return 0;
}
If we run the above code it will generate the following output −
Count of n digit numbers whose sum of digits equals to given sum are: 5
Clojure - contains?

Finds out whether the set contains a certain element or not.
Following is the syntax.
(contains? setofelements searchelement)

Parameters − ‘setofelements’ is the set of elements. ‘Searchelement’ is the element which needs to be searched for in the list.
Return Value − Returns true if the element exists in the set or false if it dosen’t.
Following is an example of contains? in Clojure.
(ns clojure.examples.example
   (:gen-class))
(defn example []
   (println (contains? (set '(3 2 1)) 2))
   (println (contains? (set '(3 2 1)) 5)))
(example)
The above code produces the following output.
true
false

 Print
 Add Notes
 Bookmark this page
Wrap the flex items with CSS

To wrap the flex items, use the flex-wrap property. You can try to run the following code to implement the flex-wrap property
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .mycontainer {
            display: flex;
            background-color: #D7BDE2;
            flex-wrap: wrap;
         }
         .mycontainer > div {
            background-color: white;
            text-align: center;
            line-height: 40px;
            font-size: 25px;
            width: 100px;
            margin: 5px;
         }
      </style>
   </head>
   <body>
      <h1>Quiz</h1>
      <div class = "mycontainer">
         <div>Q1</div>
         <div>Q2</div>
         <div>Q3</div>
         <div>Q4</div>
         <div>Q5</div>
         <div>Q6</div>
         <div>Q7</div>
         <div>Q8</div>
         <div>Q9</div>
      </div>
   </body>
</html>
C++ program for hashing with chaining

Hashing is the method by which we can map any length data element to a fixed size key. hashing works as key-value pairs.
Hashing function is the function that does the mapping in a hash map. the data elements that are given as input to the Hash Function may get same hash key. In this case the elements may overlap. To avoid overlapping of elements which have the same hash key the concept of chaining was introduced.
In order to create a hashmap we need hashing function that will define the index value of the data element.
We have a hash table, with n buckets. To insert a node into a hash table, we are given a hash function as
hashIndex = key % noOfBuckets
Now, we will use this hash function and calculate the hashindex of every inserted value to the hashmap.
Insert element and calculate the hashIndex of given key value and then insert the new node to the end of the list.
Insert element and calculate the hashIndex of given key value and then insert the new node to the end of the list.
To delete a node, we will calculate the hash index and in the bucket corresponding to hash Index we will search for the element in the bucket and remove it.
To delete a node, we will calculate the hash index and in the bucket corresponding to hash Index we will search for the element in the bucket and remove it.
 Live Demo
#include<iostream>
#include <list>
using namespace std;
class Hash{
   int BUCKET;
   list < int >*table;
   public:
   Hash (int V);
   void insertItem (int x);
   void deleteItem (int key);
   int hashFunction (int x){
      return (x % BUCKET);
   }
   void displayHash ();
};
Hash::Hash (int b){
   this->BUCKET = b;
   table = new list < int >[BUCKET];
}
void Hash::insertItem (int key){
   int index = hashFunction (key);
   table[index].push_back (key);
}
void Hash::deleteItem (int key){
   int index = hashFunction (key);
   list < int >::iterator i;
   for (i = table[index].begin (); i != table[index].end (); i++){
   if (*i == key)
      break;
   }
   if (i != table[index].end ())
      table[index].erase (i);
}
void Hash::displayHash (){
   for (int i = 0; i < BUCKET; i++){
      cout << i;
      for (auto x:table[i])
      cout << " --> " << x;
      cout << endl;
   }
}
 int main (){
   int a[] = { 5, 12, 67, 9, 16 };
   int n = 5;
   Hash h (7);
   for (int i = 0; i < n; i++)
   h.insertItem (a[i]);
   h.deleteItem (12);
   h.displayHash ();
   return 0;
}
0
1
2 --> 9 --> 16
3
4 --> 67
5 --> 5
6
How to leave space with EmptyBorder in Java Swing

Llet us first create a JPanel and set titled border:
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder("Demo Panel"));
Now to create Empty Border:
JPanel panel2 = new JPanel(new BorderLayout());
panel2.add(panel, BorderLayout.CENTER);
panel2.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
The following is an example to leave space with EmptyBorder in Java Swing:
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JPanel panel = new JPanel();
      panel.setBorder(BorderFactory.createTitledBorder("Demo Panel"));
      JPanel panel2 = new JPanel(new BorderLayout());
      panel2.add(panel, BorderLayout.CENTER);
      panel2.setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));
      panel2.setPreferredSize(new Dimension(700, 350));
      JFrame frame = new JFrame("Set Space");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setContentPane(panel2);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }
}
How to pass a variable into a jQuery attribute-contains selector?

Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.
You can try to run the following code to learn how to pass a variable into a jQuery attribute-contains selector:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(function() {
  var testString = "vp-485858383";
  $('[data-vp*="id: ' +  testString + '"]').css('color', 'blue');
});
</script>
</head>

<body>
<div data-vp='{
   id: vp-485858383,
   customTwo: "test"
}'>
Hello World
</div>
</body>
</html>
How to find the most frequent factor value in an R data frame column?

To find the most frequent factor value in an R data frame column, we can use names function with which.max function after creating the table for the particular column. This might be required while doing factorial analysis and we want to know which factor occurs the most.
Check out the below examples to understand how it can be done.
Following snippet creates a sample data frame −
Factor_1<-factor(sample(LETTERS[1:4],20,replace=TRUE))
df1<-data.frame(Factor_1)
df1
The following dataframe is created −
 Factor_1
1  B
2  D
3  B
4  D
5  C
6  D
7  D
8  C
9  C
10 C
11 C
12 C
13 C
14 C
15 A
16 D
17 C
18 C
19 B
20 C
To find which factor occurs the most in df1, add the following code to the above snippet −
Factor_1<-factor(sample(LETTERS[1:4],20,replace=TRUE))
df1<-data.frame(Factor_1)
names(which.max(table(df1$Factor_1)))
If you execute all the above given snippets as a single program, it generates the following output: −
[1] "C"

Following snippet creates a sample data frame −
Factor_2<-factor(sample(c("Male","Female"),20,replace=TRUE))
df2<-data.frame(Factor_2)
df2
The following dataframe is created −
   Factor_2
1  Female
2  Female
3  Male
4  Female
5  Male
6  Male
7  Female
8  Male
9  Male
10 Female
11 Female
12 Female
13 Female
14 Male
15 Female
16 Female
17 Female
18 Female
19 Female
20 Female
To find which factor occurs the most in df2, add the following code to the above snippet −
Factor_2<-factor(sample(c("Male","Female"),20,replace=TRUE))
df2<-data.frame(Factor_2)
names(which.max(table(df2$Factor_2)))
If you execute all the above given snippets as a single program, it generates the following output: −
[1] "Female"

Following snippet creates a sample data frame −
Factor_3<-factor(sample(c("Hot","Cold","Warm","Lukewarm"),20,replace=TRUE))
df3<-data.frame(Factor_3)
df3
The following dataframe is created −
   Factor_3
1  Hot
2  Lukewarm
3  Warm
4  Warm
5  Cold
6  Hot
7  Hot
8  Warm
9  Warm
10 Warm
11 Hot
12 Lukewarm
13 Cold
14 Lukewarm
15 Lukewarm
16 Lukewarm
17 Hot
18 Lukewarm
19 Lukewarm
20 Lukewarm
To find which factor occurs the most in df3, add the following code to the above snippet −
Factor_3<-factor(sample(c("Hot","Cold","Warm","Lukewarm"),20,replace=TRUE))
df3<-data.frame(Factor_3)
names(which.max(table(df3$Factor_3)))
If you execute all the above given snippets as a single program, it generates the following output: −
[1] "Lukewarm"
Twitter Sentiment Analysis using Python

In this article, we will be learning about the twitter sentimental analysis. We will register for twitter oAuth API, install all the dependencies and finally write our sentimental analyzer script.
An API(Application programming interface) is a gateway that allows you to access some servers(Twitter) internal functionality.
The prerequisite is that we have a twitter account set up with a verified phone number.
After this, we visit the Twitter website and tap on the create a new app icon. Now we fill all the credentials i.e. name and accept the developer agreement and finally click on create.
Now our app is created, on the top menu, we will click on the keys tab. Here we will be obtaining our OAuth verification details and all the tokenizers.
Now let's install all the dependencies −
1. tweepy module :
>>> pip install tweepy
2. textblob module :
>>> pip install textblob
It is a module used in sentiment analysis. It contains an inbuilt method to calculate sentiments on a scale of -1 to 1.
"token.sentiment.polarity"
First, we need all the access tokenizer from the twitter application website as created initially −
#Twitter credentials for the app interface
consumer_key = 'xxxxx'
consumer_secret = 'xxxx'
access_key= 'xxxx'
access_secret = 'xxxx'
No, we need to authenticate the credentials via script. For that, we create an authentication variable auth.
auth =tweepy.OauthHandler(consumer_key,consumer_secret)
now we set the access token with the help of authentication variable
auth.set_access_token(access_token,access_token_secret)
Now we create an API variable to perform our operations
api=tweepy.API(auth)
we need to get the public tweets via search method and store it in the form of a list.
public_tweet=api.search('Tutorialspoint')
for tweet in public_tweet:
   print(tweet.text)
   analysis=TextBlob(tweet.text)
   print(analysis)
In the output, we observe to thing i.e. the polarity and subjectivity.
Polarity measures how positive or negative some text is.
Subjectivity measures the text that how much it is opinionated as compared to factual.
With the help of this sentiment analyzer, we are able to understand and extract human feelings out of the data.
Golang Program to reverse a given linked list.

Approach to solve this problem
Step 1 − Define a method that accepts the head of a linked list.
Step 2 − If head == nil, return; else, call ReverseLinkedList, recursively.
Step 3 − Print head.value at the end.
 Live Demo
package main
import "fmt"
type Node struct {
   value int
   next *Node
}
func NewNode(value int, next *Node) *Node{
   var n Node
   n.value = value
   n.next = next
   return &n
}
func TraverseLinkedList(head *Node){
   fmt.Printf("Input Linked List is: ")
   temp := head
   for temp != nil {
      fmt.Printf("%d ", temp.value)
      temp = temp.next
   }
   fmt.Println()
}
func ReverseLinkedList(head *Node){
   if head == nil{
      return
   }
   ReverseLinkedList(head.next)
   fmt.Printf("%d ", head.value)
}
func main(){
   head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
   TraverseLinkedList(head)
   fmt.Printf("Reversal of the input linked list is: ")
   ReverseLinkedList(head)
}
Input Linked List is: 30 10 40 40
Reversal of the input linked list is: 40 40 10 30
dir() Method in Python

The dir() function returns list of the attributes and methods of any object like functions , modules, strings, lists, dictionaries etc. In this article we will see how to use the dir() in different ways in a program and for different requirements.
When we print the value of the dir() without importing any other module into the program, we get the list of methods and attributes that are available as part of the standard library that is available when a python program is initialized.
Print(dir())
Running the above code gives us the following result −
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']
As we import additional modules and create variables, they get added to the current environment. Then those methods and attributes also become available in the print statement woth dir().
import math

x = math.ceil(10.03)
print(dir())
Running the above code gives us the following result −
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'x']
For specific modules we can find the methods and attributes contained in that module by passing it as parameter to the dir(). In the below example we see the methods available in the math module.
import math

print(dir(math))
Running the above code gives us the following result −
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', ...., 'nan', ... 'trunc']
We can also apply the dir() to a class which was user created rather than in-bulit and gets its attributes listed through dir().
 Live Demo
class moviecount:

   def __dir__(self):
      return ['Red Man','Hello Boy','Happy Monday']

movie_dtls = moviecount()

print(dir(movie_dtls))
Running the above code gives us the following result −
['Happy Monday', 'Hello Boy', 'Red Man']
VBScript Mid Function

The Mid Function returns a specified number of characters from a given input string.
Mid(String,start[,Length])

String, a Required Parameter. Input String from which the specified number of characters to be returned.
String, a Required Parameter. Input String from which the specified number of characters to be returned.
Start, a Required Parameter. An Integer, which Specifies starting position of the string.
Start, a Required Parameter. An Integer, which Specifies starting position of the string.
Length, an Optional Parameter. An Integer, which specifies the number of characters to be returned.
Length, an Optional Parameter. An Integer, which specifies the number of characters to be returned.
<!DOCTYPE html>
<html>
   <body>
      <script language = "vbscript" type = "text/vbscript">
         var = "Microsoft VBScript"
         document.write("Line 1 : " & Mid(var,2) & "<br />")
         document.write("Line 2 : " & Mid(var,2,5) & "<br />")
         document.write("Line 3 : " & Mid(var,5,7) & "<br />")

      </script>
   </body>
</html>
When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −
Line 1 : icrosoft VBScript
Line 2 : icros
Line 3 : osoft V


    63 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Connecting to and Disconnecting from the MySQL Server

A MySQL user name needs to be provided when ‘mysql’ is invoked. Next a password has to be entered. If the server runs on a system which is not the same as that on which the user logs in, the host name also needs to be provided while trying to log in.
It is suggested to contact the administrator to find out the parameters that are required to connect to the server.
Once the parameters are determined, the below lines need to be sued to connect to the server −
shell> mysql −h host −u user −p
Enter the password: ***
Here, ‘host’ represents the name of the host where the MySQL server is running. The ‘user’ represents the user name of the MySQL account. The appropriate values are substituted in these places. The *** represents the password. This is entered when ‘mysql’ prompts ‘Enter the password’.
Once this is successful, some introductory information is displayed, and this is followed by ‘mysql>’ prompt.
shell> mysql −h host −u user −p
Enter password: ********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 25338 to server version: 8.0.25-standard

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql>
The ‘mysql’ prompt tells that ‘mysql’ is ready for the user to enter their SQL commands and execute it.
Note: If the user is trying to log in from the same machine where MySQL is running, the host name can be omitted, and the below line can be run instead:
shell> mysql −u user −p
When trying to connect, if a message like ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2), shows up, it indicates that the MySQL server daemon (Unix) or service (Windows) is not running currently. When this happens, the administrator has to be contacted.
Once the connection is successful, and you wish to disconnect, run the below lines of code −
mysql> QUIT
Bye
JavaScript String - constructor Property

A constructor returns a reference to the string function that created the instance's prototype.
Its syntax is as follows −
string.constructor

Returns the function that created this object's instance.
Try the following example.
<html>
   <head>
      <title>JavaScript String constructor Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = new String( "This is string" );
         document.write("str.constructor is:" + str.constructor); 
      </script>      
   </body>
</html>
str.constructor is: function String() { [native code] } 


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How do you automatically download a Pdf with Selenium Webdriver in Python?

We can automatically download a pdf with the Selenium webdriver in Python. A file is downloaded in the default path set in the Chrome browser. However, we can modify the path of the downloaded file programmatically in Selenium.
This is done with the help of the Options class. We have to create an object of this class and apply the add_experimental_option. We have to pass the parameters - prefs and the path where the pdf is to be downloaded to this method. Finally, this information has to be sent to the webdriver object.
Syntax
op = Options()
p = {"download.default_directory": "../pdf"}
op.add_experimental_option("prefs", p)
Code Implementation
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
#Options instance
op = Options()
#configure path of downloaded pdf file
p = {"download.default_directory": "../pdf"}
op.add_experimental_option("prefs", p)
#send browser option to webdriver object
driver = webdriver.Chrome(executable_path='../drivers/chromedriver', options=op)
#implicit wait
driver.implicitly_wait(0.8)
#url launch
driver.get("http://demo.automationtesting.in/FileDownload.html")
#browser maximize
driver.maximize_window()
#identify element
m = driver.find_element_by_id('pdfbox')
m.send_keys("infotest")
t = driver.find_element_by_id('createPdf')
t.click()
e = driver.find_element_by_id('pdf-link-to-download')
e.click()
#driver close
driver.close()
How to update MongoDB Object?

To update MongoDB object, use UPDATE(). Let us create a collection with documents −
> db.demo77.insertOne({"Details" : { "Score" : 78 } });
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bd6f371bf0181ecc4228a")
}
Display all documents from a collection with the help of find() method −
> db.demo77.find();
This will produce the following output −
{ "_id" : ObjectId("5e2bd6f371bf0181ecc4228a"), "Details" : { "Score" : 78 } }
Following is the query to update MongoDB object −
> db.demo77.update({'Details.Score':78},{$set:{'Details.Score':89}},{multi:true});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo77.find();
This will produce the following output −
{ "_id" : ObjectId("5e2bd6f371bf0181ecc4228a"), "Details" : { "Score" : 89 } }
How to destroy an object in Python?

A class implements the special method __del__(), called a destructor, that is invoked when the instance is about to be destroyed. This method might be used to clean up any non memory resources used by an instance.
This __del__() destructor prints the class name of an instance that is about to be destroyed −
#!/usr/bin/python

class Point:
   def __init__( self, x=0, y=0):
      self.x = x       self.y = y    def __del__(self):
      class_name = self.__class__.__name__       print class_name, "destroyed"
 pt1 = Point()
pt2 = pt1 pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result −
3083401324 3083401324 3083401324
Point destroyed
How to Filter Rows Based on Column Values with query function in Pandas? - GeeksforGeeks

11 Dec, 2020
In this article, let’s see how to filter rows based on column values. Query function can be used to filter rows based on column values. 
Consider below Dataframe:
Python3
import pandas as pd    data = [['A', 10], ['B', 15], ['C', 14], ['D', 12]] df = pd.DataFrame(data, columns = ['Name', 'Age'])df
Output: 
Our DataFrame 
Now, Suppose You want to get only persons that have Age >13.  We can use Query function of Pandas.
Python3
df.query("Age>13")
Output: 
Using Query with only 1 Column
Now, If you want multiple columns. For example, you want to have Age >13 and Name = C. Then,
Python3
df.query("Age>13 and Name=='C'")
Output:
Using multiple cols filter
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
Finding difference in Timestamps – Python Pandas

To find the difference in timestamps, we can use index operator i.e. the square brackets to find the difference. For timestamps, we need to also use abs(). At first, import the required library −
import pandas as pd
Create a DataFrame with 3 columns. We have two date columns with timestamp −
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],

      "Date_of_Purchase": [
         pd.Timestamp("2021-06-10"),
         pd.Timestamp("2021-07-11"),
         pd.Timestamp("2021-06-25"),
         pd.Timestamp("2021-06-29"),
         pd.Timestamp("2021-03-20"),
      ],
      "Date_of_Service": [
         pd.Timestamp("2021-11-10"),
         pd.Timestamp("2021-12-11"),
         pd.Timestamp("2021-11-25"),
         pd.Timestamp("2021-11-29"),
         pd.Timestamp("2021-08-20"),
      ]
   })


Let us now find the difference between timestamps from both the date columns −
timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])
Following is the code −
import pandas as pd

# create a dataframe with 3 columns
dataFrame = pd.DataFrame(
   {
      "Car": ["Audi", "Lexus", "Tesla", "Mercedes", "BMW"],

      "Date_of_Purchase": [
         pd.Timestamp("2021-06-10"),
         pd.Timestamp("2021-07-11"),
         pd.Timestamp("2021-06-25"),
         pd.Timestamp("2021-06-29"),
         pd.Timestamp("2021-03-20"),
      ],
      "Date_of_Service": [
         pd.Timestamp("2021-11-10"),
         pd.Timestamp("2021-12-11"),
         pd.Timestamp("2021-11-25"),
         pd.Timestamp("2021-11-29"),
         pd.Timestamp("2021-08-20"),
      ]
   })

print"DataFrame...\n", dataFrame

# find difference in timestamps
timestamp_diff = abs(dataFrame['Date_of_Purchase']-dataFrame['Date_of_Service'])
print"\nDifference between two Timestamps: \n",timestamp_diff
This will produce the following output −
DataFrame...
        Car   Date_of_Purchase   Date_of_Service
0      Audi         2021-06-10        2021-11-10
1     Lexus         2021-07-11        2021-12-11
2     Tesla         2021-06-25        2021-11-25
3  Mercedes         2021-06-29        2021-11-29
4       BMW         2021-03-20        2021-08-20

Difference between two Timestamps:
0   153 days
1   153 days
2   153 days
3   153 days
4   153 days
dtype: timedelta64[ns]
Adding Multiple Backgrounds with CSS3

To add multiple backgrounds, use the background-image property in CSS. Following is the code for adding multiple backgrounds −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
div {
   background-image:
   url("http://pngimg.com/uploads/autumn_leaves/autumn_leaves_PNG3613.png"),
   url("https://i.picsum.photos/id/256/1200/300.jpg");
   background-position: left bottom, left top;
   background-repeat: repeat, repeat;
   padding: 15px;
}
p {
   font-size: 18px;
}
</style>
</head>
<body>
<h1>Multiple Backgrounds using CSS</h1>
<div>
<h1>Some Sample Text</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Quidem, ipsum
dolorem? Adipisci accusantium eveniet necessitatibus beatae est, dolorum
nobis minima aliquam atque id at sapiente culpa, alias nulla rem.
Aliquam, modi repellendus fugiat dolore, blanditiis praesentium quam
doloribus possimus doloremque reprehenderit corporis enim distinctio,
ducimus nisi. Voluptatum vel repudiandae omnis.
</p>
</div>
</body>
</html>
The above code will produce the following output −
Matplotlib Plot Lines with Colors through Colormap

To plot lines with colors through colormap, we can take the following steps−
Create x and y data points using numpy
Plot x and y data points using plot() method.
Count n finds, number of color lines has to be plotted.
Iterate in a range (n) and plot the lines.
Limit the x ticks range.
Use show() method to display the figure.
import numpy as np
import matplotlib.pylab as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(0, 2 * np.pi, 64)
y = np.exp(x)
plt.plot(x, y)
n = 20
colors = plt.cm.rainbow(np.linspace(0, 1, n))
for i in range(n):
plt.plot(x, i * y, color=colors[i])
plt.xlim(4, 6)
plt.show()
Find the k most frequent words from data set in Python

If there is a need to find 10 most frequent words in a data set, python can help us find it using the collections module. The collections module has a counter class which gives the count of the words after we supply a list of words to it. We also use the most_common method to find out the number of such words as needed by the program input.
In the below example we take a paragraph, and then first create a list of words applying split(). We will then apply the counter() to find the count of all the words. Finally the most_common function will give us the appropriate result of how many such words with highest frequency we want.
from collections import Counter
word_set = " This is a series of strings to count " \
   "many words . They sometime hurt and words sometime inspire "\
   "Also sometime fewer words convey more meaning than a bag of words "\
   "Be careful what you speak or what you write or even what you think of. "\
# Create list of all the words in the string
word_list = word_set.split()

# Get the count of each word.
word_count = Counter(word_list)

# Use most_common() method from Counter subclass
print(word_count.most_common(3))
Running the above code gives us the following result −
[('words', 4), ('sometime', 3), ('what', 3)]
How to Append Values to Vector Using Loop in R?

28 Nov, 2021
In this article, we will discuss how to append values to a vector using a loop in R Programming Language. 
Here we are going to append the values using for loop to the empty vector.
Syntax:
for(iterator in range) {
  vector = c(vector, iterator)
}
where,
range is the range of values
iterator is to iterate the range of values
c(vector,iterator) is an append function which will append values to the vector
Example:
R
# create empty vectorvector1 = c()  # displayprint(vector1)  # use for loop to add elements from 1 to 5for(i in 1: 5) {    vector1 = c(vector1, i)}  # displayvector1
Output:
NULL
[1] 1 2 3 4 5
Here we are going to perform some numeric operations and append values to the empty vector. We can perform cube operation and append to empty vector.
Syntax:
for(iterator in range) {
 vector = c(vector, operation(iterator))
}
where,
range is the range of values
iterator is to iterate the range of values
c(vector,operation(iterator) ) is an append function which will append values to the vector by performing some operation
Here we are going to append the cube values to the vector
Example:
R
# create empty vectorvector1 = c()  # displayprint(vector1)  # use for loop to add elements from # 1 to 5 with cube valuesfor(i in 1: 5) {    vector1 = c(vector1, i*i*i)}  # displayvector1
Output:
NULL
[1]   1   8  27  64 125
Here we are going to append a value for an existing vector.
Syntax:
c(existing_vector,new)
where,
existing_vector is the vector
new is the values to be appended
Example:
R
# create  vectorvector1 = c(1, 2, 3, 4, 5)  # displayprint(vector1)  # append 34vector1 = c(vector1, 34)  # displayvector1
Output:
[1] 1 2 3 4 5
[1]  1  2  3  4  5 34
Here we are going to append multiple values to the existing vector using for loop.
Syntax:
for(iterator in range) {
 vector = c(existing_vector, iterator)
}
where,
range is the range of values
iterator is to iterate the range of values
c(existing_vector,iterator) is an append function which will append values to the existing  vector
Example:
R
# create  vectorvector1 = c(6, 7, 8, 9, 10)  # displayprint(vector1)  # use for loop to add elements from 1 to 5for(i in 1: 5) {    vector1 = c(vector1, i)}  # displayvector1
Output:
[1]  6  7  8  9 10
[1]  6  7  8  9 10  1  2  3  4  5
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
Python | numpy.assert_allclose() method

17 Sep, 2019
With the help of numpy.assert_allclose() method, we can get the assertion errors when two array objects are not equal upto the mark by using numpy.assert_allclose().
Syntax : numpy.assert_allclose(actual_array, desired_array)
Return : Return the Assertion error if two array objects are not equal.
Example #1 :In this example we can see that using numpy.assert_allclose() method, we are able to get the assertion error if two arrays are not equal.
# import numpyimport numpy as np  # using numpy.assert_allclose() methodgfg1 = [1, 2, 3]gfg2 = np.array(gfg1)  if np.testing.assert_allclose(gfg1, gfg2):     print("Matched")
Output :
Matched
Example #2 :
# import numpyimport numpy as np  # using numpy.assert_allclose() methodgfg1 = [1, 2, 3]gfg2 = np.array([4, 5, 6])  print(np.testing.assert_allclose(gfg1, gfg2))
Output :
Mismatch: 100%Max absolute difference: 3Max relative difference: 0.75gfg1: array([1, 2, 3])gfg2: array([4, 5, 6])
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Prime number in PL/SQL

02 Jun, 2021
Prerequisite – PL/SQL introductionA prime number is a whole number greater than 1, which is only divisible by 1 and itself. First few prime numbers are : 2 3 5 7 11 13 17 19 23 .....In PL/SQL code groups of commands are arranged within a block. A block group-related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.Examples:  
Input :  5
Output : true

Input : 10
Output : false
Below is the required implementation: 
SQL
declare   -- declare variable n, i-- and temp of datatype numbern number;            i number;           temp number;          begin   -- Here we Assigning 13 into nn := 13;                   -- Assigning 2 to ii := 2;  -- Assigning 1 to temptemp := 1;  -- loop from i = 2 to n/2  for i in 2..n/2    loop        if mod(n, i) = 0        then            temp := 0;            exit;        end if;    end loop;       if temp = 1    then        dbms_output.put_line('true');    else        dbms_output.put_line('false');    end if;end;          -- Program End
Output:  
true
snehabt18
Prime Number
SQL-PL/SQL
Misc
Misc
Misc
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Hypervisor
Advantages and Disadvantages of OOP
Introduction to Electronic Mail
Cloud Computing
Analog to Digital Conversion
array::size() in C++ STL
Characteristics of Cloud Computing
Bubble Sort algorithm using JavaScript
Introduction to Deep Learning
Types of Cloud
Accenture Archives - GeeksforGeeks

Binary Search
Insertion Sort
N-th root of a number
Accenture Interview Experience 2021
Randomized Binary Search Algorithm
Accenture Interview Experience for Associate Software Engineer (Off-Campus) 2022
Accenture Interview Experience | Set 1 (On-Campus)
Program for replacing one digit with other
Accenture Interview Experience for Associate Software Engineer (2021)
Accenture Interview Experience for Advanced Associate Software Engineer 2021
move() method in PyQt5

26 Mar, 2020
In order to move (changing the position) any widget like buttons or label move() method is used in PyQt5 application. By default, all the widgets are on top left corner therefore, there is a need of changing the position of the widgets.
Syntax : move( x, y )
Arguments : It takes two arguments :1. X co-ordinate2. Y co-ordinate
Below is the implementation of this method.
# importing the required librariesfrom PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Move")          # setting  the geometry of window        self.setGeometry(0, 0, 400, 300)          # creating a label widget        self.widget = QLabel('Moved', self)          # moving the widget        # move(left, top)        self.widget.move(50, 50)            # show all the widgets        self.show()      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Write the syntax to declare a scrollable cursor on the ORDERS DB2 table.

A SCROLLABLE CURSOR can move in both forward and backward direction. In other words, it can fetch next as well as previous rows. A SCROLLABLE CURSOR is declared
using the “SCROLL” clause in the DECLARE CURSOR.
For example, if we want to declare a SCROLLABLE CURSOR on the ORDERS table then we have to declare the cursor like below.
EXEC SQL
      DECLARE ORDER_CURR SCROLL CURSOR FOR
         SELECT ORDER_ID, ORDER_DATE FROM ORDERS
            WHERE ORDER_DATE = ‘2020-07-29’
END-SQL
How to read a single character using Scanner class in Java?

From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path and, String objects, reads all the primitive data types and Strings (from the given source) token by token using regular expressions. By default, whitespace is considered as the delimiter (to break the data into tokens).
Scanner class provides nextXXX() (where xxx is int, float, boolean etc) methods which are used to read various primitive datatypes. But it never provides a method to read a single character.
But, you still can read a single character using this class.
The next() method of the Scanner class returns the next token of the source in String format. This reads single characters (separated by delimiter) as a String.
String str = sc.next();
The toCharArray() method of the String class converts the current String to a character array.
char ch[] = str.toCharArray()
From the array you can get the character stored at the 0th position.
char myChar = ch[0];
Following example reads a single character from the user using the Scanner class.
import java.util.Scanner;
public class ContentsOfFile {
   public static void main(String args[]) throws Exception {
      //Creating a Scanner object
      Scanner sc = new Scanner(System.in);
      //Creating a StringBuffer object
      System.out.println("Enter your grade: (A, B, C, D)");
      char grade = sc.next().toCharArray()[0];
      if(grade == 'A'){
         System.out.println("You are very good, you have been promoted");
      }else if(grade=='B'){
         System.out.println("You are good, you have been promoted");
      }else if(grade=='C'){
         System.out.println("You are average, you have been " + "promoted, you need to work hard");
      }else if(grade=='D'){
         System.out.println("You are not promoted, try again");
      }else {
         System.out.println("Improper input");
      }
   }
}
Enter your grade: (A, B, C, D)
C
You are average, you have been promoted, you need to work hard
Rank variable by group using Dplyr package in R - GeeksforGeeks

17 Oct, 2021
In this article, we are going to see how to rank the variable by group using dplyr in R Programming Language. 
The dplyr package in R is used to perform mutations and data manipulations in R. It is particularly useful for working with data frames and data tables. The package can be downloaded and installed into the working directory using the following command :
install.packages("dplyr")
The arrange() method is invoked to arrange the data of the data frame in the ascending order or descending order. It is used to reorder the rows of the data frame based on the variable names.
arrange(col-name)
This is followed by the application of the group_by method which takes as arguments the set of column names that are used for grouping the data. It may comprise one or more columns.
group_by(col-name1, col-name2..)
The mutate() method can then be applied to the data frame to perform manipulations or modifications by changing the orientation of the data stored in the data frame. The rank() method is used to assign numerical rankings to the data values mapped to the groups assigned. By default, the rank is displayed in ascending order.
rank(col-name)
Code:
R
library("dplyr")  # creating a data framedata_frame <- data.frame(col1 = rep(letters[1:3],each = 4),                          col2 = 1:12)  print ("Original Dataframe")print (data_frame)data_frame %>% arrange(col1, col2) %>%  group_by(col1) %>%   mutate(rank = rank(col2))
Output:
In order to display the ranks in descending order, the col name is prepended with a minus sign. This displays the numerical ranks of the vector in decreasing order. The new column name can be assigned to the output of this method. The output data frame contains an additional column with the same name as that of the assigned name.
R
library("dplyr")  # creating a data framedata_frame <- data.frame(col1 = rep(letters[1:3],each = 4),                          col2 = 1:12)  print ("Original Dataframe")print (data_frame)  # ranking by col1 variableprint ("Modified Dataframe")  # ranking in descending orderdata_frame %>% arrange(col1, col2) %>%  group_by(col1) %>%   mutate(rank = rank(-col2))
Output:
Picked
R Dplyr
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?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R
How to monitor Python files for changes?

Monitoring files for changes in any language is hard because of cross platform issues. On python, there is a widely used cross platform library called watchdog that allows watching for changes. You can install it using:
$ pip install watchdog
To watch a file called 'my_file.txt' using watchdog, you can use the simple program:
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print("Got it!")
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()
 When you run this program and make any changes to any file in current directory, the on_modified function from MyHandler class gets called with the event. In the MyHandler class you can define your own functions to handle the events. In the path, you can specify the files/directories you want to monitor. To stop this program, use Ctrl + C
How do I declare a global variable in Python class?

A global variable is a variable with global scope, meaning that it is visible and accessible throughout the program, unless shadowed. The set of all global variables is known as the global environment or global scope of the program.
 We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.
Example of global variable declaration
def f():    
        global s    
        print(s)    
        s = "Only in spring, but Miami is great as well!"
         print(s)
s = "I am looking for a course in New York!"  
f()
print(s)
I am looking for a course in New York!
Only in spring, but Miami is great as well!
Only in spring, but Miami is great as well!