code-rag-bench/online-tutorials huggingface dataset:
How to plot the confidence interval of the regression model using ggplot2 with transparency in R?

To plot the confidence interval of the regression model, we can use geom_ribbon function of ggplot2 package but by default it will have dark grey color. It can become transparent with the help of alpha argument inside the same function, the alpha argument can be adjusted as per our requirement but the most recommended value by me is 0.2.
Consider the below data frame −
Live Demo
> x<-rnorm(20,25,2.24)
> y<-rnorm(20,30,1.27)
> df<-data.frame(x,y)
> df
      x         y
1 22.67102 29.37057
2 21.59415 29.54027
3 20.56817 28.27672
4 24.97228 31.38193
5 21.41651 31.86811
6 23.94699 28.22775
7 23.90155 30.03807
8 26.57466 29.32966
9 22.32727 32.10336
10 30.04399 31.76219
11 26.84023 30.12260
12 23.73143 31.71349
13 22.57145 29.10705
14 25.86364 30.61687
15 25.17939 30.79297
16 22.49971 27.51084
17 22.01182 29.96766
18 23.93069 30.31963
19 19.57823 30.01839
20 22.90537 32.30613
Loading ggplot2 package and creating a regression model plot with confidence interval −
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()+geom_ribbon(stat="smooth",method="lm",se=TRUE)+geom_line(stat="smooth",method="lm")
Creating the plot with transparent confidence interval −
> ggplot(df,aes(x,y))+geom_point()+geom_ribbon(stat="smooth",method="lm",se=TRUE,alpha=0.2)+geom_line(stat="smooth",method="lm")
Creating and using packages in Java

While creating a package, you should choose a name for the package and include a package statement along with that name at the top of every source file that contains the classes, interfaces, enumerations, and annotation types that you want to include in the package. 
The package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be placed in the current default package. 
To compile the Java programs with package statements, you have to use -d option as shown below.
javac -d Destination_folder file_name.java
Then a folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder.
Let us look at an example that creates a package called animals. It is a good practice to use names of packages with lower case letters to avoid any conflicts with the names of classes and interfaces.
Following package example contains interface named animals −
/* File name : Animal.java */ package animals;
interface Animal { public void eat(); public void travel(); }
Now, let us implement the above interface in the same package animals −
package animals; /* File name :
MammalInt.java */
public class MammalInt implements Animal {
   public void eat() {
      System.out.println("Mammal eats");
   }
   public void travel() {
      System.out.println("Mammal travels");
   }
   public int noOfLegs() {
      return 0;
   }
   public static void main(String args[]) {
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
}
Now compile the java files as shown below −
$ javac -d . Animal.java $ javac -d . MammalInt.java
Now a package/folder with the name animals will be created in the current directory and these class files will be placed in it as shown below.
You can execute the class file within the package and get the result as shown below.
Mammal eats
Mammal travels
How to get the value of div content using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.
You can try to run the following code to get the value of div content using jQuery:
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
   $("#button1").click(function() {
     var res = $('#demo').text();
     alert(res);
   });
});
</script>
</head>
<body>

<div id="demo"> This is <b>demo</b> text.
</div>
<button id="button1">Get</button>

</body>
</html>
Tryit Editor v3.7

Tryit: CSS borders
While working with Java in eclipse I got a warning saying "dead code". What does it mean?

A code block/statement in Java to which the control never reaches and never gets executed during the lifetime of the program is known as unreachable block/statement.
public class UnreachableCodeExample {
   public String greet() {
      System.out.println("This is a greet method ");
      return "Hello";
      System.out.println("This is an unreachable code ");
   }
   public static void main(String args[]) {
      new UnreachableCodeExample().greet();
   }
}
A dead code is an unreachable code, but it doesn’t generate compile time error. But if you execute it in eclipse it gives you a warning.
In the following Java program
 Live Demo
public class UnreachableCodeExample {
   public void greet() {
      System.out.println("This is the greet method ");
      if(true){
         return;
      }
      System.out.println("This is a dead code ");
   }
   public static void main(String args[]) {
      new UnreachableCodeExample().greet();
   }
}
This is the greet method
If you run the same program in eclipse it raises a warning as −
Print all combinations of factors in C++

