code-rag-bench/online-tutorials huggingface dataset:
Google Guice - Method Injection

Injection is a process of injecting dependeny into an object. Method injection is used to set value object as dependency to the object. See the example below.
Create a java class named GuiceTester.
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.name.Named;
import com.google.inject.name.Names;

public class GuiceTester {
   public static void main(String[] args) {
      Injector injector = Guice.createInjector(new TextEditorModule());
      TextEditor editor = injector.getInstance(TextEditor.class);
      editor.makeSpellCheck();
   } 
}

class TextEditor {
   private SpellChecker spellChecker;

   @Inject
   public TextEditor( SpellChecker spellChecker) {
      this.spellChecker = spellChecker;
   }

   public void makeSpellCheck(){
      spellChecker.checkSpelling();
   } 
}

//Binding Module
class TextEditorModule extends AbstractModule {

   @Override
   protected void configure() { 
      bind(String.class)
         .annotatedWith(Names.named("JDBC"))
         .toInstance("jdbc:mysql://localhost:5326/emp");
   } 
}

@ImplementedBy(SpellCheckerImpl.class)
interface SpellChecker {
   public void checkSpelling();
}

//spell checker implementation
class SpellCheckerImpl implements SpellChecker {
 
   private String dbUrl;

   public SpellCheckerImpl(){}
   
   @Inject 
   public void setDbUrl(@Named("JDBC") String dbUrl){
      this.dbUrl = dbUrl;
   }

   @Override
   public void checkSpelling() { 
      System.out.println("Inside checkSpelling." );
      System.out.println(dbUrl); 
   }
}
Compile and run the file, you will see the following output.
Find the longest path in a matrix with given constraints in C++

Suppose we have one square matrix of order n. It has all distinct elements. So we have to find the maximum length path, such that all cells along the path are in increasing order with a difference of 1. From one cell we can move to four directions. Left, Right, Top and Bottom. So if the matrix is like −
So the output will be 4. As the longest path is 6→7→8→ 9
To solve this problem, we will follow this idea. We will calculate longest path beginning with every cell. Once we have got the longest for all cells, we return maximum of all longest paths.
One important observation in this approach is many overlapping sub-problems. So this problem can be solved using Dynamic Programming. Here we will use a lookup table dp[][] to check if a problem is already solved or not.
#include <iostream>
#define n 3
using namespace std;
int getLongestPathLengthUtil(int i, int j, int matrix[n][n], int table[n][n]) {
   if (i < 0 || i >= n || j < 0 || j >= n)
   return 0;
   if (table[i][j] != -1)
      return table[i][j];
   int x = INT_MIN, y = INT_MIN, z = INT_MIN, w = INT_MIN;
   if (j < n - 1 && ((matrix[i][j] + 1) == matrix[i][j + 1]))
      x = 1 + getLongestPathLengthUtil(i, j + 1, matrix, table);
   if (j > 0 && (matrix[i][j] + 1 == matrix[i][j - 1]))
      y = 1 + getLongestPathLengthUtil(i, j - 1, matrix, table);
   if (i > 0 && (matrix[i][j] + 1 == matrix[i - 1][j]))
      z = 1 + getLongestPathLengthUtil(i - 1, j, matrix, table);
   if (i < n - 1 && (matrix[i][j] + 1 == matrix[i + 1][j]))
      w = 1 + getLongestPathLengthUtil(i + 1, j, matrix, table);
      return table[i][j] = max(x, max(y, max(z, max(w, 1))));
}
int getLongestPathLength(int matrix[n][n]) {
   int result = 1;
   int table[n][n];
   for(int i = 0; i < n; i++)
   for(int j = 0; j < n; j++)
   table[i][j] = -1;
   for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
         if (table[i][j] == -1)
         getLongestPathLengthUtil(i, j, matrix, table);
         result = max(result, table[i][j]);
      }
   }
   return result;
}
int main() {
   int mat[n][n] = { { 1, 2, 9 },
   { 5, 3, 8 },
   { 4, 6, 7 } };
   cout << "Length of the longest path is "<< getLongestPathLength(mat);
}
Length of the longest path is 4
reflect.Tag.Get() Function in Golang with Examples

28 Apr, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Tag.Get() Function in Golang is used to find the value associated with key in the tag string, an empty string is returned if there is no such key in the tag. To access this function, one needs to imports the reflect package in the program.
Syntax:
func (tag StructTag) Get(key string) string

