code-rag-bench/online-tutorials huggingface dataset:
How to test a URL for 404 error in PHP?

20 May, 2019
Checking if a Webpage URL exists or not is relatively easy in PHP. If the required URL does not exist, then it will return 404 error. The checking can be done with and without using cURL library.
cURL: The cURL stands for ‘Client for URLs’, originally with URL spelled in uppercase to make it obvious that it deals with URLs. It is pronounced as ‘see URL’. The cURL project has two products libcurl and curl.
libcurl: A free and easy-to-use client-side URL transfer library, supporting FTP, TPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE, and LDAP. libcurl supports TTPS certificates, HTTP POST, HTTP PUT, FTP uploading, kerberos, HTTP based upload, proxies, cookies, user & password authentication, file transfer resume, HTTP proxy tunneling and many more. libcurl is free, thread-safe, IPv6 compatible, feature rich, well supported and fast.
curl: A command line tool for getting or sending files using URL syntax. Since curl uses libcurl, it supports a range of common internal protocols, currently including HTTP, HTTPS, FTP, FTPS, GOPHER, TELNET, DICT, and FILE.
Example 1: This example test a URL for 404 error without using cURL approach.
<?php  // Creating a variable with an URL// to be checked$url = 'https://www.geeksforgeeks.org';  // Getting page header data$array = @get_headers($url);  // Storing value at 1st position because// that is only what we need to check$string = $array[0];  // 404 for error, 200 for no errorif(strpos($string, "200")) {    echo 'Specified URL Exists';} else {    echo 'Specified URL does not exist';}  ?>
Output:
Specified URL exists
Example 2: This example test a URL for 404 error using cURL approach.
<?php  // Initializing new session$ch = curl_init("https://www.geeksforgeeks.org");  // Request method is setcurl_setopt($ch, CURLOPT_NOBODY, true);  // Executing cURL sessioncurl_exec($ch);  // Getting information about HTTP Code$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  // Testing for 404 Errorif($retcode != 200) {    echo "Specified URL does not exist";}else {    echo "Specified URL exists";}  curl_close($ch);  ?>
Output:
Specified URL exists
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ?
Python | os.symlink() method

26 Aug, 2019
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.symlink() method in Python is used to create symbolic link. This method creates symbolic link pointing to source named destination.To read about symbolic links/soft links, please refer to this article.
Syntax: os.symlink(src, dst, target_is_directory = False, *, dir_fd = None)
Parameters:src: A path-like object representing the file system path. This is the source file path for which the symbolic link will be created.dst: A path-like object representing the file system path. This is the target file path where symbolic link will be created.target_is_directory (optional): The default value of this parameter is False. If the specified target path is directory then its value should be True.dir_fd (optional): A file descriptor referring to a directory.
Return type: This method does not return any value.
Code: Use of os.symlink() method
# Python program to explain os.symlink() method     # importing os module import os    # Source file pathsrc = '/home/ihritik/file.txt'  # Destination file pathdst = '/home/ihritik/Desktop/file(symlink).txt'  # Create a symbolic link# pointing to src named dst# using os.symlink() methodos.symlink(src, dst)  print("Symbolic link created successfully")
Symbolic link created successfully

Reference: https://docs.python.org/3/library/os.html#os.link
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Introduction To PYTHON
Tryit Editor v3.7

Tryit: Using object-fit: cover
Adding caption below X-axis for a scatter plot using Matplotlib

To add caption below X-axis for a scatter plot, we can use text() method for the current figure.
Create x and y data points using numpy.
Create x and y data points using numpy.
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Plot the scatter points with x and y data points.
Plot the scatter points with x and y data points.
To add caption to the figure, use text() method.
To add caption to the figure, use text() method.
Adjust the padding between and around the subplots.
Adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.random.rand(10)
y = np.random.rand(10)
fig = plt.figure()
plt.scatter(x, y, c=y)
fig.text(.5, .0001, "Scatter Plot", ha='center')
plt.tight_layout()
plt.show()
Dart Programming - If Statement

The if...else construct evaluates a condition before a block of code is executed.
Following is the syntax.
if(boolean_expression){ 
   // statement(s) will execute if the boolean expression is true. 
} 

