code-rag-bench/online-tutorials huggingface dataset:
DB2 - Sequences

This chapter introduces you to the concept of sequence, creation of sequence, viewing the sequence, and dropping them.
A sequence is a software function that generates integer numbers in either ascending or descending order, within a definite range, to generate primary key and coordinate other keys among the table. You use sequence for availing integer numbers say, for employee_id or transaction_id. A sequence can support SMALLINT, BIGINT, INTEGER, and DECIMAL data types. A sequence can be shared among multiple applications. A sequence is incremented or decremented irrespective of transactions.
A sequence is created by CREATE SEQUENCE statement.
There are two type of sequences available:
NEXTVAL: It returns an incremented value for a sequence number.
NEXTVAL: It returns an incremented value for a sequence number.
PREVIOUS VALUE: It returns recently generated value.
PREVIOUS VALUE: It returns recently generated value.
The following parameters are used for sequences:
Data type: This is the data type of the returned incremented value. (SMALLINT, BIGINT, INTEGER, NUMBER, DOUBLE)
START WITH: The reference value, with which the sequence starts.
MINVALUE: A minimum value for a sequence to start with.
MAXVALUE: A maximum value for a sequence.
INCREMENT BY: step value by which a sequence is incremented.
Sequence cycling: the CYCLE clause causes generation of the sequence repeatedly. The sequence generation is conducted by referring the returned value, which is stored into the database by previous sequence generation.
You can create sequence using the following syntax:
Syntax:
db2 create sequence <seq_name> 
Example: [To create a new sequence with the name ‘sales1_seq’ and increasing values from 1]
db2 create sequence sales1_seq as int start 
with 1 increment by 1  
You can view a sequence using the syntax given below:
Syntax:
db2 value <previous/next> value for <seq_name>
Example: [To see list of previous updated value in sequence ‘sales1_seq’]
db2 values previous value for sales1_seq  
Output:
 1 
----------- 
  4 
  1 record(s) selected. 
To remove the sequence, you need to use the “DROP SEQUENCE ” command. Here is how you do it:
Syntax:
db2 drop sequence <seq_name>>
Example: [To drop sequence ‘sales1_seq’ from database]
db2 drop sequence sales1_seq  
Output:
 DB20000I The SQL command completed successfully. 

    10 Lectures 
     1.5 hours 

 Nishant Malik

    41 Lectures 
     8.5 hours 

 Parth Panjabi

    53 Lectures 
     11.5 hours 

 Parth Panjabi

    33 Lectures 
     7 hours 

 Parth Panjabi

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    178 Lectures 
     14.5 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to create a plot using ggplot2 by including values greater than a certain value in R?

To create a plot using ggplot2 by excluding values greater than a certain value, we can use subsetting with single square brackets and which function. For example, if we have a data frame called df that contains two columns say x and y, then the point chart by including values of x that are greater than 0 can be created by using the command −
ggplot(df[which(df$x>0),],aes(x,y))+geom_point()
Consider the below data frame −
Live Demo
> x<-rnorm(20)
> y<-rnorm(20)
> df<-data.frame(x,y)
> df
             x           y
1  -0.62160328  0.38477515
2   0.68287365 -1.56169067
3   0.75259774  1.28849990
4   0.56688920 -0.17014225
5   1.22351113 -0.32446764
6  -1.54210099  0.29001967
7   0.08800284  1.34342269
8   1.77498480 -0.75239348
9  -0.31916824  0.24433868
10  0.09802049 -0.91107863
11 -1.63060088  0.05336120
12  0.01328284 -2.36494891
13 -1.69921881 -1.29001305
14 -0.02819300 -0.06126524
15  0.77405426  0.25468262
16 -0.36423968  0.79130216
17  0.26224330  0.10437648
18  0.31894879 -0.50317250
19  0.37739488  0.62952910
20  0.26141716 -0.97143860
Loading ggplot2 package and creating scatterplot between x and y −
> library(ggplot2)
> ggplot(df,aes(x,y))+geom_point()
Creating scatterplot between x and y by including only x values that are greater than 0 −
> ggplot(df[which(df$x>0),],aes(x,y))+geom_point()
Java Examples - String unicode

How to determine the Unicode code point in string ?
This example shows you how to use codePointBefore() method to return the character (Unicode code point) before the specified index.
public class StringUniCode {
   public static void main(String[] args) {
      String test_string = "Welcome to TutorialsPoint";
      System.out.println("String under test is = "+test_string);
      
      System.out.println("Unicode code point at" 
         +" position 5 in the string is = "
         +  test_string.codePointBefore(5));
   }
}
The above code sample will produce the following result.
String under test is = Welcome to TutorialsPoint
Unicode code point at position 5 in the string is =111

 Print
 Add Notes
 Bookmark this page
Methods for tracking database schema changes in MySQL?

