code-rag-bench/online-tutorials huggingface dataset:
The Maze in C++

Suppose there is a ball in a maze with empty spaces and walls. Now the ball can go through empty paths by rolling any direction like up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
We have to start position of ball, the destination and the maze, we have to check whether the ball could stop at the destination. The maze is represented by one 2D array. Here 1 indicates the wall and 0 indicates the empty space. The borders of the maze are all walls. The start and destination coordinates are represented by row and column indices.
So, if the input is like a maze represented by a 2D array
start position is (0, 4) destination position is (4, 4), then the output will be true, One possible way is − left to down to right.
To solve this, we will follow these steps −
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   bool hasPath(vector<vector<int<>& grid, vector<int<& start, vector<int<& destination) {
      int n = grid.size();
      int m = grid[0].size();
      queue<vector<int< > q;
      q.push(start);
      set<vector<int< > visited;
      visited.insert(start);
      while (!q.empty()) {
         vector<int< curr = q.front();
         q.pop();
         int x = curr[0];
         int y = curr[1];
         if (destination[0] == x && destination[1] == y)
            return true;
         int i = x;
         while (i + 1 < n && !grid[i + 1][y])
            i++;
         if (!visited.count({ i, y })) {
            visited.insert({ i, y });
            q.push({ i, y });
         }
         i = x;
         while (i - 1 >= 0 && !grid[i - 1][y])
            i--;
         if (!visited.count({ i, y })) {
            visited.insert({ i, y });
            q.push({ i, y });
         }
         i = y;
         while (i + 1 < m && !grid[x][i + 1])
            i++;
         if (!visited.count({ x, i })) {
            visited.insert({ x, i });
            q.push({ x, i });
         }
         i = y;
         while (i - 1 >= 0 && !grid[x][i - 1])
            i--;
         if (!visited.count({ x, i })) {
            visited.insert({ x, i });
            q.push({ x, i });
         }
      }
      return false;
   }
};
main(){
   Solution ob;
   vector<vector<int<> v = {{0,0,1,0,0},{0,0,0,0,0},{0,0,0,1,0},{1,1,0,1,1},{0,0,0,0,0}};
   vector<int< v1 = {0,4}, v2 = {4,4};
   cout << (ob.hasPath(v, v1, v2));
}
{{0,0,1,0,0},{0,0,0,0,0},{0,0,0,1,0},{1,1,0,1,1},{0,0,0,0,0}},{0,4},{4,4}
1
Python - Binomial Distribution

The binomial distribution model deals with finding the probability of success of an event which has only two possible outcomes in a series of experiments. For example, tossing of a coin always gives a head or a tail. The probability of finding exactly 3 heads in tossing a coin repeatedly for 10 times is estimated during the binomial distribution.
We use the seaborn python library which has in-built functions to create such probability distribution graphs. Also, the scipy package helps is creating the binomial distribution.
from scipy.stats import binom
import seaborn as sb

binom.rvs(size=10,n=20,p=0.8)

data_binom = binom.rvs(n=20,p=0.8,loc=0,size=1000)
ax = sb.distplot(data_binom,
                  kde=True,
                  color='blue',
                  hist_kws={"linewidth": 25,'alpha':1})
ax.set(xlabel='Binomial', ylabel='Frequency')
Its output is as follows −

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Math.Max() Method in C#

The Math.Max() method in C# is used to return the larger of two specified numbers. This method works for both the numbers being Double, Decimal, Int16, Int32, etc.
Following is the syntax −
public static ulong Max (ulong val1, ulong val2);
public static uint Max (uint val1, uint val2);
public static ushort Max (ushort val1, ushort val2);
public static float Max (float val1, float val2);
public static byte Max (byte val1, byte val2);
public static long Max (long val1, long val2);
Let us now see an example to implement Math.Max() method −
using System;
public class Demo {
   public static void Main(){
      byte val1 = 10, val2 = 15;
      decimal val3 = 1000M, val4 = 1500M;
      double val5 = 15.896745, val6 = 25.676843;
      short val7 = 20, val8 = 30;
      Console.WriteLine("Maximum Value from two byte values = "+Math.Max(val1, val2));
      Console.WriteLine("Maximum Value from two decimal values = "+Math.Max(val3, val4));
      Console.WriteLine("Maximum Value from two double values = "+Math.Max(val5, val6));
      Console.WriteLine("Maximum Value from two short values = "+Math.Max(val7, val8));
   }
}
This will produce the following output −
Maximum Value from two byte values = 15
Maximum Value from two decimal values = 1500
Maximum Value from two double values = 25.676843
Maximum Value from two short values = 30
Let us see another example to implement Math.Max() method −
using System;
public class Demo {
   public static void Main(){
      int val1 = 10, val2 = 15;
      float val3 = 10.8f, val4 = 25.6f;
      Console.WriteLine("Maximum Value from two int values = "+Math.Max(val1, val2));
      Console.WriteLine("Maximum Value from two float values = "+Math.Max(val3, val4));
   }
}
This will produce the following output −
Maximum Value from two int values = 15
Maximum Value from two float values = 25.6
How to print star pattern in JavaScript in a very simple manner?

