code-rag-bench/online-tutorials huggingface dataset:
Remove duplicates from an unsorted array using STL in C++

03 Jun, 2019
Given an unsorted array, the task is to remove the duplicate elements from the array using STL in C++
Examples:
Input: arr[] = {1, 2, 5, 1, 7, 2, 4, 2}
Output: arr[] = {1, 2, 4, 5, 7}

Input: arr[] = {1, 2, 4, 3, 5, 4, 4, 2, 5}
Output: arr[] = {1, 2, 3, 4, 5}

Approach:The duplicates of the array can be removed using the unique() function provided in STL.
Below is the implementation of the above approach.
#include <bits/stdc++.h>using namespace std;  // Function to remove duplicate elementsvoid remDup(int arr[], int n){      // Initialise a vector    // to store the array values    // and an iterator    // to traverse this vector    vector<int> v(arr, arr + n);    vector<int>::iterator it;      // sorting vector    sort(v.begin(), v.end());      // using unique() method    // to remove duplicates    it = unique(v.begin(), v.end());      // resize the new vector    v.resize(distance(v.begin(), it));      // Print the array with duplicates removed    cout << "\nAfter removing duplicates:\n";    for (it = v.begin(); it != v.end(); ++it)        cout << *it << " ";    cout << '\n';}  // Driver codeint main(){    int arr[] = { 1, 2, 5, 1, 7, 2, 4, 2 };      int n = sizeof(arr) / sizeof(arr[0]);      // Print array    cout << "\nBefore removing duplicates:\n";    for (int i = 0; i < n; i++)        cout << arr[i] << " ";      // call remDup()    remDup(arr, n);      return 0;}
Before removing duplicates:
1 2 5 1 7 2 4 2 
After removing duplicates:
1 2 4 5 7

cpp-array
STL
C++ Programs
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shallow Copy and Deep Copy in C++
C++ Program to check if a given String is Palindrome or not
How to find the minimum and maximum element of a Vector using STL in C++?
C++ Program for QuickSort
C Program to Swap two Numbers
delete keyword in C++
Passing a function as a parameter in C++
cin in C++
Enumerated Types or Enums in C++
Const keyword in C++
How to search for ^ character in a MySQL table?

To search for ^ character, use the LIKE operator as in the below syntax −
select table_schema,table_name,column_name
 from information_schema.columns
 where column_name like '%^%';
Let us first create a table −
mysql> create table DemoTable1826
     (
     `^` varchar(20),
     Name varchar(20),
     `^Age` int
     );
Query OK, 0 rows affected (0.00 sec)
Here is the query to search for ^ character in a MySQL table
mysql> select table_schema,table_name,column_name
     from information_schema.columns
     where column_name like '%^%';
This will produce the following output −
+--------------+---------------+-------------+
| TABLE_SCHEMA | TABLE_NAME    | COLUMN_NAME |
+--------------+---------------+-------------+
| web          | demotable1826 | ^           |
| web          | demotable1826 | ^Age        |
+--------------+---------------+-------------+
2 rows in set (0.00 sec)
Java throws Keyword

❮ Java Keywords

