code-rag-bench/online-tutorials huggingface dataset:
SQLAlchemy ORM - Textual SQL

Earlier, textual SQL using text() function has been explained from the perspective of core expression language of SQLAlchemy. Now we shall discuss it from ORM point of view.
Literal strings can be used flexibly with Query object by specifying their use with the text() construct. Most applicable methods accept it. For example, filter() and order_by().
In the example given below, the filter() method translates the string “id<3” to the WHERE id<3
from sqlalchemy import text
for cust in session.query(Customers).filter(text("id<3")):
   print(cust.name)
The raw SQL expression generated shows conversion of filter to WHERE clause with the code illustrated below −
SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
WHERE id<3
From our sample data in Customers table, two rows will be selected and name column will be printed as follows −
Ravi Kumar
Komal Pande

To specify bind parameters with string-based SQL, use a colon,and to specify the values, use the params() method.
cust = session.query(Customers).filter(text("id = :value")).params(value = 1).one()
The effective SQL displayed on Python console will be as given below −
SELECT customers.id 
AS customers_id, customers.name 
AS customers_name, customers.address 
AS customers_address, customers.email 
AS customers_email
FROM customers
WHERE id = ?
To use an entirely string-based statement, a text() construct representing a complete statement can be passed to from_statement().
session.query(Customers).from_statement(text("SELECT * FROM customers")).all()
The result of above code will be a basic SELECT statement as given below −
SELECT * FROM customers
Obviously, all records in customers table will be selected.
The text() construct allows us to link its textual SQL to Core or ORM-mapped column expressions positionally. We can achieve this by passing column expressions as positional arguments to the TextClause.columns() method.
stmt = text("SELECT name, id, name, address, email FROM customers")
stmt = stmt.columns(Customers.id, Customers.name)
session.query(Customers.id, Customers.name).from_statement(stmt).all()
The id and name columns of all rows will be selected even though the SQLite engine executes following expression generated by above code shows all columns in text() method −
SELECT name, id, name, address, email FROM customers

    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
Mahotas - RGB to XYZ Conversion - GeeksforGeeks

10 Dec, 2021
In this article we will see how we can covert rgb image to xyz image in mahotas. An RGB image, sometimes referred to as a truecolor image, is stored in MATLAB as an m-by-n-by-3 data array that defines red, green, and blue color components for each individual pixel. Xyz is an additive color space based on how the eye interprets stimulus from light. Unlike other additive rgb like Rgb, Xyz is a purely mathematical space and the primary components are “imaginary”, meaning we can’t create the represented color in the physical by shining any sort of lights representing x, y, and z. In this tutorial we will use “lena” image, below is the command to load it. 
mahotas.demos.load('lena')
Below is the lena image 
In order to do this we will use mahotas.colors.rgb2xyzmethod 
Syntax : mahotas.colors.rgb2xyz(img)Argument :It takes image object as argumentReturn : It returns image object  
Below is the implementation 
Python3
# importing required librariesimport mahotasimport mahotas.demosfrom pylab import gray, imshow, showimport numpy as np  # loading imageimg = mahotas.demos.load('lena')   # showing imageprint("Image")imshow(img)show() # rgb to labnew_img = mahotas.colors.rgb2xyz(img) # showing new imageprint("New Image")imshow(new_img)show()
Strong : 
Image
New Image
Another example 
Python3
# importing required librariesimport mahotasimport numpy as npimport matplotlib.pyplot as pltimport os  # loading imageimg = mahotas.imread('dog_image.png')       # filtering imageimg = img[:, :, :3] # showing imageprint("Image")imshow(img)show() # rgb to labnew_img = mahotas.colors.rgb2xyz(img) # showing new imageprint("New Image")imshow(new_img)show()
Strong : 
Image
New Image
simmytarika5
simranarora5sos
surinderdawra388
Python-Mahotas
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 String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
How to multiply a polynomial to another using NumPy in Python? - GeeksforGeeks

29 Aug, 2020
In this article, we will make a NumPy program to multiply one polynomial to another. Two polynomials are given as input and the result is the multiplication of two polynomials.
The polynomial p(x) = C3 x2 + C2 x + C1  is represented in NumPy as : ( C1, C2, C3 ) { the coefficients (constants)}.
Let take two polynomials p(x) and q(x) then multiply these to get r(x) = p(x) * q(x) as a result of multiplication of two input polynomials.
If p(x) = A3 x2 + A2 x + A1 
and 
q(x) = B3 x2 + B2 x + B1 

then result is r(x) = p(x) * q(x) 

and output is 

( (A1 * B1), (A2 * B1) + (A2 * B1),
(A3 * B1) + (A2 * B2) + (A1 * B3), 
(A2 * B2) + (A3 * B2), (A3 * B3) ).

