code-rag-bench/online-tutorials huggingface dataset:
How to add an extra point to scatterplot using ggplot2 in R?

To add an extra point to scatterplot using ggplot2, we can still use geom_point function. We just need to use aes function for quoting with new values for the variables, also we can change the color of this point using colour argument. The display of an extra point will help us to distinguish between a threshold/new value and remaining values.
Consider the below data frame −
 Live Demo
x<-rpois(20,5)
y<-rpois(20,5)
df<-data.frame(x,y)
df
   x  y
1  4  7
2  3  7
3  4  4
4  8  7
5  4  2
6  0  6
7  5  2
8  3  6
9  0  8
10 4  9
11 4  3
12 10 7
13 4  3
14 1  6
15 1  1
16 5  5
17 1  2
18 4  7
19 4  3
20 4  3
Loading ggplot2 package and creating a scatterplot between x and y −
library(ggplot2)
ggplot(df,aes(x,y))+geom_point()
Adding a new point to the above plot −
ggplot(df,aes(x,y))+geom_point()+geom_point(aes(x=2,y=2),colour="red")
Log functions in C#

With C#, you can easily work with Logarithms. It has the following methods for Log as well as Log base 10.
Let us see an example to work with Log functions in C# −
using System;

class Demo {
   static void Main() {
      double val1 = Math.Log(1);
      Console.WriteLine(val1);

      double val2 = Math.Log10(1000);
      Console.WriteLine(val2);

   }
}
Redis - Hash Hexists Command

Redis HEXISTS command is used to check whether a hash field exists or not.
Integer reply, 1 or 0.
1, if the hash contains a field.
0 if the hash does not contain a field, or the key does not exist.
Following is the basic syntax of Redis HEXISTS command.
redis 127.0.0.1:6379> HEXISTS KEY_NAME FIELD_NAME

redis 127.0.0.1:6379> HSET myhash field1 "foo" 
(integer) 1 
redis 127.0.0.1:6379> HEXISTS myhash field1 
(integer) 1 
redis 127.0.0.1:6379> HEXISTS myhash field2 
(integer) 0


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Reading an excel file using Python - GeeksforGeeks

19 Feb, 2022
Using xlrd module, one can retrieve information from a spreadsheet. For example, reading, writing or modifying the data can be done in Python. Also, the user might have to go through various sheets and retrieve data based on some criteria or modify some rows and columns and do a lot of work.
xlrd module is used to extract data from a spreadsheet. 
NOTE: xlrd has explicitly removed support for reading xlsx sheets.  Command to install xlrd module : 
pip install xlrd
Input File: 
Code #1:  Extract a specific cell
Python3
# Reading an excel file using Pythonimport xlrd # Give the location of the fileloc = ("path of file") # To open Workbookwb = xlrd.open_workbook(loc)sheet = wb.sheet_by_index(0) # For row 0 and column 0print(sheet.cell_value(0, 0))
Output :
'NAME'
Code #2: Extract the number of rows 
Python3
# Program to extract number# of rows using Pythonimport xlrd # Give the location of the fileloc = ("path of file") wb = xlrd.open_workbook(loc)sheet = wb.sheet_by_index(0)sheet.cell_value(0, 0) # Extracting number of rowsprint(sheet.nrows)
Output : 
4
Code #3: Extract the number of columns 
Python3
# Program to extract number of# columns in Pythonimport xlrd loc = ("path of file") wb = xlrd.open_workbook(loc)sheet = wb.sheet_by_index(0) # For row 0 and column 0sheet.cell_value(0, 0) # Extracting number of columnsprint(sheet.ncols)
Output : 
3
Code #4 : Extracting all columns name 
Python3
# Program extracting all columns# name in Pythonimport xlrd loc = ("path of file") wb = xlrd.open_workbook(loc)sheet = wb.sheet_by_index(0) # For row 0 and column 0sheet.cell_value(0, 0) for i in range(sheet.ncols):    print(sheet.cell_value(0, i))
Output :
NAME
SEMESTER
ROLL NO
Code #5: Extract the first column 
Python3
# Program extracting first columnimport xlrd loc = ("path of file") wb = xlrd.open_workbook(loc)sheet = wb.sheet_by_index(0)sheet.cell_value(0, 0) for i in range(sheet.nrows):    print(sheet.cell_value(i, 0))
Output :
NAME
ALEX
CLAY
JUSTIN
Code #6: Extract a particular row value  
Python3
# Program to extract a particular row valueimport xlrd loc = ("path of file") wb = xlrd.open_workbook(loc)sheet = wb.sheet_by_index(0) sheet.cell_value(0, 0) print(sheet.row_values(1))
Output :
['ALEX', 4.0, 2011272.0]
 
Kailaskm1
mtgeekman
moismohammed
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
Print lists in Python (4 Different Ways)
DLL - Registration

In order to use a DLL, it has to be registered by having appropriate references entered in the Registry. It sometimes happens that a Registry reference gets corrupted and the functions of the DLL cannot be used anymore. The DLL can be re-registered by opening Start-Run and entering the following command:
regsvr32 somefile.dll