Whenever a table is present in a project with a single database, we can do database schema changes using schema version or migration. It aims to keep track of database schema changes or structural changes.
The table creation to keep track of schema changes.
mysql> create table SchemaDatabaseMethodDemo
   -> (
   -> `WhenTime` timestamp not null default CURRENT_TIMESTAMP,
   -> `TheKey` varchar(200) not null,
   -> `Version` varchar(200),
   -> primary key(`TheKey`)
   -> )ENGINE=InnoDB;
Query OK, 0 rows affected (0.45 sec)
Inserting records into the table.
mysql> insert into SchemaDatabaseMethodDemo values(now(),'1001','version 5.6.12');
Query OK, 1 row affected (0.17 sec)
To display records.
mysql> select *from SchemaDatabaseMethodDemo;
The following is the output.
+---------------------+--------+----------------+
| WhenTime            | TheKey | Version        |
+---------------------+--------+----------------+
| 2018-10-29 14:21:47 | 1001   | version 5.6.12 |
+---------------------+--------+----------------+
1 row in set (0.00 sec)

Note − Suppose we are executing a SQL script or migration then we need to add a row in the above table as well with the help of the INSERT statement at the beginning or end of the scripts.
What is the match() function in Python?

In Python, match() is a method of the module re 
Syntax of match()
re.match(pattern, string):
This method finds match if it occurs at start of the string. For example, calling match() on the string ‘TP Tutorials Point TP’ and looking for a pattern ‘TP’ will match. However, if we look for only Tutorials, the pattern will not match. Let’s check the code.
import re
result = re.match(r'TP', 'TP Tutorials Point TP')
print result
<_sre.SRE_Match object at 0x0000000005478648>
Above, it shows that pattern match has been found. To print the matching string we use method group. Use “r” at the start of the pattern string, it designates a python raw string.
import re
result = re.match(r'TP', 'TP Tutorials Point TP')
print result.group(0)
TP
Let’s now find ‘Tutorials’ in the given string. Here we see that string is not starting with ‘TP’ so it should return no match. Let’s see what we get −
import re
result = re.match(r'Tutorials', 'TP Tutorials Point TP')
print result
None
C++ Program to Implement Parallel Array

A parallel array is a structure that contains multiple arrays. Each of these arrays are of the same size and the array elements are related to each other. All the elements in a parallel array represent a common entity.
An example of parallel arrays is as follows −
employee_name = { Harry, Sally, Mark, Frank, Judy }
employee_salary = {10000, 5000, 20000, 12000, 5000}
In the above example, the name and salary of 5 different employees is stored in 2 arrays.
A program that demonstrates parallel arrays is given as follows −
#include <iostream>
#include <string>