This can be calculated using the polymul() method of NumPy. This method evaluates the product of two polynomials and returns the polynomial resulting from the multiplication of two input polynomials ‘p1’ and ‘p2’.
Syntax:
numpy.polymul(p1, p2)
Below is the implementation with some examples :
Example 1:
Python3
# importing packageimport numpy  # define the polynomials# p(x) = 5(x**2) + (-2)x +5  px = (5, -2, 5)# q(x) = 2(x**2) + (-5)x +2qx = (2, -5, 2)  # mul the polynomialsrx = numpy.polynomial.polynomial.polymul(px, qx)  # print the resultant polynomialprint(rx)
Output :
[ 10. -29.  30. -29.  10.] 

Example 2 :
Python3
# importing packageimport numpy  # define the polynomials# p(x) = 2.2px = (0, 0, 2.2)  # q(x) = 9.8(x**2) + 4qx = (9.8, 0, 4)  # mul the polynomialsrx = numpy.polynomial.polynomial.polymul(px, qx)  # print the resultant polynomialprint(rx)
Output :
[  0.     0.    21.56   0.     8.8 ]

Example 3 :
Python3
# importing packageimport numpy  # define the polynomials# p(x) = (5/3)xpx = (0, 5/3, 0)  # q(x) = (-7/4)(x**2) + (9/5)qx = (-7/4, 0, 9/5)  # mul the polynomialsrx = numpy.polynomial.polynomial.polymul(px, qx)  # print the resultant polynomialprint(rx)
Output :
[ 0.         -2.91666667  0.          3.        ]

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
C++ IOS Library - Iword

It is used to get integer element of extensible array and returns a reference to the object of type long which corresponds to index idx in the internal extensible array.
If idx is an index to a new element and the internal extensible array is not long enough (or is not yet allocated), the function extends it (or allocates it) with as many zero-initialized elements as necessary.
The reference returned is guaranteed to be valid at least until another operation is performed on the stream object, including another call to iword. Once another operation is performed, the reference may become invalid, although a subsequent call to this same function with the same idx argument returns a reference to the same value within the internal extensible array.
The internal extensible array is a general-purpose array of objects of type long (if accessed with member iword) or void* (if accessed with member pword). Libraries may implement this array in diverse ways: iword and pword may or may not share a unique array, and they may not even be arrays, but some other data structure.
Following is the declaration for ios_base::iword function.
long& iword (int idx);
idx − An index value for an element of the internal extensible array. Some implementations expect idx to be a value previously returned by member xalloc.
A reference to the element in the internal extensible array whose index is idx. This value is returned as a reference to an object of type long.or else a valid long& initialized to 0L is returned, and (if the stream object inherits from basic_ios) the badbit state flag is set.
Basic guarantee − if an exception is thrown, the stream is in a valid state.
May modify the stream object. The returned value may also be used to modify it. Concurrent access to the same stream object may cause data races.
In below example explains about ios_base::iword function.
#include <iostream>     

std::ostream& Counter (std::ostream& os) {
   const static int index = os.xalloc();
   return os << ++os.iword(index);
}

int main() {
   std::cout << Counter << ": first line\n";
   std::cout << Counter << ": second line\n";
   std::cout << Counter << ": third line\n";
  
   std::cerr << Counter << ": error line\n";
   return 0;
}
Let us compile and run the above program, this will produce the following result −
1: first line
2: second line
3: third line
1: error line

 Print
 Add Notes
 Bookmark this page
Breadth-first search traversal in Javascript

BFS visits the neighbor vertices before visiting the child vertices, and a queue is used in the search process. Following is how a BFS works −
Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue.
If no adjacent vertex is found, remove the first vertex from the queue.
Repeat Rule 1 and Rule 2 until the queue is empty.
Let us look at an illustration of how BFS Traversal works:
At this stage, we are left with no unmarked (unvisited) nodes. But as per the algorithm we keep on dequeuing in order to get all unvisited nodes. When the queue gets emptied, the program is over.
Let's look at how we can implement this in JavaScript. 
BFS(node) {
   // Create a Queue and add our initial node in it
   let q = new Queue(this.nodes.length);
   let explored = new Set();
   q.enqueue(node);

   // Mark the first node as explored explored.
   add(node);

   // We'll continue till our queue gets empty
   while (!q.isEmpty()) {
      let t = q.dequeue();

      // Log every element that comes out of the Queue
      console.log(t);

      // 1. In the edges object, we search for nodes this node is directly connected to.
      // 2. We filter out the nodes that have already been explored.
      // 3. Then we mark each unexplored node as explored and add it to the queue.
      this.edges[t]
      .filter(n => !explored.has(n))
      .forEach(n => {
         explored.add(n);
         q.enqueue(n);
      });
   }
}
You can test this function using −
let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");
g.addNode("F");
g.addNode("G");

g.addEdge("A", "C");
g.addEdge("A", "B");
g.addEdge("A", "D");
g.addEdge("D", "E");
g.addEdge("E", "F");
g.addEdge("B", "G");

g.BFS("A");
This will give the output −
A
C
B
D
G
E
F
Python - How to search for a string in text files? - GeeksforGeeks