This command assumes that somefile.dll is in a directory or folder that is in the PATH. Otherwise, the full path for the DLL must be used. A DLL file can also be unregistered by using the switch "/u" as shown below.
regsvr32 /u somefile.dll

This can be used to toggle a service on and off.
 Print
 Add Notes
 Bookmark this page
Laravel - Namespaces

Namespaces can be defined as a class of elements in which each element has a unique name to that associated class. It may be shared with elements in other classes.
The use keyword allows the developers to shorten the namespace.
use <namespace-name>;

The default namespace used in Laravel is App, however a user can change the namespace to match with web application. Creating user defined namespace with artisan command is
mentioned as follows −
php artisan app:name SocialNet

The namespace once created can include various functionalities which can be used in controllers and various classes.

    13 Lectures 
     3 hours 

 Sebastian Sulinski

    35 Lectures 
     3.5 hours 

 Antonio Papa

    7 Lectures 
     1.5 hours 

 Sebastian Sulinski

    42 Lectures 
     1 hours 

 Skillbakerystudios

    165 Lectures 
     13 hours 

 Paul Carlo Tordecilla

    116 Lectures 
     13 hours 

 Hafizullah Masoudi
 Print
 Add Notes
 Bookmark this page
Java Examples - Exception Hierarchies

How to handle the exception hierarchies ?
Here is the sample diagram of Exception Hierarchies
This example shows how to handle the exception hierarchies by extending Exception class ?
class Animal extends Exception {
}
class Mammel extends Animal {
}
public class Human {
   public static void main(String[] args) {
      try {
         throw new Mammel();
      } catch (Mammel m) {
         System.err.println("It is mammel");
      }
   }
}
The above code sample will produce the following result.
It is mammel

 Print
 Add Notes
 Bookmark this page
HTTP headers | Content-Length

31 Oct, 2019
HTTP headers are used to pass additional information in HTTP request or HTTP response. HTTP Content-Length entity-header is used to indicate the size of entity-body in decimal no of octets i.e. bytes and sent it to the recipient. It is a forbidden header name. Basically it is the number of bytes of data in the body of the request or response. The body comes after the blank line below the headers.
Syntax:
Content-Length: <length>
Directive: This headers accepts a single directive mentioned above and described below:
Length: It defines the length of entity-body in decimal no of octets or say bytes.
Example:
content-length: 6553
content-length: 54138
To check this Content-Length in action go to Inspect Element -> Network check the request header for Content-Length like below, Content-Length is highlighted.Supported Browsers: The browsers compatible with HTTP headers Content-length are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
REST API (Introduction)
Roadmap to Learn JavaScript For Beginners
How to create footer to stay at the bottom of a Web page?
How to float three div side by side using CSS?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
ifup command in Linux with Examples

22 May, 2019
The ifup command basically brings the network interface up, allowing it to transmit and receive data. Technically ifup command is used to configure network interfaces based on interface definitions in the file /etc/network/interfaces.
Syntax:
ifup [-nv] [--no-act] [--verbose] [-i FILE|--interfaces=FILE] [--allow CLASS] -a|IFACE...

Example: Let us see an example when our interface is down and how the browser reacts to it.
In this case, the interface was not up and configured. To get the network interface up and work we use
sudo ifup -av
Here, sudo is used for permissions, -a to work on all devices and v for verbose the output.
After using ifup command, the network is working:
Options:
-a(–all): If used this option it affects all the interfaces marked as auto. Brings up interfaces in order they are defined /etc/network/interfaces. Combined with –allow, acts on all interfaces of a specified class instead.
–force: Force configuration or deconfiguration of the interface.
-V: Prints the version information.
-v: Verbose the output as they are executed.
linux-command
Linux-networking-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Plotting back-to-back bar charts Matplotlib