Throw an exception if age is below 18 (print "Access 
denied"). If age is 18 or older, print "Access granted":
public class Main {
  static void checkAge(int age) throws ArithmeticException {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
    else {
      System.out.println("Access granted - You are old enough!");
    }
  }

  public static void main(String[] args) {
    checkAge(15); // Set age to 15 (which is below 18...)
  }
}


Try it Yourself »

The throws keyword indicates what exception type may be thrown by a method.
There are many exception types available in Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc.
Differences between throw and throws:
throw is followed by an object (new type)
used inside the method
throws is followed by a class
and used with the method signature
Read more about exceptions in our Java Try..Catch Tutorial.

❮ Java Keywords

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.
Bootstrap 4 - Breadcrumb

It is used to show hierarchy-based information for a site and indicates current page's location within a navigational hierarchy. Bootstrap uses .breadcrumb class to define the list into breadcrumb and adds a separator via CSS to the list.
The following example demonstrates this −
<html lang = "en">
   <head>
      <!-- Meta tags -->
      <meta charset = "utf-8">
      <meta name = "viewport" content = "width = device-width, initial-scale = 1, shrink-to-fit = no">
      
      <!-- Bootstrap CSS -->
      <link rel = "stylesheet" 
         href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" 
         integrity = "sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" 
         crossorigin = "anonymous">
      
      <title>Bootstrap 4 Example</title>
   </head>
   
   <body>
      <div class = "container">
         <h2>Breadcrumb</h2>
         <nav aria-label = "breadcrumb">
            <!--Add the "breadcrumb" class to ul element that represents the breadcrumb-->
            <ul class = "breadcrumb">
               <!--Add the ".breadcrumb-item" class to each li element within the breadcrumb-->
               <li class = "breadcrumb-item"><a href = "#">Home</a></li>
               <li class = "breadcrumb-item"><a href="#">Tutorials Library</a></li>
               <!--Add the "active" class to li element to represent the current page-->
               <li class = "breadcrumb-item active" aria-current = "page">Bootstrap 4</li>
            </ul>
         </nav>
      </div>
      
      <!-- jQuery first, then Popper.js, then Bootstrap JS -->
      <script src = "https://code.jquery.com/jquery-3.3.1.slim.min.js" 
         integrity = "sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" 
         crossorigin = "anonymous">
      </script>
      
      <script src = "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" 
         integrity = "sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" 
         crossorigin = "anonymous">
      </script>
      
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" 
         integrity = "sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" 
         crossorigin = "anonymous">
      </script>
      
   </body>
</html>
It will produce the following result −
Home
Tutorials Library
Bootstrap 4

    26 Lectures 
     2 hours 

 Anadi Sharma

    54 Lectures 
     4.5 hours 

 Frahaan Hussain

    161 Lectures 
     14.5 hours 

 Eduonix Learning Solutions

    20 Lectures 
     4 hours 

 Azaz Patel

    15 Lectures 
     1.5 hours 

 Muhammad Ismail

    62 Lectures 
     8 hours 

 Yossef Ayman Zedan
 Print
 Add Notes
 Bookmark this page
How to check Minlength and Maxlength validation of a property in C# using Fluent Validation?

Ensures that the length of a particular string property is no longer than the specified value.
Only valid on string properties
String format args:
{PropertyName} = The name of the property being validated
{MaxLength} = Maximum length
{TotalLength} = Number of characters entered
{PropertyValue} = The current value of the property
Ensures that the length of a particular string property is longer than the specified value.
Only valid on string properties
{PropertyName} = The name of the property being validated
{MinLength} = Minimum length
{TotalLength} = Number of characters entered
{PropertyValue} = The current value of the property
static void Main(string[] args){
   List errors = new List();

   PersonModel person = new PersonModel();
   person.FirstName = "TestUser444";
   person.LastName = "TTT";

   PersonValidator validator = new PersonValidator();
   ValidationResult results = validator.Validate(person);

   if (results.IsValid == false){
      foreach (ValidationFailure failure in results.Errors){
         errors.Add(failure.ErrorMessage);
      }
   }

   foreach (var item in errors){
      Console.WriteLine(item);
   }
   Console.ReadLine();
   }
}
public class PersonModel{
   public string FirstName { get; set; }
   public string LastName { get; set; }
}
public class PersonValidator : AbstractValidator{
   public PersonValidator(){
      RuleFor(p => p.FirstName).MaximumLength(7).WithMessage("MaximumLength must be 7 {PropertyName}") ;
      RuleFor(p => p.LastName).MinimumLength(5).WithMessage("MinimumLength must be 5 {PropertyName}");
   }
}
MaximumLength must be 7 First Name
MinimumLength must be 5 Last Name
How to generate prime numbers using Python?

A prime number is the one that is not divisible by any other number except 1 and itself.
In Python % modulo operator is available to test if a number is divisible by other. 
Assuming we have to find prime numbers between 1 to 100, each number (let us say x) in the range needs to be successively checked for divisibility by 2 to x-1. This is achieved by employing two nested loops.
for x in range(1,101):
for y in range(2,x):
if x%y==0:break
else:
print (x,sep=' ', end=' ')
Above code generates prime numbers between 1-100
1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
How to get current time in milliseconds in Python?

You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time.time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off. 
import time
milliseconds = int(round(time.time() * 1000))
print(milliseconds)
This will give the output −
1514825676008
Python | Consecutive characters frequency - GeeksforGeeks