24 Jan, 2021
In this article, we are going to see how to search for a particular string in a text file.
Consider below text File :
Example 1: we are going to search string line by line if the string found then we will print that string and line number.
Steps:
Open a file.
Set variables index and flag to zero.
Run a loop through the file line by line.
In that loop check condition using the ‘in’ operator for string present in line or not. If found flag to 0.
After loop again check condition for the flag is set or not. If set string found then print a string and line number otherwise simply print the message ‘String not found’.
Close a file.
Code:
Python3
string1 = 'coding'  # opening a text filefile1 = open("geeks.txt", "r")  # setting flag and index to 0flag = 0index = 0  # Loop through the file line by linefor line in file1:      index + = 1           # checking string is present in line or not    if string1 in line:              flag = 1      break           # checking condition for string found or notif flag == 0:    print('String', string1 , 'Not Found') else:    print('String', string1, 'Found In Line', index)  # closing text file    file1.close() 
Output:
Example 2: We are just finding string is present in the file or not.
Step:
open a file.
Read a file and store it in a variable.
check condition using ‘in’ operator for string present in the file or not.
If the condition true then print the message ‘string is found’ otherwise print ‘string not found’.
Close a file.
Python3
string1 = 'portal'  # opening a text filefile1 = open("geeks.txt", "r")  # read file contentreadfile = file1.read()  # checking condition for string found or notif string1 in readfile:     print('String', string1, 'Found In File')else:     print('String', string1 , 'Not Found')   # closing a filefile1.close() 
Output:
Picked
Python file-handling-programs
python-file-handling
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Python OOPs Concepts
Different ways to create Pandas Dataframe
sum() function in Python
How to Install PIP on Windows ?
Stack in Python
Bar Plot in Matplotlib
Defaultdict in Python
Graph Plotting in Python | Set 1
Ionic - Cards

Since mobile devices have smaller screen size, cards are one of the best elements for displaying information that will feel user friendly. In the previous chapter, we have discussed how to inset lists. Cards are very similar to inset lists, but they offer some additional shadowing that can influence the performance for larger lists.
A default card can be created by adding a card class to your element. Cards are usually formed as lists with the item class. One of the most useful class is the item-text-wrap. This will help when you have too much text, so you want to wrap it inside your card. The first card in the following example does not have the item-text-wrap class assigned, but the second one is using it.
<div class = "card">
   <div class = "item">
      This is a Ionic card without item-text-wrap class.
   </div>
   
   <div class = "item item-text-wrap">
      This is a Ionic card with item-text-wrap class.
   </div>
</div>
The above code will produce the following screen −
In the previous chapter, we have already discussed how to use the item-divider class for grouping lists. This class can be very useful when working with cards to create card headers. The same class can be used for footers as shown in the following code −
<div class = "card list">
   <div class = "item item-divider">
      Card header
   </div>
   
   <div class = "item item-text-wrap">
      Card text...
   </div>
   
   <div class = "item item-divider">
      Card Footer
   </div>
</div>
The above code will produce the following screen −
You can add any element on top of your card. In following example, we will show you how to use the full-image class together with the item-body to get a good-looking windowed image inside your card.
<div class = "card">
   <div class = "item item-avatar">
      <img src = "my-image.png">
      <h2>Card Name</h2>
   </div>

   <div class = "item item-body">
      <img class = "full-image" src = "my-image.png">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eget 
      pharetra tortor. Proin quis eros imperdiet, facilisis nisi in, tincidunt orci. 
      Nam tristique elit massa, quis faucibus augue finibus ac.
   </div>
</div>
The above code will produce the following screen −

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    185 Lectures 
     46.5 hours 

 Nikhil Agarwal
 Print
 Add Notes
 Bookmark this page
Adjusting the spacing between the edge of the plot and the X-axis in Matplotlib

To adjust the spacing between the edge of the plot and the X-axis, we can use tight_layout() method or set the bottom padding of the current figure.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Plot x and y data points using plot() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt

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

x = np.linspace(-2, 2, 100)
y = np.exp(x)
plt.plot(x, y, c='red', lw=1)
plt.show()
Java program to find common elements in three sorted arrays

The common elements in three sorted arrays are the elements that occur in all three of them. An example of this is given as follows −
Array1 = 1 3 5 7 9
Array2 = 2 3 6 7 9
Array3 = 1 2 3 4 5 6 7 8 9
Common elements = 3 7 9
A program that demonstrates this is given as follows −
public class Example {
public static void main(String args[]) {
int arr1[] = {1, 4, 25, 55, 78, 99};
int arr2[] = {2, 3, 4, 34, 55, 68, 75, 78, 100};
int arr3[] = {4, 55, 62, 78, 88, 98};
int i = 0, j = 0, k = 0, x = 0;
System.out.print("Array1: ");
for(x = 0; x < arr1.length; x++) {
System.out.print(arr1[x] + " ");
}
System.out.print("\nArray2: ");
for(x = 0; x < arr2.length; x++) {
System.out.print(arr2[x] + " ");
}
System.out.print("\nArray3: ");
for(x = 0; x < arr3.length; x++) {
System.out.print(arr3[x] + " ");
}
System.out.print("\nThe common elements in the 3 sorted arrays are: ");
while (i < arr1.length && j < arr2.length && k < arr3.length) {
if (arr1[i] == arr2[j] && arr2[j] == arr3[k]) {
System.out.print(arr1[i] + " ");
i++;
j++;
k++;
}else if (arr1[i] < arr2[j]) {
i++;
}else if (arr2[j] < arr3[k]) {
j++;
}else {
k++;
}
}
}
}
Array1: 1 4 25 55 78 99
Array2: 2 3 4 34 55 68 75 78 100
Array3: 4 55 62 78 88 98
The common elements in the 3 sorted arrays are: 4 55 78
Get Started with C#