If the Boolean expression evaluates to be true, then the block of code inside the if statement will be executed. If Boolean expression evaluates to be false, then the first set of code after the end of the if statement (after the closing curly brace) will be executed.
The following illustration shows the flowchart of the if statement.
The following example shows how you can use the if statement in Dart.
void main() { 
   var  num=5; 
   if (num>0) { 
      print("number is positive"); 
   }    
}
The above example will print “number is positive” as the condition specified by the if block is true.
number is positive 


    44 Lectures 
     4.5 hours 

 Sriyank Siddhartha

    34 Lectures 
     4 hours 

 Sriyank Siddhartha

    69 Lectures 
     4 hours 

 Frahaan Hussain

    117 Lectures 
     10 hours 

 Frahaan Hussain

    22 Lectures 
     1.5 hours 

 Pranjal Srivastava

    34 Lectures 
     3 hours 

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Get only a single value from a specific MySQL row?

For this, use SELECT INTO variable with where clause. Let us first create a table −
mysql> create table DemoTable1896
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20),
   StudentMarks int
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1896(StudentName,StudentMarks) values('Chris',56);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1896(StudentName,StudentMarks) values('David',98);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1896(StudentName,StudentMarks) values('Mike',89);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1896(StudentName,StudentMarks) values('Sam',78);
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1896;
This will produce the following output −
+-----------+-------------+--------------+
| StudentId | StudentName | StudentMarks |
+-----------+-------------+--------------+
|         1 | Chris       |           56 |
|         2 | David       |           98 |
|         3 | Mike        |           89 |
|         4 | Sam         |           78 |
+-----------+-------------+--------------+
4 rows in set (0.00 sec)
Here is the query to get value from a specific MySQL row −
mysql> set @Name:=NULL;
Query OK, 0 rows affected (0.00 sec)
mysql> select StudentName into @Name from DemoTable1896 where StudentMarks=98;
Query OK, 1 row affected (0.00 sec)
Now you can display the value of the above variable −
mysql> select @Name;
This will produce the following output −
+-------+
| @Name |
+-------+
| David |
+-------+
1 row in set (0.00 sec)
Function hoisting in JavaScript

Hoisting is a JavaScript technique which moves variables and function declarations to the top of their scope before code execution begins. Within a scope no matter where functions or variables are declared, they're moved to the top of their scope.
Note that hoisting only moves the declaration while assignments are left in place.
console.log(functionBelow("Hello"));
function functionBelow(greet) {
   return `${greet} world`;
}
console.log(functionBelow("Hi"));
Hello world
Hi world
Note that the function declaration was after it was called but was still called. This was possible due to function hoisting.
Also note that it doesn't work when you assign functions like variables.
console.log(functionBelow("Hello"));
var functionBelow = function(greet) {
   return `${greet} world`;
}
console.log(functionBelow("Hi"));
This will fail with an error: functionBelow is not a function
If you remove var, it'll fail with the error: functionBelow is not defined
Note that when it was declared with var, it was hoisted as a variable in the context. But it still remained undefined. This is known as variable hoisting. Due to this property, anonymous and arrow functions are never hoisted in JavaScript.
numpy.less() in Python

28 Mar, 2022
The numpy.less() : checks whether x1 is lesser than x2 or not. Syntax : 
numpy.less(x1, x2[, out])
Parameters : 
x1, x2 : [array_like]Input arrays. If x1.shape != x2.shape, they must be 
             broadcastable to a common shape 
out    : [ndarray, boolean]Array of bools, or a single bool if x1 and x2 are scalars.
Return : 
Boolean array indicating results, whether x1 is lesser than x2 or not.
Code 1 : 
Python
# Python Program illustrating# numpy.less() method  import numpy as geek a  = geek.less([8., 2.], [5., 3.])print("Not equal : \n", a, "\n") b = geek.less([2, 2], [[1, 3],[1, 4]])print("Not equal : \n", b, "\n") a = geek.array([4,2])b = geek.array([6,2]) print("Is a lesser than b : ", a < b)
Output : 
Not equal : 
 [False  True] 

Not equal : 
 [[False  True]
 [False  True]] 

Is a lesser than b :  [ True False]]
Code 2 : 
Python
# Python Program illustrating# numpy.less() method   import numpy as geek  # Here we will compare Complex values with inta = geek.array([1j,2])b = geek.array([1,2])  # indicating 1j is lesser than 1print("Comparing complex with int : ", a < b) # indicating 1j is lesser than 1d  = geek.less(a, b)print("\n Comparing complex with int  .less() : ", d)
Output : 
Comparing complex with int :  [ True False]

 Comparing complex with int  .less() :  [ True False]
Code 3 : 
Python
# Python Program illustrating# numpy.less() method   import numpy as geek # Here we will compare Float with int valuesa = geek.array([1.1, 1])b = geek.array([1, 2])  # indicating 1.1 is greater than 1print("Comparing float with int : ", a < b) # indicating 1.1 is greater than 1d  = geek.less(a, b)print("\n Comparing float with int using  .less() : ", d)
Output : 
Comparing float with int :  [False  True]

 Comparing float with int using  .less() :  [False  True]