using namespace std;
int main() {
   int max = 0, index = 0;
   string empName [ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" };
   string empDept [ ] = {"IT", "Sales", "IT", "HR", "Sales"};
   int empSal[ ] = {10000, 5000, 20000, 12000, 5000 };
   int n = sizeof(empSal)/sizeof(empSal[0]);

   for(int i = 0; i < n; i++) {
      if (empSal[i] > max) {
         max = empSal[i];
         index = i;
      }
   }
   cout << "The highest salary is "<< max <<" and is earned by
   "<<empName[index]<<" belonging to "<<empDept[index]<<" department";
   return 0;
}
The output of the above program is as follows −
The highest salary is 20000 and is earned by Mark belonging to IT department
In the above program, three arrays are declared, containing the employee name, department and salary respectively. This is given below −
string empName [ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" };
string empDept [ ] = {"IT", "Sales", "IT", "HR", "Sales"};
int empSal[ ] = {10000, 5000, 20000, 12000, 5000 };
The highest salary is found using the for loop and stored in max. The index that contains the highest salary is stored in index. This is shown below −
int n = sizeof(empSal)/sizeof(empSal[0]);
for(int i = 0; i < n; i++) {
   if (empSal[i] > max) {
      max = empSal[i];
      index = i;
   }
}
Finally, the highest salary and its corresponding employee name and department are displayed. This is given below −
cout << "The highest salary is "<< max <<" and is earned by "<<empName[index]<<"
belonging to "<<empDept[index]<<" department";
How to Calculate Weighted MAPE in Excel? - GeeksforGeeks

28 Jul, 2021
In statistics, we often use Forecasting Accuracy which denotes the closeness of a quantity to the actual value of that particular quantity. The actual value is also known as the true value. It basically denotes the degree of closeness or a verification process that is highly used by business professionals to keep track records of their sales and exchanges to maintain the demand and supply mapping every year. There are various methods to calculate Forecasting Accuracy.
So, one of the most common methods used to calculate the Forecasting Accuracy is MAPE which is abbreviated as Mean Absolute Percentage Error. It is an effective and more convenient method because it becomes easier to interpret the accuracy just by seeing the MAPE value. Here, we face a problem of infinite error when the Actual value of any entity becomes zero.
WMAPE or Weighted MAPE abbreviated as Weighted Mean Absolute Percentage Error is also an accuracy prediction technique. Here, the problem of infinite error (divide by zero) is removed since the summation of actual value in the denominator can never be zero. It calculates the error based on weights but in case of MAPE error was calculated based on the average values. So, WMAPE is more reliable and gives efficient accuracy than MAPE.
The formula to calculate WMAPE in Excel is :
In this article we are going to discuss how to calculate WMAPE in Excel using a suitable example.
Example : Consider the dataset shown below :
The functions needed for formulas in Excel are-
SUM : To calculate the sum of multiple values
ABS : To calculate the absolute value.
The steps are :
1. Insert the data set in the Excel sheet.
2. Calculate the sub part of the formula inside the summation which is also known as Weighted Error.
=ABS(Cell_No_Act-Cell_No_Fore)

where
ABS : Used to calculate the absolute value
Cell_No_Act : Cell number where Actual value is present
Cell_No_Fore : Cell number where Forecast value is present
The above formula will calculate the weighted error for the first entry in the data set. Now, you can drag the Auto Fill Options button to get the weighted error for the remaining entries.
3. Now use the SUM function to find the summation of both weighted errors and the actual values and divide them to get the WMAPE.
The entries of Weighted Error are in the Cell range : D3 to D12
The entries of Actual Value are in the Cell range : B3 to B12
The value of WMAPE is 0.09189 or 9.189% approximately.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Use Solver in Excel?
How to Find the Last Used Row and Column in Excel VBA?
How to Show Percentages in Stacked Column Chart in Excel?
How to Get Length of Array in Excel VBA?
How to Remove Duplicates From Array Using VBA in Excel?
Introduction to Excel Spreadsheet
Macros in Excel
How to Extract the Last Word From a Cell in Excel?
How to Sum Values Based on Criteria in Another Column in Excel?
How to Easily Calculate the Dot Product in Excel?
How to replace a particular character in a MySQL column?

To replace a particular character, use REPLACE() and to update, use the UPDATE command. Let us first create a table −
mysql> create table DemoTable1899
   (
   Code varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1899 values('John_123');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1899 values('32189_Sam_987');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1899 values('Miller_David_456_909');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1899;
This will produce the following output −
+----------------------+
| Code                 |
+----------------------+
| John_123             |
| 32189_Sam_987        |
| Miller_David_456_909 |
+----------------------+
3 rows in set (0.00 sec)
Here is the query to replace a particular character −
mysql> update DemoTable1899 set Code=replace(Code,'_','');
Query OK, 3 rows affected (0.00 sec)
Rows matched: 3  Changed: 3 Warnings: 0
Let us check the table records once again:
mysql> select * from DemoTable1899;
This will produce the following output −
+-------------------+
| Code              |
+-------------------+
| John123           |
| 32189Sam987       |
| MillerDavid456909 |
+-------------------+
3 rows in set (0.00 sec)
Conditional ternary operator ( ?: ) in C++

The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows −
The first operand is implicitly converted to bool. It is evaluated and all side effects are completed before continuing.
If the first operand evaluates to true (1), the second operand is evaluated.
If the first operand evaluates to false (0), the third operand is evaluated.
The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression. The evaluation of the conditional operator is very complex. The steps above were just a quick intro to it. Conditional expressions have right-to-left associativity. The first operand must be of integral or pointer type. The following rules apply to the second and third operands −
If both operands are of the same type, the result is of that type.
If both operands are of arithmetic or enumeration types, the usual arithmetic conversions (covered in Standard Conversions) are performed to convert them to a common type.
If both operands are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type.
If both operands are of reference types, reference conversions are performed to convert them to a common type.
If both operands are of type void, the common type is type void.
If both operands are of the same user-defined type, the common type is that type.
If the operands have different types and at least one of the operands has user-defined type then the language rules are used to determine the common type. (See warning below.)
#include <iostream>  
using namespace std;  

int main() {  
   int i = 1, j = 2;  
   cout << ( i > j ? i : j ) << " is greater." << endl;  
}
This will give the output −
2 is greater.
How to find mode(s) of a vector in R?

Just like mean and median there is no in-built function in R to find the mode.
We can make use of the following user created function for this purpose
> Modes <- function(x) {
   ux <- unique(x)
   tab <- tabulate(match(x, ux))
   ux[tab == max(tab)]
}
> x<-c(3,2,3,4,3,2,1,2,3,45,6,7,6,4,3,32,4,5,6,4,4,3,4,5,4,4,3,6)
> Modes(x)
[1] 4
We have created a function called modes because a data can have more than one mode as
shown below −
> y<-c(3,2,3,4,3,2,1,2,3,45,6,7,6,4,3,32,4,5,6,4,4,3,4,5,4,4,3,3)
> Modes(y)
[1] 3 4
Pointer Basics in C - GeeksQuiz

12 Nov, 2020
  int *ptr;  /* Note: the use of * here is not for dereferencing, 
               it is for data type int */
  int x;

  ptr = &x;   /* ptr now points to x (or ptr is equal to address of x) */
  *ptr = 0;   /* set value ate ptr to 0 or set x to zero */

  printf(" x = %d\n", x);   /* prints x =  0 */
  printf(" *ptr = %d\n", *ptr);  /* prints *ptr =  0 */


  *ptr += 5;        /* increment the value at ptr by 5 */
  printf(" x  = %d\n", x);  /* prints x = 5 */
  printf(" *ptr = %d\n", *ptr); /* prints *ptr =  5 */


  (*ptr)++;         /* increment the value at ptr by 1 */
  printf(" x  = %d\n", x);  /* prints x = 6 */
  printf(" *ptr = %d\n", *ptr);  /* prints *ptr =  6 */

int main()
{
 char *ptr = "GeeksQuiz";
 printf("%s\n", *&*&ptr);
 return 0;
}
void fun(int arr[])
void fun(int *arr)

Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
What is Transmission Control Protocol (TCP)?
Difference Between Skewness and Kurtosis
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
Hash Functions and list/types of Hash functions
How to Replace Values in a List in Python?
Understanding Semantic Analysis - NLP
How to Read Text Files with Pandas?
How to Calculate Moving Averages in Python?
C# String.ToUpperInvariant Method

The String.ToUpperInvariant() method in C# is used to return a copy of this String object converted to uppercase using the casing rules of the invariant culture.
The syntax is as follows -
public string ToUpperInvariant ();
Let us now see an example -
 Live Demo
using System;
using System.Text;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "one";
      string str2 = "TWO";
      string str3 = "ThrEE";
      Console.WriteLine("String 1 = "+str1);
      Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant());
      Console.WriteLine("String 2 = "+str2);
      Console.WriteLine("String2 ToUpperInvariant = "+str2.ToUpperInvariant());
      Console.WriteLine("String 3 = "+str3);
      Console.WriteLine("String3 ToUpperInvariant = "+str3.ToUpperInvariant());
   }
}
String 1 = one
String1 ToUpperInvariant = ONE
String 2 = TWO
String2 ToUpperInvariant = TWO
String 3 = ThrEE
String3 ToUpperInvariant = THREE
 Live Demo