22 Apr, 2020
Sometimes, while working with Python, we can have a problem in which we need to compute the frequency of consecutive characters till character changes. This can have application in many domains. Lets discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + groupby()This is one of the shorthand with the help of which this task can be performed. In this, we employ groupby() to group consecutives together to perform frequency calculations.
# Python3 code to demonstrate working of # Consecutive characters frequency# Using list comprehension + groupby()from itertools import groupby  # initializing stringtest_str = "geekksforgggeeks"  # printing original stringprint("The original string is : " + test_str)  # Consecutive characters frequency# Using list comprehension + groupby()res = [len(list(j)) for _, j in groupby(test_str)]  # printing result print("The Consecutive characters frequency : " + str(res)) 
The original string is : geekksforgggeeks
The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]

 
Method #2 : Using regexAnother way to solve this problem is using regex. In this we employ regex character finding technique and find count using len().
# Python3 code to demonstrate working of # Consecutive characters frequency# Using regeximport re  # initializing stringtest_str = "geekksforgggeeks"  # printing original stringprint("The original string is : " + test_str)  # Consecutive characters frequency# Using regexres = [len(sub.group()) for sub in re.finditer(r'(.)\1*', test_str)]  # printing result print("The Consecutive characters frequency : " + str(res)) 
The original string is : geekksforgggeeks
The Consecutive characters frequency : [1, 2, 2, 1, 1, 1, 1, 3, 2, 1, 1]

Python string-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
How to add calendar events in Android App?