The easiest way to get started with C#, is to use an IDE.
An IDE (Integrated Development Environment) is used to edit and compile code.
In our tutorial, we will use Visual Studio Community, which is free to download from https://visualstudio.microsoft.com/vs/community/.
Applications written in C# use the .NET Framework, so it makes sense to use 
Visual Studio, as the program, the framework, and the language, are all created by 
Microsoft.
Once the Visual Studio Installer is downloaded and installed, choose the .NET workload and click on the 
Modify/Install button:
After the installation is complete, click on the Launch button to get started with Visual Studio.
On the start window, choose Create a new project:
Then click on the "Install more tools and features" button:
Choose "Console App (.NET Core)" from the list and click on the Next button:
Enter a name for your project, and click on the Create button:
Visual Studio will automatically generate some code for your project:
The code should look something like this:
using System;

namespace HelloWorld
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World!");    
    }
  }
}

Try it Yourself »

Don't worry if you don't understand the code above - we will discuss it in detail in later chapters. For now, focus on how to run the code.
Run the program by pressing the F5 button on your keyboard (or click on "Debug" -> "Start Debugging"). This will compile and execute your code. The result will look something to this:
Congratulations! You have now written and executed your first C# program.
When learning C# at W3Schools.com, you can use our "Try it Yourself" tool, which shows both the code and the result. This will make it easier for 
you to understand every part as we move forward:
using System;

namespace HelloWorld
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World!");    
    }
  }
}
Result:

Try it Yourself »

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
What does the two question marks together (??) mean in C#?

It is the null-coalescing operator. The null-coalescing operator ?? returns the value of its left-hand operand if it isn't null; otherwise, it evaluates the right-hand operand and returns its result. The ?? operator doesn't evaluate its right-hand operand if the lefthand operand evaluates to non-null.
A nullable type can represent a value that can be undefined or from the type's domain. We can use the ?? operator to return an appropriate value when the left operand has a nullable type. If we try to assign a nullable value type to a non-nullable value type without using the ?? operator, we will get a compile-time error and if we forcefully cast it, an InvalidOperationException exception will be thrown.
The following are the advantages of the Null-Coalescing Operator (??) operator −
It is used to define a default value for a nullable item (for both value types and reference types).
It is used to define a default value for a nullable item (for both value types and reference types).
It prevents the runtime InvalidOperationException exception.
It prevents the runtime InvalidOperationException exception.
It helps us to remove many redundant "if" conditions.
It helps us to remove many redundant "if" conditions.
It works for both reference types and value types.
It works for both reference types and value types.
The code becomes well-organized and readable.
The code becomes well-organized and readable.
 Live Demo
using System;
namespace MyApplication{
   class Program{
      static void Main(string[] args){
         int? value1 = null;
         int value2 = value1 ?? 99;
         Console.WriteLine("Value2: " + value2);
         string testString = "Null Coalescing";
         string resultString = testString ?? "Original string is null";
         Console.WriteLine("The value of result message is: " + resultString);
      }
   }
}
The output of the above example is as follows.
Value2: 99
The value of result message is: Null Coalescing
Java Program to get random letters

To generate random letters, set letters as a strong and use the toCharArray() to convert it into character array −
"abcdefghijklmnopqrstuvwxyz".toCharArray()
Now, use the nextInt() to generate random letters from it −
System.out.println("" + "abcdefghijklmnopqrstuvwxyz".toCharArray()[randNum.nextInt("abcdefghijklmnopqrstuvwxyz".toCharArray().length)]);
Above, initially we have created a Random object −
static Random randNum = new Random();
 Live Demo
import java.util.Random;
public class Demo {
   static Random randNum = new Random();
   public static void main(String args[]) {
      System.out.println("Lowercase random letters...");
      for (int i = 0; i < 5; i++) {
         System.out.println("" + "abcdefghijklmnopqrstuvwxyz".toCharArray()[randNum.nextInt("abcdefghijklmnopqrstuvwxyz".toCharArray().length)]);
      }
      System.out.println("Uppercase random letters...");
      for (int i = 0; i < 5; i++) {
         System.out.println("" + "ABCDEFGHIJKLMNOPQRSTUVWZYZ".toCharArray()[randNum.nextInt("ABCDEFGHIJKLMNOPQRSTUVWZYZ".toCharArray().length)]);
      }
   }
}
Lowercase random letters...
d
l
h
j
s
Uppercase random letters...
B
K
I
Z
N
GATE | GATE CS 2019 | Question 55 - GeeksforGeeks