In this problem, we are given a number n. Our task is to print all combinations of factors of n.
Let’s take an example to understand the topic better −
Input: 24
Output:
2 2 2 3
2 4 3
8 3
4 6
2 12
For this, we will use recursion function which will find a combination of factors of the number. And we will store all our combinations in an array of array.
This code will show the implementation of our solution.
 Live Demo
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> factor_Combo;
void genreateFactorCombinations(int first, int eachFactor, int n, vector<int>factor) {
   if (first>n || eachFactor>n)
      return;
   if (eachFactor == n){
      factor_Combo.push_back(factor);
      return;
   }
   for (int i = first; i < n; i++) {
      if (i*eachFactor>n)
      break;
      if (n % i == 0){
         factor.push_back(i);
         genreateFactorCombinations(i, i*eachFactor, n, factor);
         factor.pop_back();
      }
   }
}
void printcombination() {
   for (int i = 0; i < factor_Combo.size(); i++){
      for (int j = 0; j < factor_Combo[i].size(); j++)
         cout<<factor_Combo[i][j]<<"\t";
      cout<<endl;
   }
}
int main() {
   int n = 24;
   vector<int>single_result_list;
   cout<<"All Factor combinations of "<<n<<" are :\n";
   genreateFactorCombinations(2, 1, n, single_result_list);
   printcombination();
   return 0;
}
All Factor combinations of 24 are −
2 2 2 3
2 2 6
2 3 4
2 12
3 8
4 6
How to change color of Button in Android when Clicked?

This example demonstrates about How do I change the color of Button in Android when clicked.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Click here to change color!"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      tools:ignore="HardcodedText" />
</android.support.constraint.ConstraintLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      final Button button = findViewById(R.id.button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
            button.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
         }
      });
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click  here  to download the project code
How to copy files with the specific extension in PowerShell?

To copy the files with the specific extension, you need to use the Get-ChildItem command. Through the Get-ChildItem you first need to retrieve the files with the specific extension(s) and then you need to pipeline Copy-Item command.
Here, we need to copy *.txt files from the source to the destination location.
First, we will retrieve all the *.txt files available in the source path.
Get-ChildItem D:\Temp\ -Filter *.txt
PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Filter *.txt
    Directory: D:\Temp
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       26-01-2020     19:20          13818 aliases.txt
-a----       18-01-2020     18:25             48 delim.txt
-a----       18-01-2020     17:25             14 GetContentExample.txt
-a----       17-01-2020     22:04          55190 Processes.txt
-a----       18-01-2020     18:22          27620 ReadC.txt
-ar---       13-01-2020     18:19              0 Readonlyfile.txt
-a----       18-01-2020     18:44             22 stream1.txt
-a----       18-01-2020     16:26          27620 testreadC.txt
We are going to copy the above files to the destination folder.
Get-ChildItem D:\Temp\ -Filter *.txt | Copy-Item -
Destination D:\TempContent\ -Force -PassThru
PS C:\WINDOWS\system32> Get-ChildItem D:\Temp\ -Filter *.txt | Copy-Item -Destination D:\TempContent\ -Force -PassThru
    Directory: D:\TempContent
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----       26-01-2020     19:20          13818 aliases.txt
-a----       18-01-2020     18:25             48 delim.txt
-a----       18-01-2020     17:25             14 GetContentExample.txt
-a----       17-01-2020     22:04          55190 Processes.txt
-a----       18-01-2020     18:22          27620 ReadC.txt
-ar---       13-01-2020     18:19              0 Readonlyfile.txt
-a----       18-01-2020     18:44             22 stream1.txt
-a----       18-01-2020     16:26          27620 testreadC.txt
trunc() , truncf() , truncl() in C language

Here we will see three functions. These functions are trunc(), truncf() and the truncl(). These functions are used to convert floating point values into truncated form.
This function is used to truncate double type value. And return only the integer part. The syntax is like below.
double trunc(double argument)
#include <stdio.h>
#include <math.h>
main() {
   double a, b, x, y;
   x = 53.26;
   y = 75.86;
   a = trunc(x);
   b = trunc(y);
   printf("The value of a: %lf\n",a);
   printf("The value of a: %lf\n",b);
}
The value of a: 53.000000
The value of a: 75.000000
This function is used to truncate floating type value. And return only the integer part. The syntax is like below.
float tuncf(float argument)
#include <stdio.h>
#include <math.h>
main() {
   float a, b, x, y;
   x = 53.26;
   y = 75.86;
   a = truncf(x);
   b = truncf(y);
   printf("The value of a: %f\n",a);
   printf("The value of a: %f\n",b);
}
The value of a: 53.000000
The value of a: 75.000000
This is like trunc() or truncf(). But the main difference is, this function is used to truncate long double type value. And return only the integer part.
The syntax is like below.
long double truncl(long double argument)
#include <stdio.h>
#include <math.h>
main() {
   long double a, b, x, y;
   x = 53547.55555555555;
   y = 78547.55555555523;
   a = truncl(x);
   b = truncl(y);
   printf("The value of a: %Lf\n",a);
   printf("The value of a: %Lf\n",b);
}
The value of a: 53547.000000
The value of a: 78547.000000
Nested Classes in C#