16 Dec, 2021
In this article, we will learn how to plot back-to-back bar charts in matplotlib in python. Let’s discuss some concepts :
Matplotlib: Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It was introduced by John Hunter in the year 2002.
Bar chart:  Bar plot or Bar chart is a graph that represents the category of data with rectangular bars with lengths and heights that is proportional to the values which they represent. The bar plots can be plotted horizontally or vertically.
Back-to-Back Bar Chart: Back-to-Back Bar Chart is just a combination of two bar charts drawn with respect to a axis.
Import library (matplotlib)Import / Load / Create dataPlot the Back-to-Back Bar Chart over data.
Import library (matplotlib)
Import / Load / Create data
Plot the Back-to-Back Bar Chart over data.
Here, we discuss some examples step by step to understand the concept in a better way.
Example 1: Simple Back-to-Back Bar Chart
Python3
# import packagesimport numpy as npimport matplotlib.pyplot as plt # create dataA = np.array([3,6,9,4,2,5])X = np.arange(6) # plot the barsplt.bar(X, A, color = 'r')plt.bar(X, -A, color = 'b')plt.title("Back-to-Back Bar Chart")plt.show()
Output : 
Example 2: Horizontal Back-to-Back Bar Chart. 
Python3
# import packagesimport numpy as npimport matplotlib.pyplot as plt # create dataA = np.array([3,6,9,4,2,5])B = np.array([2,8,1,9,7,3])X = np.arange(6) # plot the barsplt.barh(X, A, color = 'r')plt.barh(X, -B, color = 'b')plt.title("Back-to-Back Bar Chart")plt.show()
Output : 
Example 3: Complete Back-to-Back Bar Chart with Some styles in matplotlib. 
Python3
# import packagesimport numpy as npimport matplotlib.pyplot as plt # create dataA = np.array([3,6,9,4,2,5])B = np.array([2,8,1,9,7,3])X = np.arange(6) # plot the barsplt.barh(X, A, align='center',         alpha=0.9, color = 'y') plt.barh(X, -B, align='center',         alpha=0.6, color = 'c') plt.grid()plt.title("Back-to-Back Bar Chart")plt.ylabel("Indexes")plt.xlabel("Values")plt.show()
Output : 
 
surinderdawra388
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Stream forEachOrdered() method in Java with examples