Parameters: This function takes one parameters of string type, i.e. key.
Return Value: This function returns the value associated with key in the tag string.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.Tag.Get() Function  package main  import (    "fmt"    "reflect")  type Employee struct {    ID      string `auto_increment:"true" increment:"1"`    Name    string `varchar: "255"`    Surname string `"varchar: "255"`}  // Main functionfunc main() {    e := Employee{}    // c variable represents table columns    c := reflect.TypeOf(e).Field(0).Tag    fmt.Printf("%s\n\n", c)      // use of Get method    g := c.Get("increment")    fmt.Printf("Get method: %s\n", g)}
Output:
auto_increment:"true" increment:"1"

Get method: 1

Example 2:
// Golang program to illustrate// reflect.Tag.Get() Function   package main  import (    "fmt"    "reflect")  // Main function func main() {    type tag struct {        val string `Value_1:"GeeksforGeeks" Value_2:"Best Platform :"`    }      src := tag {}    st := reflect.TypeOf(src)    field := st.Field(0)          // use of Get method    fmt.Println(field.Tag.Get("Value_2"), field.Tag.Get("Value_1"))  }
Output:
Best Platform : GeeksforGeeks

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
strings.Replace() Function in Golang With Examples
fmt.Sprintf() Function in Golang With Examples
Arrays in Go
Golang Maps
How to Split a String in Golang?
Interfaces in Golang
Slices in Golang
Different Ways to Find the Type of Variable in Golang
How to Parse JSON in Golang?
How to convert a string in lower case in Golang?
OS Path module in Python

The os.path module is a very extensively used module that is handy when processing files from different places in the system. It is used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters. Its results are specific to the OS on which it is being run.
This function gives us the last part of the path which may be a folder or a file name. Please the difference in how the path is mentioned in Windows and Linux in terms of the backslash and the forward slash.
import os
# In windows
fldr = os.path.basename("C:\\Users\\xyz\\Documents\\My Web Sites")
print(fldr)
file = os.path.basename("C:\\Users\\xyz\\Documents\\My Web Sites\\intro.html")
print(file)
# In nix*
fldr = os.path.basename("/Documents/MyWebSites")
print(fldr)
file = os.path.basename("/Documents/MyWebSites/music.txt")
print(file)
Running the above code gives us the following result −
My Web Sites
intro.html
MyWebSites
music.txt
This function gives us the directory name where the folder or file is located.
import os
# In windows
DIR = os.path.dirname("C:\\Users\\xyz\\Documents\\My Web Sites")
print(DIR)
# In nix*
DIR = os.path.dirname("/Documents/MyWebSites")
print(DIR)
Running the above code gives us the following result −
C:\Users\xyz\Documents
/Documents
Sometimes we may need to check if the complete path given, represents a folder or a file. If the file does not exist then it will give False as the output. If the file exists then the output is True.   
print(IS_FILE)
IS_FILE = os.path.isfile("C:\\Users\\xyz\\Documents\\My Web Sites\\intro.html")
print(IS_FILE)
# In nix*
IS_FILE = os.path.isfile("/Documents/MyWebSites")
print(IS_FILE)
IS_FILE = os.path.isfile("/Documents/MyWebSites/music.txt")
print(IS_FILE)

Running the above code gives us the following result −
False
True
False
True
This is a interesting function which will normalize the given path by eliminating extra slashes or changing the backslash to forward slash depending on which OS it is. As you can see the output below varies depending on which OS you run the program on.
import os
# Windows path
NORM_PATH = os.path.normpath("C:/Users/Pradeep/Documents/My Web Sites")
print(NORM_PATH)
# Unix Path
NORM_PATH = os.path.normpath("/home/ubuuser//Documents/")
print(NORM_PATH)
Running the above code gives us the following result −
# Running in Windows
C:\Users\Pradeep\Documents\My Web Sites
\home\ubuuser\Documents

# Running in Linux
C:/Users/Pradeep/Documents/My Web Sites
/home/ubuuser/Documents
C++ Program to Find Fibonacci Numbers using Dynamic Programming

The Fibonacci sequence is like this,
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55,......
In this sequence the nth term is the sum of (n-1)th and (n-2)th terms.
To generate we can use the recursive approach, but in dynamic programming the procedure is simpler. It can store all Fibonacci numbers in a table, by using that table it can easily generate the next terms in this sequence.
Input − Take the term number as an input. Say it is 10
Output − The 10th fibinacci term is 55
Input
max number of terms.
Output
The nth Fibonacci term.
Begin
define array named fibo of size n+2
fibo[0] := 0
fibo[1] := 1
for i := 2 to n, do
fibo[i] := fibo[i-1] + fibo[i-2]
done
return fibo[n]
End
#include<iostream>
using namespace std;
int genFibonacci(int n) {
   int fibo[n+2]; //array to store fibonacci values
   // 0th and 1st number of the series are 0 and 1
   fibo[0] = 0;
   fibo[1] = 1;
   for (int i = 2; i <= n; i++) {
      fibo[i] = fibo[i-1] + fibo[i-2]; //generate ith term using previous
      two terms
   }
   return fibo[n];
}
int main () {
   int n;
   cout << "Enter number of terms: "; cin >>n;
   cout << n<<" th Fibonacci Terms: "<<genFibonacci(n)<<endl;
}
Enter number of terms: 10
10th Fibonacci Terms: 55
Class isInstance() method in Java with Examples