Nested class is a class declared in another enclosing class. It is a member of its enclosing class and the members of an enclosing class have no access to members of a nested class.
Let us see an example code snippet of nested classes in C# −
class One {
   public int val1;

   public class Two {
      public int val1;
   }
}

class Demo {
   static void Main() {
      One a = new One();
      a.val1++;

      One.Two ab = new One.Two();
      ab.val2++;
   }
}
The example shows that class Two is a nested class. The class Two is enclosed inside the class One declaration.
The class Two here is enclosed inside the declaration of class One. Class Two is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than class One's scope.
How to Fix: TypeError: ‘numpy.float’ object is not callable? - GeeksforGeeks

28 Nov, 2021
In this article, we are going to see how to fix TypeError: ‘numpy.float’ object is not callable in Python. There is only one case in which we can see this error: 
If we try to call a NumPy array as a function, we are most likely to get such an error. 
Example:
Python3
import numpy as np  a = np.array([1,2,3])  a()
Output:
TypeError: 'numpy.ndarray' object is not callable
In the older version of Numpy, we used to see “numpy.float64” instead of “numpy.ndarray”.
Solution: 
This can be solved simply by removing the parenthesis after the array. 
Python3
import numpy as np  a = np.array([1,2,3])  a
Output:
array([1, 2, 3])
Here version of NumPy is ‘1.21.2’.
Note: In the earlier version of Numpy, we also used to get this error while using Python min() or max() function with a NumPy array. In the recent versions of NumPy, this is solved.  In the earlier versions, this particular error was supposed to be solved using np.max() or np.min() instead of min() and max(). 
Picked
Python How-to-fix
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
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
pow() in Python - GeeksforGeeks

22 Sep, 2021
Python pow() function returns the power of the given numbers. This function computes x**y. This function first converts its arguments into float and then computes the power. 
Syntax: pow(x,y)
Parameters : 
x : Number whose power has to be calculated.
y : Value raised to compute power.
Return Value :  Returns the value x**y in float.
Python3
# Python code to demonstrate pow()# version 1 print("The value of 3**4 is : ", end="") # Returns 81print(pow(3, 4))
Output: 
The value of 3**4 is : 81.0
float pow(x,y,mod) function computes (x**y) % mod. This function first converts its arguments into float and then computes the power. 
Syntax: float pow(x,y,mod)
Parameters : 
x : Number whose power has to be calculated.
y : Value raised to compute power.
mod :  Value with which modulus has to be computed.
Return Value :  Returns the value (x**y) % mod in float.
Python3
# Python code to demonstrate pow()# version 2 print("The value of (3**4) % 10 is : ", end="") # Returns 81%10# Returns 1print(pow(3, 4, 10))
Output: 
The value of (3**4) % 10 is : 1
Python3
# Python code to discuss negative# and non-negative cases # positive x, positive y (x**y)print("Positive x and positive y : ", end="")print(pow(4, 3)) print("Negative x and positive y : ", end="")# negative x, positive y (-x**y)print(pow(-4, 3)) print("Positive x and negative y : ", end="")# positive x, negative y (x**-y)print(pow(4, -3)) print("Negative x and negative y : ", end="")# negative x, negative y (-x**-y)print(pow(-4, -3))
Output:
Positive x and positive y : 64
Negative x and positive y : -64
Positive x and negative y : 0.015625
Negative x and negative y : -0.015625
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
RajuKumar19
kumar_satyam
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Lodash _.concat() Function - GeeksforGeeks