using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "abcd";
      string str2 = "PQRS";
      Console.WriteLine("String 1 = "+str1);
      Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant());
      Console.WriteLine("String 2 = "+str2);
      Console.WriteLine("String2 ToUpperInvariant = "+str2.ToLowerInvariant());
   }
}
String 1 = abcd
String1 ToUpperInvariant = ABCD
String 2 = PQRS
String2 ToUpperInvariant = pqrs
Ordered Set and GNU C++ PBDS

In this tutorial, we will be discussing a program to understand ordered set and GNU C++ PBDS.
Ordered set is a policy based structure other than those in the STL library. The ordered set keeps all the elements in a sorted order and doesn’t allow duplicate values.
 Live Demo
#include <iostream>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, 
rb_tree_tag,tree_order_statistics_node_update>
int main(){
   //declaring ordered set
   ordered_set o_set;
   o_set.insert(5);
   o_set.insert(1);
   o_set.insert(2);
   cout << *(o_set.find_by_order(1))
      << endl;
   cout << o_set.order_of_key(4)
      << endl;
   cout << o_set.order_of_key(5)
      << endl;
   if (o_set.find(2) != o_set.end())
      o_set.erase(o_set.find(2));
   cout << *(o_set.find_by_order(1))
      << endl;
   cout << o_set.order_of_key(4)
      << endl;
   return 0;
}
2
2
2
5
1
EnumSet noneOf() Method in Java - GeeksforGeeks

02 Jul, 2018
The java.util.EnumSet.noneOf(Class elementType) method in Java is used to create a null set of the type elementType.
Syntax:
public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType)
Parameters: The method accepts one parameter elementType of element type and refers to the class object of the element type for this enum set.
Return Value: The method does not return any value.
Exceptions: The method throws NullPointerException if the elementType is Null.
Below programs illustrate the working of Java.util.EnumSet.noneOf() method:Program 1:
// Java program to demonstrate noneof() methodimport java.util.*;  // Creating an enum of GFG typeenum GFG {    Welcome,    To,    The,    World,    of,    Geeks};  public class Enum_Set_Demo {      public static void main(String[] args)    {          // Creating an empty EnumSet        // Getting all elements from GFG        EnumSet<GFG> e_set = EnumSet.allOf(GFG.class);          // Displaying the initial EnumSet        System.out.println("The first set is: " + e_set);          // Creating another empty set        EnumSet<GFG> other_set = EnumSet.noneOf(GFG.class);          // Displaying the new set        System.out.println("The other set is: " + other_set);    }}
The first set is: [Welcome, To, The, World, of, Geeks]
The other set is: []