19 Feb, 2019
Let T be a full binary tree with 8 leaves. (A full binary tree has every level full.) Suppose two leaves a and b of T are chosen uniformly and independently at random. The expected value of the distance between a and b in T (i.e., the number of edges in the unique path between a and b) is (rounded off to 2 decimal places) ___________ .
Note: This was Numerical Type question.(A) 5.71 to 5.73(B) 4.85 to 4.86(C) 2.71 to 2.73(D) 4.24 to 4.26Answer: (D)Explanation: Full binary tree with 8 leaf nodes,
Two leaf nodes can be selected in 8*8 = 64 ways.
Where, X is length between two nodes selected.
The expected value of the length between a and b in T,
= E[X]
= X * P[X]
= 0*(8/64) + 2*(8/64) + 4*(16/64) + 6*(32/64)
= 272/64
= 4.25 
So, answer is 4.25.
Alternative way:Sum of distances from a particular leaf to the remaining 7 leaves is 34. The sum would remain the same for each leaf node. Therefore total sum of distance of all the leaf nodes = 34*8.
Two leaf nodes can be selected in 8*8 = 64 ways.
Therefore, the expected value of the length between a and b in T,
= (34*8) / (8*8)
= 34 / 8
= 4.25
Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
NLP | Brill Tagger - GeeksforGeeks

05 Jun, 2020
BrillTagger class is a transformation-based tagger. It is not a subclass of SequentialBackoffTagger.
Moreover, it uses a series of rules to correct the results of an initial tagger.
These rules it follows are scored based. This score is equal to the no. of errors they correct minus the no. of new errors they produce.
Code #1 : Training a BrillTagger class
# Loading Librariesfrom nltk.tag import brill, brill_trainer  def train_brill_tagger(initial_tagger, train_sents, **kwargs):    templates = [            brill.Template(brill.Pos([-1])),            brill.Template(brill.Pos([1])),            brill.Template(brill.Pos([-2])),            brill.Template(brill.Pos([2])),            brill.Template(brill.Pos([-2, -1])),            brill.Template(brill.Pos([1, 2])),            brill.Template(brill.Pos([-3, -2, -1])),            brill.Template(brill.Pos([1, 2, 3])),            brill.Template(brill.Pos([-1]), brill.Pos([1])),            brill.Template(brill.Word([-1])),            brill.Template(brill.Word([1])),            brill.Template(brill.Word([-2])),            brill.Template(brill.Word([2])),            brill.Template(brill.Word([-2, -1])),            brill.Template(brill.Word([1, 2])),            brill.Template(brill.Word([-3, -2, -1])),            brill.Template(brill.Word([1, 2, 3])),            brill.Template(brill.Word([-1]), brill.Word([1])),            ]          # Using BrillTaggerTrainer to train     trainer = brill_trainer.BrillTaggerTrainer(            initial_tagger, templates, deterministic = True)          return trainer.train(train_sents, **kwargs)
 Code #2 : Let’s use the trained BrillTagger
from nltk.tag import brill, brill_trainerfrom nltk.tag import DefaultTaggerfrom nltk.corpus import treebankfrom tag_util import train_brill_tagger  # Initializingdefault_tag = DefaultTagger('NN')  # initializing training and testing set    train_data = treebank.tagged_sents()[:3000]test_data = treebank.tagged_sents()[3000:]  initial_tag = backoff_tagger(        train_data, [UnigramTagger, BigramTagger,                     TrigramTagger], backoff = default_tagger)      a = initial_tag.evaluate(test_data)print ("Accuracy of Initial Tag : ", a)
Output :
Accuracy of Initial Tag : 0.8806820634578028

 Code #3 :
brill_tag = train_brill_tagger(initial_tag, train_data)b = brill_tag.evaluate(test_data)  print ("Accuracy of brill_tag : ", b)
Output :
Accuracy of brill_tag : 0.8827541549751781

Akanksha_Rai
Code_Mech
Natural-language-processing
Python-nltk
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Intuition of Adam Optimizer
CNN | Introduction to Pooling Layer
Convolutional Neural Network (CNN) in Machine Learning
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Dictionary get() Method in Java with Examples - GeeksforGeeks