05 May, 2021
Lodash proves to be much useful when working with arrays, strings, objects etc. It makes math operations and function paradigm much easier, concise. The _.concat() function is used to concatenating the arrays in JavaScript.
Syntax:
_.concat(array, [values])
Parameters: This function accept two parameters as mentioned above and described below: 
array: It is an array to which values are to be added.
values: It is the Array of values that is to be added to the original array.
Note: The array value can also contain arrays of array or simple a single object to be added to original array.
Return Value: This function returns the array after concatenation.
Few examples are given below for better understanding of the function.
Example 1:
Javascript
// Requiring the lodash librarylet lodash = require("lodash"); // Original array to be concatenatedlet array = [1, 2, 3]; // Values to be added to original arraylet values = [0, 5, "a", "b"] let newArray = lodash.concat(array, values);console.log("Before concat: " + array); // Printing newArrayconsole.log("After concat: " + newArray);
Output:
Example 2: Adding array of array to original array.
JavaScript
// Requiring the lodash librarylet lodash = require("lodash"); // Original array to be concatenatedlet array = ["a", 2, 3]; // Array of array to be added// to original arraylet values = [0, 5, ["a", "b"]]let newArray = lodash.concat(array, values);console.log("Before concat: ", array); // Printing arrayconsole.log("After concat: ", newArray);
Output:
Example 3: This example adding the object to the array.
Javascript
// Requiring the lodash librarylet lodash = require("lodash"); // Original array to be concatenatedlet array = ["a", 2, 3]; // Object of values to be// added to original arraylet values = { "a": 1, "b": 2 }let newArray = lodash.concat(array, values);console.log("Before concat: ", array); // Printing arrayconsole.log("After concat: ", newArray);
Output:
surinderdawra388
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
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?
Matcher lookingAt() method in Java with Examples - GeeksforGeeks

26 Nov, 2018
The lookingAt() method of Matcher Class attempts to match the pattern partially or fully in the matcher. It returns a boolean value showing if the pattern was matched even partially or fully starting from the start of the pattern.
Syntax:
public boolean lookingAt()

Parameters: This method do not takes any parameter.
Return Value: This method returns a boolean value showing if a prefix of the input sequence matches this matcher’s pattern.
Below examples illustrate the Matcher.lookingAt() method:
Example 1:
// Java code to illustrate lookingAt() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "Geeks";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GeeksForGeeks";          // Create a matcher for the input String        Matcher matcher            = pattern                  .matcher(stringToBeMatched);          // Get the possible result        // using lookingAt() method        System.out.println(matcher.lookingAt());    }}
true

Example 2:
// Java code to illustrate lookingAt() method  import java.util.regex.*;  public class GFG {    public static void main(String[] args)    {          // Get the regex to be checked        String regex = "GFG";          // Create a pattern from regex        Pattern pattern            = Pattern.compile(regex);          // Get the String to be matched        String stringToBeMatched            = "GFGFGFGFGFGFGFGFGFG";          // Create a matcher for the input String        Matcher matcher            = pattern                  .matcher(stringToBeMatched);          // Get the possible result        // using lookingAt() method        System.out.println(matcher.lookingAt());    }}
true

Reference: https://docs.oracle.com/javase/9/docs/api/java/util/regex/Matcher.html#lookingAt–
Java - util package
Java-Functions
Java-Matcher
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
HTML DOM revokeObjectURL() method - GeeksforGeeks

14 Jul, 2020
The URL revokeObjectURL() method releases an existing object URL which was created by using URL createObjectURL(). This method is called when you are finished using an object URL and don’t want the browser to keep the reference to that file any longer.
Syntax:
URL.revokeObjectURL(objectURL);
Parameters:
objectURL: A DOMString object URL to be released.
Return Value: This method has no return value.
Example: In this example, create an objectURL using createObjectURL() method and then revoked it.
<!DOCTYPE html><html><head>  <meta charset="utf-8">  <title>URL.revokeObjectURL example</title></head><body>  <h1>GeeksforGeeks</h1>  <input type="file">  <img>  <p class="p">The URL of this image is : </p></body><script>    var Element = document.querySelector('input');    var img = document.querySelector('img');    Element.addEventListener('change', function() {      var url = URL.createObjectURL(Element.files[0]);      img.src = url;      console.log(url);      URL.revokeObjectURL(url)      var d=document.querySelector(".p");      d.textContent+=url;});</script></html>
Output:
Before Choosing Image:
After Choosing Image: In the console, an error can be seen that “Not allowed to load local resource” as the URL is revoked.
Checking the Object URL will also give “File not found”:
Supported Browsers:
Google Chrome
Edge
Firefox
Safari
Opera
Internet Explorer
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-DOM
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
GATE | GATE-CS-2009 | Question 17 - GeeksforGeeks