06 Dec, 2018
Stream forEachOrdered(Consumer action) performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. Stream forEachOrdered(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
Syntax :
void forEachOrdered(Consumer<? super T> action)

Where, Consumer is a functional interface which 
is expected to operate via side-effects. and T 
is the type of stream elements.

Note : This operation processes the elements one at a time, in encounter order if one exists. Performing the action for one element happens-before performing the action for subsequent elements.
Example 1 : To print the elements of integer array in original order.
// Java code for forEachOrdered// (Consumer action) in Java 8import java.util.*;  class GFG {          // Driver code    public static void main(String[] args) {      // Creating a list of Integers    List<Integer> list = Arrays.asList(10, 19, 20, 1, 2);          // Using forEachOrdered(Consumer action) to     // print the elements of stream in encounter order    list.stream().forEachOrdered(System.out::println);        }}
10
19
20
1
2

Example 2 : To print the elements of string array in original order.
// Java code for forEachOrdered// (Consumer action) in Java 8import java.util.*;  class GFG {          // Driver code    public static void main(String[] args) {      // Creating a list of Strings    List<String> list = Arrays.asList("GFG", "Geeks",                              "for", "GeeksforGeeks");          // Using forEachOrdered(Consumer action) to     // print the elements of stream in encounter order    list.stream().forEachOrdered(System.out::println);        }}
GFG
Geeks
for
GeeksforGeeks

Example 3 : To print the characters at index 2 of string array in original order.
// Java code for forEachOrdered// (Consumer action) in Java 8import java.util.*;import java.util.stream.Stream;    class GFG {          // Driver code    public static void main(String[] args) {      // Creating a Stream of Strings    Stream<String> stream = Stream.of("GFG", "Geeks",                              "for", "GeeksforGeeks");          // Using forEachOrdered(Consumer action)     stream.flatMap(str-> Stream.of(str.charAt(2)))          .forEachOrdered(System.out::println);        }}
G
e
r
e

Java - util package
Java-Functions
java-stream
Java-Stream interface
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
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java
Ruby | String gsub! Method

12 Dec, 2019
gsub! is a String class method in Ruby which is used to return a copy of the given string with all occurrences of pattern substituted for the second argument. If no substitutions were performed, then it will return nil. If no block and no replacement is given, an enumerator is returned instead.
Syntax: str.gsub!(pattern, replacement)
Parameters: Here, str is the given string. pattern may be specified regex or character set to be removed. replacement is the set of characters which is to be put.
Returns: A copy of the string with all occurrences of pattern substituted for the second argument or nil if no substitutions were performed.
Example 1:
# Ruby program to demonstrate # the gsub! method        # Taking a string and # using the methodputs "Sample".gsub!(/[bcd]/, '*')                 puts "Program".gsub!(/([gmra])/, '<\1>')      
Output:

Po

Example 2:
# Ruby program to demonstrate # the gsub! method        # Taking a string and # using the methodputs "Ruby".gsub!(/[tyru]/, '<\1>')                 puts "String".gsub!(/([ab])/, '*')     
Output:
Rb


Ruby String-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between Flatten() and Ravel() Numpy Functions

23 Oct, 2020
We have two similar kind of ways to convert a ndarray to 1D array : Flatten() and Ravel()
import numpy as np
a = np.array( [ (1,7,3,4),(3,2,4,1) ] )
#OUTPUT:
print( a.flatten() )
# [ 1,7,3,4,3,2,4,1 ] 
print ( a.ravel() )
# [ 1,7,3,4,3,2,4,1 ] 

The question arises here, why are there two numpy functions to do the same task ?
Differences between Flatten() and Ravel()
a.ravel():(i) Return only reference/view of original array(ii) If you modify the array you would notice that the value of original array also changes.(iii) Ravel is faster than flatten() as it does not occupy any memory.(iv) Ravel is a library-level function.
a.flatten() :(i) Return copy of original array(ii) If you modify any value of this array value of original array is not affected.(iii) Flatten() is comparatively slower than ravel() as it occupies memory.(iv) Flatten is a method of an ndarray object.
Let us check out the difference by this code
# Python code to differentiate# between flatten and ravel in numpyimport numpy as np  # Create a numpy arraya = np.array([(1,2,3,4),(3,1,4,2)])  # Let's print the array aprint ("Original array:\n ") print(a)  # To check the dimension of array (dimension =2)# ( and type is numpy.ndarray )print ("Dimension of array-> " , (a.ndim))    print("\nOutput for RAVEL \n") # Convert nd array to 1D arrayb = a.ravel()  # Ravel only passes a view of # original array to array 'b'print(b)b[0]=1000print(b)  # Note here that value of original# array 'a' at also a[0][0] becomes 1000print(a)  # Just to check the dimension i.e. 1# (and type is same numpy.ndarray )print ("Dimension of array->" ,(b.ndim))  print("\nOutput for FLATTEN \n")   # Convert nd array to 1D arrayc = a.flatten()  # Flatten passes copy of# original array to 'c'print(c)c[0]=0print(c)  # Note that by changing# value of c there is no# affect on value of original# array 'a'print(a)  print ("Dimension of array-> " , (c.ndim))
OUTPUT:
Original array:
 
[[1 2 3 4]
 [3 1 4 2]]
Dimension of array->  2

Output for RAVEL 

[1 2 3 4 3 1 4 2]
[1000    2    3    4    3    1    4    2]
[[1000    2    3    4]
 [   3    1    4    2]]
Dimension of array-> 1

Output for FLATTEN 

[1000    2    3    4    3    1    4    2]
[0 2 3 4 3 1 4 2]
[[1000    2    3    4]
 [   3    1    4    2]]
Dimension of array->  1
This article is contributed by SHAURYA UPPAL.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python-numpy
Difference Between
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Stack vs Heap Memory Allocation
Difference between Clustered and Non-clustered index
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Python | Remove substring list from String

22 Apr, 2020
Sometimes, while working with Python Strings, we can have problem in which we need to remove a substring from String. This is quite easy and many times solved before. But sometimes, we deal with list of strings that need to be removed and String adjusted accordingly. Lets discuss certain ways in which this task is achieved.
Method #1 : Using loop + replace()The combination of above functions can be used to solve this problem. In this, we perform the replace of multiple Strings as they occur using replace().
# Python3 code to demonstrate working of # Remove substring list from String# Using loop + replace()  # initializing stringtest_str = "gfg is best for all geeks"  # printing original stringprint("The original string is : " + test_str)  # initializing sub list sub_list = ["best", "all"]  # Remove substring list from String# Using loop + replace()for sub in sub_list:    test_str = test_str.replace(' ' + sub + ' ', ' ')  # printing result print("The string after substring removal : " + test_str) 
The original string is : gfg is best for all geeks
The string after substring removal : gfg is for geeks

 
Method #2 : Using replace() + join() + split()The combination of above functions can be used to solve this problem. In this, we perform the task of handling single space using join() + split().
# Python3 code to demonstrate working of # Remove substring list from String# Using replace() + join() + split()  # initializing stringtest_str = "gfg is best for all geeks"  # printing original stringprint("The original string is : " + test_str)  # initializing sub list sub_list = ["best", "all"]  # Remove substring list from String# Using replace() + join() + split()for sub in sub_list:    test_str = test_str.replace(sub, ' ')res = " ".join(test_str.split())  # printing result print("The string after substring removal : " + res) 
The original string is : gfg is best for all geeks
The string after substring removal : gfg is for geeks

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Symbol upcase function

10 Dec, 2019
Symbol#upcase() : upcase() is a Symbol class method which returns the uppercase representation of the symbol object.
Syntax: Symbol.upcase()
Parameter: Symbol values
Return: the uppercase representation of the symbol object.
Example #1 :
# Ruby code for Symbol.upcase() method  # declaring Symbol a = :aBcDeF  # declaring Symbolb = :"\u{e4 f6 fc}"  # declaring Symbolc = :ABCDEF  # Symbol puts "Symbol a : #{a}\n\n"puts "Symbol b : #{b}\n\n"puts "Symbol c : #{c}\n\n\n\n"    # upcase form puts "Symbol a upcase form : #{a.upcase}\n\n"puts "Symbol b upcase form : #{b.upcase}\n\n"puts "Symbol c upcase form : #{c.upcase}\n\n"
Output :
Symbol a : aBcDeF

Symbol b : äöü

Symbol c : ABCDEF



Symbol a upcase form : ABCDEF

Symbol b upcase form : äöü

Symbol c upcase form : ABCDEF

Example #2 :
# Ruby code for Symbol.upcase() method  # declaring Symbol a = :geeks  # declaring Symbolb = :"\u{e5 f6 f3}"  # declaring Symbolc = :GEEKS  # Symbol puts "Symbol a : #{a}\n\n"puts "Symbol b : #{b}\n\n"puts "Symbol c : #{c}\n\n\n\n"    # upcase form puts "Symbol a upcase form : #{a.upcase}\n\n"puts "Symbol b upcase form : #{b.upcase}\n\n"puts "Symbol c upcase form : #{c.upcase}\n\n"
Output :
Symbol a : geeks

Symbol b : åöó

Symbol c : GEEKS



Symbol a upcase form : GEEKS

Symbol b upcase form : åöó

Symbol c upcase form : GEEKS


Ruby Symbol-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby | Array class find_index() operation
Ruby For Beginners
Ruby | String concat Method
Ruby | Array shift() function
Ruby on Rails Introduction
Ruby | Types of Variables
MongoDB - Distinct() Method - GeeksforGeeks

05 Feb, 2021
In MongoDB, the distinct() method finds the distinct values for a given field across a single collection and returns the results in an array. It takes three parameters first one is the field for which to return distinct values and the others are optional.
If you are using this method in the sharded cluster, then this method may return orphaned documents.
In this method, if the value of the given field is an array, then this method will be considered each array value as a separate value. For example, if the value of the specified field is [2, [23], 45], then this method considered 2, [23], and 45 separately.
In this method, you can also use indexes.
Syntax:
db.Collection_name.distinct(
    field : <string>,
    query : <document>,
    collation : <document> 
)
Parameters:
The first parameter is the field for which to return distinct values.
Others are optional.
Optional Parameters:
query: A query that specifies the documents from which to retrieve the distinct values.
collation: It specifies the use of the collation for operations. It allows users to specify the language-specific rules for string comparison like rules for lettercase and accent marks. The type of this parameter is a document.
Return:
It returns an array of all the distinct values for specified fields that match to the given query.
Examples:
In the following examples, we are working with:
Database: gfg
Collections: student
Document: Three documents contains the details of the students
Return name of all the student present in the collection:
db.student.distinct("name")
Here, the distinct() method returns the value of the name field.
Return the distinct value of the embedded field from the given collection:
db.student.distinct("detail.age")
Here, the distinct() method returns the value of the age field.
Return the distinct value from an array field
db.student.distinct("marks")
Here, the distinct() method returns the value of the marks field.
MongoDB-method
Picked
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - Regex
MongoDB - FindOne() Method
Create user and add role in MongoDB
Export data from MongoDB
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB Cursor
MongoDB - Map Reduce
MongoDB insertMany() Method - db.Collection.insertMany()
Equal Sum and XOR in C++

In this problem, we are given an integer n. Our task is to create a program to find the count of integers from i = 0 to n, where sum is equal to XOR i.e. (n+i) = (n^i).
Input:  n = 4
Output: 4
Explanation: 
Considering all values of i from 0 to n,
i = 0,  4 + 0 = 4, 4^0 = 4i = 1,  4 + 1 = 5, 4^1 = 5i = 2,  4 + 2 = 6, 4^2 = 6i = 3,  4 + 3 = 7, 4^3 = 7i = 4,  4 + 4 = 8, 4^4 = 0Count = 4
A simple solution is to find the values of the sum of n and i and xor of n and i. Compare both these values and then count the values for which they are equal.
Step 1: Loop for all values from i = 0 to n.
Step 1.1: Find the value of (n + i).
Step 1.2: Find the value of (n^i).
Step 1.3: compare values found in step 1.1 and 1.2.Step 1.4: If they are equal, increase count.
Step 2: Print count values.
Live Demo
#include <iostream>
using namespace std;

int main() {
   
   int n = 5;
   int counter = 0;
   for(int i=0; i<=n; i++ )
      if ( (n+i) == (n^i) )
         counter++;
   cout<<"The count of integers with equal sum and XOR is "<<counter;
   return 0;
}
The count of integers with equal sum and XOR is 2
The method is good but their can be a better solution to the problem, which is using the fact that
If n^i = n+i, then n&i = 0.
If the value of n&i = 0, for that we need the two numbers to have opposite set and unset bits. And we need to count such values. Here is a program to do it,
Live Demo
#include <iostream>
using namespace std;

int countValuesWithEqualSumXOR(int n) {
   
   int countUnSetBits=0;
   while (n) {
      if ((n & 1) == 0)
         countUnSetBits++;
      n=n>>1;
   }
   return 1 << countUnSetBits;
}

int main()
{
   int n = 6;
   cout<<"The count of integers with equal sum and XOR is "<<countValuesWithEqualSumXOR(n);
   return 0;
}
The count of integers with equal sum and XOR is 2
How to add a text editor field in Django?

Many online exam taking websites use text editors for text entries. image uploading, etc. Quill text editor is very popular and it also provides a model field to directly store in database. So, you don't need to configure anything extra to save its data in database.
In this article, we will see how to make a text editor field in Django.
First of all, create a Django project and an app. Do some basic settings like including urls of app. Create a media folder at the same level of project and app.
In settings.py, add −
INSTALLED_APPS = [ 'myapp.apps.MyappConfig', #django app
' django_quill' #module name]
.
.
.
.
..
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Install the django_quill package −
pip install django_quill
n app's urls.py, add the following −
from django.urls import path
from . import views
urlpatterns = [
   path('', views.home,name="home"),
]
urlpatterns += static(settings.MEDIA_URL,
                           document_root=settings.MEDIA_ROOT)
Here we simply set our main view on url and media folder url.
Now, create a templates folder in app's directory and create home.html file in it. Add the following lines in home.html −
<!DOCTYPE html>
<html>
   <head>
   {{ form.media }}
      {% include 'django_quill/media.html' %}
      <title>
         TUT
      </title>
   </head>
   <body>
      <form role="form" method="POST">
         <legend>Form Title</legend>
         {% csrf_token %}
      {{form}}
         <button type="submit" class="btn btnprimary">Submit</button>
      </form>
</html>
Here we rendered our form that we send from our backend.
In views.py, add the following lines −
from django.shortcuts import render
from django import forms
from .models import another_model

class NewForm(forms.ModelForm):
   class Meta:
      model=another_model
      fields="__all__"

def home(request):
   if request.method =="POST":
      form=NewForm(request.POST)
      if form.is_valid():
         form.save()
   form=NewForm()
   return render(request,'home.html',{"form":form})
Here we created a form and then we rendered it using home view. For
handling POST view, we validated the form data and then saved it.
In models.py, add the following lines −
from django.db import models
from django_quill.fields import QuillField

class another_model(models.Model):
   name = models.CharField(max_length=200)
   place = models.CharField(max_length=100)
   animal = models.CharField(max_length=100)
   thing = models.CharField(max_length=100)
   content = QuillField(blank=True)
Here we created a model and in it, we created the text editor field, which
will store the data of our text editor.
Angular Highcharts - 3D Pie Chart

Following is an example of a 3D Pie Chart.
We have already seen the configuration used to draw a chart in Highcharts Configuration Syntax chapter.
An example of a 3D Pie Chart is given below.
Let us now see the additional configurations/steps taken.
Configure the pie chart type to be 3D based. Options3D sets the 3D options enabled.
chart: {         
   options3d: {
      enabled: true,
      alpha: 15,
      beta: 15,
      depth: 50,
      viewDistance: 25
   }
}  
app.component.ts
import { Component } from '@angular/core';
import * as Highcharts from 'highcharts';
import highcharts3D from 'highcharts/highcharts-3d.src';
highcharts3D(Highcharts);
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   highcharts = Highcharts;
   chartOptions = {   
      chart : {
         type:'pie',
         options3d: {
            enabled: true,
            alpha: 45,
            beta: 0
         }
      },
      title : {
         text: 'Browser market shares at a specific website, 2014'   
      },
      tooltip : {
         pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
      },
      plotOptions : {
         pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            depth: 35,
            dataLabels: {
               enabled: true,
               format: '<b>{point.name}%</b>: {point.percentage:.1f} %',
               style: {
                  color: (Highcharts.theme && Highcharts.theme.contrastTextColor)||
                  'black'
               }
            }
         }
      },
      series : [{
         type: 'pie',
         name: 'Browser share',
         data: [
            ['Firefox',   45.0],
            ['IE',       26.8],
            {
               name: 'Chrome',
               y: 12.8,
               sliced: true,
               selected: true
            },
            ['Safari',    8.5],
            ['Opera',     6.2],
            ['Others',      0.7]
         ]
      }]
   };
}