References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.less.html#numpy.less Note : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working. This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
vinayedula
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
outtextxy() function in C

05 Dec, 2019
The header file graphics.h contains outtextxy() function which displays the text or string at a specified point (x, y) on the screen.
Syntax :
void outtextxy(int x, int y, char *string);

where, x, y are coordinates of 
the point and, third argument contains
the address of string to be displayed.

Examples :
Input : x = 200, y = 150, 
        string = "Hello Geek, Have a good day !"
Output : 

Input : x = 150, y = 250, 
        string = "GeeksforGeeks is the best !"
Output : 

Below is the implementation for outtextxy() function:
// C Implementation for outtextxy()#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, "");      // outtextxy function    outtextxy(200, 150, "Hello Geek, Have a good day !");      getch();      // closegraph function closes the    // graphics mode and deallocates    // all memory allocated by    // graphics system .    closegraph();      return 0;}
Output :


Akanksha_Rai
c-graphics
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Grouping similar substrings in list

17 Jun, 2021
Sometimes we have an application in which we require to group common prefix strings into one such that further processing can be done according to the grouping. This type of grouping is useful in the cases of Machine Learning and Web Development. Let’s discuss certain ways in which this can be done.Method #1 : Using lambda + itertools.groupby() + split() The combination of above three functions help us achieve the task. The split method is key as it defines the separator by which grouping has to be performed. The groupby function does the grouping of elements. 
Python3
# Python3 code to demonstrate# group similar substrings# using lambda + itertools.groupby() + split()from itertools import groupby # initializing listtest_list = ['geek_1', 'coder_2', 'geek_4', 'coder_3', 'pro_3'] # sort list# essential for groupingtest_list.sort() # printing the original listprint ("The original list is : " + str(test_list)) # using lambda + itertools.groupby() + split()# group similar substringsres = [list(i) for j, i in groupby(test_list,                  lambda a: a.split('_')[0])] # printing resultprint ("The grouped list is : " + str(res))
The original list is : [‘coder_2’, ‘coder_3’, ‘geek_1’, ‘geek_4’, ‘pro_3’] The grouped list is : [[‘coder_2’, ‘coder_3’], [‘geek_1’, ‘geek_4’], [‘pro_3’]] 
 
 Method #2 : Using lambda + itertools.groupby() + partition() The similar task can also be performed replacing the split function with the partition function. This is more efficient way to perform this task as it uses the iterators and hence internally quicker. 
Python3
# Python3 code to demonstrate# group similar substrings# using lambda + itertools.groupby() + partition()from itertools import groupby # initializing listtest_list = ['geek_1', 'coder_2', 'geek_4', 'coder_3', 'pro_3'] # sort list# essential for groupingtest_list.sort() # printing the original listprint ("The original list is : " + str(test_list)) # using lambda + itertools.groupby() + partition()# group similar substringsres = [list(i) for j, i in groupby(test_list,              lambda a: a.partition('_')[0])] # printing resultprint ("The grouped list is : " + str(res))
The original list is : [‘coder_2’, ‘coder_3’, ‘geek_1’, ‘geek_4’, ‘pro_3’] The grouped list is : [[‘coder_2’, ‘coder_3’], [‘geek_1’, ‘geek_4’], [‘pro_3’]] 
 
sweetyty
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Joining Threads in Java

java.lang.Thread class provides a method join() which serves the following purposes usign its overloaded version.
join() − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates.
join() − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates.
join(long millisec) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
join(long millisec) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
join(long millisec, int nanos) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds + nanoseconds passes.
join(long millisec, int nanos) − The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds + nanoseconds passes.
See the below example demonstrating the concept.
 Live Demo
class CustomThread implements Runnable {
   public void run() {
      System.out.println(Thread.currentThread().getName() + " started.");
      try {
         Thread.sleep(500);
      } catch (InterruptedException e) {
         System.out.println(Thread.currentThread().getName() + " interrupted.");
      }
      System.out.println(Thread.currentThread().getName() + " exited.");
   }
}
public class Tester {
   public static void main(String args[]) throws InterruptedException {
      Thread t1 = new Thread( new CustomThread(), "Thread-1");
      t1.start();
      //main thread class the join on t1
      //and once t1 is finish then only t2 can start
      t1.join();
      Thread t2 = new Thread( new CustomThread(), "Thread-2");
      t2.start();
      //main thread class the join on t2
      //and once t2 is finish then only t3 can start
      t2.join();
      Thread t3 = new Thread( new CustomThread(), "Thread-3");
      t3.start();
   }
}
Thread-1 started.
Thread-1 exited.
Thread-2 started.
Thread-2 exited.
Thread-3 started.
Thread-3 exited.
How to open multiple filenames in Tkinter and add the file names to a list?