17 Sep, 2017
Match all items in Group 1 with correct options from those given in Group 2.
Group 1                          Group 2
P. Regular expression        1. Syntax analysis
Q. Pushdown automata         2. Code generation
R. Dataflow analysis         3. Lexical analysis
S. Register allocation       4. Code optimization
 (A) P-4. Q-1, R-2, S-3(B) P-3, Q-1, R-4, S-2(C) P-3, Q-4, R-1, S-2(D) P-2, Q-1, R-4, S-3Answer: (B)Explanation: Regular expressions are used in lexical analysis.
Pushdown automata is related to context free grammar which is related to syntax analysis.
Dataflow analysis is done in code optimization.
Register allocation is done in code generation.Quiz of this Question
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
XOR of a subarray in C++

In this problem, we are given an arr[] and some queries that are range between L to R in the array. Our task is to print the XOR of the subarray between L to R.
Let’s take an example to understand the problem,
Input − array = {1, 4, 5, 7, 2, 9} L = 1 , R = 5
Output −
Explanation − 4^5^7^2^9
To solve this problem, we will create an array, based on the following observation,
To solve this problem, we will create an array, based on the following observation,
We will XOR multiple bits, if there are odd number of 1s, the result will be 1 otherwise the result is 0.
We will XOR multiple bits, if there are odd number of 1s, the result will be 1 otherwise the result is 0.
Now, we will create a two-dimensional array count that will store the count of 1s. The value count[i][j] is the count of number of 1s for position i-j which is the number of 1’s that are present in subarray arr[0..j] at ith position of the bit. The number of 1s for all bits of the sub-array arr[L..R] is found using the count array. Formula to find arr[L...R] = count[i][R] - count[i][L-1]. If the number of 1s is odd, then ith bit is set in result. The final result can be obtained by summing up the power of 2 corresponding to ith bit given that it is set bit.
Program to show the implementation of our solution,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void preProcessArray(int arr[], int n, vector<vector<int> >& cnt) {
   int i, j;
   for (i = 0; i < 32; i++) {
      cnt[i][0] = 0;
      for (j = 0; j < n; j++) {
         if (j > 0) {
            cnt[i][j] = cnt[i][j - 1];
         }
         if (arr[j] & (1 << i))
         cnt[i][j]++;
      }
   }
}
int findXORofSubArray(int L, int R, const vector<vector<int> > count) {
   int result = 0;
   int noOfOnes;
   int i, j;
   for (i = 0; i < 32; i++) {
      noOfOnes = count[i][R] - ((L > 0) ? count[i][L - 1] : 0);
      if (noOfOnes & 1) {
         result+=(1 << i);
      }
   }
   return result;
}
int main(){
   int arr[] = { 1, 4, 5, 7, 2, 9 };
   int n = sizeof(arr) / sizeof(arr[0]);
   vector<vector<int> > count(32, vector<int>(n));
   preProcessArray(arr, n, count);
   int L = 1;
   int R = 5;
   cout<<"The XOR of SubArray: "<<findXORofSubArray(L, R, count);
   return 0;
}
The XOR of SubArray: 13
For and While loops in Arduino

The for and while loops in Arduino follow the C language syntax.
The syntax for the for loop is −
for(iterator initialization; stop condition; increment instruction){
   //Do something
}
for(int i = 0; i< 50; i++){
   //Do something
}
Similarly, the syntax for the while loop is −
while(condition){
   //Do something
}
int i = 0
while(i < 50){
   //Do something
   i = i+1;
}
The following example will illustrate the working of for and while loops in an Arduino program.
void setup() {
   Serial.begin(9600);
}
void loop() {
   // put your main code here, to run repeatedly:
   int i = 0;
   for(i = 0; i< 10; i++){
         Serial.println(i);
      }

   while(i < 20){
         i = i+1;
         Serial.println(i);
      }
}
Note that we defined the integer i outside the for loop. Had I written for(int i = 0; i< 10; i++), then the scope of the variable i would have been restricted to the for loop only, and the while loop would not have been able to access it. 
The Serial Monitor output of the above program is shown below −
As you can see, the two loops are sharing the variable, i.
In order to write infinite loops, you can use the following syntax for for loops −
for(;;){
   //Do something continuously
}
And the following for the while loops −
while(1){
   //Do something continuously
}
How do I get interactive plots again in Spyder/Ipython/matplotlib?