27 Dec, 2018
The get() method of Dictionary class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the dictionary contains no such mapping for the key.
Syntax:
DICTIONARY.get(Object key_element)
Parameters: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched.
Return Value: The method returns the value associated with the key_element in the parameter.
Below programs are used to illustrate the working of java.util.Dictionary.get() Method:Program 1:
// Java code to illustrate the get() methodimport java.util.*;  public class Dictionary_Demo {    public static void main(String[] args)    {          // Creating an empty Dictionary        Dictionary<Integer, String> dict            = new Hashtable<Integer, String>();          // Inserting the values into dictionary        dict.put(10, "Geeks");        dict.put(15, "4");        dict.put(20, "Geeks");        dict.put(25, "Welcomes");        dict.put(30, "You");          // Displaying the Dictionary        System.out.println("Initial Dictionary is: " + dict);          // Getting the value of 25        System.out.println("The Value is: " + dict.get(25));          // Getting the value of 10        System.out.println("The Value is: " + dict.get(10));    }}
Initial Dictionary is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The Value is: Welcomes
The Value is: Geeks

Program 2:
// Java code to illustrate the get() methodimport java.util.*;  public class Dictionary_Demo {    public static void main(String[] args)    {          // Creating an empty Dictionary        Dictionary<String, Integer> dict            = new Hashtable<String, Integer>();          // Inserting the values into dictionary        dict.put("Geeks", 10);        dict.put("4", 15);        dict.put("Geeks", 20);        dict.put("Welcomes", 25);        dict.put("You", 30);          // Displaying the Dictionary        System.out.println("Initial Dictionary is: "                           + dict);          // Getting the value of 25        System.out.println("The Value is: "                           + dict.get("Geeks"));          // Getting the value of 10        System.out.println("The Value is: "                           + dict.get(20));    }}
Initial Dictionary is: {You=30, Welcomes=25, 4=15, Geeks=20}
The Value is: 20
The Value is: null

Java - util package
Java-Collections
Java-Dictionary
Java-Functions
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
PHP | Remove duplicate elements from Array - GeeksforGeeks

30 Mar, 2018
You are given an Array of n-elements.You have to remove the duplicate values without using any loop in PHP and print the array.
Examples:
Input : array[] = {2, 3, 1, 6, 1, 6, 2, 3}
Output : array (
                [6] => 2
                [7] => 3
                [4] => 1
                [5] => 6
               )

Input : array[] = {4, 2, 7, 3, 2, 7, 3}
Output : array (
                [0] => 4
                [4] => 2
                [5] => 7
                [6] => 3 
               )

In C/Java, we have to traverse the array and for each element you have to check if its duplicate is present. But PHP provides an inbuilt function (array_flip()) with the use of which we can remove duplicate elements without the use of loop.
The array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.
Note that the values of array need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result.
Note: If a value has several occurrences, the latest key will be used as its value, and all others will be lost. Also as array_flip() returns array with preserved keys, we will use array_values() which will re-order the keys.
Approach: The idea is to use this property of the array_flip() function of selecting the latest key as its value if the value has multiple occurrences. We will use the array_flip() function twice to remove the duplicate values. On using the array_flip() function for the first time, it will return an array with keys and values exchanged with removed duplicates. On using it the second time, it will again reorder it to the original configuration.
Below is the implementation of above idea:
<?php    // define array    $a = array(1, 5, 2, 5, 1, 3, 2, 4, 5);          // print original array    echo "Original Array : \n";    print_r($a);         // remove duplicate values by using     // flipping keys and values    $a = array_flip($a);       // restore the array elements by again     // flipping keys and values.    $a = array_flip($a);      // re-order the array keys    $a= array_values($a);      // print updated array    echo "\nUpdated Array : \n ";    print_r($a);?>
Output:
Original Array : 
Array
(
    [0] => 1
    [1] => 5
    [2] => 2
    [3] => 5
    [4] => 1
    [5] => 3
    [6] => 2
    [7] => 4
    [8] => 5
)

Updated Array : 
Array
(
    [0] => 1
    [1] => 5
    [2] => 2
    [3] => 3
    [4] => 4
)

PHP-array
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
HTML <a> ping Attribute - GeeksforGeeks

02 Jun, 2021
The HTML <a> ping Attribute is generally used to either specify a particular URL or a list of URLs that will be notified when the user will click on the hyperlink passed int HTML <a> href Attribute. This is achieved by sending a short HTTP post request to the specified URL as soon as the user clicks on the hyperlink. 
Syntax :
<a href="url_hyperlink" ping="specified_url" />
Attribute Values:
specified_url: This is the URL where the short HTTP post request will be sent as soon as the user follows the link given in url_hyperlink.
Example:
HTML
<!DOCTYPE html><html>  <head> </head>  <body>    <h2>Welcome To GFG</h2>    <a href="https://auth.geeksforgeeks.org/user/codersaty/articles"       ping="https://www.geeksforgeeks.org/">      Read codersaty articles    </a>  </body></html>
Output:
Note: A short HTTP post request will be sent to “https://www.geeksforgeeks.org/” whenever someone clicks  “Read codersaty articles”
Supported Browsers: 
Edge 17.0
Apple Safari 6.0
Opera 15.0
Google Chrome 15.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Attributes
HTML-Basics
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to check if a date has passed in MySQL?

Let us first create a table −
mysql> create table DemoTable1340
   -> (
   -> Deadline date
   -> );