Program 2:
// Java program to demonstrate copyOf() methodimport java.util.*;  // Creating an enum of CARS typeenum CARS {    RANGE_ROVER,    MUSTANG,    CAMARO,    AUDI,    BMW};  public class Enum_Set_Demo {      public static void main(String[] args)    {          // Creating an empty EnumSet        // Getting all elements from CARS        EnumSet<CARS> e_set = EnumSet.allOf(CARS.class);          // Displaying the initial EnumSet        System.out.println("The first set is: " + e_set);          // Creating another empty set        EnumSet<CARS> other_set = EnumSet.noneOf(CARS.class);          // Displaying the new set        System.out.println("The other set is: " + other_set);    }}
The first set is: [RANGE_ROVER, MUSTANG, CAMARO, AUDI, BMW]
The other set is: []

java-EnumSet
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Overriding in Java
LinkedList in Java
Initializing a List in Java
CSS | translateX() Function - GeeksforGeeks

07 Aug, 2019
The translateX() function is an inbuilt function which is used to reposition the element along the horizontal axis.
Syntax:
translateX( t )
Parameters: This function accepts single parameter t which holds the length of translation corresponding to x-axis.
Below examples illustrate the translateX() function in CSS:
Example 1:
<!DOCTYPE html><html>  <head>    <title>      CSS translateX() function  </title>    <style>        body {            text-align: center;        }                  h1 {            color: green;        }                  .translateX_image {            transform: translateX(100px);        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>CSS translateX() function</h2>      <h4>Original Image</h4>    <img src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"         alt="GeeksforGeeks logo">    <br>      <h4>Translated image</h4>    <img class="translateX_image"          src="https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"         alt="GeeksforGeeks logo"></body>  </html>
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <title>      CSS translateX() function  </title>    <style>        body {            text-align: center;        }                  h1 {            color: green;        }                  .GFG {            font-size: 35px;            font-weight: bold;            color: green;        }                  .geeks {            transform: translateX(100px);        }    </style></head>  <body>    <h1>GeeksforGeeks</h1>    <h2>      CSS translateX() function  </h2>      <h4>Original Element</h4>    <div class="GFG">      Welcome to GeeksforGeeks  </div>      <h4>Translated Element</h4>    <div class="GFG geeks">      Welcome to GeeksforGeeks  </div></body>  </html>
Output:
Supported Browsers: The browsers supported by translateX() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
Form validation using jQuery
How to set space between the flexbox ?
Search Bar using HTML, CSS and JavaScript
How to Create Time-Table schedule using HTML ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Scrapy - Create a Project

To scrap the data from web pages, first you need to create the Scrapy project where you will be storing the code. To create a new directory, run the following command −
scrapy startproject first_scrapy

The above code will create a directory with name first_scrapy and it will contain the following structure −
first_scrapy/
scrapy.cfg            # deploy configuration file
first_scrapy/         # project's Python module, you'll import your code from here
__init__.py
items.py              # project items file
pipelines.py          # project pipelines file
settings.py           # project settings file
spiders/              # a directory where you'll later put your spiders
__init__.py


    27 Lectures 
     3.5 hours 

 Attreya Bhatt
 Print
 Add Notes
 Bookmark this page
Java Program to find Product of unique prime factors of a number

To find product of unique prime factors of a number, the Java code is as follows −
 Live Demo
public class Demo {
   public static long prime_factors(int num){
      long my_prod = 1;
      for (int i = 2; i <= num; i++){
         if (num % i == 0){
            boolean is_prime = true;
            for (int j = 2; j <= i / 2; j++){
               if (i % j == 0){
                  is_prime = false;
                  break;
               }
            }
            if (is_prime){
               my_prod = my_prod * i;
            }
         }
      }
      return my_prod;
   }
   public static void main(String[] args){
      int num = 68;
      System.out.println("The product of unique prime factors is ");
      System.out.print(prime_factors(num));
   }
}
The product of unique prime factors is
34
A class named Demo contains a static function named ‘prime_factors’ that finds the prime factors of a number, find the unique numbers, and stores the product of these prime factors in a variable. In the main function, the value for the number is defined, and the function is called by passing the number as the parameter. Relevant message is displayed on the console.
How can I put two buttons next to each other in Tkinter?

Tkinter generally provides three general ways to define the geometry of the widgets. They are − Place, Pack, and Grid Management. If we use the Pack geometry manager, then place the two buttons in the frame using side property. It places the buttons horizontally stacked in the window in (Left, Right, Top and Bottom) direction. The side property maintains the same width and internal padding between all the adjacent widget in the application.
#Import the required Libraries
from tkinter import *
from tkinter import ttk
import random

#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of Tkinter frame
win.geometry("750x250")

def clear():
   entry.delete(0,END)
def display_num():
   for i in range(1):
      entry.insert(0, random.randint(5,20))

#Define an Entry widget
entry= Entry(win, width= 40)
entry.pack()
#Create Buttons with proper position
button1= ttk.Button(win, text= "Print", command=display_num)
button1.pack(side= TOP)
button2= ttk.Button(win, text= "Clear", command= clear)
button2.pack(side=TOP)

win.mainloop()
Running the above code will display a window that contains two Buttons horizontally stacked adjacent to each other.
Now, click each button to see the resultant output.
C++ Array Library - size() Function

The C++ function std::array::size() is used to get the number of elements present in the array.
Following is the declaration for std::array::size() function form std::array header.
constexpr size_type size(); noexcept
None
Returns the number of elements present in the array. This value is always same as the second
parameter of the array template used to instantiate array.
Do not confuse with sizeof() operator which return the size of data type in bytes.
This member function never throws exception.
Constant i.e. O(1)
The following example shows the usage of std::array::size() function.
#include <iostream>
#include <array>

using namespace std;

int main(void) {

   array<int, 5> int_arr;        /* Array of 5 integers */
   array<float, 0> float_arr;    /* Array of 0 floats */

   cout << "Number of elements in int_arr   = " << int_arr.size() << endl;
   cout << "Number of elements in float_arr = " << float_arr.size() << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Number of elements in int_arr   = 5
Number of elements in float_arr = 0

 Print
 Add Notes
 Bookmark this page
How to validate Password is strong or not in ReactJS?

07 Jun, 2022
Password must be strong so that hackers can not hack them easily. The following example shows how to check the password strength of the user input password in ReactJS. 
Syntax: 
isStrongPassword(str [, options])
Parameters: This function accepts two parameters as mentioned above and described below:
str: It is the input value of the string type.
options: It is an optional parameter. These are options that are checked for the input password. For example minLength, minLowercase, etc.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the validator module using the following command:
npm install validator
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React, { useState } from "react";import validator from 'validator' const App = () => {   const [errorMessage, setErrorMessage] = useState('')   const validate = (value) => {     if (validator.isStrongPassword(value, {      minLength: 8, minLowercase: 1,      minUppercase: 1, minNumbers: 1, minSymbols: 1    })) {      setErrorMessage('Is Strong Password')    } else {      setErrorMessage('Is Not Strong Password')    }  }   return (    <div style={{      marginLeft: '200px',    }}>      <pre>        <h2>Checking Password Strength in ReactJS</h2>        <span>Enter Password: </span><input type="text"          onChange={(e) => validate(e.target.value)}></input> <br />        {errorMessage === '' ? null :        <span style={{          fontWeight: 'bold',          color: 'red',        }}>{errorMessage}</span>}      </pre>    </div>  );} export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
The following will be the output if the user enters a weak password.
 
The following will be the output if the user enters a strong password.
mp06121
react-js
JavaScript
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS - CLI Commands

Let us learn the basic command available in Create React App command line application in this chapter.
Create React App provides multiple ways to create React application.
Using npx script.
npx create-react-app <react-app-name>
npx create-react-app hello-react-app

Using npm package manager.
npm init react-app <react-app-name>
npm init react-app hello-react-app

Using yarn package manager.
yarn init react-app <react-app-name>
yarn init react-app hello-react-app

Create React App creates React application using default template. Template refers the initial code with certain build-in functionality. There are hundreds of template with many advanced features are available in npm package server. Create React App allows the users to select the template through –template command line switch.
create-react-app my-app --template typescript

Above command will create react app using cra-template-typescript package from npm server.
React dependency package can be installed using normal npm or yarn package command as React uses the project structure recommended by npm and yarn.
Using npm package manager.
npm install --save react-router-dom

Using yarn package manager.
yarn add react-router-dom

React application can be started using npm or yarn command depending on the package manager used in the project.
Using npm package manager.
npm start

Using yarn package manager.
yarn start

To run the application in secure mode (HTTPS), set an environment variable, HTTPS and set it to true before starting the application. For example, in windows command prompt (cmd.exe), the below command set HTTPS and starts the application is HTTPS mode.
set HTTPS=true && npm start
numpy.random.get_state() in Python

26 Nov, 2021
With the help of numpy.random.get_state() method, we can get the internal state of a generator and return the tuple by using this method.
Syntax : numpy.random.get_state()
Return : Return the tuple having {tuple(str, ndarray of 624 units, int, int, float), dict}
Example #1 :
In this example we can see that by using numpy.random.get_state() method, we are able to get the tuple having internal state of a generator and return the tuple by using this method.
Python3
# import numpy and get_stateimport numpy as np # Using get_state() methodgfg = np.random.get_state()[0] print(gfg)
Output :
MT19937
Example #2 :
Python3
# import numpy and get_stateimport numpy as npimport matplotlib.pyplot as plt # Using get_state() methodgfg = np.random.get_state()[1] count, bins, ignored = plt.hist(gfg, 24, density = True)plt.show()
Output :
kalrap615
Python numpy-Random
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular 10 formatDate() Method

24 May, 2021
In this article, we are going to see what is formatDate in Angular 10 and how to use it. formatDate is used to format a date according to locale rules.
Syntax:
formatDate(value, locale, format, timezone)
Parameters:
value: The number to format.
locale: A locale code for the locale format.
format: The date-time components to include.
timezone: The time zone of the place.
Return Value:
string: the formatted date string.
NgModule: Module used by formatDate is:
CommonModule
Approach: 
Create the Angular app to be used.
In app.module.ts import LOCALE_ID because we need locale to be imported for using get formatDate.
import { LOCALE_ID, NgModule } from '@angular/core';
In app.component.ts import formatDate and LOCALE_ID
inject LOCALE_ID as a public variable.
In app.component.html show the local variable using string interpolation
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import {  formatDate }  from '@angular/common';  import {Component,  Inject,  LOCALE_ID }  from '@angular/core';  @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatDate("02-feburary-0202", 'dd-MM-yyyy' ,this.locale);constructor(  @Inject(LOCALE_ID) public locale: string,){}}
app.component.html
<h1>  GeeksforGeeks</h1>  <p>Locale Date is : {{curr}}</p>
Output:
Example 2:
app.component.ts
import {  formatDate }  from '@angular/common';  import {Component,  Inject,  LOCALE_ID }  from '@angular/core';  @Component({selector: 'app-root',templateUrl: './app.component.html'})export class AppComponent {curr = formatDate("03-march-0303", 'yyyy-dd-MM' ,this.locale);constructor(  @Inject(LOCALE_ID) public locale: string,){}}
app.component.html
<h1>  GeeksforGeeks</h1>  <p>Locale Date is : {{curr}}</p>
Output:
Reference: https://angular.io/api/common/formatDate
Angular10
AngularJS-Function
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | os.mknod() method

08 Sep, 2021
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.os.mknod() method in Python is used to create a file system node i.e a file, device special file or named pipe with specified path name. 
Syntax: os.mknod(path, mode = 0o600, device = 0, *, dir_fd = None)Parameters: path: A path-like object representing the file system path. device (optional): This defines the newly created device files. The default value of this parameter is 0. dir_fd (optional): This is a file descriptor referring to a directory. Return type: This method does not return any value.  
Code: Use of os.mknod() method  
Python3
# Python3 program to explain os.mknod() method # importing os moduleimport os # importing stat moduleimport stat  # Pathpath = "filex.txt" # Permission to useper = 0o600 # type of node to be creatednode_type = stat.S_IRUSRmode = per | node_type # Create a file system node# with specified permission# and type using# os.mknod() methodos.mknod(path, mode) print("Filesystem node is created successfully")
File system node is created successfully
 
avtarkumar719
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the difference between HTTP_HOST and SERVER_NAME in PHP?

06 Sep, 2021
HTTP_HOST: It is fetched from HTTP request header obtained from the client request
Example:
Website: https://www.geeksforgeeks.org
HTTP_HOST: www.geeksforgeeks.org

HTTP_SERVER: It is fetched from the server name based on the host configuration.
Example:
Website: https://www.geeksforgeeks.org
HTTP_SERVER: Display the server name

Example of HTTP_HOST:
<?php echo $_SERVER['HTTP_HOST']; ?>
Output:
It display the host name.
Example of HTTP_SERVER:
<?phpecho $_SERVER['SERVER_NAME'];?>
Output:
It display the server name.
Note: In case of localhost, HOST and SERVER name both will same.
kalrap615
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
Comparing two dates in PHP
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
Comparing two dates in PHP
Split a comma delimited string into an array in PHP
How to fetch data from localserver database and display on HTML table using PHP ?
Ruby | Array class join() function

31 May, 2021
join() is an Array class method which returns the string which is created by converting each element of the array to a string, separated by the given separator. 
Syntax: Array.join()Parameter: Array separatorReturn: join value of the array elements
Example #1: 
Ruby
# Ruby code for join() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # joinputs "join : #{a.join("4")}\n\n" # joinputs "join : #{b.join('-')}\n\n" # joinputs "join : #{c.join("*")}\n\n"
Output :  
join : 1842243344546

join : 1-4-1-1-88-9

join : 18*22***50*6
Example #2:  
Ruby
# Ruby code for join() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayb = ["cow", nil, "dog"] # declaring arrayc = ["cat", nil, nil] # joinputs "join : #{a.join("4")}\n\n" # joinputs "join : #{b.join('-')}\n\n" # joinputs "join : #{c.join("*")}\n\n"
Output :  
join : abc4nil4dog

join : cow--dog

join : cat**
 
anikakapoor
Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add Site Header, Site Title, Index Title in a Django Project?

08 Jun, 2022
Automatic admin interface one of the most powerful parts of Django. Metadata is read from your models to provide a quick, model-centric interface where trusted users can manage content on your site. The admin’s recommended use is limited to an organization’s internal management tool. It’s not intended for building your entire front end around.
OVERVIEW:
Add ‘django.contrib.admin’ along with its dependencies – django.contrib.auth, django.contrib.contenttypes, django.contrib.messages, and django.contrib.sessions – to your INSTALLED_APPS setting.
Configure a DjangoTemplates backend in your TEMPLATES setting with django.template.context_processors.request, django.contrib.auth.context_processors.auth, and django.contrib.messages.context_processors.messages in the ‘context_processors’ option of OPTIONS.
If you have used customised MIDDLEWARE setting, django.contrib.auth.middleware.AuthenticationMiddleware and django.contrib.messages.middleware.MessageMiddleware must be included.
Make following changes in urls.py – 
python3
from django.contrib import adminfrom django.urls import path, include # Adds site header, site title, index title to the admin side.admin.site.site_header = 'Geeks For Geeks'admin.site.site_title = 'GFG'admin.site.index_title = 'Welcome Geeks' urlpatterns = [    path('', include('main.urls')),    path('admin/', admin.site.urls),]
Output – 
DJANGO ADMIN CUSTOMISATION: 
The Python code enables to add site_header, site_heading and  index_title.
vinayedula
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
Introduction To PYTHON
HTML5 - Modernizr

Modernizr is a small JavaScript Library that detects the availability of native implementations for next-generation web technologies
There are several new features which are being introduced through HTML5 and CSS3 but same time many browsers do not support these news features.
Modernizr provides an easy way to detect any new feature so that you can take corresponding action. For example, if a browser does not support video feature then you would like to display a simple page.
You can create CSS rules based on the feature availability and these rules would apply automatically on the webpage if browser does not support a new feature.
You can download latest version of this utility from Modernizr Download.
Before you start using Modernizr, you would have to include its javascript library in your HTML page header as follows −
<script src="modernizr.min.js" type="text/javascript"></script>
As mentioned above, you can create CSS rules based on the feature availability and these rules would apply automatically on the webpage if browser does not support a new featur.
Following is the simple syntax to handle supported and non supported features −
/* In your CSS: */
.no-audio #music {
   display: none; /* Don't show Audio options */
}
.audio #music button {
   /* Style the Play and Pause buttons nicely */
}