Verify the result.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to select only one Radiobutton in Tkinter?

To implement the selection for one or more options, we can use the Radiobutton widget. The Radiobutton widget in Tkinter allows the user to make a selection for only one option from a set of given choices. The Radiobutton has only two Boolean values: True or False.
If we want to get the output to check which option the user has selected, then we can use the get() method. It returns the object that is defined as the variable. We can display the selection in a label widget by casting the integer value in a string object and pass it in the text attributes.
# Import the required libraries
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")


# Define a function to get the output for selected option
def selection():
   selected = "You have selected " + str(radio.get())
   label.config(text=selected)


radio = IntVar()
Label(text="Your Favourite programming language:", font=('Aerial 11')).pack()

# Define radiobutton for each options
r1 = Radiobutton(win, text="C++", variable=radio, value=1, command=selection)
r1.pack(anchor=N)

r2 = Radiobutton(win, text="Python", variable=radio, value=2, command=selection)
r2.pack(anchor=N)

r3 = Radiobutton(win, text="Java", variable=radio, value=3, command=selection)
r3.pack(anchor=N)

# Define a label widget
label = Label(win)
label.pack()

win.mainloop()
Running the above code will display a window with a label widget and a set of radiobuttons that correspond to an option. Select any option from the list to see the output.
Implementing a custom function like Array.prototype.filter() function in JavaScript