27 Nov, 2019
The isInstance() method of java.lang.Class class is used to check if the specified object is compatible to be assigned to the instance of this Class. The method returns true if the specified object is non-null and can be cast to the instance of this Class. It returns false otherwise.
Syntax:
public boolean isInstance(Object object)

Parameter: This method accepts object as parameter which is the specified object to checked for compatibility to this Class instance.
Return Value: This method returns true if the specified object is non-null and can be cast to the instance of this Class. It returns false otherwise.
Below programs demonstrate the isInstance() method.
Example 1:
// Java program to demonstrate isInstance() method  public class Test {    public static void main(String[] args)        throws ClassNotFoundException    {          // returns the Class object for this class        Class myClass = Class.forName("Test");          System.out.println("Class represented by myClass: "                           + myClass.toString());          // get the Class instance using forName() method        Class c = Class.forName("java.lang.String");          System.out.println("Class represented by c: "                           + c.toString());          // Check if object c is compatible        // using isInstance() method        System.out.println("Is c compatible: "                           + myClass.isInstance(c));    }}
Class represented by myClass: class Test
Class represented by c: class java.lang.String
Is c compatible: false

Example 2:
// Java program to demonstrate isInstance() method  public class Test {    public static void main(String[] args)        throws ClassNotFoundException    {          // returns the Class object for this class        Class myClass = Class.forName("Test");          System.out.println("Class represented by myClass: "                           + myClass.toString());          // get the Class instance using forName() method        Class c = Class.forName("Test");          System.out.println("Class represented by c: "                           + c.toString());          // Check if object c is compatible        // using isInstance() method        System.out.println("Is c compatible: "                           + myClass.isInstance(c));    }}
Class represented by myClass: class Test
Class represented by c: class Test
Is c compatible: false

Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#isInstance-java.lang.Object-
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SAS | Delete Empty Rows

30 Jul, 2019
Generally, when we import data from external sources such as Excel/CSV files, it loads additional rows that are totally blank. Sometimes empty values in the database also affect the desired output so it’s necessary to check missing cases and perform operations accordingly
Example:Input: The sample dataset looks like below have four variables – 1 character and 3 numeric. It would be used further in the example to demonstrate how to remove empty rows.
Create a SAS datasetThe below defined code is a sample dataset to perform delete empty operation.
data outdata;LENGTH name $12.;input name $ phys chem maths ;infile datalines missover;datalines;Shubhash 70 68 66    samar 55 . 85     ashutosh 54 78 89     varun 50 96 85     pratiksha . 68 93 ;run;
Output:
Method I: Removes complete row where all variables having blank/missing valuesOPTIONS missing = ' ';data readin;    SET outdata;    IF missing(cats(of _all_))     THEN       DELETE;run;Note:The MISSING= system option is used to display the missing values as a single space rather than as the default period (.) options missing = ‘ ‘;The CATS function concatenates the values. It also removes leading and trailing blanks. cats(of _all_) – Concatenate all the variablesmissing(cats(of _all_)) – Identifies all the rows in which missing values exist in all the variables.Output:
OPTIONS missing = ' ';data readin;    SET outdata;    IF missing(cats(of _all_))     THEN       DELETE;run;
Note:
The MISSING= system option is used to display the missing values as a single space rather than as the default period (.) options missing = ‘ ‘;
The CATS function concatenates the values. It also removes leading and trailing blanks. cats(of _all_) – Concatenate all the variables
missing(cats(of _all_)) – Identifies all the rows in which missing values exist in all the variables.
Output:
Method II: Removes only that rows where any of the variable has missing/blank valuesdata readin;    SET outdata;     IF cmiss(of _character_)     OR nmiss(of _numeric_) > 0     THEN       DELETE;run;In this case, we are using the OR operator to check if any of the variables have missing values. It returns 4 observations. Check out the output below –
data readin;    SET outdata;     IF cmiss(of _character_)     OR nmiss(of _numeric_) > 0     THEN       DELETE;run;
In this case, we are using the OR operator to check if any of the variables have missing values. It returns 4 observations. Check out the output below –
SAS Programming
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction of Object Oriented Programming
Difference between for and while loop in C, C++, Java
Which Programming Language Should I Choose as a Beginner?
7 Highest Paying Programming Languages For Freelancers in 2022
Exception Handling in C#
Learn C++ Programming Step by Step - A 20 Day Curriculum!
C# | Variables
Top 10 Programming Languages for Blockchain Development
7 Best IDEs For C/C++ Developers in 2022
R - Charts and Graphs
numpy.trim_zeros() in Python