Here is a simple star pattern that we are required to print inside the JavaScript console. Note
that it has to be printed inside the console and not in the output or HTML window −
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
Here’s the code for doing so in JavaScript −
const star = "* ";
//where length is no of stars in longest streak
const length = 6;
for(let i = 1; i <= (length*2)-1; i++){
   const k = i <= length ? i : (length*2)-i;
   console.log(star.repeat(k));
}
The console output will be −
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
The String repeat() function is way of telling the compiler to produce a string with n copies of the
string it is used in context of, where n is the argument it receives.
The time complexity of this code is O(length^2) and the space complexity is O(1).
How to set vertical alignment for a component in Java?

For vertical alignment, create a frame and set the layout using the BoxLayout manager −
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
Above, we have set the BoxLayout to set the alignment since it is a layout manager that allows multiple components to be laid out either vertically or horizontally. We have set vertical alignment here −
BoxLayout.X_AXIS
The following is an example to set vertical alignment for a component −
package my;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SwingDemo {
   public static void main(String[] args) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
      JPanel panel = new JPanel();
      JButton btn1 = new JButton("Clear");
      JButton btn2 = new JButton("Reset");
      JButton btn3 = new JButton("Submit");
      panel.add(btn1);
      panel.add(btn2);
      panel.add(btn3);
      panel.setAlignmentX(Component.LEFT_ALIGNMENT);
      panel.setPreferredSize(new Dimension(100, 500));
      panel.setMaximumSize(new Dimension(100, 500));
      panel.setBorder(BorderFactory.createTitledBorder("demo"));
      frame.getContentPane().add(panel);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}
How can I make my layout scroll vertically in Android?

Before getting into example, we should know what is vertical Scroll View(Scroll View). Vertical Scroll view provide by android.widget.ScrollView class. It is used to scroll child views in a vertical direction.
This example demonstrates how to use Vertical Scroll view.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:id="@+id/layout"
   android:layout_height="match_parent">
   <ScrollView
      android:layout_width="match_parent"
      android:layout_height="match_parent">
      <LinearLayout
         android:layout_width="match_parent"
         android:orientation="vertical"
         android:layout_height="match_parent">
         <ImageView
            android:layout_width="match_parent"
            android:background="#c1c1c1"
            android:layout_height="300dp"
            android:src="@drawable/a"/>
         <ImageView
            android:layout_width="match_parent"
            android:background="#c1c1c1"
            android:layout_height="300dp"
            android:layout_marginTop="30dp"
            android:src="@drawable/b"/>
         <ImageView
            android:layout_width="match_parent"
            android:background="#c1c1c1"
            android:layout_height="300dp"
            android:layout_marginTop="30dp"
            android:src="@drawable/c"/>
         <ImageView
            android:layout_width="match_parent"
            android:background="#c1c1c1"
            android:layout_height="300dp"
            android:layout_marginTop="30dp"
            android:src="@drawable/d"/>
         <ImageView
            android:layout_width="match_parent"
            android:background="#c1c1c1"
            android:layout_height="300dp"
            android:layout_marginTop="30dp"
            android:src="@drawable/e"/>
      </LinearLayout>
   </ScrollView>
</LinearLayout>
In this above code, we have declare Linear layout as parent and added Vertical Scroll view. Vertical scroll view going to scroll its child view in Vertical direction so we have created Linear layout as a child for Vertical scroll view and added child for linear layout. We have given five child images views to scroll.
Step 3 − No need to change manifest.xml and activities.
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run icon  from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result is the initial screen when you scroll vertically it will scroll as shown below image-
In the above result, we are scrolling imageviews vertically.
At finally it will reach to the last position of vertical scroll view as shown above.
Click here to download the project code
Interpolation Search

For the binary search technique, the lists are divided into equal parts. For the interpolation searching technique, the procedure will try to locate the exact position using interpolation formula. After finding the estimated location, it can separate the list using that location. As it tries to find exact location every time, so the searching time reduces. This technique can find items easily if the items are uniformly distributed.
Time Complexity: O(log2(log2 n)) for the average case, and O(n) for the worst case (when items are distributed exponentially)
Space Complexity: O(1)
Input:
A sorted list of data:
10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995
The search key 780
Output:
Item found at location: 16
interpolationSearch(array, start, end, key)
Input − An sorted array, start and end location, and the search key
Output: location of the key (if found), otherwise wrong location.
Begin
   while start <= end AND key >= array[start] AND key <= array[end] do
      dist := key – array[start]
      valRange := array[end] – array[start]
      fraction := dist / valRange
      indexRange := end – start
      estimate := start + (fraction * indexRange)
      if array[estimate] = key then
         return estimate position
      if array[estimate] < key then
         start := estimate + 1
      else
         end = estimate -1
   done
   return invalid position