We are required to write a JavaScript function that lives on the prototype Object of the Array class.
Our function should take in a callback function as the only argument. This callback function should be called for each element of the array.
And that callback function should take in two arguments the corresponding element and its index. If the callback function returns true, we should include the corresponding element in our output array otherwise we should exclude it.
Following is the code −
 Live Demo
const arr = [5, 3, 6, 2, 7, -4, 8, 10];
const isEven = num => num % 2 === 0;
Array.prototype.customFilter = function(callback){
   const res = [];
   for(let i = 0; i < this.length; i++){
      const el = this[i];
      if(callback(el, i)){
         res.push(el);
      };
   };
   return res;
};
console.log(arr.customFilter(isEven));
[ 6, 2, -4, 8, 10 ]
Redis - Connection Auth Command

Redis AUTH command is used to authenticate to the server with the given password. If the password matches the password in the configuration file, the server replies with the OK status code and starts accepting commands. Otherwise, an error is returned and the clients needs to try a new password.
String reply.
Following is the basic syntax of Redis AUTH command.
redis 127.0.0.1:6379> AUTH PASSWORD

redis 127.0.0.1:6379> AUTH PASSWORD 
(error) ERR Client sent AUTH, but no password is set 
redis 127.0.0.1:6379> CONFIG SET requirepass "mypass" 
OK 
redis 127.0.0.1:6379> AUTH mypass 
Ok 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
JavaScript Array toSource() Method