This example demonstrates how do I add calendar events in android.
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"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="8dp"
   tools:context=".MainActivity">
   <Button
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:onClick="AddCalendarEvent"
      android:text="Add Calendar Event" />
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Calendar Event In Android"
      android:textSize="18sp"
      android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
   public void AddCalendarEvent(View view) {
      Calendar calendarEvent = Calendar.getInstance();
      Intent i = new Intent(Intent.ACTION_EDIT);
      i.setType("vnd.android.cursor.item/event");
      i.putExtra("beginTime", calendarEvent.getTimeInMillis());
      i.putExtra("allDay", true);
      i.putExtra("rule", "FREQ=YEARLY");
      i.putExtra("endTime", calendarEvent.getTimeInMillis() + 60 * 60 * 1000);
      i.putExtra("title", "Calendar Event");
      startActivity(i);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Bootstrap .checkbox-inline class

Use .checkbox-inline class to a series of checkboxes for controls to appear on the same line. 
You can try to run the following code to implement the .checkbox-inline class
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Forms</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <label for = "name">Best IDE (You can select more than one)</label>
      <div>
         <label class = "checkbox-inline">
            <input type = "checkbox" id = "inlineCheckbox1" value = "option1"> NetBeans IDE
         </label>
         <label class = "checkbox-inline">
            <input type = "checkbox" id = "inlineCheckbox2" value = "option2"> Eclipse IDE
         </label>
      </div>
   </body>
</html>
Tryit Editor v3.7

CSS Style Images
Tryit: Create circled image
C++ do...while loop

Unlike for and while loops, which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.
The syntax of a do...while loop in C++ is −
do {
   statement(s);
} 
while( condition );

Notice that the conditional expression appears at the end of the loop, so the statement(s) in the loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop execute again. This process repeats until the  given condition becomes false.
#include <iostream>
using namespace std;
 
int main () {
   // Local variable declaration:
   int a = 10;

   // do loop execution
   do {
      cout << "value of a: " << a << endl;
      a = a + 1;
   } while( a < 20 );
 
   return 0;
}
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19


    154 Lectures 
     11.5 hours 

 Arnab Chakraborty

    14 Lectures 
     57 mins

 Kaushik Roy Chowdhury

    30 Lectures 
     12.5 hours 

 Frahaan Hussain

    54 Lectures 
     3.5 hours 

 Frahaan Hussain

    77 Lectures 
     5.5 hours 

 Frahaan Hussain

    12 Lectures 
     3.5 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
Draw circle in C graphics

06 Dec, 2019
The header file graphics.h contains circle() function which draws a circle with center at (x, y) and given radius.
Syntax :
circle(x, y, radius);

where,
(x, y) is center of the circle.
'radius' is the Radius of the circle.

Examples :
Input : x = 250, y = 200, radius = 50
Output : 

Input : x = 300, y = 150, radius = 90
Output : 

Below is the implementation to draw circle in C:
// C Implementation for drawing circle#include <graphics.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;      // initgraph initializes the    // graphics system by loading a    // graphics driver from disk    initgraph(&gd, &gm, "");      // circle function    circle(250, 200, 50);      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output :


Akanksha_Rai
circle
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | bgcolor attribute

10 Jan, 2022
The HTML bgcolor attribute is used to set the background color of an HTML element. Bgcolor is one of those attributes that has become deprecated with the implementation of Cascading Style Sheets (see CSS Backgrounds).Syntax:  
<"tag" bgcolor="Value">
Attribute Values:
color_name: It sets the background color by using the color name. For example “red”.
hex_number: It sets the background color by using the color hex code. For example “#0000ff”.
rgb_number: It sets the background color by using the RGB code. For example: “RGB(0, 153, 0)” .
Supported tags:  
body
marquee
table
tBody
td
tFoot
th
tHead
tr
col
colgroup
Note: The bgcolor attribute is not supported by HTML5. 
Example: HTML <table> bgcolor attribute  
html
<!DOCTYPE html><html> <head>    <title>        HTML table bgcolor Attribute    </title></head> <body>    <h1>GeeksforGeeks</h1>     <h2>HTML table bgcolor Attribute</h2>     <table border="1"        bgcolor="green">        <caption>        Author Details    </caption>         <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>        <tr>            <td>BITTU</td>            <td>22</td>            <td>CSE</td>        </tr>        <tr>            <td>RAM</td>            <td>21</td>            <td>ECE</td>        </tr>    </table></body> </html>
Output:  
Example:HTML body Bgcolor Attribute  
html
<!DOCTYPE html><html> <head>    <title>    HTML body Bgcolor Attribute</title></head> <!-- body tag starts here --> <body text="green" bgcolor="orange">    <center>        <h1>GeeksforGeeks</h1>        <h2>        HTML <body> bgcolor Attribute    </h2>           <p>        It is a Computer        Science portal For Geeks    </p>        </center></body><!-- body tag ends here --> </html>
Output:  
Note: The bgcolor attribute is not supported in HTML5.Supported Browsers: The browsers supported by bgcolor attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
ManasChhabra2
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to remove spaces from a string?

The program takes a string and removes the spaces in it. This is useful when we want to save the space of our The following sample shows how it is done with an explanation.
Input: Hello World
Output: HelloWorld
To remove or delete spaces from the string or sentence, you have to ask the user to enter a string.
Now start checking for spaces. If space will be found, then start placing the next character from the space to the back until the last character and continue to check for the next space to remove all the spaces present in the string
#include <iostream>
#include<string.h>
using namespace std;
int  {
   char str[80]="Hello World";
   int i=0, len, j;
   len = strlen(str);
   for( i = 0; i < len; i++) {
      if (str[i] == ' ') {
         for (j = i; j < len; j++)
            str[j] = str[j+1];
            len--;
      }
   }
   cout << str;
   return 0;
}
Concatenate string with numbers in MySQL?

To concatenate string with numbers, use the CONCAT() method. Let us first create a table −
mysql> create table DemoTable682(
   Name varchar(100),
   Age int
);
Query OK, 0 rows affected (0.49 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable682 values('John',23);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable682 values('Chris',21);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable682 values('David',25);
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement:
Display all records from the table using select statement -
mysql> select *from DemoTable682;
This will produce the following output −
+-------+------+
| Name  | Age  |
+-------+------+
| John  |   23 |
| Chris |   21 |
| David |   25 |
+-------+------+
3 rows in set (0.00 sec)
Following is the query to implement concat() method to concatenate records −
mysql> select concat(Name,Age) from DemoTable682;
This will produce the following output −
+------------------+
| concat(Name,Age) |
+------------------+
| John23           |
| Chris21          |
| David25          |
+------------------+
3 rows in set (0.00 sec)
How can I create directory tree using C++ in Linux?

In this section we will see how to create a directory tree using C++ code in Linux. In Linux terminal we can put some command like “mkdir –p /dir/dir1/dir2” Here –p is used to mark as parent (recursively create inner directories).
In C++ code we can use some libraries of Linux system. Then we can use Linux terminal commands as string argument of the system() function. We can create directory tree like this.
#include <bits/stdc++.h>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
int main() {
   int status;
   status = system("mkdir -p TP/My_Folder/test"); // Creating a directory
   if (status == -1)
      cerr << "Error : " << strerror(errno) << endl;
   else
      cout << "Directories are created" << endl;
}
Directories are created
If we check manually, we can get the directories inside the current directory.
Switching on and off bulb in JavaScript

Consider this following situation −
There are n bulbs that are initially off. We first turn on all the bulbs. Then, we turn off every
second bulb. On the third round, we toggle every third bulb (turning on if it's off or turning off if
it's on).
In general, for the ith round, we toggle every i bulb. And lastly for the nth round, we only toggle
the last bulb.
We are required to write a JavaScript function that takes n as the only input and finds out how
many bulbs are on after n rounds.
For example, if the input to the function is −
const n = 4;
Then the output should be −
const output = 2;
In the state array, a 0 indicates off whereas 1 indicates on −
Hence after the fifth round only two bulbs are on.
The code for this will be −
const n = 5;
const findOn = (n = 1) => {
   let off = 0;
   let on = n;
   while(off <= on){
      let mid = Math.floor((off + on) / 2);
      if(mid * mid > n){
         on = mid - 1;
      }else{
         off = mid + 1;
      };
   };
   return Math.floor(on);
};
console.log(findOn(n));
And the output in the console will be −
2
Python Program for Subset Sum Problem

In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given a set of non-negative integers in an array, and a value sum, we need to determine if there exists a subset of the given set with a sum equal to a given sum.
Now let’s observe the solution in the implementation below −
# Naive approach
def SubsetSum(set, n, sum) :
   # Base Cases
   if (sum == 0) :
      return True
   if (n == 0 and sum != 0) :
      return False
   # ignore if last element is > sum
   if (set[n - 1] > sum) :
      return SubsetSum(set, n - 1, sum);
   # else,we check the sum
   # (1) including the last element
   # (2) excluding the last element
   return SubsetSum(set, n-1, sum) or SubsetSum(set, n-1, sumset[n-1])
# main
set = [2, 14, 6, 22, 4, 8]
sum = 10
n = len(set)
if (SubsetSum(set, n, sum) == True) :
   print("Found a subset with given sum")
else :
   print("No subset with given sum")
Found a subset with given sum
# dynamic approach
# maximum number of activities that can be performed by a single person
def Activities(s, f ):
   n = len(f)
   print ("The selected activities are:")
   # The first activity is always selected
   i = 0
   print (i,end=" ")
   # For rest of the activities
   for j in range(n):
      # if start time is greater than or equal to that of previous activity
      if s[j] >= f[i]:
         print (j,end=" ")
         i = j
# main
s = [1, 2, 0, 3, 2, 4]
f = [2, 5, 4, 6, 8, 8]
Activities(s, f)
Found a subset with given sum
In this article, we have learned about how we can make a Python Program for Subset Sum Problem
Find nth term of a given recurrence relation in Python

Suppose we have a sequence of numbers called bn, this is represented using a recurrence relation like b1=1 and bn+1/bn=2n . We have to find the value of log2(bn) for a given n.
So, if the input is like 6, then the output will be 5 as log2(bn) = (n * (n - 1)) / 2 = (6*(6-1))/2 = 15
We can solve this problem by solving this relation as follows −
bn+1/bn = 2n
bn/bn-1 = 2n-1
...
b2/b1 = 21 , If we multiply all of above, we can get
(bn+1/bn).(bn/bn-1)......(b2/b1) = 2n + (n-1)+..........+1
So, bn+1/b1 = 2n(n+1)/2
As 1 + 2 + 3 + .......... + (n-1) + n = n(n+1)/2
So, bn+1 = 2n(n+1)/2 * b1; We are assuming that initial value b1 = 1
So, bn+1 = 2n(n+1)/2
After substituting (n+1) for n, we get,
bn = 2n(n-1)/2
By taking log both sides, we get,
log2(bn) = n(n-1)/2
Let us see the following implementation to get better understanding −
 Live Demo
def add_upto_n(n):
   res = (n * (n - 1)) / 2
   return res
n = 6
print(int(add_upto_n(n)))
6
15
Apache Derby - Syntax

This chapter gives you the syntax of all the Apache Derby SQL statements.
All the statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE, ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;).
The SQL statements of Apache Derby are case in sensitives including table names.
CREATE TABLE table_name (
   column_name1 column_data_type1 constraint (optional),
   column_name2 column_data_type2 constraint (optional),
   column_name3 column_data_type3 constraint (optional)
);

DROP TABLE table_name;

INSERT INTO table_name VALUES (column_name1, column_name2, ...);

SELECT column_name, column_name, ... FROM table_name;

UPDATE table_name
   SET column_name = value, column_name = value, ...
   WHERE conditions;

DELETE FROM table_name WHERE condition;

Describe table_name

TRUNCATE TABLE table_name;

ALTER TABLE table_name ADD COLUMN column_name column_type;

ALTER TABLE table_name ADD CONSTRAINT constraint_name constraint (column_name);

ALTER TABLE table_name DROP COLUMN column_name;

ALTER TABLE table_name DROP CONSTRAINT constraint_name;

SELECT * from table_name WHERE condition;
or,
DELETE from table_name WHERE condition;
or,
UPDATE table_name SET column_name = value WHERE condition;

SELECT column1, column2, . . . table_name GROUP BY column1, column2, . . .;

SELECT * FROM table_name ORDER BY column_name ASC|DESC.

SELECT column1, column2 . . . from table_name GROUP BY column having
condition;

CTREATE INDEX index_name on table_name (column_name);

CREATE UNIQUE INDEX index_name on table_name (column_name);

CREATE INDEX index_name on table_name (column_name1, column_name2);

SHOW INDEXES FROM table_name;

DROP INDEX index_name;


    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
RxJava - ReplaySubject

ReplaySubject replays events/items to current and late Observers.
Following is the declaration for io.reactivex.subjects.ReplaySubject<T> class −
public final class ReplaySubject<T>
extends Subject<T>

Create the following Java program using any editor of your choice in, say, C:\> RxJava.
import io.reactivex.subjects.ReplaySubject;
public class ObservableTester  {
   public static void main(String[] args) {   
      final StringBuilder result1 = new StringBuilder();
      final StringBuilder result2 = new StringBuilder();         

      ReplaySubject<String> subject = ReplaySubject.create(); 
      subject.subscribe(value -> result1.append(value) ); 
      subject.onNext("a"); 
      subject.onNext("b"); 
      subject.onNext("c"); 
      subject.subscribe(value -> result2.append(value)); 
      subject.onNext("d"); 
      subject.onComplete();

      //Output will be abcd
      System.out.println(result1);
      //Output will be abcd being ReplaySubject
      //as ReplaySubject emits all the items
      System.out.println(result2);
   }
}
Compile the class using javac compiler as follows −
C:\RxJava>javac ObservableTester.java

Now run the ObservableTester as follows −
C:\RxJava>java ObservableTester

It should produce the following output −
abcd
abcd

 Print
 Add Notes
 Bookmark this page
HTTP headers | Access-Control-Max-Age - GeeksforGeeks

07 Nov, 2019
The Access-Control-Max-Age HTTP header is a response header that gives the time for which results of a CORS preflight request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers, can be cached. The CORS preflight request contained in the Access-Control-Allow-Methods and Access-Control-Allow-Headers headers.
Syntax:
Access-Control-Max-Age: <delta-seconds>
Directives: This header accepts a single directive mentioned above and described below:
<delta-seconds>: It specifies how many maximum seconds can the result be cached.
Note: If -1 is present then caching is disabled.
Examples:
In this example, the results of a preflight request get cached for 200 seconds.Access-Control-Max-Age: 200
Access-Control-Max-Age: 200
In this example, the results are not allowed to be cached.Access-Control-Max-Age: -1
Access-Control-Max-Age: -1
To check this Access-Control-Max-Age in action, go to Inspect Element -> Network check the response header for Access-Control-Max-Age like below, Access-Control-Max-Age is highlighted you can see.
Supported Browsers: The browsers are compatible with HTTP Access-Control-Max-Age header are listed below:
Google Chrome 4.0
Internet Explorer 10.0
Opera 12.0
Firefox 3.5
Safari 4.0
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Insert Form Data into Database using PHP ?
How to redirect to another page in ReactJS ?
Set the value of an input field in JavaScript
How to execute PHP code using command line ?
.NET Core - Package References

In this chapter, we will discuss how to add packages in your .NET Core application and how to find a specific package. We can directly go to NuGet and add package, but here we will see some other places.
Let us now go to the source code of .NET Core which is located here − https://github.com/dotnet/corefx
In CoreFx repo, open the src folder −
And you will see the whole list of folders that correspond to different packages. Let us now search Json −
There is another way to find your package, you probably know various types if you are familiar with .NET Framework, but the assembling of packages in .NET Core is totally different and you won’t know where that packages in.
If you know the type, you can search to reverse package search by using https://packagesearch.azurewebsites.net/
Here you can enter any type of package you would like to find. Then, this site will scan NuGet and find the relevant packages for you.
Let us now search for DataContractJson.
You will now see that we get the same package; let us click on the package.
You will now see the NuGet page; you need to confirm that you need this package. You can add this in your application using a few methods.
Let us open the project.json file.
{ 
   "version": "1.0.0-*", 
   "buildOptions": { 
      "emitEntryPoint": true 
   }, 
   "dependencies": { 
      "Microsoft.NETCore.App": { 
         "type": "platform", 
         "version": "1.0.1" 
      } 
   }, 
   "frameworks": { 
      "netcoreapp1.0": { 
         "imports": "dnxcore50" 
      } 
   } 
} 
This is the new project format and inside this file you will see the dependencies section. Let us add a new dependency as shown below.
{ 
   "version": "1.0.0-*", 
   "buildOptions": { 
      "emitEntryPoint": true 
   }, 
   "dependencies": { 
      "Microsoft.NETCore.App": { 
         "type": "platform", 
         "version": "1.0.1" 
      }, 
      "System.Runtime.Serialization.Json": "4.0.2" 
   }, 
   "frameworks": { 
      "netcoreapp1.0": { 
         "imports": "dnxcore50" 
      } 
   } 
}
Now if you look at your references, then you will see that System.Runtime.Serialization.Json package is added to your project.
Another way is to go to the NuGet Manager and browse the package you want to add.
 Print
 Add Notes
 Bookmark this page
Data Structures | Linked List | Question 17 - GeeksforGeeks

28 Jun, 2021
Consider the following function to traverse a linked list.
void traverse(struct Node *head){   while (head->next != NULL)   {       printf("%d  ", head->data);       head = head->next;   }}
Which of the following is FALSE about above function?(A) The function may crash when the linked list is empty(B) The function doesn’t print the last node when the linked list is not empty(C) The function is implemented incorrectly because it changes headAnswer: (C)Explanation:Quiz of this Question
Data Structures
Data Structures-Linked List
Linked Lists
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Advantages and Disadvantages of Linked List
Introduction to Data Structures | 10 most commonly used Data Structures
FIFO vs LIFO approach in Programming
Multilevel Linked List
Data Structures | Array | Question 2
Advantages of vector over array in C++
Difference between data type and data structure
Bit manipulation | Swap Endianness of a number
Program to create Custom Vector Class in C++
Data Structures | Queue | Question 1
Bokeh - Developing with JavaScript

The Bokeh Python library, and libraries for Other Languages such as R, Scala, and Julia, primarily interacts with BokehJS at a high level. A Python programmer does not have to worry about JavaScript or web development. However, one can use BokehJS API, to do pure JavaScript development using BokehJS directly.
BokehJS objects such as glyphs and widgets are built more or less similarly as in Bokeh Python API. Typically, any Python ClassName is available as Bokeh.ClassName from JavaScript. For example, a Range1d object as obtained in Python.
xrange = Range1d(start=-0.5, end=20.5)

It is equivalently obtained with BokehJS as −
var xrange = new Bokeh.Range1d({ start: -0.5, end: 20.5 });

Following JavaScript code when embedded in a HTML file renders a simple line plot in the browser.
First include all BokehJS libraries in <head>..</head> secion of web page as below
<head>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-widgets-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-tables-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-gl-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js"></script>
<script type="text/javascript" src="https://cdn.pydata.org/bokeh/release/bokeh-api-1.3.4.min.js"></script>
</head>
In the body section following snippets of JavaScript construct various parts of a Bokeh Plot.
<script>
// create some data and a ColumnDataSource
var x = Bokeh.LinAlg.linspace(-0.5, 20.5, 10);
var y = x.map(function (v) { return v * 0.5 + 3.0; });
var source = new Bokeh.ColumnDataSource({ data: { x: x, y: y } });
// make the plot
var plot = new Bokeh.Plot({
   title: "BokehJS Plot",
   plot_width: 400,
   plot_height: 400
});

// add axes to the plot
var xaxis = new Bokeh.LinearAxis({ axis_line_color: null });
var yaxis = new Bokeh.LinearAxis({ axis_line_color: null });
plot.add_layout(xaxis, "below");
plot.add_layout(yaxis, "left");

// add a Line glyph
var line = new Bokeh.Line({
   x: { field: "x" },
   y: { field: "y" },
   line_color: "#666699",
   line_width: 2
});
plot.add_glyph(line, source);

Bokeh.Plotting.show(plot);
</script>
Save above code as a web page and open it in a browser of your choice.
 Print
 Add Notes
 Bookmark this page
How do I find an element that contains specific text in Selenium Webdriver?

We can find an element with a specific text visible on the screen in Selenium. This is achieved with the xpath locator. The xpath locator contains some in-built functions that help to create customized xpath.
Let us consider a portion of the web page as given below −
text() − It is a built in function to identify an element based on the text displayed on the screen. For example, if we want to identify Library from the above webpage, the customized xpath with text() should be −
text() − It is a built in function to identify an element based on the text displayed on the screen. For example, if we want to identify Library from the above webpage, the customized xpath with text() should be −
Syntax
//*[text()='Library']
contains() − It is a built in function to identify an element based on the partial text match. For example, if we want to identify GATE Exams from the above webpage, the customized xpath with contains() should be
contains() − It is a built in function to identify an element based on the partial text match. For example, if we want to identify GATE Exams from the above webpage, the customized xpath with contains() should be
Syntax
//*[contains(text(),'GATE')]
Code Implementation .
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TextMatch{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // identify element with text()
      WebElement l=driver.findElement(By.xpath("//*[text()='Library']"));
      // identify element with contains()
      WebElement m=driver.findElement(By.xpath("//*[contains(text(),'GATE')]"));
      System.out.println("Element with text(): " + l.getText());
      System.out.println("Element with contains(): " + m.getText());
      driver.quit();
   }
}
Python | Remove prefix strings from list - GeeksforGeeks

29 Nov, 2019
Sometimes, while working with data, we can have a problem in which we need to filter the strings list in such a way that strings starting with specific prefix are removed. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + remove() + startswith()The combination of above functions can solve this problem. In this, we remove the elements that start with particular prefix accessed using loop and return the modified list.
# Python3 code to demonstrate working of# Remove prefix strings from list# using loop + remove() + startswith()  # initialize list test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']  # printing original list print("The original list : " + str(test_list))  # initialize prefix pref = 'x'  # Remove prefix strings from list# using loop + remove() + startswith()for word in test_list[:]:    if word.startswith(pref):        test_list.remove(word)  # printing resultprint("List after removal of Kth character of each string : " + str(test_list))
The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
List after removal of Kth character of each string : ['gfg', 'is', 'best']

 
Method #2 : Using list comprehension + startswith()This is another way in which this task can be performed. In this, we don’t perform removal in place, instead, we recreate the list without the elements that match the prefix.
# Python3 code to demonstrate working of# Remove prefix strings from list# using list comprehension + startswith()  # initialize list test_list = ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']  # printing original list print("The original list : " + str(test_list))  # initialize prefix pref = 'x'  # Remove prefix strings from list# using list comprehension + startswith()res = [ele for ele in test_list if not ele.startswith(pref)]  # printing resultprint("List after removal of Kth character of each string : " + str(res))
The original list : ['xall', 'xlove', 'gfg', 'xit', 'is', 'best']
List after removal of Kth character of each string : ['gfg', 'is', 'best']

Python list-programs
Python
Python Programs
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
Iterate over a list in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Add an element to a Stack in Java

An element can be added into the stack by using the java.util.Stack.push() method. This method pushes the required element to the top of the stack. The only parameter required for the Stack.push() method is the element that is to be pushed into the stack.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.Stack;
public class Demo {
   public static void main (String args[]) {
      Stack stack = new Stack();
      stack.push("Apple");
      stack.push("Mango");
      stack.push("Guava");
      stack.push("Pear");
      stack.push("Orange");
      System.out.println("The stack elements are: " + stack);
   }
}
The stack elements are: [Apple, Mango, Guava, Pear, Orange]
Now let us understand the above program.
The Stack is created. Then Stack.push() method is used to add the elements to the stack. Finally the stack is displayed. A code snippet which demonstrates this is as follows −
Stack stack = new Stack();
stack.push("Apple");
stack.push("Mango");
stack.push("Guava");
stack.push("Pear");
stack.push("Orange");
System.out.println("The stack elements are: " + stack);
How to use toUpperCase () in Android textview?

This example demonstrate about How to use toUpperCase () in Android textview.
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"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/name"
      android:layout_width="match_parent"
      android:hint="Enter name"
      android:layout_height="wrap_content" />
   <Button
      android:id="@+id/click"
      android:text="Click"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/textview"
      android:layout_width="wrap_content"
      android:textSize="25sp"
      android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken name as Edit text, when user click on button it will take data and Convert into upper case letters.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   EditText name;
   Button button;
   TextView text;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      name = findViewById(R.id.name);
      button = findViewById(R.id.click);
      text = findViewById(R.id.textview);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (!name.getText().toString().isEmpty()) {
               if (name.getText().toString().length() >= 0) {
                  String touppercase = name.getText().toString().toUpperCase();
                  text.setText(String.valueOf(touppercase));
               }
            } else {
               name.setError("Plz enter name");
            }
         }
      });
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, enter the string as “krishna” (ALL LOWER CASE) and it returned upper case letters as KRISHNA.
Click here to download the project code