Query OK, 0 rows affected (0.43 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1340 values('2019-09-18');
Query OK, 1 row affected (0.52 sec)
mysql> insert into DemoTable1340 values('2019-09-23');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1340 values('2018-12-24');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1340 values('2016-11-01');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1340 values('2019-09-28');
Query OK, 1 row affected (0.18 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1340;
This will produce the following output −
+------------+
| Deadline   |
+------------+
| 2019-09-18 |
| 2019-09-23 |
| 2018-12-24 |
| 2016-11-01 |
| 2019-09-28 |
+------------+
5 rows in set (0.00 sec)
We should know the current date as well. The current date is as follows −
mysql> select curdate();
+------------+
| curdate()  |
+------------+
| 2019-09-21 |
+------------+
1 row in set (0.00 sec)
Here is the query to check if a date has passed −
mysql> select * from DemoTable1340 where Deadline >= curdate();
This will produce the following output −
+------------+
| Deadline   |
+------------+
| 2019-09-23 |
| 2019-09-28 |
+------------+
2 rows in set (0.00 sec)
Array algorithms in C++ STL

Since C++11 there are different functions added into the STL. These functions are present at algorithm header file. Here we will see some functions of this.
The all_of() function is used to check one condition, that is true for all elements of a container. Let us see the code to get the idea
The all_of() function is used to check one condition, that is true for all elements of a container. Let us see the code to get the idea
#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(all_of(arr, arr + n, [](int x){return x%2 == 0;})) {
      cout << "All are even";
   } else {
      cout << "All are not even";
   }
}
All are even
The any_of() function is used to check one condition, that is true for at least one element of a container. Let us see the code to get the idea.
The any_of() function is used to check one condition, that is true for at least one element of a container. Let us see the code to get the idea.
#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10, 5, 62};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(any_of(arr, arr + n, [](int x){return x%2 == 1;})) {
      cout << "At least one element is odd";
   } else {
      cout << "No odd elements are found";
   }
}
At least one element is odd
The none_of() function is used to check whether no element of a container is satisfies the given condition. Let us see the code to get the idea.
The none_of() function is used to check whether no element of a container is satisfies the given condition. Let us see the code to get the idea.
#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10, 5, 62};
   int n = sizeof(arr)/sizeof(arr[0]);
   if(none_of(arr, arr + n, [](int x){return x < 0 == 1;})) {
      cout << "All elements are positive";
   } else {
      cout << "Some elements are negative";
   }
}
All elements are positive
The copy_n() function is used to copy elements of one array into another array. Let us see the code to get better idea.
The copy_n() function is used to copy elements of one array into another array. Let us see the code to get better idea.
#include <iostream>
#include <algorithm>
using namespace std;
main() {
   int arr[] = {2, 4, 6, 8, 10, 5, 62};
   int n = sizeof(arr)/sizeof(arr[0]);
   int arr2[n];
   copy_n(arr, n, arr2);
   for(int i = 0; i < n; i++) {
      cout << arr2[i] << " ";
   }
}
2 4 6 8 10 5 62
The itoa() function is used assign continuous values into array. This function is present under numeric header file. It takes three arguments. The array name, size and the starting value.
The itoa() function is used assign continuous values into array. This function is present under numeric header file. It takes three arguments. The array name, size and the starting value.
#include <iostream>
#include <numeric>
using namespace std;
main() {
   int n = 10;
   int arr[n];
   iota(arr, arr+n, 10);
   for(int i = 0; i < n; i++) {
      cout << arr[i] << " ";
   }
}
10 11 12 13 14 15 16 17 18 19
private access modifier in Java

Methods, variables, and constructors that are declared private can only be accessed within the declared class itself.
Private access modifier is the most restrictive access level. Class and interfaces cannot be private.
Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.
Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world.
The following class uses private access control -
public class Logger {
   private String format;
   public String getFormat() {
      return this.format;
   }
   public void setFormat(String format) {
      this.format = format;
   }
}
Here, the format variable of the Logger class is private, so there's no way for other classes to retrieve or set its value directly.
So, to make this variable available to the outside world, we defined two public methods: getFormat(), which returns the value of format, and setFormat(String), which sets its value.
TCS Coding Practice Question | HCF or GCD of 2 Numbers - GeeksforGeeks

09 Apr, 2019
Given two numbers, the task is to find the HCF of two numbers using Command Line Arguments. GCD (Greatest Common Divisor) or HCF (Highest Common Factor) of two numbers is the largest number that divides both of them.
Examples:
Input: n1 = 10, n2 = 20
Output: 10

Input: n1 = 100, n2 = 101
Output: 1