Javascript array  toSource() method returns a string representing the source code of the array. This method is supported by Mozilla.
Its syntax is as follows −
array.toSource();

Here is the detail of parameters −
NA
NA
Returns a string representing the source code of the array.
<html>
   <head>
      <title>JavaScript Array toSource Method</title>
   </head>
   
   <body>      
      <script type = "text/javascript">
         var arr = new Array("orange", "mango", "banana", "sugar");
         var str = arr.toSource();
         document.write("Returned string is : " + str );
      </script>   
   </body>
</html>
Returned string is : ["orange", "mango", "banana", "sugar"]


    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
Check if a given graph is tree or not

In this problem, one undirected graph is given, we have to check the graph is tree or not. We can simply find it by checking the criteria of a tree. A tree will not contain a cycle, so if there is any cycle in the graph, it is not a tree.
We can check it using another approach, if the graph is connected and it has V-1 edges, it could be a tree. Here V is the number of vertices in the graph.
Input:
The adjacency matrix.
0 0 0 0 1
0 0 0 0 1
0 0 0 0 1
0 0 0 0 1
1 1 1 1 0

Output:
The Graph is a tree
isCycle(u, visited, parent)
Input: The start vertex u, the visited list to mark visited or not, the parent vertex.
Output: True if there is a cycle in the graph.
Begin
   mark u as visited
   for all vertex v which are adjacent with u, do
      if v is visited, then
         if isCycle(v, visited, u) = true, then
            return true
         else if v ≠ parent, then
            return true
   done
   return false
End
isTree(graph)
Input: The undirected graph.
Output: True when the graph is a tree.
Begin
   define a visited array to mark which node is visited or not
   initially mark all node as unvisited
   if isCycle(0, visited, φ) is true, then //the parent of starting vertex is null
      return false
   if the graph is not connected, then
      return false
   return true otherwise
End
#include<iostream>
#define NODE 5
using namespace std;

int graph[NODE][NODE] = {
   {0, 1, 1, 1, 0},
   {1, 0, 1, 0, 0},
   {1, 1, 0, 0, 0},
   {1, 0, 0, 0, 1},
   {0, 0, 0, 1, 0}
};
                                                               
bool isCycle(int u, bool visited[], int parent) {
   visited[u] = true;    //mark v as visited
   for(int v = 0; v<NODE; v++) {
      if(graph[u][v]) {
         if(!visited[v]) {     //when the adjacent node v is not visited
            if(isCycle(v, visited, u)) {
               return true;
            }
         } else if(v != parent) {    //when adjacent vertex is visited but not parent
            return true;    //there is a cycle
         }
      }
   }
   return false;
}

bool isTree() {
   bool *vis = new bool[NODE];

   for(int i = 0; i<NODE; i++)
      vis[i] = false;    //initialize as no node is visited
         
   if(isCycle(0, vis, -1))    //check if there is a cycle or not
      return false;
         
   for(int i = 0; i<NODE; i++) {
      if(!vis[i])    //if there is a node, not visited by traversal, graph is not connected
         return false;
   }
   return true;
}

int main() {
   if(isTree())
      cout << "The Graph is a Tree.";
   else
      cout << "The Graph is not a Tree.";
}
The Graph is a Tree.
Finding a particular value in internal table itab in ABAP

you can use a READ statement in combination with TRANSPORTING NO FIELDS. This will skip the values to be transferred to the work area and avoid the loop. Here is an example:
READ TABLE itab WITH KEY FIELD = 'ABC' TRANSPORTING NO FIELDS.
IF SY-SUBRC = 0.
"Field Match.”
ENDIF.
Instruction type MOV r1, r2 in 8085 Microprocessor