27 Sep, 2019
numpy.trim_zeros function is used to trim the leading and/or trailing zeros from a 1-D array or sequence.
Syntax: numpy.trim_zeros(arr, trim)
Parameters:arr : 1-D array or sequencetrim : trim is an optional parameter with default value to be ‘fb'(front and back) we can either select ‘f'(front) and ‘b’ for back.
Returns: trimmed : 1-D array or sequence (without leading and/or trailing zeros as per user’s choice)
Code 1:
import numpy as geek   gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0))  # without trim parameter# returns an array without leading and trailing zeros   res = geek.trim_zeros(gfg)print(res)
Output :array([1, 5, 7, 0, 6, 2, 9, 0, 10])

Code 2:
import numpy as geek gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0))  # without trim parameter# returns an array without any leading  zeros   res = geek.trim_zeros(gfg, 'f')print(res)
Output :array([1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0])

Code 3:
import numpy as geek gfg = geek.array((0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10, 0, 0))  # without trim parameter# returns an array without any trailing  zeros   res = geek.trim_zeros(gfg, 'b')print(res)
Output :array([0, 0, 0, 0, 1, 5, 7, 0, 6, 2, 9, 0, 10])

Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2015 (Set 2) | Question 11

28 Jun, 2021
Consider the following transaction involving two bank accounts x and y.
read(x);  x := x – 50;  write(x);  read(y);  y := y + 50;  write(y) 
The constraint that the sum of the accounts x and y should remain constant is that of
(A) Atomicity(B) Consistency(C) Isolation(D) DurabilityAnswer: (B)Explanation: Consistency in database systems refers to the requirement that any given database transaction must only change affected data in allowed ways, that is sum of x and y must not change.
Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2004 | Question 31
GATE | GATE CS 2011 | Question 49
GATE | GATE CS 1996 | Question 38
Python | Get elements till particular element in list

28 Aug, 2019
Sometimes, while working with Python list, we can have a requirement in which we need to remove all the elements after a particular element, or, get all elements before a particular element. These both are similar problems and having a solution to it is always helpful. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using index() + list slicingThis problem can be solved using the combination of these functions. The index() can be used to find the index of desired element and list slicing can perform the remaining task of getting the elements.
# Python3 code to demonstrate working of# Get elements till particular element in list# using index() + list slicing  # initialize listtest_list = [1, 4, 6, 8, 9, 10, 7]  # printing original listprint("The original list is : " + str(test_list))  # declaring elements till which elements requiredN = 8  # Get elements till particular element in list# using index() + list slicingtemp = test_list.index(N)res = test_list[:temp]  # printing resultprint("Elements till N in list are : " + str(res))
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]

 
Method #2 : Using generatorThis task can also be performed using the generator function which uses yield to get the elements just till the required element and breaks the yields after that element.
# Python3 code to demonstrate working of# Get elements till particular element in list# using generator  # helper function to perform taskdef print_ele(test_list, val):    for ele in test_list:        if ele == val:            return        yield ele  # initialize listtest_list = [1, 4, 6, 8, 9, 10, 7]  # printing original listprint("The original list is : " + str(test_list))  # declaring elements till which elements requiredN = 8  # Get elements till particular element in list# using generatorres = list(print_ele(test_list, N))  # printing resultprint("Elements till N in list are : " + str(res))
The original list is : [1, 4, 6, 8, 9, 10, 7]
Elements till N in list are : [1, 4, 6]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
MySQL date format to convert dd.mm.yy to YYYY-MM-DD?