Approach:
Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line
Extract the input numbers from the command line argument
This extracted numbers will be in String type.
Convert these numbers into integer type and store it in variables, say num1 and num2
Find the HCF of the numbers. An efficient solution is to use Euclidean algorithm which is the main algorithm used for this purpose. The idea is, GCD of two numbers doesn’t change if smaller number is subtracted from a bigger number.
Print or return the HCF
Program:
C
Java
// C program to compute the HCF of two numbers// using command line arguments  #include <stdio.h>#include <stdlib.h> /* atoi */  // Function to compute the HCF of two numbersint HCF(int a, int b){    if (b == 0)        return a;      return HCF(b, a % b);}  // Driver codeint main(int argc, char* argv[]){      int num1, num2;      // Check if the length of args array is 1    if (argc == 1)        printf("No command line arguments found.\n");      else {          // Get the command line argument and        // Convert it from string type to integer type        // using function "atoi( argument)"        num1 = atoi(argv[1]);        num2 = atoi(argv[2]);          // Find the HCF and print it        printf("%d\n", HCF(num1, num2));    }    return 0;}
// Java program to compute the HCF of two numbers// using command line arguments  class GFG {      // Function to compute the HCF of two numbers    static int HCF(int a, int b)    {        if (b == 0)            return a;          return HCF(b, a % b);    }      // Driver code    public static void main(String[] args)    {          // Check if length of args array is        // greater than 0        if (args.length > 0) {              // Get the command line argument and            // Convert it from string type to integer type            int num1 = Integer.parseInt(args[0]);            int num2 = Integer.parseInt(args[1]);              // Find the HCF            int res = HCF(num1, num2);              // Print the HCF            System.out.println(res);        }        else            System.out.println("No command line "                               + "arguments found.");    }}
In C:
In Java:
TCS
TCS-coding-questions
C++ Programs
Java Programs
Placements
TCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C++ Program for QuickSort
cin in C++
delete keyword in C++
Shallow Copy and Deep Copy in C++
Check if given number is perfect square
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Find numbers a and b that satisfy the given condition in C++

Consider we have an integer n. Our task is to find two numbers a and b, where these three conditions will be satisfied.
a mod b = 0
a * b > n
a / b < n
If no pair is found, print -1.
For an example, if the number n = 10, then a and b can be a = 90, b = 10. This satisfies given rules.
To solve this problem, we will follow these steps −
Let b = n. a can be found using these three conditions
a mod b = 0 when a is multiple of b
a / b < n, so a / b = n – 1 which is < n
(a * b > n) => a = n
#include<iostream>
using namespace std;
void findAandB(int n) {
   int b = n;
   int a = b * (n - 1);
   if (a * b > n && a / b < n) {
      cout << "a: " << a << endl;
      cout << "b: " << b;
   }else
      cout << -1 << endl;
   }
int main() {
   int n = 10;
   findAandB(n);
}
a: 90
b: 10
How to create a JavaScript code for multiple keys pressed at once?

Use the keydown event in JavaScript to get to know which keys are pressed at once. The following is the script −
var log = $('#log')[0],
   keyPressed = [];

$(document.body).keydown(function (evt) {
   var li = keyPressed [evt.keyCode];
   if (!li) {
      li = log.appendChild(document.createElement('li'));
      keyPressed [evt.keyCode] = li;
   }
   $(li).text(Key Down: ' + evt.keyCode);
   $(li).removeClass('key-up');
});

$(document.body).keyup(function (evt) {
   var li = keyPressed [evt.keyCode];
   if (!li) {
      li = log.appendChild(document.createElement('li'));
   }
   $(li).text('Key Up: ' + evt.keyCode);
   $(li).addClass('key-up');
});
React useReducer Hook

The useReducer Hook is similar to the useState Hook.
It allows for custom state logic.
If you find yourself keeping track of multiple pieces of state that rely on complex logic, useReducer may be useful.
The useReducer Hook accepts two arguments.
useReducer(<reducer>, <initialState>)
The reducer function contains your custom state logic and the initialStatecan be a simple value but generally will contain an object.
The useReducer Hook returns the current stateand a dispatchmethod.
Here is an example of useReducer in a counter app:
import { useReducer } from "react";
import ReactDOM from "react-dom/client";

const initialTodos = [
  {
    id: 1,
    title: "Todo 1",
    complete: false,
  },
  {
    id: 2,
    title: "Todo 2",
    complete: false,
  },
];

const reducer = (state, action) => {
  switch (action.type) {
    case "COMPLETE":
      return state.map((todo) => {
        if (todo.id === action.id) {
          return { ...todo, complete: !todo.complete };
        } else {
          return todo;
        }
      });
    default:
      return state;
  }
};

function Todos() {
  const [todos, dispatch] = useReducer(reducer, initialTodos);

  const handleComplete = (todo) => {
    dispatch({ type: "COMPLETE", id: todo.id });
  };

  return (
    <>
      {todos.map((todo) => (
        <div key={todo.id}>
          <label>
            <input
              type="checkbox"
              checked={todo.complete}
              onChange={() => handleComplete(todo)}
            />
            {todo.title}
          </label>
        </div>
      ))}
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Todos />);


Run 
Example »

This is just the logic to keep track of the todo complete status.
All of the logic to add, delete, and complete a todo could be contained within a single
useReducer Hook by adding more actions.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.