To get interactive plots, we need to activate the figure. Using plt.ioff() and plt.ion(), we can perform interactive actions with plot.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Create fig and ax variables using subplots method, where default nrows and ncols are 1.
Draw a line, using plot() method.
Draw a line, using plot() method.
Set the color of the line, i.e., orange.
Set the color of the line, i.e., orange.
Stopped the interaction, using plt.ioff() method.
Stopped the interaction, using plt.ioff() method.
To make the interaction plots, change the color of the line coordinate.
To make the interaction plots, change the color of the line coordinate.
Start the interaction, using plt.ion() method.
Start the interaction, using plt.ion() method.
To use interactive plot in Ipython -
In [1]: %matplotlib auto

Using matplotlib backend: GTK3Agg

In [2]: import matplotlib.pyplot as plt

In [3]: fig, ax = plt.subplots()    # Diagram will get popped up, Let’s interact.

In [4]: ln, = ax.plot(range(5))     # Drawing a line

In [5]: ln.set_color('orange')      # Changing drawn line to orange

In [6]: plt.ioff()                  # Stopped interaction

In [7]: ln.set_color('green')
# Since we have stopped the interaction in the last step

In [8]: plt.ion()                   # Started interaction
Python - Every Kth Strings Uppercase - GeeksforGeeks

05 Sep, 2020
Given a String list, change every Kth string to uppercase.
Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], K = 3Output : [‘GFG’, ‘is’, ‘best’, ‘FOR’, ‘geeks’]Explanation : All Kth strings are uppercased.
Input : test_list = [“gfg”, “is”, “best”, “for”, “geeks”], K = 4Output : [‘GFG’, ‘is’, ‘best’, ‘for’, ‘GEEKS’]Explanation : All Kth strings are uppercased.
Method #1 : Using loop + upper()
In this, we iterate for all strings using loop and upper is used to perform uppercase, Kth index is detected using modulo operator.
Python3
# Python3 code to demonstrate working of # Every Kth Strings Uppercase# Using loop + upper()  # initializing listtest_list = ["gfg", "is", "best", "for", "geeks", "and", "CS"]   # printing original listprint("The original list is : " + str(test_list))  # initializing K K = 3  res = []for idx in range(len(test_list)):          # checking for Kth index    if idx % K == 0:        res.append(test_list[idx].upper())    else :        res.append(test_list[idx])  # printing result print("The resultant String list : " + str(res))
The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'CS']
The resultant String list : ['GFG', 'is', 'best', 'FOR', 'geeks', 'and', 'CS']

Method #2 : Using list comprehension
This yet another way in which this task can be performed. In this we use list comprehension as shorthand, performs tasks similar to above method.
Python3
# Python3 code to demonstrate working of # Every Kth Strings Uppercase# Using list comprehension  # initializing listtest_list = ["gfg", "is", "best", "for", "geeks", "and", "CS"]   # printing original listprint("The original list is : " + str(test_list))  # initializing K K = 3  # shorthand to perform this taskres = [test_list[idx].upper() if idx % K == 0 else test_list[idx]       for idx in range(len(test_list))]  # printing result print("The resultant String list : " + str(res))
The original list is : ['gfg', 'is', 'best', 'for', 'geeks', 'and', 'CS']
The resultant String list : ['GFG', 'is', 'best', 'FOR', 'geeks', 'and', 'CS']

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
How to set priority to the test cases in TestNG?

We can set priority for test cases in order of their execution, by giving priority to each test method. A test method having lower priority runs first then the test methods with higher priority are executed.
@Test (priority = 1)
public void verifyTravel(){
   System.out.println("Travel history successful ");
}
@Test (priority = 2)
public verifyIncome(){
   System.out.println ("Income history successful");
}
In the Java class file, verifyTravel() will run first followed by verifyIncome().
How to extract part of a URL in MySQL?

You need to use SUBSTRING_INDEX() function from MySQL to extract part of a URL.
 Let us first create a table −
mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   URL text
);
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(URL) values('https:\\www.example.com\\homepage');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable(URL) values('https:\\www.onlinetest.com\\welcome\\indexpage');
Query OK, 1 row affected (0.12 sec)
Following is the query to display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output. Here, we can only a slash is visible because internally MySQL removes one slash in result −
+----+---------------------------------------------+
| Id | URL                                         |
+----+---------------------------------------------+
| 1  | https:\www.example.com\homepage             |
| 2  | https:\www.onlinetest.com\welcome\indexpage |
+----+---------------------------------------------+
2 rows in set (0.00 sec)
Following is the query to extract part of a URL in MySQL −
mysql> select substring_index(URL,'\\',-1) from DemoTable;
This will produce the following output −
+------------------------------+
| substring_index(URL,'\\',-1) |
+------------------------------+
| homepage                     |
| indexpage                    |
+------------------------------+
2 rows in set (0.00 sec)
Python | Number to Words using num2words - GeeksforGeeks