<!-- In your HTML: -->
<div id="music">
   
   <audio>
      <source src="audio.ogg" />
      <source src="audio.mp3" />
   </audio>
   
   <button id="play">Play</button>
   <button id="pause">Pause</button>
</div>
Here it is notable that you need to prefix "no-" to every feature/property you want to handle for the browser which does not support them.
Following is the syntax to detect a particular feature through Javascript −
if (Modernizr.audio) {
   /* properties for browsers that
   support audio */
}

else{
   /* properties for browsers that
   does not support audio */
}

Following is the list of features which can be detected by Modernizr −
How to Hide Legend in ggplot2 in R ?

18 Jul, 2021
In this article we will discuss how can we hide a legend in R programming language, using ggplot2.
Note: Here, a line plot is used for illustration the same can be applied to any other plot.
Let us first draw a regular plot, with a legend, so that the difference is apparent. For this, firstly, import the required library and create dataframe, the dataframe should be such that it can be drawn on the basis of groups and is color differentiated because only then a legend will appear.
Example:
R
library("ggplot2")  year <- c(2000, 2001, 2002, 2003, 2004)winner <- c('A', 'B', 'B', 'A', 'B')score <- c(9, 7, 9, 8, 8)  df <- data.frame(year, winner, score)  ggplot(df,aes(x=year,y=score,group=winner))+geom_line(aes(color=winner))+geom_point()
Output:
Now to hide the legend, theme() function is used after normally drawing the plot.
theme() function is a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. This function can also be used to give plots a consistent customized look.
Syntax:
theme (line, text, axis.title,legend.position)
Parameter:
line: all line elements (element_line())
text: all text elements (element_text())
axis.title: labels of axes (element_text()). Specify all axes’ labels (axis.title)
legend.position: changes the legend position to some specified value.
To hide the legend this function is called with legend.position parameter, to which “none” is passed to not make ut appear on the plot.
Syntax: theme(legend.position=”none”)
Code:
R
library("ggplot2")  year<-c(2000,2001,2002,2003,2004)winner<-c('A','B','B','A','B')score<-c(9,7,9,8,8)  df<-data.frame(year,winner,score)  ggplot(df,aes(x=year,y=score,group=winner))+geom_line(aes(color=winner))+geom_point()+theme(legend.position="none")
Output:
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.