code-rag-bench/online-tutorials huggingface dataset:
Check that a table exists in MySQL?

In order to check a table exists in MySQL, you can use INFORMATION_SCHEMA.TABLES. Let us first create a table −
mysql> create table Client_information
   -> (
   -> Id int,
   -> Name varchar(10)
   -> );
Query OK, 0 rows affected (0.48 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into Client_information values(1,'Larry');
Query OK, 1 row affected (0.14 sec)

mysql> insert into Client_information values(2,'Mike');
Query OK, 1 row affected (0.17 sec)

mysql> insert into Client_information values(3,'Sam');
Query OK, 1 row affected (0.19 sec)
Following is the query to display all records from the table using select statement −
mysql> select * from Client_information;
This will produce the following output −
+------+-------+
| Id   | Name  |
+------+-------+
| 1    | Larry |
| 2    | Mike  |
| 3    | Sam   |
+------+-------+
3 rows in set (0.00 sec)
Following is the query to check that a table exists in MySQL or not −
mysql> select * from information_schema.tables where table_name='Client_information';
Following output states, the table “Client_information“exist −
+---------------+--------------+--------------------+------------+--------+---------+------------+------------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------------+
| TABLE_CATALOG | TABLE_SCHEMA | TABLE_NAME         | TABLE_TYPE | ENGINE | VERSION | ROW_FORMAT | TABLE_ROWS | AVG_ROW_LENGTH | DATA_LENGTH | MAX_DATA_LENGTH | INDEX_LENGTH | DATA_FREE | AUTO_INCREMENT | CREATE_TIME | UPDATE_TIME | CHECK_TIME | TABLE_COLLATION | CHECKSUM | CREATE_OPTIONS | TABLE_COMMENT |
+---------------+--------------+--------------------+------------+--------+---------+------------+------------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------------+
| def           | sample       | client_information | BASE TABLE | InnoDB | 10      | Dynamic    | 4          | 4096           | 16384       | 0 | 0 | 0 | NULL | 2019-03-11 20:02:40 | NULL | NULL | utf8_general_ci | NULL | | |
| def           | test         | client_information | BASE TABLE | InnoDB | 10      | Dynamic    | 3          | 5461           | 16384       | 0 | 0 | 0 | NULL | 2019-04-03 02:28:31 | 2019-04-03 02:29:00 | NULL | utf8mb4_0900_ai_ci | NULL | | |
+---------------+--------------+--------------------+------------+--------+---------+------------+------------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+---------------------+------------+--------------------+----------+----------------+---------------+
2 rows in set (0.13 sec)
Java program to count occurrences of a word in string

The number of times a word occurs in a string denotes its occurrence count. An example of this is given as follows −
String = An apple is red in colour.
Word = red
The word red occurs 1 time in the above string.
A program that demonstrates this is given as follows.
 Live Demo
public class Example {
public static void main(String args[]) {
String string = "Spring is beautiful but so is winter";
String word = "is";
String temp[] = string.split(" ");
int count = 0;
for (int i = 0; i < temp.length; i++) {
if (word.equals(temp[i]))
count++;
}
System.out.println("The string is: " + string);
System.out.println("The word " + word + " occurs " + count + " times in the above string");
}
}
The string is: Spring is beautiful but so is winter
The word is occurs 2 times in the above string
Now let us understand the above program.
The values of the string and word are provided. Then the string is split by spaces in temp. A for loop is used to find if the word is available in temp. Each time it happens, count is incremented by 1. The code snippet that demonstrates this is given as follows −
String string = "Spring is beautiful but so is winter";
String word = "is";
String temp[] = string.split(" ");
int count = 0;
for (int i = 0; i < temp.length; i++) {
if (word.equals(temp[i]))
count++;
}
The string and the value of count i.e. number of times the word occurs in string is displayed. The code snippet that demonstrates this is given as follows −
System.out.println("The string is: " + string);
System.out.println("The word " + word + " occurs " + count + " times in the above string");
Math pow() method in Java with Example - GeeksforGeeks

20 Sep, 2019
The java.lang.Math.pow() is used to calculate a number raise to the power of some other number. This function accepts two parameters and returns the value of first parameter raised to the second parameter. There are some special cases as listed below:
If the second parameter is positive or negative zero then the result will be 1.0.
If the second parameter is 1.0 then the result will be same as that of the first parameter.
If the second parameter is NaN then the result will also be NaN.
Syntax:
public static double pow(double a, double b)
Parameter:
a : this parameter is the base
b : this parameter is the exponent.
Return :
This method returns ab.

Example 1: To show working of java.lang.Math.pow() method.
// Java program to demonstrate working// of java.lang.Math.pow() method  import java.lang.Math;  class Gfg {      // driver code    public static void main(String args[])    {        double a = 30;        double b = 2;        System.out.println(Math.pow(a, b));          a = 3;        b = 4;        System.out.println(Math.pow(a, b));          a = 2;        b = 6;        System.out.println(Math.pow(a, b));    }}
Output:
900.0
81.0
64.0

Example 2: To show working of java.lang.Math.pow() method when argument is NaN.
// Java program to demonstrate working// of java.lang.Math.pow() methodimport java.lang.Math; // importing java.lang package  public class GFG {    public static void main(String[] args)    {          double nan = Double.NaN;        double result;          // Here second argument is NaN,        // output will be NaN        result = Math.pow(2, nan);        System.out.println(result);          // Here second argument is zero        result = Math.pow(1254, 0);        System.out.println(result);          // Here second argument is one        result = Math.pow(5, 1);        System.out.println(result);    }}
Output:
NaN
1.0
5.0

Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
Singleton Class in Java
Set in Java
Multithreading in Java
LinkedList in Java
Collections in Java
Overriding in Java
Different ways of Reading a text file in Java
Initializing a List in Java
Stream In Java
Create empty array of a given size in JavaScript

To create an empty array of given size, use the new operator −
var numberArray = new Array(10);
After that, let’s set some values in the array. Following is the code −
var numberArray = new Array(10);
console.log("The length="+numberArray.length)
numberArray=[10,20,30,40,50,60];
console.log("The array value=");
for(var i=0;i<numberArray.length;i++)
console.log(numberArray[i]);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo52.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo52.js
The length=10
The array value=
10
20
30
40
50
60
Python - Group similar value list to dictionary - GeeksforGeeks

06 Mar, 2020
Sometimes, while working with Python list, we can have a problem in which we need to group similar value lists indices to values into a dictionary. This can have a good application in domains in which we need grouped dictionary as output for pair of lists. Lets discuss certain ways in which this task can be performed.
Method #1 : Using dictionary comprehensionThis is way in which this task can be performed. In this, we iterate one list along with other and keep constructing dictionary with similar key from one list and corresponding values from other. This is one liner solution.
# Python3 code to demonstrate # Group similar value list to dictionary# using dictionary comprehension  # Initializing liststest_list1 = [4, 4, 4, 5, 5, 6, 6, 6, 6]test_list2 = ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Group similar value list to dictionary# using dictionary comprehensionres = {key : [test_list2[idx]       for idx in range(len(test_list2)) if test_list1[idx]== key]      for key in set(test_list1)}  # printing result print ("Mapped resultant dictionary : " + str(res))
The original list 1 is : [4, 4, 4, 5, 5, 6, 6, 6, 6]The original list 2 is : [‘G’, ‘f’, ‘g’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’]Mapped resultant dictionary : {4: [‘G’, ‘f’, ‘g’], 5: [‘i’, ‘s’], 6: [‘b’, ‘e’, ‘s’, ‘t’]}
 
Method #2 : Using defaultdict() + loopThis is yet another way in which this task can be performed. In this we avoid testing for keys presence in dictionary by creating a defaultdict().
# Python3 code to demonstrate # Group similar value list to dictionary# using defaultdict() + loopfrom collections import defaultdict  # Initializing liststest_list1 = [4, 4, 4, 5, 5, 6, 6, 6, 6]test_list2 = ['G', 'f', 'g', 'i', 's', 'b', 'e', 's', 't']  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Group similar value list to dictionary# using defaultdict() + loopres = defaultdict(set)for key, val in zip(test_list1, test_list2):    res[key].add(val)res = {key: list(val) for key, val in res.items()}  # printing result print ("Mapped resultant dictionary : " + str(res))
The original list 1 is : [4, 4, 4, 5, 5, 6, 6, 6, 6]The original list 2 is : [‘G’, ‘f’, ‘g’, ‘i’, ‘s’, ‘b’, ‘e’, ‘s’, ‘t’]Mapped resultant dictionary : {4: [‘G’, ‘f’, ‘g’], 5: [‘i’, ‘s’], 6: [‘b’, ‘e’, ‘s’, ‘t’]}
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to create a combo box with auto-completion in Tkinter?

Tkinter Combobox widget is one of the useful widgets to implement dropdown menus in an application. It uses the combination of the Entry widget and ListBox widget on the top of it. We can select Menu items by typing the item name (if it exists in the Menu List) in the Entry field. However, sometimes, there might be cases when we need to use autocompletion to select the menu items.
In order to create an auto-completion Combobox, we will create a Listbox first to list out the menus and an Entry widget to display the selected Menu. You can bind the "Keyrelease" event with the entry widget to search for a particular keyword in the list. If the item exists, we will update the Listbox widget.
In this example, we will create two functions such that,
A function check(e) will find if the entered item exists in the list or not. If the item matches with the entered keyword, we will update the Entry widget by inserting the particular data.
A function update(data) will update the Entry box by inserting the value in the Entry widget.
# Import the Required libraries
from tkinter import *
from tkinter import ttk

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

# Set the size of the window
win.geometry("700x350")

# Set the title of the window
win.title("Combobox- TutorialsPoint")

# Update the Entry widget with the selected item in list
def check(e):
   v= entry.get()
      if v=='':
      data= values
   else:
      data=[]
      for item in values:
         if v.lower() in item.lower():
            data.append(item)
   update(data)

def update(data):
   # Clear the Combobox
   menu.delete(0, END)
   # Add values to the combobox
   for value in data:
      menu.insert(END,value)


# Add a Label widget
label= Label(win, text= "Demo Combobox Widget", font= ('Helvetica 15
bold'), background= "green3")
label.pack(padx= 10, pady= 25)

# Add a Bottom Label
text= Label(win, text="Select a Programming Language")
text.pack(padx= 15,pady= 20)

# Create an Entry widget
entry= Entry(win, width= 35)
entry.pack()
entry.bind('<KeyRelease>',check)

# Create a Listbox widget to display the list of items
menu= Listbox(win)
menu.pack()

# Create a list of all the menu items
values= ['Python', 'C++', 'Java','Ruby on Rails', 'Rust',
'GoLang','Objective-C', 'C# ', 'PHP', 'Swift', 'JavaScript']

# Add values to our combobox
update(values)

# Binding the combobox onclick

win.mainloop()
Running the above Python script will display a window with an Entry widget and a ListBox. Whenever we enter a Keyword, it will update the ListBox widget showing the result that matches with the entered keyword.
How do I know if Python has pandas installed?

To check whether the pandas package is installed or not in python we can simply verify the version. To get the version details of pandas we have two options.
The first one is using the __version__ attribute.
import pandas as pd
print(pd.__version__)
To verify the version number of pandas, we can use this __version__ built-in attribute provided by pandas, this will return you the number specifying which version of pandas we have.
1.1.5
The number 1.1.5 represents the version of pandas that is already available.
The second way is using the pandas show_versions() method.
print(pd.show_versions())
show_versions() is a pandas method that will not only give you the information about pandas version, it also provides the details about versions of python and pandas dependent packages and OS Type.
INSTALLED VERSIONS
------------------
commit            : b5958ee1999e9aead1938c0bba2b674378807b3d
python            : 3.8.3.final.0
python-bits       : 32
OS                : Windows
OS-release        : 10 
Version           : 10.0.19041
machine           : AMD64
processor         : Intel64 Family 6 Model 78 Stepping 3, GenuineIntel
byteorder         : little
LC_ALL            : None
LANG              : None
LOCALE            : English_United States.1252

pandas            : 1.1.5
NumPy             : 1.19.4
pytz              : 2020.1
dateutil          : 2.8.1
pip               : 20.3.3
setuptools        : 41.2.0
Cython            : None
pytest            : None
hypothesis        : None
sphinx            : None
blosc             : None
feather           : None
xlsxwriter        : None
lxml.etree        : None
html5lib          : None
pymysql           : None
psycopg2          : None
jinja2            : 2.11.2
IPython           : 7.19.0
pandas_datareader : None
bs4               : None
bottleneck        : None
fsspec            : None
fastparquet       : None
gcsfs             : None
matplotlib        : 3.3.3
numexpr           : None
odfpy             : None
openpyxl          : None
pandas_gbq        : None
pyarrow           : None
pytables          : None
pyxlsb            : None
s3fs              : None
scipy             : 1.5.4
sqlalchemy        : None
tables            : None
tabulate          : None
xarray            : None
xlrd              : None
xlwt              : None
numba             : None
The above block represents the version of all pandas dependents and python.
You will find an error message if we don’t have the pandas package. The error message will be like this.
ModuleNotFoundError
The above error will rise when python cannot successfully import a module. In our situation, there may be a chance that we have not yet installed the pandas package or it may be a spelling mistake.
If you found this above error, then install the pandas package. These are the two ways to identify if pandas installed or not.
C++ Stack Library - empty() Function

The C++ function std::stack::empty() tests whether stack is empty or not. Stack of zero size is considered as empty stack.
Following is the declaration for std::stack::empty() function form std::stack header.
bool empty() const;

None
Returns true if stack is empty otherwise false.
Provides no-throw guarantee for standard container.
Constant i.e. O(1)
The following example shows the usage of std::stack::empty() function.
#include <iostream>
#include <stack>

using namespace std;

int main(void) {
   stack<int> s;

   if (s.empty())
      cout << "Stack is empty." << endl;

   s.emplace(1);

   if (!s.empty())
      cout << "Stack is not empty." << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
Stack is empty.
Stack is not empty.

 Print
 Add Notes
 Bookmark this page
LEX code to extract HTML tags from a file - GeeksforGeeks

28 Aug, 2019
Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt.Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.Prerequisite: Flex (Fast lexical Analyzer Generator)
Approach:The extraction is based on the way tags are written in HTML. All tags are included in < >. This will set the rule to extract the HTML tags from the given input file.
Input File: tags.txt
Below is the implementation to extract HTML tags from file:
/* Declaration section*/%{%}  %%"<"[^>]*> {printf("%s\n", yytext); }  /* if anything enclosed in                                       these < > occur print text*/. ;  // else do nothing%%      int yywrap(){}       int main(int argc, char*argv[]){    // Open tags.txt in read mode    extern FILE *yyin = fopen("tags.txt","r");       // The function that starts the analysis    yylex();       return 0;}
Output :
nidhi_biet
Lex program
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Smart Pointers in C++ and How to Use Them
Understanding "extern" keyword in C
Multiple Inheritance in C++
Ways to copy a vector in C++
How to split a string in C/C++, Python and Java?
Program to find Nth term of series 0, 10, 30, 60, 99, 150, 210, 280........... - GeeksforGeeks

15 Mar, 2021
Given a number N. The task is to write a program to find the Nth term of the below series: 
0, 10, 30, 60, 99, 150, 210, 280.....(N Terms)
Examples:  
Input: N = 4
Output: 60
For N = 4
4th Term = ( 5 * 4 * 4 - 5 * 4) 
         = 60

Input: N = 10
Output: 449
 
Approach: The generalized Nth term of this series:  
 
Below is the required implementation:  
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find the N-th term of the series:// 0, 10, 30, 60, 99, 150, 210, .....#include <iostream>#include <math.h>using namespace std; // calculate Nth term of seriesint nthTerm(int n){    return 5 * pow(n, 2) - 5 * n;} // Driver codeint main(){    int N = 4;     cout << nthTerm(N) << endl;     return 0;}
// Java program to find the N-th term of the series:// 0, 10, 30, 60, 99, 150, 210, .....import java.util.*; class solution{ // calculate Nth term of seriesstatic int nthTerm(int n){    return 5 * (int)Math.pow(n, 2) - 5 * n;} //Driver codepublic static void main(String arr[]){       int N = 4;     System.out.println(nthTerm(N) ); }} //This code is contributed by Surendra_Gangwar
# Python3 program to find the# N-th term of the series:# 0, 10, 30, 60, 99, 150, 210, ..... # calculate Nth term of seriesdef nthTerm(n):     return 5 * pow(n, 2) - 5 * n # Driver codeN = 4print(nthTerm(N)) # This code is contributed by# Sanjit_Prasad
// C# program to find the// N-th term of the series:// 0, 10, 30, 60, 99, 150, 210, .....using System; class GFG{ // calculate Nth term of seriesstatic int nthTerm(int n){    return 5 * (int)Math.Pow(n, 2) - 5 * n;} // Driver codepublic static void Main(){    int N = 4;    Console.Write(nthTerm(N));}} // This code is contributed// by ChitraNayal
<?php// PHP program to find the// N-th term of the series:// 0, 10, 30, 60, 99, 150, 210,... // calculate Nth term of seriesfunction nthTerm($n){    return 5 * pow($n, 2) - 5 * $n;} // Driver code$N = 4; echo nthTerm($N); // This code is contributed// by inder_verma?>
<script> // JavaScript program to find the N-th term of the series:// 0, 10, 30, 60, 99, 150, 210, ..... // calculate Nth term of seriesfunction nthTerm( n){    return 5 * Math.pow(n, 2) - 5 * n;} // Driver code let N = 4;    document.write( nthTerm(N) ); // This code contributed by gauravrajput1 </script>
60
 
Time Complexity: O(1) 
Sanjit_Prasad
SURENDRA_GANGWAR
ukasp
inderDuMCA
GauravRajput1
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
Operating Systems | CPU Scheduling | Question 2 - GeeksforGeeks

03 Oct, 2019
Consider three processes, all arriving at time zero, with total execution time of 10, 20 and 30 units, respectively. Each process spends the first 20% of execution time doing I/O, the next 70% of time doing computation, and the last 10% of time doing I/O again. The operating system uses a shortest remaining compute time first scheduling algorithm and schedules a new process either when the running process gets blocked on I/O or when the running process finishes its compute burst. Assume that all I/O operations can be overlapped as much as possible. For what percentage of time does the CPU remain idle?(A) 0%(B) 10.6%
(C) 30.0%
(D) 89.4%
Answer: (B)Explanation: Let three processes be p0, p1 and p2. Their execution time is 10, 20 and 30 respectively. p0 spends first 2 time units in I/O, 7 units of CPU time and finally 1 unit in I/O. p1 spends first 4 units in I/O, 14 units of CPU time and finally 2 units in I/O. p2 spends first 6 units in I/O, 21 units of CPU time and finally 3 units in I/O.
 idle   p0    p1     p2    idle
0    2     9     23     44     47

Total time spent = 47Idle time = 2 + 3 = 5Percentage of idle time = (5/47)*100 = 10.6 %Quiz of this Question
cpu-scheduling
Operating Systems-CPU Scheduling
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Page Replacement Algorithms in Operating Systems
Paging in Operating System
Program for FCFS CPU Scheduling | Set 1
Introduction of Deadlock in Operating System
Program for Round Robin scheduling | Set 1
Introduction of Operating System - Set 1
Semaphores in Process Synchronization
Inter Process Communication (IPC)
Difference between Process and Thread
Program for Shortest Job First (or SJF) CPU Scheduling | Set 1 (Non- preemptive)
How to determine which element the mouse pointer move over using JavaScript ? - GeeksforGeeks

12 Sep, 2019
Given an HTML document and the task is to get the element where mouse pointer moves over. There are two approaches to solve this problem which are discussed below:
Approach 1:
Get the x and y coordinates value by using .clientX and .clientY property.
Use document.elementFromPoint(x, y) method to get the element content on that position when mouse pointer moves over.
Example 1: This example implements the above approach.
<!DOCTYPE HTML> <html>   <head>     <title>         How to determine which element the mouse        pointer move over using JavaScript ?    </title> </head>   <body style = "text-align:center;">           <h1 style = "color:green;" onmouseover = "GFG_Fun()">         GeeksForGeeks     </h1>           <p id = "GFG_UP" onmouseover = "GFG_Fun()"            style = "font-size: 15px; font-weight: bold;">     </p>          <button onmouseover = "GFG_Fun()">         click here     </button>           <p id = "GFG_DOWN" style =         "font-size: 24px; font-weight: bold; color: green;">     </p>          <script>         var up = document.getElementById('GFG_UP');         var down = document.getElementById('GFG_DOWN');         up.innerHTML = "Hover over the document to know the element.";                   function GFG_Fun() {             var x = event.clientX;            var y = event.clientY;            el = document.elementFromPoint(x, y);            down.innerHTML = el.innerHTML;        }     </script> </body>  </html>
Output:
Before Hover on the button:
After Hover on the button:
Approach 2:
Attach the event ‘onmouseover’ to the element.
Call the alert function with the id of that element, each time when event occurs.
Example 2: This example using the approach discussed above.
<!DOCTYPE HTML> <html>   <head>     <title>         How to determine which element the mouse        pointer move over using JavaScript ?    </title> </head>   <body style = "text-align:center;">           <h1 id = "h1" style = "color:green;"            onmouseover = "alert(this.id)">         GeeksForGeeks     </h1>           <p id = "p" onmouseover = "alert(this.id)"            style = "font-size: 15px; font-weight: bold;">         Hover over the document to know the element.    </p>          <button id = "button" onmouseover = "alert(this.id)">         click here     </button> </body>   </html>
Output:
Before Hover on the button:
After Hover on the button:
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
UUID_SHORT() function in MySQL - GeeksforGeeks

22 Dec, 2020
This function in MySQL is used to return a “short” universal identifier as a 64-bit unsigned integer. The value of UUID_SHORT() is guaranteed to be unique if the following conditions hold :
The server_id value of the current server is between 0 and 255 and is unique among our set of source and replica servers.We do not set back the system time for our server host between mysqld restarts.We should invoke UUID_SHORT() on average fewer than 16 million times per second between mysqld restarts.
The server_id value of the current server is between 0 and 255 and is unique among our set of source and replica servers.
We do not set back the system time for our server host between mysqld restarts.
We should invoke UUID_SHORT() on average fewer than 16 million times per second between mysqld restarts.
Syntax :
UUID_SHORT()
Parameter :This method does not any parameter.
Returns :It returns a Universal Unique Identifier number.
Example-1 :Generating a short Universal Unique Identifier value with the help of UUID_SHORT Function.
SELECT UUID_SHORT() AS Short_UUID_Value ;

Output :
Example-2 :Whenever we will use UUID_SHORT function we will get different short Universal Unique Identifier value. Lets check it –
SELECT UUID_SHORT() 
AS  SHORT_UUID_VALUE1, UUID_SHORT() 
AS SHORT_UUID_VALUE2, UUID_SHORT() 
AS SHORT_UUID_VALUE3 ;

Output :
Example-3 :In this example we will use UUID_SHORT as a primary key in a table. To demonstrate create a table named OrderDetails.
CREATE TABLE OrderDetails2(
  OrderId BIGINT PRIMARY KEY,
  ProductName VARCHAR(100) NOT NULL,
  Price DECIMAL(10, 2) NOT NULL,
  ExpectedDelivery DATE NOT NULL
);
Now, inserting data into OrderDetails table. Here, We will use UUID_SHORT functions to assign the value in OrderId Column.
INSERT INTO OrderDetails2(OrderId, ProductName, Price, ExpectedDelivery)
VALUES(UUID_SHORT(), 'Asus Rog', 90000.00, '2020-12-20'),
     (UUID_SHORT(), 'Acer Predator', 100000.00, '2020-12-18'),
     (UUID_SHORT(), 'Lenovo Legion', 85000.00, '2020-12-19'),
     (UUID_SHORT(), 'Hp Omen', 70000.00, '2020-12-18'),
     (UUID_SHORT(), 'Dell Inspiron', 65000.00, '2020-12-23'),
     (UUID_SHORT(), 'Acer Nitro', 60000.00, '2020-12-22'),
     (UUID_SHORT(), 'Asus Tuf', 80000.00, '2020-12-19');
Next we will use the following command to check the table.
SELECT  * from OrderDetails2;

Output :
DBMS-SQL
mysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
Python | Numpy np.digitize() method - GeeksforGeeks

21 Nov, 2019
With the help of np.digitize() method, we can get the indices of the bins to which the each value is belongs to an array by using np.digitize() method.
Syntax : np.digitize(Array, Bin, Right)Return : Return an array of indices of the bins.
Example #1 :In this example we can see that by using np.digitize() method, we are able to get the array of indices of the bin of each value which belongs to an array by using this method.
# import numpyimport numpy as np  a = np.array([1.2, 2.4, 3.6, 4.8])bins = np.array([1.0, 1.3, 2.5, 4.0, 10.0])  # using np.digitize() methodgfg = np.digitize(a, bins)  print(gfg)
Output :
[1 2 3 4]
Example #2 :
# import numpyimport numpy as np  a = np.array([[10.2, 21.4, 3.6, 14.8], [1.0, 5.0, 10.0, 15.0]])bins = np.array([1.0, 1.3, 2.5, 4.0, 10.0])  # using np.digitize() methodgfg = np.digitize(a, bins)  print(gfg)
Output :
[[5 5 3 5][1 4 5 5]]
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
Node.js Stream writable.write() Method - GeeksforGeeks

12 Oct, 2021
The writable.write() method is an inbuilt application programming interface of Stream module which is used to write some data to the Writable stream. The callback function is called once the data has been completely handled.
Syntax:
writable.write( chunk, encoding, callback)
Parameters: This method accepts three parameters as mentioned above and described below:
chunk: It is an optional data to write. The value of chunk must be a string, buffer or Uint8Array. For object mode, the chunk value may be anything other than null.
encoding: It holds the encoding value if chunk is a string value.
callback: It is an optional callback function for stream.
Return Value: It returns false if the ‘drain’ event is emitted before this method otherwise returns true.
Below examples illustrate the use of writable.write() method in Node.js:
Example 1:
// Node.js program to demonstrate the     // writable.write() method    // Including stream moduleconst stream = require('stream');  // Creating a stream and creating // a write functionconst writable = new stream.Writable({    // Write function with its   // parameters  write: function(chunk, encoding, next) {      // Converting the chunk of    // data to string    console.log(chunk.toString());    next();  }});  // Calling write method with// all its parameterwritable.write("GfG", "utf8", () => {     console.log("CS-Portal!");});
Output:
GfG
true
CS-Portal!

Example 2:
// Node.js program to demonstrate the     // writable.write() method    // Including stream moduleconst stream = require('stream');  // Creating a stream and creating // a write functionconst writable = new stream.Writable({    // Write function with its   // parameters  write: function(chunk, encoding, next) {      // Converting the chunk of    // data to string    console.log(chunk.toString());    next();  }});  // Calling write method with one// parameterwritable.write('GeeksforGeeks');
Output:
GeeksforGeeks
true

Reference: https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Express.js res.render() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to import Google Fonts in HTML ? - GeeksforGeeks

14 May, 2019
Choosing the right font for your webpage is a very important aspect of any design. Using a web font service enables you to use a wide variety of fonts fit for presenting the data in your webpage. Google Fonts is a free web font service which hosts a huge variety of fonts to choose from. We can use these fonts in our webpages.
To use a custom font, we need to import the font family from the web font service, Google Fonts, in this case.
Method-1: Using <link> tag
<link href=’https://fonts.googleapis.com/css?family=Sofia’ rel=’stylesheet’/>
Method-2: Using @import rule
@import url(‘https://fonts.googleapis.com/css?family=Poppins’);
Example-1:
<html>  <head>    <link href='https://fonts.googleapis.com/css?family=Sofia'           rel='stylesheet' />    <style>        h1 {            font-family: Sofia;            color: green;        }    </style></head>  <body>    <center>        <h1>GeeksforGeeks</h1>    </center></body>  </html>
Output:Example:
<html>  <head>    <style>        @import url(         https://fonts.googleapis.com/css?family=Open+Sans);        h1 {            font-family: 'Open Sans', serif;            color: green;        }    </style></head>  <body>    <center>        <h1>GeeksforGeeks</h1>    </center></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
How to position a div at the bottom of its container using CSS?
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to Upload Image into Database and Display it using PHP ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Error Detection Code - Checksum - GeeksforGeeks

16 Jul, 2021
Prerequisite – Error Detection in Computer Networks 
Checksum is the error detection method used by upper layer protocols and is considered to be more reliable than LRC, VRC and CRC. This method makes the use of Checksum Generator on Sender side and Checksum Checker on Receiver side. 
At the Sender side, the data is divided into equal subunits of n bit length by the checksum generator. This bit is generally of 16-bit length. These subunits are then added together using one’s complement method. This sum is of n bits. The resultant bit is then complemented. This complemented sum which is called checksum is appended to the end of original data unit and is then transmitted to Receiver. 
 
The Receiver after receiving data + checksum passes it to checksum checker. Checksum checker divides this data unit into various subunits of equal length and adds all these subunits. These subunits also contain checksum as one of the subunits. The resultant bit is then complemented. If the complemented result is zero, it means the data is error-free. If the result is non-zero it means the data contains an error and Receiver rejects it. 
Example – If the data unit to be transmitted is 10101001 00111001, the following procedure is used at Sender site and Receiver site. 
Sender Site : 
 
10101001        subunit 1  
00111001        subunit 2        
11100010        sum (using 1s complement)       
00011101        checksum (complement of sum)
Data transmitted to Receiver is – 
 
Receiver Site : 
 
10101001        subunit 1  
00111001        subunit 2     
00011101        checksum 
11111111        sum
00000000        sum's complement

Result is zero, it means no error.
Advantage : The checksum detects all the errors involving an odd number of bits as well as the error involving an even number of bits. 
Disadvantage : The main problem is that the error goes undetected if one or more bits of a subunit is damaged and the corresponding bit or bits of a subunit are damaged and the corresponding bit or bits of opposite value in second subunit are also damaged. This is because the sum of those columns remains unchanged. 
Example – If the data transmitted along with checksum is 10101001 00111001 00011101. But the data received at destination is 00101001 10111001 00011101. 
Receiver Site : 
 
00101001              1st bit of subunit 1 is damaged
10111001              1st bit of subunit 2 is damaged
00011101              checksum
11111111              sum
00000000              Ok 1's complement
Although data is corrupted, the error is undetected. 
sooda367
Data Link Layer
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advanced Encryption Standard (AES)
Intrusion Detection System (IDS)
Introduction and IPv4 Datagram Header
Secure Socket Layer (SSL)
Cryptography and its Types
Multiple Access Protocols in Computer Network
Congestion Control in Computer Networks
Routing Information Protocol (RIP)
Wireless Sensor Network (WSN)
Architecture of Internet of Things (IoT)
Brutex - Open Source Tool for Brute Force Automation - GeeksforGeeks

23 Sep, 2021
Brutex is a free and open-source tool available on GitHub. This tool is basically made to make the work of penetration tester easier. This tool is a package of three different tools which are Nmap, Hydra, DNSenum. Once you start scanning your target using brutex tool the tool will start scanning using Nmap and after scanning, brutex will force all the open services which can be FTP service or SSH service.
Step 1: Open your kali Linux operating system and use the following command to download the tool from GitHub. Use the second command to move into the directory of the tool.
git clone https://github.com/1N3/BruteX.git
cd BruteX/
Step 2: Now you are in the directory of the tool. Use the following command to install the tool.
./install.sh
The tool has been installed and running successfully. Now we will see examples to use the tool.
Use the Brutex tool to bruteforce an IP address:
brutex <ip address>
You can see that we have used brutex on a vulnerable Ipaddress. The tool started scanning the IP address and after that, the tool has started brute-forcing and found passwords of some administrators 
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
Logic Gates in Python

In this article, we will learn about Logic Gates in Python. Let’s look at each of the logic gates in Python in detail with some easy examples.
All of us are quite familiar while implementing logic gates in the processing of electrical signals and are widely used in the electrical and electronics industry. They are used in the diodes and transistors so that we can design by proper alignment of these electronic devices. In this article we will learn about the implementation of some basic gates ‘and‘, ‘or‘ ,’not‘ , ‘nand‘ ,’nor‘ in Python 3.x or earlier.
These gates can be implemented by using user-defined functions designed in accordance with that of the truth table associated with the respective gate.
def AND (a, b):
   if a == 1 and b == 1:
      return True
   else:
      return False

# main function
if __name__=='__main__':
   print(AND(0,0))
   print(AND(1,0))
   print(AND(0,1))
   print(AND(1,1))
False
False
False
True
def OR(a, b):
   if a == 1:
      return True
   elif b == 1:
      return True
   else:
      return False
# main function
if __name__=='__main__':
   print(OR(0,0))
   print(OR(1,0))
   print(OR(0,1))
   print(OR(1,1))
False
True
True
True
def NOT(a):
   if(a == 0):
      return 1
   elif(a == 1):
      return 0

# main function
if __name__=='__main__':
   print(OR(0))
   print(OR(1))
True
False
def NAND (a, b):
   if a == 1 and b == 1:
      return False
   else:
      return True

# main function
if __name__=='__main__':
   print(NAND(0,0))
   print(NAND(1,0))
   print(NAND(0,1))
   print(NAND(1,1))
True
True
True
False
def NOR(a, b):
   if(a == 0) and (b == 0):
      return True
   elif(a == 0) and (b == 1):
      return False
   elif(a == 1) and (b == 0):
      return False
   elif(a == 1) and (b == 1):
      return False

# main function
if __name__=='__main__':
   print(NOR(0,0))
   print(NOR(1,0))
   print(NOR(0,1))
   print(NOR(1,1))
True
False
False
False
In this article, we learned how to implement logic gates in Python 3.x. Or
earlier. We also learned about two universal gates i.e. NAND and NOR gates.
How to Change a Dictionary Into a Class?

29 Dec, 2020
Working with Dictionary is a good thing but when we get a lot of dictionaries then it gets tough to use. So let’s understand how we can convert a dictionary into a class.
Let’s take a simple dictionary “my_dict” which has the Name, Rank, and Subject as my Keys and they have the corresponding values as Geeks, 1223, Python. We are calling a function here Dict2Class which takes our dictionary as an input and converts it to class. We then loop over our dictionary by using setattr() function to add each of the keys as attributes to the class. 
setattr() is used to assign the object attribute its value. Apart from ways to assign values to class variables, through constructors and object functions, this method gives you an alternative way to assign value.
Syntax : setattr(obj, var, val)
Parameters :obj : Object whose which attribute is to be assigned.var : object attribute which has to be assigned.val : value with which variable is to be assigned.
Returns :None
Below is the implementation.
Python3
# Turns a dictionary into a classclass Dict2Class(object):          def __init__(self, my_dict):                  for key in my_dict:            setattr(self, key, my_dict[key])  # Driver Codeif __name__ == "__main__":          # Creating the dictionary    my_dict = {"Name": "Geeks",               "Rank": "1223",               "Subject": "Python"}          result = Dict2Class(my_dict)          # printing the result    print("After Converting Dictionary to Class : ")    print(result.Name, result.Rank, result.Subject)    print(type(result))
Output:
After Converting Dictionary to Class : 
Geeks 1223 Python
<class '__main__.Dict2Class'>

Picked
Python Oops-programs
python-dict
Python-OOP
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
PyQt5 QSlider | Python

27 Sep, 2019
Slider in PyQt5 is used to set a value with the help of an indicator which can move back and forth over a graphical slide or bar. Many times one needs to provide values which lie between a range and in such cases slider is very useful. QSlider is the class used to add slider in an application.
Example:
A window has a slider and a label(QSlider). The size of the text gets scaled in or out as one move the indicator of the slider.
from PyQt5 import QtCore, QtGui, QtWidgetsimport sys  class Ui_MainWindow(object):      def setupUi(self, MainWindow):          MainWindow.resize(550, 393)        self.centralwidget = QtWidgets.QWidget(MainWindow)        self.centralwidget.setObjectName("centralwidget")          self.slider = QtWidgets.QSlider(self.centralwidget)        self.slider.setGeometry(QtCore.QRect(190, 100, 160, 16))        self.slider.setOrientation(QtCore.Qt.Horizontal)          # After each value change, slot "scaletext" will get invoked.        self.slider.valueChanged.connect(self.scaletext)          self.label = QtWidgets.QLabel(self.centralwidget)        self.label.setGeometry(QtCore.QRect(230, 150, 301, 161))                  # set initial font size of label.        self.font = QtGui.QFont()        self.font.setPointSize(7)        self.label.setFont(self.font)        MainWindow.setCentralWidget(self.centralwidget)          self.retranslateUi(MainWindow)        QtCore.QMetaObject.connectSlotsByName(MainWindow)      def retranslateUi(self, MainWindow):        _translate = QtCore.QCoreApplication.translate        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))        self.label.setText(_translate("MainWindow", "QSlider"))              def scaletext(self, value):        # Change font size of label. Size value could         # be anything consistent with the dimension of label.        self.font.setPointSize(7 + value//2)        self.label.setFont(self.font)            if __name__ == "__main__":     app = QtWidgets.QApplication(sys.argv)         MainWindow = QtWidgets.QMainWindow()     ui = Ui_MainWindow()     ui.setupUi(MainWindow)     MainWindow.show()     sys.exit(app.exec_()) 
Output:
Python-gui
Python-PyQt
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
Python OOPs Concepts
Introduction To PYTHON