19 Jul, 2019
num2words module in Python, which converts number (like 34) to words (like thirty-four). Also, this library has support for multiple languages. In this article, we will see how to convert number to words using num2words module.
InstallationOne can easily install num2words using pip.
pip install num2words

Consider the following two excerpts from different files taken from 20 Newsgroups, a popular NLP database. Pre-processing 20 Newsgroups effectively has remained to be a matter of interest.
In article, Martin Preston writes: Why not use the PD C library for reading/writing TIFF files? It took me a good 20 minutes to start using them in your own app.ISCIS VIII is the eighth of a series of meetings which have brought together computer scientists and engineers from about twenty countries. This year’s conference will be held in the beautiful Mediterranean resort city of Antalya, in a region rich in natural as well as historical sites.
In the above two excerpts, one can observe that the number ’20’ appears in both numeric and alphabetical forms. Simply following the pre-processing steps, that involve tokenization, lemmatization and so on would not be able to map ’20’ and ‘twenty’ to the same stem, which is of contextual importance. Luckily, we have the in-built library, num2words which solves this problem in a single line.
Below is the sample usage of the tool.
from num2words import num2words  # Most common usage.print(num2words(36))  # Other variants, according to the type of article.print(num2words(36, to = 'ordinal'))print(num2words(36, to = 'ordinal_num'))print(num2words(36, to = 'year'))print(num2words(36, to = 'currency'))  # Language Support.print(num2words(36, lang ='es'))
Output:
thirty-six
thirty-sixth
36th
zero euro, thirty-six cents
treinta y seis

Therefore, in the pre-processing step, one could convert ALL numeric values to words for better accuracy in the further stages.
References: https://pypi.org/project/num2words/
Natural-language-processing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
numpy.remainder() in Python - GeeksforGeeks

10 Feb, 2019
numpy.remainder() is another function for doing mathematical operations in numpy.It returns element-wise remainder of division between two array arr1 and arr2 i.e. arr1 % arr2 .It returns 0 when arr2 is 0 and both arr1 and arr2 are (arrays of) integers.
Syntax : numpy.remainder(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj], ufunc ‘remainder’)
Parameters :arr1 : [array_like] Dividend array.arr2 : [array_like] Divisor array.dtype : The type of the returned array. By default, the dtype of arr is used.out : [ndarray, optional] A location into which the result is stored.  -> If provided, it must have a shape that the inputs broadcast to.  -> If not provided or None, a freshly-allocated array is returned.where : [array_like, optional] Values of True indicate to calculate the ufunc at that position, values of False indicate to leave the value in the output alone.**kwargs : Allows to pass keyword variable length of argument to a function. Used when we want to handle named argument in a function.
Return : [ndarray] The element-wise remainder i.e arr1 % arr2 .
Code #1 :
# Python program explaining# numpy.remainder() function  import numpy as geekin_num1 = 4in_num2 = 6  print ("Dividend : ", in_num1)print ("Divisor : ", in_num2)    out_num = geek.remainder(in_num1, in_num2) print ("Remainder : ", out_num) 
Dividend :  4
Divisor :  6
Remainder :  4

 
Code #2 :
# Python program explaining# numpy.remainder() function  import numpy as geek  in_arr1 = geek.array([5, -4, 8])in_arr2 = geek.array([2, 3, 4])   print ("Dividend array : ", in_arr1)print ("Divisor array : ", in_arr2)       out_arr = geek.remainder(in_arr1, in_arr2) print ("Output remainder array: ", out_arr) 
Dividend array :  [ 5 -4  8]
Divisor array :  [2 3 4]
Output remainder array:  [1 2 0]

Python numpy-Mathematical Function
Python-numpy
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()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Case sensitive string comparison in Java.

You can compare two strings using either equals() method or compareTo() method.
Where,
The equals() method compares this string to the specified object.
The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings.
These two methods compare the given strings with respective to Case i.e. String with the different case are treated differently.
Following example demonstrates the comparison of two strings using the equals() method.
Live Demo
public class Sample{
   public static void main(String args[]) {
      String str = "Hello World";
      String anotherString = "hello world";
      Object objStr = str;
      System.out.println( str.equals(anotherString) );
   }
}
false
Check if given number is perfect square in Python