End
#include<iostream>
using namespace std;
int interpolationSearch(int array[], int start, int end, int key) {
   int dist, valRange, indexRange, estimate;
   float fraction;

   while(start <= end && key >= array[start] && key <= array[end]) {
      dist = key - array[start];
      valRange = array[end] - array[start]; //range of value
      fraction = dist / valRange;
      indexRange = end - start;
      estimate = start + (fraction * indexRange); //estimated position of the key

      if(array[estimate] == key)
         return estimate;
      if(array[estimate] < key)
         start = estimate +1;
      else
         end = estimate - 1;
   }
   return -1;
}

int main() {
   int n, searchKey, loc;
   cout << "Enter number of items: ";
   cin >> n;
   int arr[n]; //create an array of size n
   cout << "Enter items: " << endl;

   for(int i = 0; i< n; i++) {
      cin >> arr[i];
   }

   cout << "Enter search key to search in the list: ";
   cin >> searchKey;

   if((loc = interpolationSearch(arr, 0, n-1, searchKey)) >= 0)
      cout << "Item found at location: " << loc << endl;
   else
      cout << "Item is not found in the list." << endl;
}
Enter number of items: 20
Enter items:
10 13 15 26 28 50 56 88 94 127 159 356 480 567 689 699 780 850 956 995
Enter search key to search in the list: 780
Item found at location: 16
Max Min | Practice | GeeksforGeeks

Given an array A of size N of integers. Your task is to find the sum of minimum and maximum elements in the array.
 
Example 1:
Input:
N = 5
A[] = {-2, 1, -4, 5, 3}
Output: 1
Explanation: min = -4, max =  5. Sum = -4 + 5 = 1
 
Example 2:
Input:
N = 4
A[]  = {1, 3, 4, 1}
Output: 5
Explanation: min = 1, max = 4. Sum = 1 + 4 = 5

 
Your Task:  
You don't need to read input or print anything. Your task is to complete the function findSum() which takes the array A[] and its size N as inputs and returns the summation of minimum and maximum element of the array.
 
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
 
Constraints:
1 <= N <= 105
-109 <= Ai <= 109
0
saurabhg78172 months ago
class Solution{    public static int findSum(int A[],int N)    {       int pickMax=A[0];       int pickMin=A[0];      for(int i=1;i<N;i++)      {          if(pickMax<A[i])           pickMax=A[i];          if(pickMin>A[i])           pickMin=A[i];      }      return pickMax+pickMin;   }} 
0
ladle patel3 months ago
//Java Code:
 
public static int findSum(int A[],int N)    {       //code here
 if(N==1) {  return A[0]+A[0]; }
 int min = 0; int max = 0;
 if(A[0]> A[1]) {  max = A[0];  min = A[1]; } else {  max = A[1];  min = A[0]; }
 for(int i=2; i<N; i++) {  if(A[i]>max)   max = A[i];  else if(A[i]<min)   min = A[i]; }
 return max+min;   }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
p5.js | stroke() Function - GeeksforGeeks

25 Jul, 2019
The stroke() function is used to draw the lines and border around the text and shapes. The color object can be set in terms of RGB or HSB depending on the color mode. The color object can also be set as string in terms of RGB, RGBA, Hex CSS color or named color string.
Syntax:
stroke( v1, v2, v3, alpha )
or
stroke( value )
or
stroke( gray, alpha )
or
stroke( values )
or
stroke( color )
Parameters:
v1: It is used to set the red or hue value relative to current color range.
v2: It is used to set the green or saturation value relative to current color range.
v3: It is used to set the blue or brightness value relative to current color range.
alpha: It is used to set the transparency of the drawing.
value: It is used to set the value of color string.
gray: It is used to set the gray value.
values: It is an array containing the red, green, blue and alpha value.
color: It is used to set the stroke color.
Below examples illustrate the stroke() function in p5.js:
Example 1:
function setup() {       // Create Canvas of given size     createCanvas(400, 200); }   function draw() {           // Set the background color     background(220);           // Set the stroke width     strokeWeight(10);           // Set the stroke    stroke('green');        // Set the filled color     fill('white');           // Draw the circle     circle(90, 90, 34);           // Set the text size     textSize(20);           // Set the text to print     text("GeeksForGeeks", 140, 100); }
Output:
Example 2:
function setup() {           // Create Canvas of given size     createCanvas(400, 200); }   function draw() {           // Set the background color     background(220);           // Set the stroke clor     stroke('orange');           // Set the stroke width to 10     strokeWeight(30); // Orange           // Draw a line     line(100, 50, 300, 50);           // Set the stroke color     stroke('white');           // Set the stroke width to 8     strokeWeight(30); // White           // Draw a line     line(100, 100, 300, 100);           // Set stroke color     stroke('green');           // Set the stroke width to 6     strokeWeight(30); // Green           // Draw a line     line(100, 150, 300, 150); } 
Output:
Reference: https://p5js.org/reference/#/p5/stroke
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
How to work multiple AND conditions in MySQL?

To work with multiple AND conditions in MySQL, following is the syntax −
select *from yourTableName where yourColumnName1=yourValue1 and yourColumnName2=yourValue2 and yourColumnName3=yourValue3;
Let us first create a table −
mysql> create table DemoTable
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20),
   StudentAge int,
   StudentCountryName varchar(40)
   );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(StudentName,StudentAge,StudentCountryName) values('John',23,'US');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName,StudentAge,StudentCountryName) values('Carol',21,'UK');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(StudentName,StudentAge,StudentCountryName) values('John',21,'US');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(StudentName,StudentAge,StudentCountryName) values('John',21,'AUS');