To open a file dialog in a tkinter application, tkinter provides the tkfiledialog package which creates a dialog box to interact with the external files located on the system. In order to work with filedialog, we have to first import the package using the following command,
import tkinter.filedialog as fd
To open the explorer in the window, use asopenfilename(parent, title, **options) function. It will just pull the window and allow the user to select the file from the explorer. Once the file has been opened, we can define a function to print the list of all the selected files.
# Import the required libraries
from tkinter import *
from tkinter import ttk
import tkinter.filedialog as fd

# Create an instance of tkinter frame or window
win = Tk()

# Set the geometry of tkinter frame
win.geometry("700x350")

def open_file():
   file = fd.askopenfilenames(parent=win, title='Choose a File')
   print(win.splitlist(file))

# Add a Label widget
   label = Label(win, text="Select the Button to Open the File", font=('Aerial 11'))
label.pack(pady=30)

# Add a Button Widget
ttk.Button(win, text="Select a File", command=open_file).pack()

win.mainloop()
Running the above code will display a window that contains a button and a Label Text widget.
Click the Button "Select a File" to open the Dialog for selecting the Files from the Explorer.
Create a dynamic table name from current year in MySQL like 2019

To create a table name like year (2019), use PREPARE statement. Let us first create a table −
mysql> create table DemoTable1959
   (
   UserName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1959 values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1959 values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1959 values('Bob');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1959;
This will produce the following output −
+----------+
| UserName |
+----------+
| Chris    |
| David    |
| Bob      |
+----------+
3 rows in set (0.00 sec)
Here is the query to create a dynamic table name from current year
mysql> set @dynamicQuery = CONCAT('create table `', date_format(curdate(),'%Y'), '` as select UserName from DemoTable1959');
Query OK, 0 rows affected (0.00 sec)
mysql> prepare st from @dynamicQuery;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute st;
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0
Display all records from the table using select statement. Here the current year is 2019 −
mysql> select * from `2019`;
This will produce the following output −
+----------+
| UserName |
+----------+
| Chris    |
| David    |
| Bob      |
+----------+
3 rows in set (0.00 sec)
Python code to move spaces to front of string in single traversal - GeeksforGeeks

23 Nov, 2020
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once.
Examples:
Input  : str = "geeks for geeks"
Output : ste = "  geeksforgeeks"

Input  : str = "move these spaces to beginning"
Output : str = "    movethesespacestobeginning"
There were four space characters in input,
all of them should be shifted in front. 

This problem has existing solution, please refer Move spaces to front of string in single traversal link.We will solve this problem quickly in Python using List Comprehension.Approach:
Traverse input string and create a string without any space character using list comprehension.Now to know how many space characters were there in original string just take a difference of length of original string and new string.Now create another string and append space characters at the beginning.
Traverse input string and create a string without any space character using list comprehension.
Now to know how many space characters were there in original string just take a difference of length of original string and new string.
Now create another string and append space characters at the beginning.
# Function to move spaces to front of string # in single traversal in Python   def moveSpaces(input):           # Traverse string to create string without spaces     noSpaces = [ch for ch in input if ch!=' ']       # calculate number of spaces     space= len(input) - len(noSpaces)       # create result string with spaces     result = ' '*space       # concatenate spaces with string having no spaces     result = '"'+result + ''.join(noSpaces)+'"'    print (result)   # Driver program if __name__ == "__main__":     input = 'geeks for geeks'    moveSpaces(input) 
Output:
"  geeksforgeeks"

Python string-programs
python-string
Python
Strings
Strings
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()
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
Python Type Object

Everything in Python is an object including classes. All classes are instances of a class called "type".The type object is also an instance of type class. You can inspect the inheritance hierarchy of class by examining the __bases__ attribute of a class object. type() method returns class type of the argument(object) passed as parameter.If single argument type(obj) is passed to type method, it returns the type of given object. If three arguments type(name, bases, dict) is passed, it returns a new type object.
Let’s look at the classes for the most used data types. In the below program we initialize some variables and then use the type() to ascertain their class.
 Live Demo
# Some variables
a = 5
b = 5.2
c = 'hello'
A = [1,4,7]
B = {'k1':'Sun','K2':"Mon",'K3':'Tue'}
C = ('Sky','Blue','Vast')
print(type(a))
print(type(b))
print(type(c))

print(type(A))
print(type(B))
print(type(C))
Running the above code gives us the following result −
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'tuple'>
If we go deeper to look at the type of classes above, we will see that they are all belong to class named ‘type’.
 Live Demo
print(type(int))
print(type(dict))
print(type(list))

print(type(type))
Running the above code gives us the following result −
<class 'type'>
<class 'type'>
<class 'type'>
<class 'type'>
We can also use a similar approach as above to create new objects. Here we pass three parameters to create the new type object.
 Live Demo
Object1 = type('A', (object,), dict(a='Hello', b=5))
print(type(Object1))
print(vars(Object1))
class NewCalss:
   a = 'Good day!'
   b = 7
Object2 = type('B', (NewCalss,), dict(a='Hello', b=5))
print(type(Object2))
print(vars(Object2))
Running the above code gives us the following result −
<class 'type'>
{'a': 'Hello', 'b': 5, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None}
<class 'type'>
{'a': 'Hello', 'b': 5, '__module__': '__main__', '__doc__': None}
Difference between EnumMap and HashMap in Java

EnumMap is introduced in JDK5. It is designed to use Enum as key in the Map. It is also the implementation of the Map interface. All of the key in the EnumMap should be of the same enum type. In EnumMap , key can’t be null and any it will throw NullPointerException.
As per java docs −
 EnumMap internally using as arrays, this representation is extremely compact and efficient.
HashMap is also the implementation of the Map interface. It is used to store the data in Key and Value form. It can contain one null key and multiple null values . In HashMap, keys can’t be a primitive type. Java HashMap implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. 
1
Basic 
A specialized Map implementation for use with enum type keys
HashMap is also the implementation of the Map interface.
2
Null Key
It can’t have null key.
 It can have one null key and multiple null values
3
Performance 
All operations execute in constant time therefore it is faster than HashMap 
It is slower than HashMap
4. 
Internal Implementation 
It uses Array internally 
It uses Hashtable internally 
5.
Ordering 
EnumMap stores keys in the natural order of their keys
HashMap is not ordered
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
public class EnumMapExample {
   public enum LaptopEnum {
      HCL, DELL, IBM
   };
   public static void main(String[] args) {
      // create enum map
      EnumMap map = new EnumMap(LaptopEnum.class);
      map.put(LaptopEnum.HCL, "100");
      map.put(LaptopEnum.DELL, "200");
      map.put(LaptopEnum.IBM, "300");
      // print the map
      for (Map.Entry m : map.entrySet()) {
         System.out.println(m.getKey() + " " + m.getValue());
      }
   }
}
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HashMapExample {
   public static void main(String[] args) {
      // create Hash map
      Map map = new HashMap();
      map.put("HCL", "100");
      map.put("DELL", "200");
      map.put("IBM", "300");
      // print the map
      for (Map.Entry m : map.entrySet()) {
         System.out.println(m.getKey() + " " + m.getValue());
      }
   }
}
Java - max() Method

This method gives the maximum of the two arguments. The argument can be int, float, long, double.
This method has the following variants −
double max(double arg1, double arg2)
float max(float arg1, float arg2)
int max(int arg1, int arg2)
long max(long arg1, long arg2)

Here is the detail of parameters −
This method accepts any primitive data type as a parameter.
This method returns the maximum of the two arguments.
public class Test { 

   public static void main(String args[]) {
      System.out.println(Math.max(12.123, 12.456));      
      System.out.println(Math.max(23.12, 23.0));  
   }
}
This will produce the following result −
12.456
23.12


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Python program to check credit card number is valid or not

Suppose we have a credit card number. We have to check whether the card number is valid or not. The card numbers have certain properties −
It will start with 4, 5 and 6
It will start with 4, 5 and 6
It will be 16 digits’ long
It will be 16 digits’ long
Numbers must contain only digits
Numbers must contain only digits
It may have digits in four groups separated by '-'
It may have digits in four groups separated by '-'
It must not use any other separator like space or underscore
It must not use any other separator like space or underscore
It must not have 4 or more consecutive same digits
It must not have 4 or more consecutive same digits
So, if the input is like s = "5423-2578-8632-6589", then the output will be True
To solve this, we will follow these steps −
if number of '-' in s is greater than 0, thena := a list of parts separated by "-"p:= 1if size of a is not same as 4, thenp:= nulla:= blank listfor each b in a, doif size of b is not same as 4, thenp:= nullcome out from loop
a := a list of parts separated by "-"
p:= 1
if size of a is not same as 4, thenp:= nulla:= blank list
p:= null
a:= blank list
for each b in a, doif size of b is not same as 4, thenp:= nullcome out from loop
if size of b is not same as 4, thenp:= nullcome out from loop
p:= null
come out from loop
otherwise,p := search a substring which is starting with 4 or 5 or 6 and remaining are numbers of 15 digits longs := remove "-" from sq := search substring where 4 or more consecutive characters are sameif p is not null and q is null, thenreturn Trueotherwise,return False
p := search a substring which is starting with 4 or 5 or 6 and remaining are numbers of 15 digits long
s := remove "-" from s
q := search substring where 4 or more consecutive characters are same
if p is not null and q is null, thenreturn True
return True
otherwise,return False
return False
Let us see the following implementation to get better understanding
import re

def solve(s):
   if s.count("-")>0:
      a = s.split("-")
      p=1
      if len(a)!=4:
         p=None
         a=[]
      for b in a:
         if len(b)!=4:
            p=None
            break
         else:
            p = re.search("[456][0-9]{15}",s)
         s = s.replace("-","")
         q = re.search(".*([0-9])\\1{3}.*",s)

         if p!=None and q==None:
            return True
         else:
            return False

s = "5423-2578-8632-6589"
print(solve(s))
"5423-2578-8632-6589"

False
How to use HTML5 GeoLocation API with Google Maps?

HTML5 Geolocation API lets you share your location with your favorite websites. A Javascript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map. The geolocation coordinates specify the geographic location of the device.
We will be using getCurrentPostion() method to get the current location. To get current location using HTML5 Geolocation with Google Maps, you need to set an API key for Google Static Maps API.
Go to https://console.developers.google.com and get a free API key for Google Map. Add this key to the code to work Geolocation with it.
You can try to run the following code to show current location using HTML5 Geolocation with Google Maps −
<!DOCTYPE HTML>
<html>
   <head>
      <script type = "text/javascript">
         function showLocation(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var latlongvalue = position.coords.latitude + ","
                              + position.coords.longitude;
            var img_url = "https://maps.googleapis.com/maps/api/staticmap?center="
                          +latlongvalue+"&zoom=14&size = 400x300&key =
                          AIzaSyAa8HeLH2lQMbPeOiMlM9D1VxZ7pbGQq8o";
            document.getElementById("mapholder").innerHTML =
            "<img src ='"+img_url+"'>";
         }
         function errorHandler(err) {
            if(err.code == 1) {
               alert("Error: Access is denied!");
            }else if( err.code == 2) {
               alert("Error: Position is unavailable!");
            }
         }
         function getLocation(){
            if(navigator.geolocation){
               // timeout at 60000 milliseconds (60 seconds)
               var options = {timeout:60000};
               navigator.geolocation.getCurrentPosition
               (showLocation, errorHandler, options);
            }else{
               alert("Sorry, browser does not support geolocation!");
            }
         }
      </script>
   </head>
   <body>
      <div id="mapholder"></div>
      <form>
         <input type="button" onclick="getLocation();" value="Your Location"/>
      </form>
   </body>
</html>
Program to find GCD or HCF of two numbers in C++

In this tutorial, we will be discussing a program to find GCD and HCF of two numbers.
For this we will be provided with two numbers. Our task is to find the GCD or HCF (highest common factor) for those given two numbers.
 Live Demo
#include <iostream>
using namespace std;
int gcd(int a, int b){
   if (a == 0)
      return b;
   if (b == 0)
      return a;
   if (a == b)
      return a;
   if (a > b)
      return gcd(a-b, b);
   return gcd(a, b-a);
}
int main(){
   int a = 98, b = 56;
   cout<<"GCD of "<<a<<" and "<<b<<" is "<<gcd(a, b);
   return 0;
}
GCD of 98 and 56 is 14
p5.js camera() Method

04 Mar, 2021
The camera() function in p5.js is used to set the virtual camera’s position on a 3D sketch. This can be used to simulate the position of the camera as it would move around the scene making it possible to view objects from various angles.
The parameters of this function include setting the position for the camera, the center of the camera, and the vector which is pointing upside. 
Syntax:
camera([x], [y], [z], [centerX], [centerY], [centerZ],
            [upX], [upY], [upZ])
Parameters: This function accept nine parameters as mentioned above and described below:
x: This is a number that denotes the camera position on x-axis.
y: This is a number that denotes the camera position on y-axis.
z: This is a number that denotes the camera position on z-axis.
centerX: This is a number that denotes the x coordinate of the center of the sketch. 
centerY: This is a number that denotes the y coordinate of the center of the sketch.
centerZ: This is a number that denotes the z coordinate of the center of the sketch.
upX: This is a number that denotes the x component of direction ‘up’ from camera. 
upY: This is a number that denotes the y component of direction ‘up’ from camera.
upZ: This is a number that denotes the z component of direction ‘up’ from camera.
Below examples illustrates the camera() function in p5.js:
Example 1: Set the view of the camera on the x-axis.
Javascript
function setup() {      createCanvas(600, 400, WEBGL);}  function draw() {      background(175);      // Map the coordinates of the mouse  // to the variable  let cX = map(mouseX, 0,               width, -200, 200);      // Set the camera to the given coordinates  camera(cX, 0, (height/2) / tan(PI/6),         cX, 0, 0, 0, 1, 0);      ambientLight(255);      rotateZ(frameCount * 0.01);  rotateX(frameCount * 0.03);  rotateY(frameCount * 0.06);  noStroke();  normalMaterial();      box(100, 100, 100);}
Output:
Example 2: Set the view of the camera in a random direction every frame.
Javascript
function setup() {      frameRate(5);  createCanvas(600, 400, WEBGL);}  function draw() {      background(175);      let cX = random(-10,10);  let cY = random(-10,10);  let cZ = random(-10,10);      camera(cX, cY,         cZ+(height/2) / tan(PI/6),         cX, 0, 0, 0, 1, 0);      ambientLight(255);      rotateX(frameCount * 0.1);  rotateY(frameCount * 0.1);      noStroke();  normalMaterial();      box(100, 100, 100);}
Output:
Reference:https://p5js.org/reference/#/p5.Camera
JavaScript-p5.js
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Perform DDoS attack using Torshammer

11 Jul, 2022
There are very few methods available which claim to be successful for DDoS or any type of network loss. Let’s see one of such method to perform DDoS attack. This attack is really powerful and requires the only skill that you should know how to operate commands on Kali Linux Operating System.
First of all, If you want to check that any website has its TCP port 80 opened or not, you can go for nmap, and all the tutorial given for nmap .
This tool we are using is Torshammer. It is written in Python and can give damage to unprotected web servers in an instance that’s why it is a slow post tool.
Main feature of this tool is it works on the 7th layer of HTTP(Hyper Text Transfer Protocol).
Install Torshammer tool:
Go to GitHub dotfighter/torshammer by this link or, just open a terminal and write this command-
git clone https://github.com/dotfighter/torshammer.git
Now, Come to the directory wherever that script is cloned. You will find something like this:
You can see there are five Python scripts, two for the terminal, two for sockets and remaining one is main torshammer script. Now Right click on the blank space and select “Open In Terminal”, it will directly open a terminal with that right path. Otherwise, you can type “cd torshammer” in the newly opened terminal.
Write this command-
python torshammer.py
It will finally open the main interface for the tool.
Let’s understand these first:
Any Python tool in Kali Linux should start with “python” suffix and follow by toolname(.)py also. Like that any PHP tool should start with “php” and follow by toolname(.)php.
-t is for the target, some domain or ip-address.-p is for port Defaults to 80.-r is for the threads, how many threads we want to run for this attack.-T stands for tor customized attacks.
Let’s do the main thing:
python torshammer.py <i>any hostname/IP</i>  -t -p 80 -r 5000
For example-
python torshammer.py -t xyz.com  -p 80 -r 5000
As you hit enter after writing those commands, something will appear like this:
So, you have successfully run an attack. Please note that, if that website is opening normally then they have settled up their website on some Content Delivery Network(CDN) e.g. Akamai, Cloudflare which is designed to work against any kind of DoS or DDoS attacks. For checking that attack is successful or not, you can go to isitdownrightnow to verify.
Disclaimer: This article is just for knowledge purpose. Please don’t use this article to perform any malicious activity. Remember, before targeting or attacking anyone’s IP/hostname/Servers one must have the necessary permissions.
user_zmkb
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Make pair from two list such that elements are not same in pairs

28 Feb, 2019
Given two lists, the task is to create pairs of elements (pairs can be repeated) from two list such that elements are not same in pairs.
Examples:
Input : list1 = [100, 20, 30, 400]
        list2 = [400, 2, 30]
Output:
[[100, 400], [100, 2], [100, 30],
 [20, 400], [20, 2], [20, 30],
 [30, 400], [30, 2], [400, 2], [400, 30]]

Input: list1 = [10,20,30,40]
       list2 = [60, 10, 20]
Output:
[[10, 60], [10, 20], [20, 60], [20, 10],
 [30, 60], [30, 10], [30, 20],
 [40, 60], [40, 10], [40, 20]]

 Method #1: Using list comprehension
# Python code to create pair of element # from two list such that element # in pairs are not equal.  # List initializationlist1 =[10, 20, 30, 40]list2 =[40, 50, 60]  # using list comprehensionoutput = [[a, b] for a in list1           for b in list2 if a != b]  # printing outputprint(output)
[[10, 40], [10, 50], [10, 60], [20, 40], [20, 50], [20, 60], [30, 40], [30, 50], [30, 60], [40, 50], [40, 60]]
 
Method #2: Using itertools and iteration
# Python code to create pair of element # from two list such that element # in pairs are not equal.  # Importingimport itertools  # List initializationlist1 =[11, 22, 33, 44]list2 =[22, 44, 66]  # using itertoolstemp = list(itertools.product(list1, list1))  # output list initializationout = []  # iterationfor elem in temp:    if elem[0]!= elem[1]:        out.append(elem)  # printing outputprint(out)
[(11, 22), (11, 33), (11, 44), (22, 11), (22, 33), (22, 44), (33, 11), (33, 22), (33, 44), (44, 11), (44, 22), (44, 33)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create Price Range Selector in ReactJS?

22 Jan, 2021
Price Range Selector means the user is able to select the range between the given values. Material UI for React has this component available for us and it is very easy to integrate. Price Ranges Selectors is a very popular feature for filter the results on the basis of the range selected by the user.
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 material-ui modules using the following command:
npm install @material-ui/core
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 from 'react';import Typography from '@material-ui/core/Typography';import Slider from '@material-ui/core/Slider';  const App = () => {    // Our States  const [value, setValue] =  React.useState([2,10]);    // Changing State when volume increases/decreases  const rangeSelector = (event, newValue) => {    setValue(newValue);    console.log(newValue)  };    return (    <div style={{      margin: 'auto',      display: 'block',      width: 'fit-content'    }}>      <h3>How to create Price Range Selector in ReactJS?</h3>      <Typography id="range-slider" gutterBottom>        Select Price Range:      </Typography>      <Slider        value={value}        onChange={rangeSelector}        valueLabelDisplay="auto"      />      Your range of Price is between {value[0]} /- and {value[1]} /-    </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: Now open your browser and go to http://localhost:3000/, you will see the following output:
Supported Browser:
Chrome
Explorer
Microsoft Edge
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
How to fetch data from an API in ReactJS ?
Axios in React: A Guide for Beginners
How to redirect to another page in ReactJS ?
ReactJS Functional Components
numpy.log() in Python

04 Dec, 2020
The numpy.log() is a mathematical function that helps user to calculate Natural logarithm of x where x belongs to all the input array elements.Natural logarithm log is the inverse of the exp(), so that log(exp(x)) = x. The natural logarithm is log in base e.
Syntax :numpy.log(x[, out] = ufunc ‘log1p’)Parameters :
array : [array_like] Input array or object.out : [ndarray, optional] Output array with same dimensions as Input array, placed with result.
Return :An array with Natural logarithmic value of x; where x belongs to all elements of input array.
Code #1 : Working
# Python program explaining# log() functionimport numpy as np  in_array = [1, 3, 5, 2**8]print ("Input array : ", in_array)  out_array = np.log(in_array)print ("Output array : ", out_array)    print("\nnp.log(4**4) : ", np.log(4**4))print("np.log(2**8) : ", np.log(2**8))
Output :
Input array :  [1, 3, 5, 256]
Output array :  [ 0.          1.09861229  1.60943791  5.54517744]

np.log(4**4) :  5.54517744448
np.log(2**8) :  5.54517744448

 Code #2 : Graphical representation
# Python program showing# Graphical representation  # of log() functionimport numpy as npimport matplotlib.pyplot as plt  in_array = [1, 1.2, 1.4, 1.6, 1.8, 2]out_array = np.log(in_array)  print ("out_array : ", out_array)  plt.plot(in_array, in_array,          color = 'blue', marker = "*")  # red for numpy.log()plt.plot(out_array, in_array,          color = 'red', marker = "o")           plt.title("numpy.log()")plt.xlabel("out_array")plt.ylabel("in_array")plt.show() 
Output :
out_array :  [ 0.          0.18232156  0.33647224  0.47000363  0.58778666  0.69314718]

References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.log.html#numpy.log.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.