Suppose we have a number n. We have to check whether the number n is perfect square or not. A number is said to be a perfect square number when its square root is an integer.
So, if the input is like n = 36, then the output will be True as 36 = 6*6.
To solve this, we will follow these steps −
sq_root := integer part of (square root of n)
return true when sq_root^2 is same as n otherwise false
Let us see the following implementation to get better understanding −
 Live Demo
from math import sqrt
def solve(n):
   sq_root = int(sqrt(n))
   return (sq_root*sq_root) == n
n = 36
print (solve(n))
36
True
Python - Filter dictionary key based on the values in selective list

Sometimes in a Python dictionary we may need to to filter out certain keys of the dictionary based on certain criteria. In this article we will see how to filter out keys from Python dictionary.
In this approach we put the values of the keys to be filtered in a list. Then iterate through each element of the list and check for its presence in the given dictionary. We create a resulting dictionary containing these values which are found in the dictionary.
 Live Demo
dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}
key_list = ['Tue','Thu']

print("Given Dictionary:\n",dictA)
print("Keys for filter:\n",key_list)
res = [dictA[i] for i in key_list if i in dictA]

print("Dictionary with filtered keys:\n",res)
Running the above code gives us the following result −
Given Dictionary:
   {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}
Keys for filter:
   ['Tue', 'Thu']
Dictionary with filtered keys:
   ['chem', 'Bio']
We use intersection to find the common elements between the given dictionary and the list. Then apply the set function to get the distinct elements and convert the result to a list.
 Live Demo
dictA= {'Mon':'Phy','Tue':'chem','Wed':'Math','Thu':'Bio'}
key_list = ['Tue','Thu']

print("Given Dictionary:\n",dictA)
print("Keys for filter:\n",key_list)

temp = list(set(key_list).intersection(dictA))

res = [dictA[i] for i in temp]

print("Dictionary with filtered keys:\n",res)
Running the above code gives us the following result −
Given Dictionary:
   {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'}
Keys for filter:
   ['Tue', 'Thu']
Dictionary with filtered keys:
   ['chem', 'Bio']
Unary Operators Overloading in C++

The unary operators operate on a single operand and following are the examples of Unary operators −
The increment (++) and decrement (--) operators.
The unary minus (-) operator.
The logical not (!) operator.
The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++obj but sometime they can be used as postfix as well like obj++ or obj--.
Following example explain how minus (-) operator can be overloaded for prefix as well as postfix usage.
#include <iostream>
using namespace std;
 
class Distance {
   private:
      int feet;             // 0 to infinite
      int inches;           // 0 to 12
      
   public:
      // required constructors
      Distance() {
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i) {
         feet = f;
         inches = i;
      }
      
      // method to display distance
      void displayDistance() {
         cout << "F: " << feet << " I:" << inches <<endl;
      }
      
      // overloaded minus (-) operator
      Distance operator- () {
         feet = -feet;
         inches = -inches;
         return Distance(feet, inches);
      }
};

int main() {
   Distance D1(11, 10), D2(-5, 11);
 
   -D1;                     // apply negation
   D1.displayDistance();    // display D1

   -D2;                     // apply negation
   D2.displayDistance();    // display D2

   return 0;
}
When the above code is compiled and executed, it produces the following result −
F: -11 I:-10
F: 5 I:-11

Hope above example makes your concept clear and you can apply similar concept to overload Logical Not Operators (!).

    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Java Program to center a JLabel in a JPanel with LayoutManager

Here, we are using the LayoutManager GridBagLayout to center the components. We have two components here including a label and we have set the layout as GridBagLayout −
JLabel label = new JLabel("Name (Centered Label): ");
JTextArea text = new JTextArea();
text.setText("Add name here...");
panel.setLayout(new GridBagLayout());
The following is an example to center a JLabel in a JPanel with LayoutManager −
package my;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame("Demo Frame");
      JPanel panel = new JPanel();
      JLabel label = new JLabel("Name (Centered Label): ");
      JTextArea text = new JTextArea();
      text.setText("Add name here...");
      panel.setLayout(new GridBagLayout());
      panel.add(label);
      panel.add(text);
      panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.setSize(500, 300);
      frame.setVisible(true);
   }
}