In 8085 Instruction set, MOV is a mnemonic, which stands for “MOVe”. In this instruction 8-bit data value in register r2 will be moved to the 8-bit register r1. Note that in 8085 instructions, as the first operand specifies the destination, and the second one the source, so here also r1 is destination register and r2 is the source register. This instruction uses register addressing for specifying the data. Here, “r1” and “r2”can be any one of the following registers.
r1, r2 = A, B, C, D, E, H, or L

As r1 can have any one of the seven values, and r2 can have any of the seven values, there are 7 × 7 = 49 opcodes for this type of instruction.
It occupies only 1-Byte in memory. MOV E, H is an example instruction of this type. It is a 1-Byte instruction. Suppose E register content is AB H, and H register content is 9C H. When the 8085 executes this instruction, the contents of E register will change to 9C H. This is shown as follows.
(E)
(H)
Note that H register’s content has not been changed at all.Although Intel has called it a “move” instruction, but actually in reality it seems to be a“copy” instruction.
The timing diagram of MOV E, H instruction is as follows.
Summary − So this instruction MOV E, Hrequires 1-Byte, 1-Machine Cycles (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
How to create a new Azure resource group using PowerShell?

Azure Resource Group is a container that stores the resources like Virtual Machines, Storage, IP addresses, etc. To create a new Azure Resource group, we need to use the New-AZResourceGroup command.
To use this cmdlet, you first need to connect to the Azure account, and then if you want to create a resource group for the particular subscription you need to select that subscription.
To create a new resource group, you need the location for the resource group. The below code will first connect to your Azure account, selects the Azure subscription, and then creates a new resource group.
$ErrorActionPreference = "Stop"
Connect-AzAccount
Set-AzContext -SubscriptionName 'Enter your subscription name here'
New-AzResourceGroup -Name 'TestRG' -Location 'Central US' -Tag @{'RG'='APP'}
ResourceGroupName : TestRG
Location          : centralus
ProvisioningState : Succeeded
Tags              :
                    Name  Value
                    ====  =====
                    RG    APP

ResourceId        : /subscriptions/8ac5a3e4-390b-9034-8ad5-3585aseesasac/resourceGroups/TestRG
The above command will create the Azure Resource group at the Central US location with the associated tag ‘RG’ and its value ‘APP’
Convert String to Long in Python - GeeksforGeeks

28 Jul, 2020
Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing information about converting a string to long.
A long is an integer type value that has unlimited length. By converting a string into long we are translating the value of string type to long type. In Python3 int is upgraded to long by default which means that all the integers are long in Python3. So we can use int() to convert a string to long in Python.
Syntax :
int(string, base)
Parameter :
string : consists of 1's and 0's
base : (integer value) base of the number.example 1
Example 1:
Python3
a_string = "123"print(type(a_string))  # Converting to longa_long = int(a_string)print(a_long)print(type(a_long))
Output:
<class 'str'>
123
<class 'int'>
Example 2:
Python3
a='0x'arr0 = '00000018000004000000000000000000'arr1 = '00000000000000000000000000000000'arr2 = 'fe000000000000000000000000000000'arr3 = '00000000000000000000000000ffffff'data = a+arr0+arr1+arr2+arr3print(data)print(type(data))  # Converting to longdata1 = int(data, 16)print(type(data1))
Output:
0x0000001800000400000000000000000000000000000000000000000000000000fe00000000000000000000000000000000000000000000000000000000ffffff<type ‘str’><type ‘int’>
python-basics
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
How to append an text message when an input field is modified in jQuery ? - GeeksforGeeks

25 Mar, 2021
In this article, we will see how to append an element with a text message when an input field is changed in jQuery. To append an element with a text message when the input field is changed, change() and appendTo() methods are used. The change() method is used to detect the change in the value of input fields. This method works only on the “<input>, <textarea> and <select>” elements. The appendTo() method is used to append the elements.
Syntax:
$($selector).change(function() { })
Here, first we use change() method to detect the changes of the input field and appendTo() method is used to display the message.
Example:
HTML
<!DOCTYPE html><html>  <head>    <title>        How to append an element with a text message        when an input field is changed in jQuery?    </title>      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>      <script>        $(document).ready(function () {            $("#textInput").change(function () {                $("<p>Input text has changed.</p>")                .appendTo("body");            });        });    </script>      <style>        body {            text-align: center;        }          h1 {            color: green;        }          .clickable_ele {            font-size: 20px;            font-weight: bold;        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>      <h3>        How to append an element with a text message        <br>when an input field is changed in jQuery?    </h3>      <form action="#">        <input id="textInput" type="text"             value="GeeksforGeeks">    </form></body>  </html>
Output:
CSS-Properties
HTML-Tags
jQuery-Questions
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
jQuery | ajax() Method
jQuery | removeAttr() with Examples
How to get the value in an input text box using jQuery ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?