Use STR_TO_DATE() method from MySQL to convert. The syntax is as follows wherein we are using format specifiers. The format specifiers begin with %.
SELECT STR_TO_DATE(yourDateColumnName,'%d.%m.%Y') as anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows.
mysql> create table ConvertIntoDateFormat
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> LoginDate varchar(30),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.47 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into ConvertIntoDateFormat(LoginDate) values('11.01.2019');
Query OK, 1 row affected (0.10 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('10.04.2017');
Query OK, 1 row affected (0.16 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('21.10.2016');
Query OK, 1 row affected (0.12 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('26.09.2018');
Query OK, 1 row affected (0.14 sec)

mysql> insert into ConvertIntoDateFormat(LoginDate) values('25.12.2012');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement. The query is as follows−
mysql> select *from ConvertIntoDateFormat;
The following is the output.
+----+------------+
| Id | LoginDate  |
+----+------------+
|  1 | 11.01.2019 |
|  2 | 10.04.2017 |
|  3 | 21.10.2016 |
|  4 | 26.09.2018 |
|  5 | 25.12.2012 |
+----+------------+
5 rows in set (0.00 sec)
The following is the query to format the date to YYYY-MM-DD.
mysql> select str_to_date(LoginDate,'%d.%m.%Y') as DateFormat from ConvertIntoDateFormat;
Here is the output.
+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+
5 rows in set (0.00 sec)
You can also use DATE_FORMAT() method for the same purpose. The query is as follows
mysql> select DATE_FORMAT(STR_TO_DATE(LoginDate,'%d.%m.%Y'), '%Y-%m-%d') as DateFormat from
   -> ConvertIntoDateFormat;
The following is the output−
+------------+
| DateFormat |
+------------+
| 2019-01-11 |
| 2017-04-10 |
| 2016-10-21 |
| 2018-09-26 |
| 2012-12-25 |
+------------+
5 rows in set (0.00 sec)
Problem with getline() after cin >>

25 Feb, 2021
The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters. So special care should be taken care of about using getline() after cin because cin ignores white space characters and leaves it in the stream as garbage.
Program 1:
Below is the C++ program to illustrate the same:
C++
// C++ program for the above problem#include <iostream>using namespace std;  // Driver Codeint main(){    int fav_no;    string name;      cout << "Type your favorite number: ";      // The cin statement uses the    // fav_no and leaves the \n    // in the stream as garbage    cin >> fav_no;      cout << "Type your name : ";      // getline() reads \n    // and finish reading    getline(cin, name);      // In output only fav_no    // will be displayed not    // name    cout << name         << ", your favourite number is : "         << fav_no;      return 0;}
Output:
Explanation:
The solution to solve the above problem is to use something which extracts all white space characters after cin. std::ws in C++ to do the same thing. This is actually used with the “>>” operator on input streams.
Program 2:
Below is the C++ program to illustrate the solution for the above problem:
C++
// C++ program for the above solution#include <iostream>using namespace std;  // Driver Codeint main(){    int fav_no;    string name;    cout << "Type your favourite number: ";    cin >> fav_no;      cout << "Type your name: ";      // Usage of std::ws will extract    // all  the whitespace character    getline(cin >> ws, name);      cout << name         << ", your favourite number is : "         << fav_no;    return 0;}
Output:
CPP-Basics
Technical Scripter 2020
C++
C++ Programs
Technical Scripter
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
C++ program for hashing with chaining
How to read only the first line of a file with Python?

To read only the first line of a file, open the file in read mode and call readline method on the file object. For example,
f = open('my_file.txt', 'r')
line = f.readline()
print line
f.close()
The above code reads first line from my_file.txt and prints to stdout. A safer approach would be using the with open syntax to avoid file from not closeing in case of an exception:
with open('my_file.txt', 'r') as f:
    print f.readline()
Python Program for KMP Algorithm for Pattern Searching

08 Jun, 2022
Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples: 
Input:  txt[] = "THIS IS A TEST TEXT"
        pat[] = "TEST"
Output: Pattern found at index 10

Input:  txt[] =  "AABAACAADAABAABA"
        pat[] =  "AABA"
Output: Pattern found at index 0
        Pattern found at index 9
        Pattern found at index 12
 
Pattern searching is an important problem in computer science. When we do search for a string in notepad/word file or browser or database, pattern searching algorithms are used to show the search results.  
Python3
# Python program for KMP Algorithmdef KMPSearch(pat, txt):    M = len(pat)    N = len(txt)     # create lps[] that will hold the longest prefix suffix    # values for pattern    lps = [0]*M    j = 0 # index for pat[]     # Preprocess the pattern (calculate lps[] array)    computeLPSArray(pat, M, lps)     i = 0 # index for txt[]    while i < N:        if pat[j] == txt[i]:            i += 1            j += 1         if j == M:            print ("Found pattern at index", str(i-j))            j = lps[j-1]         # mismatch after j matches        elif i < N and pat[j] != txt[i]:            # Do not match lps[0..lps[j-1]] characters,            # they will match anyway            if j != 0:                j = lps[j-1]            else:                i += 1 def computeLPSArray(pat, M, lps):    len = 0 # length of the previous longest prefix suffix     lps[0] # lps[0] is always 0    i = 1     # the loop calculates lps[i] for i = 1 to M-1    while i < M:        if pat[i]== pat[len]:            len += 1            lps[i] = len            i += 1        else:            # This is tricky. Consider the example.            # AAACAAAA and i = 7. The idea is similar            # to search step.            if len != 0:                len = lps[len-1]                 # Also, note that we do not increment i here            else:                lps[i] = 0                i += 1 txt = "ABABDABACDABABCABAB"pat = "ABABCABAB"KMPSearch(pat, txt) # This code is contributed by Bhavya Jain
Found pattern at index 10
 
Time Complexity: O(m+n)
Space Complexity: O(m)
Please refer complete article on KMP Algorithm for Pattern Searching for more details! 
amartyaghoshgfg
chandramauliguptach
python searching-exercises
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to interchange first and last elements in a list
Appending to list in Python dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
Appending a dictionary to a list in Python
Python Program to check Armstrong Number
Python | Difference between two dates (in minutes) using datetime.timedelta() method
Python | Remove spaces from a string
Python Program for Merge Sort
Python - Convert JSON to string
Python Program for simple interest
Impala - Limit Clause

The limit clause in Impala is used to restrict the number of rows of a resultset to a desired number, i.e., the resultset of the query does not hold the records beyond the specified limit.
Following is the syntax of the Limit clause in Impala.
select * from table_name order by id limit numerical_expression;

Assume we have a table named customers in the database my_db and its contents are as follows −
[quickstart.cloudera:21000] > select * from customers; 
Query: select * from customers 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 3  | kaushik  | 23  | Kota      | 30000  | 
| 6  | Komal    | 22  | MP        | 32000  | 
| 1  | Ramesh   | 32  | Ahmedabad | 20000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  | 
| 8  | ram      | 22  | vizag     | 31000  | 
| 9  | robert   | 23  | banglore  | 28000  | 
| 7  | ram      | 25  | chennai   | 23000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
+----+----------+-----+-----------+--------+ 
Fetched 9 row(s) in 0.51s

You can arrange the records in the table in the ascending order of their id’s using the order by clause as shown below.
[quickstart.cloudera:21000] > select * from customers order by id; 
Query: select * from customers order by id 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 1  | Ramesh   | 32  | Ahmedabad | 20000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  | 
| 3  | kaushik  | 23  | Kota      | 30000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
| 6  | Komal    | 22  | MP        | 32000  | 
| 7  | ram      | 25  | chennai   | 23000  | 
| 8  | ram      | 22  | vizag     | 31000  |
| 9  | robert   | 23  | banglore  | 28000  | 
+----+----------+-----+-----------+--------+ 
Fetched 9 row(s) in 0.54s

Now, using the limit clause, you can restrict the number of records of the output to 4, using the limit clause as shown below.
[quickstart.cloudera:21000] > select * from customers order by id limit 4;

On executing, the above query gives the following output.
Query: select * from customers order by id limit 4 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 1  | Ramesh   | 32  | Ahmedabad | 20000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  |
| 3  | kaushik  | 23  | Kota      | 30000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
+----+----------+-----+-----------+--------+ 
Fetched 4 row(s) in 0.64s

 Print
 Add Notes
 Bookmark this page
Plot a multicolored line based on a condition in Python Matplotlib

To plot a multicolored line based on a condition in Python Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create y data points using numpy.
Create y data points using numpy.
Make l and u data points to differentiate the colors.
Make l and u data points to differentiate the colors.
Plot the u and l data points using plot() method, with different colors.
Plot the u and l data points using plot() method, with different colors.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

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

y = np.sin(np.linspace(-10, 10, 100))

u = y.copy()
l = y.copy()

u[u <= 0] = np.nan
l[l >= 0] = np.nan

plt.plot(u, color='red')
plt.plot(l, color='blue')

plt.show()
Tryit Editor v3.7

Tryit: Using align-items: center
Find inverse of matrix in MATLAB - GeeksforGeeks

28 Apr, 2021
Inverse function in MATLAB is used to find the inverse of a matrix. Suppose A is a matrix and B is the inverse of a then A*B will be an identity matrix. This function computes the inverse of a square matrix. This is used while solving linear equations. We can compute the inverse of a matrix by passing it to inv().
Syntax:
inv(A)
Parameters:
It takes a matrix as parameter.
Returns:
It returns a matrix which is inverse of input matrix.
Below are some examples which depict how to compute the inverse of a matrix in MATLAB.
Example 1: This example takes a 3×3 matrix as input and computes its inverse using inv() function.
Matlab
% Defining matrixA = [1 2 0; 3 1 4; 5 6 7]  % Getting inverse matrixinv(A)
Output:
Example 2: Here is another example that takes a 2×2 matrix as input and computes its inverse.
Matlab
% Defining matrixA = [1 2; 3 1]  % Getting inverse matrixinv(A)
Output:
Example 3: This example uses a singular matrix and tries to find its inverse. It will show a warning that the matrix is a singular matrix. Different versions of MATLAB gave a different value of inverse for singular matrix. This is due to the different versions of Math Kernel Library used in different versions of MATLAB.
Matlab
% Defining matrixA = [2 4 6;2 0 2;6 8 14]  % Getting inverse matrixinv(A)
Output:
warning: matrix singular to machine precision, rcond = 1.34572e-17
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Boundary Extraction of image using MATLAB
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Laplacian of Gaussian Filter in MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
Differential or Derivatives in MATLAB
MATLAB Syntax
How to Remove Salt and Pepper Noise from Image Using MATLAB?
How to Normalize a Histogram in MATLAB?
Laplace Transform in MATLAB
Change the order of index of a series in Pandas - GeeksforGeeks

06 Jan, 2022
Suppose we want to change the order of the index of series, then we have to use the Series.reindex() Method of pandas module for performing this task.
Series, which is a 1-D labeled array capable of holding any data.
Syntax: pandas.Series(data, index, dtype, copy) 
Parameters:
data takes ndarrys, list, constants.
index values.
dtypes for data types.
Copy data, default is False.
For knowing more about the pandas Series click here.
Series.reindex() Method is used for changing the data on the basis of indexes.
Syntax: Series.reindex(labels=None, index=None, columns=None, axis=None, method=None, copy=True, level=None, fill_value=nan, limit=None, tolerance=None) 
For knowing more about the pandas Series.reindex() method click here.
Let’s create a series:
Python3
# import required libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array(["Android dev",                 "content writing",                 "competitive coding"])#create a seriestotal_series = pd.Series(data,                         index = [1, 2, 3]) # show the seriestotal_series
Output:
Series
Example 1: 
Python3
# import required libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array(["Android dev",                 "content writing",                 "competitive coding"])# create a seriestotal_series = pd.Series(data,                         index = [1, 2, 3])# reindexing of seriestotal_series = total_series.reindex(index                                    = [3, 2, 1])# show the seriestotal_series
Output: 
Example 2: 
Python3
# import required libraryimport pandas as pdimport numpy as np # create numpy arraydata = np.array(["Android dev",                 "content writing",                 "competitive coding"])# create a seriestotal_series = pd.Series(data,                         index = [1, 2, 3])# reindexing of seriestotal_series = total_series.reindex([2, 3, 1]) # show the seriestotal_series
Output:
 
adnanirshad158
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Split string into list of characters
How to take input in Python?

Programs are written to solve a specific problem of a user. Thus, the program must be such which can interact with the user. This means that a program must take input from the user and perform the task accordingly on the input which user provides.
The method to take input is different for different datatypes. We’ll discuss how to take input for various datatypes as well as how to take array input from the user.
The input() method is used to take string input from the user.The user can enter numeric value as well but it will be treated as a string. The program can contain any logic or operation to be performed on the string entered by the user ,but in example, we’ll simply print the string which the user enters.
print("Enter a string")
a=input()
print("The string entered by user is",a)
Enter a string
TutorialsPoint
The string entered by user is TutorialsPoint
The above example upon execution, prints the message “Enter a string” on the output screen and lets the user enter something. When input() function executes, the program flow will be stopped until the user gives some input. After entering the string, the second print statement executes.
The integer input can be taken by just type casting the input received into input(). Thus, for taking integer input, we use int(input()) . Only numerical values can be entered by the user, else it throws an error.
print("Enter a number")
a=int(input())
print("The number entered by user is",a)
Enter a number
10
The number entered by user is 10
The float input can be taken by type casting input received in input() .We’ll use float(input()) to take float input. The user can enter integer or float values but the value will be treated as float.
print("Enter a number")
a=float(input())
print("The number entered by user is",a)
Enter a number
2.5
The number entered by user is 2.5
We may at times, need to take an array as input from the user. There is no separate syntax for taking array input.
print("Enter no. of elements")
a=int(input())
print("Enter",a,"integer elements")
array=[]
for i in range(a):
   array.append(int(input()))
print("Array entered by user is",array)
Enter no. of elements
5
Enter 5 integer elements
1
2
3
4
5
Array entered by user is [1, 2, 3, 4, 5]
In the above example, the size of the array is taken as input from the user. Then the array is declared and using for loop, we take further elements input from the user and append those in the array.
For taking string array input, we can use input() instead of int(input()) inside for loop.
Java Examples - Exception Methods

How to handle the exception methods ?
This example shows how to handle the exception methods by using System.err.println() method of System class.
public class NewClass {
   public static void main(String[] args) {
      try {
         throw new Exception("My Exception");
      } catch (Exception e) {
         System.err.println("Caught Exception");
         System.err.println("getMessage():" + e.getMessage());
         System.err.println("getLocalizedMessage():" + e.getLocalizedMessage());
         System.err.println("toString():" + e);
         System.err.println("printStackTrace():");
         e.printStackTrace();
      }
   }
}
The above code sample will produce the following result.
Caught Exception
getMassage(): My Exception
gatLocalisedMessage(): My Exception
toString():java.lang.Exception: My Exception
print StackTrace():
   java.lang.Exception: My Exception
   at ExceptionMethods.main(ExceptionMeyhods.java:12)

 Print
 Add Notes
 Bookmark this page
C++ Algorithm Library - count_if() Function

The C++ function std::algorithm::count_if() returns the number of occurrences of value from range that satisfies condition.
Following is the declaration for std::algorithm::count_if() function form std::algorithm header.
template <class InputIterator, class Predicate>
typename iterator_traits<InputIterator>::difference_type
count_if (InputIterator first, InputIterator last, UnaryPredicate pred);

first − Input iterators to the initial positions of the searched sequence.
first − Input iterators to the initial positions of the searched sequence.
last − Input iterators to the final positions of the searched sequence.
last − Input iterators to the final positions of the searched sequence.
pred − Unary predicate which takes an argument and returns bool.
pred − Unary predicate which takes an argument and returns bool.
Returns the number of elements in the range for which pred returns true.
Throws an exception if either predicate or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Linear in the distance between first to last.
The following example shows the usage of std::algorithm::count_if() function.
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool predicate(int n) {
   return (n > 3);
}

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};
   int cnt;

   cnt = count_if(v.begin(), v.end(), predicate);

   cout << "There are " << cnt << " numbers are greater that 3." << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
There are 2 numbers are greater that 3.

 Print
 Add Notes
 Bookmark this page
How to create a JLabel with an image icon in Java?

Let us create a label with image icon −
JLabel label = new JLabel("SUBJECT ");
label.setIcon(new ImageIcon("E:\\new.png"));
Now, create another component −
JTextArea text = new JTextArea();
text.setText("Add subject here...");
Align the components with GridBagLayout −
panel.setLayout(new GridBagLayout());
The following is an example to center a label with an image icon −
package my;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
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("SUBJECT ");
      label.setIcon(new ImageIcon("E:\\new.png"));
      JTextArea text = new JTextArea();
      text.setText("Add subject 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);
   }
}
IntStream average() method in Java

The average() method of the IntStream class in Java returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. It gets the average of the elements of the stream.
The syntax is as follows
OptionalDouble average()
Here, OptionalDouble is a container object which may or may not contain a double value.
Create an IntStream with some elements
IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);
Now, get the average of the elements of the stream
OptionalDouble res = intStream.average();
The following is an example to implement IntStream average() method in Java. The isPresent() method of the OptionalDouble class returns true if the value is present
 Live Demo