Query OK, 1 row affected (0.14 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+-----------+-------------+------------+--------------------+
| StudentId | StudentName | StudentAge | StudentCountryName |
+-----------+-------------+------------+--------------------+
| 1         | John        | 23         | US                 |
| 2         | Carol       | 21         | UK                 |
| 3         | John        | 21         | US                 |
| 4         | John        | 21         | AUS                |
+-----------+-------------+------------+--------------------+
4 rows in set (0.00 sec)
Following is the query for multiple AND conditions in MySQL −
mysql> select *from DemoTable where StudentName="John" and StudentAge=21 and StudentCountryName="AUS";
+-----------+-------------+------------+--------------------+
| StudentId | StudentName | StudentAge | StudentCountryName |
+-----------+-------------+------------+--------------------+
| 4         | John        | 21         | AUS                |
+-----------+-------------+------------+--------------------+
1 row in set (0.00 sec)
PHP | http_build_query() Function - GeeksforGeeks

09 Jul, 2019
The http_build_query() function is an inbuilt function in PHP which is used to generate URL-encoded query string from the associative (or indexed) array.
Syntax:
string http_build_query( $query_data, $numeric_prefix, $arg_separator, $enc_type = PHP_QUERY_RFC1738 )
Parameters: This function accepts four parameters as mentioned above and described below:
$query_data: This parameter holds the array or object containing properties which are given below:It may be a single dimensional array or multi-dimensional array.If $query_data is an object then only public property will be incorporated into the result .
It may be a single dimensional array or multi-dimensional array.
If $query_data is an object then only public property will be incorporated into the result .
$numeric_prefix: This parameter is used if numeric indices are used in the base array, it will be prepended to the numeric index for elements in the base array only.
$arg_separator: It is used to separate arguments but may be overridden by specifying this parameter.
$enc_type: Its default value is PHP_QUERY_RFC1738.
Return Values: It returns a URL-encoded string.
Below programs illustrate the http_build_query() function in PHP:
Program 1:
<?php$info = array(    'sudo' => 'placement',    'CPP' => 'course',    'FORK' => 'C',);  echo http_build_query($info) . "#";echo http_build_query($info, '', '&');  ?>
sudo=placement&CPP=course&FORK=C#sudo=placement&CPP=course&FORK=C

Program 2:
<?php$info = array('geeks', 'gfg' => 'sudo', 'placement' => 'hypertext processor');  echo http_build_query($info) . "$";echo http_build_query($info, 'myvar_');?>
0=geeks&gfg=sudo&placement=hypertext+processor$myvar_0=geeks&gfg=sudo&placement=hypertext+processor

Reference: http://docs.php.net/manual/da/function.http-build-query.php
PHP-function
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 ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Collect.js | chunk() Function - GeeksforGeeks

12 Jun, 2020
The chunk() function breaks the collection to many small collections of the given size.  In JavaScript, the array is first converted to a collection and then the function is applied to the collection.
Syntax: 
data.chunk(x)

Parameter:  This function accepts a single parameter as mentioned above and described below.
x : This parameter holds an integer number that defines where to break the collection
Return value: Return the sub collection of the main collection
Below examples illustrate the chunk() function in collect.js:Example 1: Here in this example, we take a collection and then using the chunk() function we divide the collection.
Javascript
// It is used to import collect.js library   const collect = require('collect.js');  const collection = collect([1, 2, 3, 4, 5, 6, 7]);  const x = collection.chunk(5);  console.log(x.all());
Output :  
[ Collection { items: [ 1, 2, 3, 4, 5 ] },
  Collection { items: [ 6, 7 ] } ]

Example 2: In this example, we will pass two values in the chunk() function.
Javascript
// It is used to import collect.js library   const collect = require('collect.js');  const collection = collect([0 , 1 , 2 , 3 , 4 , 5 , 6 ]);  const x = collection.chunk(2, 4);  console.log(x.all());
Output: 
[ Collection { items: [ 0, 1 ] },
  Collection { items: [ 2, 3 ] },
  Collection { items: [ 4, 5 ] },
  Collection { items: [ 6 ] } ]

akhilsharma870
Collect.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python | Numpy matrix.choose()

10 Apr, 2019
With the help of Numpy matrix.choose() method, we can select the elements from a matrix by passing a parameter as an array which contain the index of row number to be selected. Output array having the same size as passed in the parameter.
Syntax : matrix.choose()
Return : Return an array of element choice
Example #1 :In this example we can see that with the help of matrix.choose() method we are able to extract an array of choices from matrix.
# import the important module in pythonimport numpy as np             # make a matrix with numpygfg = np.matrix('[1, 2, 3, 4; 3, 1, 5, 6]')             # applying matrix.choose() methodgeeks = np.choose([1, 0, 1, 0], gfg)       print(geeks)
[[3 2 5 4]]

Example #2 :
# import the important module in pythonimport numpy as np             # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]')             # applying matrix.choose() methodgeeks = np.choose([2, 0, 1], gfg)       print(geeks)
[[7 2 6]]

Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
getmaxx() function in C

25 Jan, 2018
The header file graphics.h contains getmaxx() function which returns the maximum X coordinate for current graphics mode and driver.Syntax :
int getmaxx();

Below is the implementation of getmaxx() function:
// C Implementation for getmaxx()#include <graphics.h>#include <stdio.h>  // driver codeint main(){    // gm is Graphics mode which is    // a computer display mode that    // generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;    char arr[100];      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // sprintf stands for “String print”.    // Instead of printing on console, it    // store output on char buffer which    // are specified in sprintf    sprintf(arr, "Maximum X coordinate for current "        "graphics mode And driver = %d", getmaxx());      // outtext function displays text at    // current position.    outtext(arr);      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output :


c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add a new column at the front of an existing R data frame?

Generally, when we add a new column to an existing R data frame that column is added at the end of the columns but we might need it at the front. This totally depends on our ease of use, familiarity with variables, and their need. We can add a new column at the front of an existing R data frame by using cbind function.
Consider the below data frame −
ID <-1:20
Class <-rep(c("A","B","C","D"),times=5)
df1 <-data.frame(ID,Class)
df1
ID Class
1 1 A
2 2 B
3 3 C
4 4 D
5 5 A
6 6 B
7 7 C
8 8 D
9 9 A
10 10 B
11 11 C
12 12 D
13 13 A
14 14 B
15 15 C
16 16 D
17 17 A
18 18 B
19 19 C
20 20 D
Now suppose that we want to add a new column Score at the front of the data frame, then it can be done as shown below −
Score <-sample(1:100,20)
df1 <-cbind(Score,df1)
df1
Score ID Class
1 87 1 A
2 99 2 B
3 90 3 C
4 13 4 D
5 100 5 A
6 50 6 B
7 51 7 C
8 89 8 D
9 70 9 A
10 72 10 B
11 36 11 C
12 12 12 D
13 98 13 A
14 93 14 B
15 86 15 C
16 2 16 D
17 35 17 A
18 34 18 B
19 67 19 C
20 44 20 D
Let’s have a look at another example −
x1<-rnorm(20)
x2<-rnorm(20,1)
x3<-rnorm(20,5)
df2<-data.frame(x1,x2,x3)
df2
      x1       x2       x3
1 -0.78695273 -0.16032953 7.353717
2 0.42981155 1.43909343 3.984902
3 -0.37641622 1.20485374 5.290978
4 -1.21622907 0.30081866 6.565326
5 1.02927851 0.07337432 4.152882
6 0.43039700 -0.01348238 6.327660
7 -1.24557402 1.60498706 5.477046
8 -0.60272849 2.73440013 5.185251
9 0.66006939 0.65014947 5.253295
10 2.05074953 2.19918551 7.592227
11 0.49080818 2.02390100 6.074347
12 -1.73147942 0.95372485 3.403098
13 0.71088366 2.38650843 4.912411
14 0.01382291 -1.19527272 5.360768
15 -1.40104160 0.87244309 4.120040
16 1.25912367 -0.31699684 1.676665
17 -0.12747752 -0.42693514 4.532485
18 -0.72938651 1.87944163 5.431540
19 -1.21136136 1.39399158 4.396011
20 0.59961974 1.68892548 5.674447
y<-rpois(20,2)
df2<-cbind(y,df2)
df2
   y       x1       x2       x3
1 3 -0.78695273 -0.16032953 7.353717
2 2 0.42981155 1.43909343 3.984902
3 1 -0.37641622 1.20485374 5.290978
4 4 -1.21622907 0.30081866 6.565326
5 2 1.02927851 0.07337432 4.152882
6 1 0.43039700 -0.01348238 6.327660
7 3 -1.24557402 1.60498706 5.477046
8 1 -0.60272849 2.73440013 5.185251
9 2 0.66006939 0.65014947 5.253295
10 4 2.05074953 2.19918551 7.592227
11 5 0.49080818 2.02390100 6.074347
12 0 -1.73147942 0.95372485 3.403098
13 1 0.71088366 2.38650843 4.912411
14 3 0.01382291 -1.19527272 5.360768
15 2 -1.40104160 0.87244309 4.120040
16 1 1.25912367 -0.31699684 1.676665
17 3 -0.12747752 -0.42693514 4.532485
18 3 -0.72938651 1.87944163 5.431540
19 2 -1.21136136 1.39399158 4.396011
20 2 0.59961974 1.68892548 5.674447
Perl | shift() Function

07 May, 2019
shift() function in Perl returns the first value in an array, removing it and shifting the elements of the array list to the left by one. Shift operation removes the value like pop but is taken from the start of the array instead of the end as in pop. This function returns undef if the array is empty otherwise returns the first element of the array.
Syntax: shift(Array)
Returns: -1 if array is Empty otherwise first element of the array
Example 1:
#!/usr/bin/perl -w  # Defining Array to be shifted@array1 = ("Geeks", "For", "Geeks");  # Original Arrayprint "Original Array: @array1\n";  # Performing the shift operation$shifted_element = shift(@array1);  # Printing the shifted elementprint "Shifted element: $shifted_element\n";  # Updated Arrayprint "Updated Array: @array1";
Original Array: Geeks For Geeks
Shifted element: Geeks
Updated Array: For Geeks

Example 2:
#!/usr/bin/perl -w  # Program to move first element # of an array to the end  # Defining Array to be shifted@array1 = ("Geeks", "For", "Geeks");  # Original Arrayprint "Original Array: @array1\n";  # Performing the shift operation$shifted_element = shift(@array1);  # Placing First element in the end@array1[3] = $shifted_element;  # Updated Arrayprint "Updated Array: @array1";
Original Array: Geeks For Geeks
Updated Array: For Geeks  Geeks

Perl-Array-Functions
Perl-function
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Polymorphism in OOPs
Perl Tutorial - Learn Perl With Examples
Perl | length() Function
Perl | Boolean Values
Perl | Subroutines or Functions
Use of print() and say() in Perl
Perl | Basic Syntax of a Perl Program
Perl | eq operator
Perl | ne operator
Perl | substitution Operator
C Program for Find largest prime factor of a number

06 Dec, 2018
Given a positive integer ‘n'( 1 <= n <= 1015). Find the largest prime factor of a number.
Input: 6
Output: 3
Explanation
Prime factor of 6 are- 2, 3
Largest of them is '3'

Input: 15
Output: 5

// C Program to find largest prime// factor of number#include <math.h>#include <stdio.h>  // A function to find largest prime factorlong long maxPrimeFactors(long long n){    // Initialize the maximum prime factor    // variable with the lowest one    long long maxPrime = -1;      // Print the number of 2s that divide n    while (n % 2 == 0) {        maxPrime = 2;        n >>= 1; // equivalent to n /= 2    }      // n must be odd at this point, thus skip    // the even numbers and iterate only for    // odd integers    for (int i = 3; i <= sqrt(n); i += 2) {        while (n % i == 0) {            maxPrime = i;            n = n / i;        }    }      // This condition is to handle the case    // when n is a prime number greater than 2    if (n > 2)        maxPrime = n;      return maxPrime;}  // Driver program to test above functionint main(){    long long n = 15;    printf("%lld\n", maxPrimeFactors(n));      n = 25698751364526;    printf("%lld", maxPrimeFactors(n));      return 0;}
5
328513

Time complexity: Auxiliary space: 
Please refer complete article on Find largest prime factor of a number for more details!
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Difference between break and continue statement in C
C Hello World Program
C program to find the length of a string
Exit codes in C/C++ with Examples
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C Program to concatenate two strings without using strcat
Conditional wait and signal in multi-threading
Python - Remove Stopwords

Stopwords are the English words which does not add much meaning to a sentence. They can safely be ignored without sacrificing the meaning of the sentence. For example, the words like the, he, have etc. Such words are already captured this in corpus named corpus. We first download it to our python environment. 
import nltk
nltk.download('stopwords')
It will download a file with English stopwords. 
from nltk.corpus import stopwords
stopwords.words('english')
print stopwords.words() [620:680]
When we run the above program we get the following output −
[u'your', u'yours', u'yourself', u'yourselves', u'he', u'him', u'his', u'himself', u'she', 
u"she's", u'her', u'hers', u'herself', u'it', u"it's", u'its', u'itself', u'they', u'them', 
u'their', u'theirs', u'themselves', u'what', u'which', u'who', u'whom', u'this', 
u'that', u"that'll", u'these', u'those', u'am', u'is', u'are', u'was', u'were', u'be',
u'been', u'being', u'have', u'has', u'had', u'having', u'do', u'does', u'did', u'doing',
u'a', u'an', u'the', u'and', u'but', u'if', u'or', u'because', u'as', u'until',
u'while', u'of', u'at']

The various language other than English which has these stopwords are as below. 

from nltk.corpus import stopwords
print stopwords.fileids()

When we run the above program we get the following output −
[u'arabic', u'azerbaijani', u'danish', u'dutch', u'english', u'finnish', 
u'french', u'german', u'greek', u'hungarian', u'indonesian', u'italian', 
u'kazakh', u'nepali', u'norwegian', u'portuguese', u'romanian', u'russian',
u'spanish', u'swedish', u'turkish']

 We use the below example to show how the stopwords are removed from the list of words.
from nltk.corpus import stopwords
en_stops = set(stopwords.words('english'))

all_words = ['There', 'is', 'a', 'tree','near','the','river']
for word in all_words: 
    if word not in en_stops:
        print(word)
When we run the above program we get the following output −
HTML <nav> Tag

17 Mar, 2022
The <nav> tag is used for declaring the navigational section in HTML documents. Websites typically have sections dedicated to navigational links, which enables users to navigate the site. These links can be placed inside a nav tag. In other words, the nav element represents a section of the page whose purpose is to provide navigational links, either in the current document or to another document. The links in the nav element may point to other webpages or to different sections of the same webpage. It is a semantic element. Common examples of the nav elements are menus, tables, contents, and indexes. 
The nav tag is reserved for primary navigation areas, like the main menu across the top of the page or section. A document may have several nav elements, for example, site navigation and one for intra-page navigation. Links within nav tag can be codes within a ul list or simply coded as separate links, without ul element. This element makes it much easier to create a navigation menu, creates a neat horizontal menu of text links, and helps screen reading software to correctly identify primary navigation areas in the document.
 Syntax: 
<nav> Links... </nav>
Example: 
html
<!DOCTYPE html><html> <body>    <h1>GeeksforGeeks</h1>    <h2> HTML nav Tag</h2>    <!-- nav tag starts -->    <nav>        <a href="#">Home</a> |        <a href="#">Interview</a> |        <a href="#">Languages</a> |        <a href="#">Data Structure</a> |        <a href="#">Algorithm</a>    </nav>    <!-- nav tag ends --></body> </html>
Output:  
Example: Styling nav using CSS.
html
<!DOCTYPE html><html> <head>    <style>        nav {            border: 1px;            background-color: green;            color: white;            padding: 6px;        }                 a {            text-decoration: none;            color: white;            font-size: 20px;        }    </style></head> <body>    <h1>GeeksforGeeks</h1>    <h2>HTML nav Tag</h2>    <!-- nav tag starts -->    <nav>        <a href="https://www.geeksforgeeks.org/">                Home</a> |        <a href="https://www.geeksforgeeks.org/company-interview-corner/">                Interview</a> |        <a href="https://www.geeksforgeeks.org/gate-cs-notes-gq/">                Gate</a> |        <a href="https://www.geeksforgeeks.org/data-structures/">                Data Structure</a> |        <a href="https://www.geeksforgeeks.org/fundamentals-of-algorithms/">                Algorithm</a>    </nav>    <!-- nav tag ends --></body> </html>
Output:  
 Supported Browser: 
Google Chrome 6.0 and above
Internet Explorer 9.0 and above
Mozilla 4.0 and above
Safari 5.0 and above
Opera 11.1 and above
ghoshsuman0129
HTML-Tags
HTML
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript focus a particular element with div class, not div id declaration?

You can use the concept of focus(). Following is the JavaScript code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<span class="TEXT_FOCUS" tabindex="-1"><center>TEXT BOX FOR
FOCUS</center></span><br>
<button id="focusButton">click me to get the tab on focus</button>
<script>
   document.getElementById('focusButton').addEventListener('click', function() {
      document.querySelectorAll('.TEXT_FOCUS')[0].focus();
   });
</script>
</body>
</html>
To run the above program, save the file name anyName.html(index.html) and right click on the file and select the option open with live server in VS code editor.
When you click the button, the focus will be on a particular element. The snapshot is as follows −
strcmp() in C/C++

The function strcmp() is a built-in library function and it is declared in “string.h” header file. This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.
If the first character of both strings are equal, it checks second character and so on. This process will be continued until NULL character is found or both characters are unequal.
Here is the syntax of strcmp() in C language,
int strcmp(const char *leftStr, const char *rightStr );
This function returns the following three different values based on the comparison.
1.Zero(0) − It returns zero if both strings are identical. All characters are same in both strings.
Here is an example of strcmp() when both strings are equal in C language,
 Live Demo
#include<stdio.h>
#include<string.h>
int main() {
   char str1[] = "Tom!";
   char str2[] = "Tom!";
   int result = strcmp(str1, str2);
   if (result==0)
   printf("Strings are equal");
   else
   printf("Strings are unequal");
   printf("\nValue returned by strcmp() is: %d" , result);
   return 0;
}
Strings are equal
Value returned by strcmp() is: 0
2.Greater than zero(>0) − It returns a value greater than zero when the matching character of left string has greater ASCII value than the character of the right string.
Here is an example of strcmp() when it returns greater than zero value in C language,
 Live Demo
#include<stdio.h>
#include<string.h>
int main() {
   char str1[] = "hello World!";
   char str2[] = "Hello World!";
   int result = strcmp(str1, str2);
   if (result==0)
   printf("Strings are equal");
   else
   printf("Strings are unequal");
   printf("\nValue returned by strcmp() is: %d" , result);
   return 0;
}
Strings are unequal
Value returned by strcmp() is: 32
3.Less than zero(<0) − It returns a value less than zero when the matching character of left string has lesser ASCII value than the character of the right string.
Here is an example of strcmp() in C language
 Live Demo
#include<stdio.h>
#include<string.h>
int main() {
   char leftStr[] = "Hello World!";
   char rightStr[] = "hello World!";
   int result = strcmp(leftStr, rightStr);
   if (result==0)
   printf("Strings are equal");
   else
   printf("Strings are unequal");
   printf("\nValue returned by strcmp() is: %d" , result);
   return 0;
}
Strings are unequal
Value returned by strcmp() is: -32
numpy.ravel

This function returns a flattened one-dimensional array. A copy is made only if needed. The returned array will have the same type as that of the input array. The function takes one parameter.
numpy.ravel(a, order)

The constructor takes the following parameters.
order
'C': row major (default. 'F': column major 'A': flatten in column-major order, if a is Fortran contiguous in memory, row-major order otherwise 'K': flatten a in the order the elements occur in the memory
import numpy as np 
a = np.arange(8).reshape(2,4) 

print 'The original array is:' 
print a 
print '\n'  

print 'After applying ravel function:' 
print a.ravel()  
print '\n' 

print 'Applying ravel function in F-style ordering:' 
print a.ravel(order = 'F')
Its output would be as follows −
The original array is:
[[0 1 2 3]
 [4 5 6 7]]

After applying ravel function:
[0 1 2 3 4 5 6 7]

Applying ravel function in F-style ordering:
[0 4 1 5 2 6 3 7]


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to Remove duplicate elements from array in JavaScript ? - GeeksforGeeks

06 Aug, 2021
There are various different methods for finding the duplicates in the array. We will discuss two ways for finding the duplicates in the array.
Using Set: The Set object lets you store unique values of any type, whether primitive values or object references. This is the easiest method to remove the duplicate element and get unique elements from an array.
Example: Suppose we have an array called City which consists of the duplicate city names and we want to remove the duplicates and find the unique elements from it.
Javascript
<script>  // Defining a set of the cities  let city = [    "surat",    "ahmedabad",    "rajkot",    "mumbai",    "surat",    "delhi",    "ahmedabad",    "anand",  ];    // For removing the duplicate values  // we are using the Set() function  let unique_city = [new Set(city)];    // Printing the unique cities  console.log(unique_city);</script>
Output:
["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]
 
Using forEach() Method: We use the JavaScript includes() function which returns true if an element is in an array or false if it is not present.
The following example iterates over elements of an array and adds elements to a new array that are not already present.
Example :
Javascript
<script>  // Defining a set of the cities  let city = [    "surat",    "ahmedabad",    "rajkot",    "mumbai",    "surat",    "delhi",    "ahmedabad",    "anand",  ];    // Defining the unique cities from the above  // array by using forEach loop  let unique_city = [];  city.forEach((c) => {    if (!unique_city.includes(c)) {      unique_city.push(c);    }  });    // Printing the unique cities  console.log(unique_city);</script>
Output:
["surat", "ahmedabad", "rajkot", "mumbai", "delhi"]
javascript-array
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Get maximum and minimum value in MongoDB?

Use maxandmin operator along with aggregate framework to get the maximum and minimum value. Let us first create a collection with documents −
> db.maxAndMinDemo.insertOne({"Value":98});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698a357806ebf1256f129")
}
> db.maxAndMinDemo.insertOne({"Value":97});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698af57806ebf1256f12a")
}
> db.maxAndMinDemo.insertOne({"Value":69});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698b357806ebf1256f12b")
}
> db.maxAndMinDemo.insertOne({"Value":96});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698b657806ebf1256f12c")
}
> db.maxAndMinDemo.insertOne({"Value":99});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd698b957806ebf1256f12d")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.maxAndMinDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5cd698a357806ebf1256f129"), "Value" : 98 }
{ "_id" : ObjectId("5cd698af57806ebf1256f12a"), "Value" : 97 }
{ "_id" : ObjectId("5cd698b357806ebf1256f12b"), "Value" : 69 }
{ "_id" : ObjectId("5cd698b657806ebf1256f12c"), "Value" : 96 }
{ "_id" : ObjectId("5cd698b957806ebf1256f12d"), "Value" : 99 }
Following is the query to max and min in MongoDB −
> db.maxAndMinDemo.aggregate([
   { "$group": {
      "_id": null,
      "MaximumValue": { "$max": "$Value" },
      "MinimumValue": { "$min": "$Value" }
   }}
]);
This will produce the following output −
{ "_id" : null, "MaximumValue" : 99, "MinimumValue" : 69 }