import java.util.*;
import java.util.stream.IntStream;
public class Demo {
   public static void main(String[] args) {
      IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);
      OptionalDouble res = intStream.average();
      System.out.println("Average of the elements of the stream...");
      if (res.isPresent()) {
         System.out.println(res.getAsDouble());
      } else {
         System.out.println("Nothing!");
      }
   }
}
Average of the elements of the stream...
47.75
Calculate the Weighted Mean in R Programming - weighted.mean() Function - GeeksforGeeks

23 Jun, 2020
weighted.mean() function in R Language is used to compute the weighted arithmetic mean of input vector values.
Syntax: weighted.mean(x, weights)
Parameters:x: data input vectorweights: It is weight of input data.
Returns: weighted mean of given values
Example 1:
# Create example datax1 <- c(1, 2, 7, 5, 3, 2, 5, 4)  # Create example weights                    w1 <- c(7, 5, 3, 5, 7, 1, 3, 7)                      # Apply weighted.mean() functionweighted.mean(x1, w1)
Output:
[1] 3.394737

Example 2:
# Create example datax1 <- c(1, 2, 7, 5, 3, 2, 5, 4)  # Create example weights                    w1 <- c(7, 5, 3, 8, 7, 1, 3, 7)                      # Create vector with NA# Extend weights vectorx2 <- c(x1, NA)                                    w2 <- c(w1, 3)                                     weighted.mean(x2, w2)        # Remove missing valuesweighted.mean(x2, w2, na.rm = TRUE)  
Output:
[1] NA
[1] 3.512195

R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R