code-rag-bench/online-tutorials huggingface dataset:
C++ Program for How to check if a given number is Fibonacci number? - GeeksforGeeks

14 Jan, 2022
Given a number ‘n’, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 141, .. Examples : 
Input : 8
Output : Yes

Input : 34
Output : Yes

Input : 41
Output : No
Following is an interesting property about Fibonacci numbers that can also be used to check if a given number is Fibonacci or not. A number is Fibonacci if and only if one or both of (5*n2 + 4) or (5*n2 – 4) is a perfect square (Source: Wiki). 
CPP
// C++ program to check if x is a perfect square#include <iostream>#include <math.h>using namespace std; // A utility function that returns true if x is perfect squarebool isPerfectSquare(int x){    int s = sqrt(x);    return (s * s == x);} // Returns true if n is a Fibonacci Number, else falsebool isFibonacci(int n){    // n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both    // is a perfect square    return isPerfectSquare(5 * n * n + 4) || isPerfectSquare(5 * n * n - 4);} // A utility function to test above functionsint main(){    for (int i = 1; i <= 10; i++)        isFibonacci(i) ? cout << i << " is a Fibonacci Number \n"                       : cout << i << " is a not Fibonacci Number \n";    return 0;}
1 is a Fibonacci Number 
2 is a Fibonacci Number 
3 is a Fibonacci Number 
4 is a not Fibonacci Number 
5 is a Fibonacci Number 
6 is a not Fibonacci Number 
7 is a not Fibonacci Number 
8 is a Fibonacci Number 
9 is a not Fibonacci Number 
10 is a not Fibonacci Number
 
Please refer complete article on How to check if a given number is Fibonacci number? for more details!
varshagumber28
simranarora5sos
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Handling the Divide by Zero Exception in C++
Hamming code Implementation in C/C++
Different ways to print elements of vector
Dynamic _Cast in C++
isdigit() function in C/C++ with Examples
Student record management system using linked list
Literals in C#

The fixed values are called literals. The constants refer to fixed values that the program may not alter during its execution.
Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, or a string literal. There are also enumeration constants as well.
Let us learn about integer, float, and string literals in C# −
An integer literal can be a decimal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, and there is no prefix id for decimal.
Here are some example of Integer Literals −
20 // int
30u // unsigned int
30l // long
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part. You can represent floating point literals either in decimal form or exponential form.
Here are some examples of Float Literals −
2.64734
314159E-5F
String literals or constants are enclosed in double quotes "" or with @"". A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters.
Here are some examples of String Literals −
Hello, World"
"Welcome, \
LocalTime plusMinutes() method in Java with Examples - GeeksforGeeks

04 Dec, 2018
The plusMinutes() method of LocalTime class is used to add specified number of Minutes value to this LocalTime and return the result as a LocalTime object. This instant is immutable. The calculation wraps around midnight.
Syntax:
public LocalTime plusMinutes(long MinutesToAdd)

Parameters: This method accepts a single parameter MinutesToAdd which is the value of Minutes to be added, it can be a negative value.
Return value: This method returns a LocalTime based on this time with the Minutes added.
Below programs illustrate the plusMinutes() method:
Program 1:
// Java program to demonstrate// LocalTime.plusMinutes() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalTime object        LocalTime time            = LocalTime.parse("19:34:50.63");          // print LocalTime        System.out.println("LocalTime before addition: "                           + time);          // add 55 Minutes using plusMinutes()        LocalTime value = time.plusMinutes(55);          // print result        System.out.println("LocalTime after addition: "                           + value);    }}
LocalTime before addition: 19:34:50.630
LocalTime after addition: 20:29:50.630

Program 2:
// Java program to demonstrate// LocalTime.plusMinutes() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create a LocalTime object        LocalTime time            = LocalTime.parse("01:00:01");          // print LocalTime        System.out.println("LocalTime before addition: "                           + time);          // add -600 Minutes using plusMinutes()        LocalTime value = time.plusMinutes(-600);          // print result        System.out.println("LocalTime after addition: "                           + value);    }}
LocalTime before addition: 01:00:01
LocalTime after addition: 15:00:01

References: https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#plusMinutes(long)
Java-Functions
Java-LocalTime
Java-time package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java
Playit

#myDIV {  background-color:lightblue;  transform:scaleY(1.1);}
GATE | GATE-CS-2004 | Question 82 - GeeksforGeeks

04 Feb, 2019
Let A[1, ..., n] be an array storing a bit (1 or 0) at each location, and f(m) is a function whose time complexity is θ(m). Consider the following program fragment written in a C like language:
counter = 0;for (i = 1; i < = n; i++){       if (A[i] == 1)          counter++;      else {         f(counter);          counter = 0;      }}
The complexity of this program fragment is(A) Ω(n2)(B) Ω(nlog n) and O(n2)(C) θ(n)(D) O(n)Answer: (C)Explanation: Please note that inside the else condition, f() is called first, then counter is set to 0.
Consider the following cases:
a) All 1s in A[]: Time taken is Θ(n) as
                  only counter++ is executed n times.

b) All 0s in A[]: Time taken is Θ(n) as
                  only f(0) is called n times

c) Half 1s, then half 0s: Time taken is  Θ(n) as
                  only f(n/2) is called once.
Quiz of this Question
OnkarMarbhal
GATE-CS-2004
GATE-GATE-CS-2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE CS 2011 | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2012 | Question 65
How can I create MySQL stored procedure with IN parameter?

To make it understand we are using the table named ‘student_info’ which have the following values −
mysql> Select * from student_info;
+-----+---------+------------+------------+
| id  | Name    | Address    | Subject    |
+-----+---------+------------+------------+
| 101 | YashPal | Amritsar   | History    |
| 105 | Gaurav  | Jaipur     | Literature |
| 110 | Rahul   | Chandigarh | History    |
| 125 | Raman   | Shimla     | Computers  |
+------+--------+------------+------------+
4 rows in set (0.00 sec)
Now, with the help of the following query, we will create a stored procedure with IN parameter which will show all the details of a particular student by providing the name as the parameter.
mysql> DELIMITER // ;
mysql> Create PROCEDURE detail(IN S_Name VARCHAR(20))
    -> BEGIN
    -> SELECT * From Student_info WHERE Name = S_Name;
    -> END //
Query OK, 0 rows affected (0.16 sec)
mysql> DELIMITER ;
S_Name is the IN parameter of the stored procedure ‘detail’. If we want to see all the details of the student name ‘Gaurav’ then it can be done with the help of the following query −
mysql> CALL detail('Gaurav');
+-----+--------+---------+------------+
| id  | Name   | Address | Subject    |
+-----+--------+---------+------------+
| 105 | Gaurav | Jaipur  | Literature |
+-----+--------+---------+------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)

mysql> CALL detail('Raman');
+-----+-------+---------+-----------+
| id  | Name  | Address | Subject   |
+-----+-------+---------+-----------+
| 125 | Raman | Shimla  | Computers |
+-----+-------+---------+-----------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.01 sec)
C++ Vector Library - pop_back() Function

The C++ function std::vector::pop_back() removes last element from vector and reduces size of vector by one.
Following is the declaration for std::vector::pop_back() function form std::vector header.
void pop_back();

None
None
This member function never throws exception. Calling this function on empty vector causes undefined behavior.
Constant i.e. O(1)
The following example shows the usage of std::vector::pop_back() function.
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 3, 4, 5};

   /* Remove last three elements */
   v.pop_back();
   v.pop_back();
   v.pop_back();

   for (int i = 0; i < v.size(); ++i)
      cout << v[i] << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
1
2

 Print
 Add Notes
 Bookmark this page
How do I close all the open pyplot windows (Matplotlib)?

plt.figure().close(): Close a figure window.
close() by itself closes the current figure
close(h), where h is a Figure instance, closes that figure
close(num) closes the figure with number=num
close(name), where name is a string, closes the figure with that label
close('all') closes all the figure windows
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot()
plt.show()
plt.close()
Now, swap the statements "plt.show()" and "plt.close()" in the code. You wouldn't get to see any plot as the output because the plot would already have been closed.
How to create a new thread in Python - GeeksforGeeks

30 Sep, 2021
Threads in python are an entity within a process that can be scheduled for execution. In simpler words, a thread is a computation process that is to be performed by a computer. It is a sequence of such instructions within a program that can be executed independently of other codes.
In Python, there are two ways to create a new Thread. In this article, we will also be making use of the threading module in Python. Below is a detailed list of those processes:
Below has a coding example followed by the code explanation for creating new threads using class in python.  
Python3
# import the threading moduleimport threading class thread(threading.Thread):    def __init__(self, thread_name, thread_ID):        threading.Thread.__init__(self)        self.thread_name = thread_name        self.thread_ID = thread_ID         # helper function to execute the threads    def run(self):        print(str(self.thread_name) +" "+ str(self.thread_ID)); thread1 = thread("GFG", 1000)thread2 = thread("GeeksforGeeks", 2000); thread1.start()thread2.start() print("Exit")
Output: 
GFG 1000
GeeksforGeeks 2000
Exit
Now let’s look into what we did up there in the code.  
We created a sub-class of the thread class.Then we override the __init__ function of the thread class.Then we override the run method to define the behavior of the thread.The start() method starts a Python thread. 
We created a sub-class of the thread class.
Then we override the __init__ function of the thread class.
Then we override the run method to define the behavior of the thread.
The start() method starts a Python thread. 
The below code shows the creation of new thread using a function:  
Python3
from threading import Threadfrom time import sleep # function to create threadsdef threaded_function(arg):    for i in range(arg):        print("running")                 # wait 1 sec in between each thread        sleep(1)  if __name__ == "__main__":    thread = Thread(target = threaded_function, args = (10, ))    thread.start()    thread.join()    print("thread finished...exiting")
Output: 
running
running
running
running
running
running
running
running
running
running
thread finished...exiting
So what we did in the above code, 
We defined a function to create a thread.Then we used the threading module to create a thread that invoked the function as its target.Then we used start() method to start the Python thread.  
We defined a function to create a thread.
Then we used the threading module to create a thread that invoked the function as its target.
Then we used start() method to start the Python thread.  
 
ayushharwani2011
sarveshad65
Python-threading
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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Create a DataFrame from a Numpy array and specify the index column and column headers - GeeksforGeeks

28 Jul, 2020
Let us see how to create a DataFrame from a Numpy array. We will also learn how to specify the index and the column headers of the DataFrame.
Approach :
Import the Pandas and Numpy modules.Create a Numpy array.Create list of index values and column values for the DataFrame.Create the DataFrame.Display the DataFrame.
Import the Pandas and Numpy modules.
Create a Numpy array.
Create list of index values and column values for the DataFrame.
Create the DataFrame.
Display the DataFrame.
Example 1 :
# importiong the modulesimport pandas as pdimport numpy as np  # creating the Numpy arrayarray = np.array([[1, 1, 1], [2, 4, 8], [3, 9, 27],                   [4, 16, 64], [5, 25, 125], [6, 36, 216],                   [7, 49, 343]])  # creating a list of index namesindex_values = ['first', 'second', 'third',                'fourth', 'fifth', 'sixth', 'seventh']   # creating a list of column namescolumn_values = ['number', 'squares', 'cubes']  # creating the dataframedf = pd.DataFrame(data = array,                   index = index_values,                   columns = column_values)  # displaying the dataframeprint(df)
Output :
Example 2 :
# importiong the modulesimport pandas as pdimport numpy as np  # creating the Numpy arrayarray = np.array([['Aditya', 20], ['Samruddhi', 15],                  ['Rohan', 21], ['Anantha', 20],                   ['Abhinandan', 21]])  # creating a list of index namesindex_values = ['A', 'B', 'C', 'D', 'E']   # creating a list of column namescolumn_values = ['Names', 'Age']  # creating the dataframedf = pd.DataFrame(data = array,                   index = index_values,                   columns = column_values)  # displaying the dataframeprint(df)
Output :
Example 3 :
# importiong the modulesimport pandas as pdimport numpy as np  # creating the Numpy arrayarray = np.array([['CEO', 20, 5], ['CTO', 22, 4.5],                   ['CFO', 21, 3], ['CMO', 24, 2]])  # creating a list of index namesindex_values = [1, 2, 3, 4]   # creating a list of column namescolumn_values = ['Names', 'Age',                  'Net worth in Millions']  # creating the dataframedf = pd.DataFrame(data = array,                   index = index_values,                   columns = column_values)  # displaying the dataframeprint(df)
Output :
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
*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
How To Convert Python Dictionary To JSON?
Python | Pandas DatetimeIndex.to_frame() - GeeksforGeeks

29 Dec, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas DatetimeIndex.to_frame() function create a DataFrame with a column containing the Index. By default the labels of the DatetimeIndex object is used as an index for the newly constructed Dataframe.
Syntax: DatetimeIndex.to_frame(index=True)
Parameters :index : Set the index of the returned DataFrame as the original Index
Return : DataFrame containing the original Index data.
Example #1: Use DatetimeIndex.to_frame() function to create a DataFrame object from the given DatetimeIndex object. Also set the index value to False
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'S' represents secondly frequency didx = pd.DatetimeIndex(start ='2018-11-15 09:45:10', freq ='S', periods = 5)  # Print the DatetimeIndexprint(didx)
Output :
Now we want to construct a DataFrame out of the DatetimeIndex object.
# construct the DataFramedidx.to_frame(index = False)
Output :As we can see in the output, the function has returned a DataFrame object constructed from the didx DatetimeIndex object. Example #2: Use DatetimeIndex.to_frame() function to create a DataFrame object from the given DatetimeIndex object.
# importing pandas as pdimport pandas as pd  # Create the DatetimeIndex# Here 'M' represents monthly frequency didx = pd.DatetimeIndex(start ='2015-03-02', freq ='M', periods = 5)  # Print the DatetimeIndexprint(didx)
Output :
Now we want to construct a DataFrame out of the DatetimeIndex object.
# construct the DataFramedidx.to_frame(index = True)
Output :As we can see in the output, the function has returned a DataFrame object constructed from the didx DatetimeIndex object.
Python pandas-datetimeIndex
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
How to Install Linux on Windows PowerShell Subsystem? - GeeksforGeeks

06 Oct, 2021
There are several ways to Install a Linux subsystem on your Windows PC Powershell Environment. It is good for learners, but it is recommended using original Linux OS if you are a developer as the Subsystem lacks the pre-installed Linux tools.
Before we begin installing a Linux subsystem, we need to first enable a Windows feature for Subsystems.
To install Linux Subsystem, there is a need to Turn Windows features ON. Steps to do the same are as follows:
Step 1: Search and open Turn Windows features on or off in Start Menu. Step 2: Look for Windows Subsystem for Linux and enable it. Step 3: Once the installation is over, reboot your system to finish adding the changes. Downloading and Installing Linux OS:There are two ways to download and install any Linux OS in the Windows Subsystem:
Downloading from the Microsoft Store
Downloading using Windows PowerShell
Step 1: Open MS Store and search for Linux. Now, download any of the listed Linux OSs. Step 2: Click on the Get button and begin with the downloading of Kali Linux OS. Step 3: Once the Installation is over click on the Launch button. Step 4: Begin with the final installation process on the command-line. Step 5: Provide a Username and password for your Linux OS and finish the installation process.
Step 1: Search for Windows Powershell in the Start Menu and open it. Step 2: Type the following command to install Linux OS and press Enter:
Invoke-WebRequest -Uri https://wsldownload.azureedge.net/Ubuntu_1604.2019.523.0_x64.appx -OutFile Ubuntu.appx -UseBasicParsing
Add-AppxPackage .\Ubuntu.appx
 Step 3: Launch Ubuntu from the Start Menu and begin with the rest of the Installation process: Step 4: Provide Username and password to setup your Linux OS and finish the installation process. Once the installation of the Linux Subsystem is over, it can be launched anytime with Windows PowerShell. Just type the name of the OS in the PowerShell and press Enter.
how-to-install
Technical Scripter 2019
How To
Installation Guide
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
How to filter object array based on attributes?
Java Tutorial
How to Install FFmpeg on Windows?
Installation of Node.js on Linux
How to Install OpenCV for Python on Windows?
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
How to Install Pygame on Windows ?
Primitive Wrapper Classes are Immutable in Java

In Java Immutable class is a class which once created and it's contents can not be changed.On same concept Immutable objects are the objects whose state can not be changed once constructed.
Wrapper classes are made to be immutable due to following advantages −
Since the state of the immutable objects can not be changed once they are created they are automatically synchronized.Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
Since the state of the immutable objects can not be changed once they are created they are automatically synchronized.Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
Once created the state of the wrapper class immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
Once created the state of the wrapper class immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
The best use of the wrapper class as immutable objects is as the keys of a map.
The best use of the wrapper class as immutable objects is as the keys of a map.
Also due to immutability of wrapper class instances the purpose of caching is to facilitate sharing. So, if you have a dozen places in your application that needed to have the Integer instance with a value of 42, then you can use only one instance instead.
Also due to immutability of wrapper class instances the purpose of caching is to facilitate sharing. So, if you have a dozen places in your application that needed to have the Integer instance with a value of 42, then you can use only one instance instead.
class Demo {
   public static void main(String[] args) {
      Integer i = new Integer(20); //initialize a object of Integer class with value as 20.
      System.out.println(i);
      operate(i);// method to change value of object.
      System.out.println(i); //value doesn't change shows that object is immutable.
   }
   private static void operate(Integer i) {
      i = i + 1;
   }
}
20
20
Rust - Tuple

Tuple is a compound data type. A scalar type can store only one type of data. For example, an i32 variable can store only a single integer value. In compound types, we can store more than one value at a time and it can be of different types.
Tuples have a fixed length - once declared they cannot grow or shrink in size. The tuple index starts from 0.
//Syntax1
let tuple_name:(data_type1,data_type2,data_type3) = (value1,value2,value3);

//Syntax2
let tuple_name = (value1,value2,value3);

The following example displays the values in a tuple.
fn main() {
   let tuple:(i32,f64,u8) = (-325,4.9,22);
   println!("{:?}",tuple);
}
The println!("{ }",tuple) syntax cannot be used to display values in a tuple. This is because a tuple is a compound type. Use the println!("{:?}", tuple_name) syntax to print values in a tuple.
(-325, 4.9, 22)

The following example prints individual values in a tuple.
fn main() {
   let tuple:(i32,f64,u8) = (-325,4.9,22);
   println!("integer is :{:?}",tuple.0);
   println!("float is :{:?}",tuple.1);
   println!("unsigned integer is :{:?}",tuple.2);
}
integer is :-325
float is :4.9
unsigned integer is :2

The following example passes a tuple as parameter to a function. Tuples are passed by value to functions.
fn main(){
   let b:(i32,bool,f64) = (110,true,10.9);
   print(b);
}
//pass the tuple as a parameter

fn print(x:(i32,bool,f64)){
   println!("Inside print method");
   println!("{:?}",x);
}
Inside print method
(110, true, 10.9)

Destructing assignment is a feature of rust wherein we unpack the values of a tuple. This is achieved by assigning a tuple to distinct variables.
Consider the following example −
fn main(){
   let b:(i32,bool,f64) = (30,true,7.9);
   print(b);
}
fn print(x:(i32,bool,f64)){
   println!("Inside print method");
   let (age,is_male,cgpa) = x; //assigns a tuple to 
   distinct variables
   println!("Age is {} , isMale? {},cgpa is 
   {}",age,is_male,cgpa);
}
Variable x is a tuple which is assigned to the let statement. Each variable - age, is_male and cgpa will contain the corresponding values in a tuple.
Inside print method
Age is 30 , isMale? true,cgpa is 7.9


    45 Lectures 
     4.5 hours 

 Stone River ELearning

    10 Lectures 
     33 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
Reshaping array dimensions in Julia | Array reshape() Method

23 Mar, 2020
The reshape() is an inbuilt function in julia which is used to return an array with the same data as the specified array, but with different specified dimension sizes.
Syntax:reshape(A, dims)
Parameters:
A: Specified array.
dims: Specified dimension.
Returns: It returns an array with the same data as the specified array, but with different specified dimension sizes.
Example 1:
# Julia program to illustrate # the use of Array reshape() method  # Getting an array with the same data# as the specified 1D array, but with# (2 * 2) dimension sizes.A = [1, 2, 3, 4];println(reshape(A, (2, 2)))  # Getting an array with the same data# as the specified 2D array, but with# (4 * 4) dimension sizes.B = [1  2  3  4; 5  6  7  8; 9  10  11  12; 13  14  15  16];println(reshape(B, (4, 4)))  # Getting an array with the same data# as the specified 2D array, but with# (2 * 8) dimension sizes.C = [1  5   9  13; 2  6  10  14; 3  7  11  15; 4  8  12  16];println(reshape(C, 2, :))
Output:
Example 2:
# Julia program to illustrate # the use of Array reshape() method  # Getting an array with the same data# as the specified 1D array, but with# (2 * 2) dimension sizes.A = ["a", "b", "c", "d"];println(reshape(A, (2, 2)))  # Getting an array with the same data# as the specified 2D array, but with# (2 * 2) dimension sizes.B = ["a" "b"; "c" "d"];println(reshape(B, (2, 2)))  # Getting an array with the same data# as the specified 3D array, but with# (2 * 2*3) dimension sizes.C = cat(["a" "b"; "c" "d"], ["e" "f"; "g" "h"], ["i" "j"; "k" "l"], dims = 3);println(reshape(C, (2, 2, 3)))
Output:
Julia Array-functions
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
G-Fact 21 | Collatz Sequence

07 Jul, 2021
Starting with any positive integer N, we define the Collatz sequence corresponding to N as the numbers formed by the following operations:
N → N/2 ( if N is even)
N → 3N + 1 (if N is odd)

i.e. If N is even, divide it by 2 to get N/2. 
If N is odd, multiply it by 3 and add 1 to obtain 3N + 1.

It is conjectured but not yet proven that no matter which positive integer we start with; we always end up with 1.
For example, 10 → 5 → 16 → 8 → 4 → 2 → 1
A Coding Practice Question on Collatz Sequence
If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Dynamic Programming
GFacts
Mathematical
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Find if there is a path between two vertices in an undirected graph
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Return values of printf() and scanf() in C/C++
How are variables scoped in C - Static or Dynamic?
What are the Operators that Can be and Cannot be Overloaded in C++?
Difference between YOLO and SSD
G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
help_text – Django Form Field Validation

13 Feb, 2020
Built-in Form Field Validations in Django Forms are the default validations that come predefined to all fields. Every field comes in with some built-in validations from Django validators. Each Field class constructor takes some fixed arguments.
The help_text argument lets you specify descriptive text for this Field. If you provide help_text, it will be displayed next to the Field when the Field is rendered by one of the convenience Form methods. The default help_text for a Field is empty. Let’s check how to use help_text in a field using a project.
Syntax
field_name = models.Field(option = value)
Illustration of help_text using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into forms.py file of geeks app. We will be using CharField for experimenting for all field options.
from django import forms  class GeeksForm(forms.Form):    geeks_field = forms.CharField(help_text = "Enter your Name")
Add the geeks app to INSTALLED_APPS
# Application definition  INSTALLED_APPS = [    'django.contrib.admin',    'django.contrib.auth',    'django.contrib.contenttypes',    'django.contrib.sessions',    'django.contrib.messages',    'django.contrib.staticfiles',    'geeks',]
Now to render this form into a view we need a view and a URL mapped to that view. Let’s create a view first in views.py of geeks app,
from django.shortcuts import renderfrom .forms import GeeksForm  # Create your views here.def home_view(request):    context = {}    form = GeeksForm(request.POST or None)    context['form'] = form    if request.POST:        if form.is_valid():            temp = form.cleaned_data.get("geeks_field")            print(temp)    return render(request, "home.html", context)
Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.
<form method = "POST">    {% csrf_token %}    {{ form }}    <input type = "submit" value = "Submit"></form>
Finally, a URL to map to this view in urls.py
from django.urls import path  # importing views from views..pyfrom .views import home_view  URLpatterns = [    path('', home_view ),]
Let’s run the server and check what has actually happened, Run
Python manage.py runserver
Thus, an geeks_field CharField is created with help_text “Enter your Name”.
NaveenArora
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Forensics - Dshell and Scapy

Dshell is a Python-based network forensic analysis toolkit. This toolkit was developed by the US Army Research Laboratory. The release of this open source toolkit was in the year 2014. The major focus of this toolkit is to make forensic investigations with ease.
The toolkit consists of large number of decoders which are listed in the following table.
dns
This is used to extract DNS related queries
reservedips
Identifies the solutions for DNS problems
large-flows
Listing of the netflows
rip-http
It is used extract the files from the HTTP traffic
Protocols
Used for identification of non-standard protocols
The US Army Laboratory has maintained the clone repository in GitHub in the following link −
https://github.com/USArmyResearchLab/Dshell
The clone consists of a script install-ubuntu.py () used for installation of this toolkit.
Once the installation is successful, it will automatically build the executables and dependencies that will be used later.
The dependencies are as follows −
dependencies = { 
   "Crypto": "crypto", 
   "dpkt": "dpkt", 
   "IPy": "ipy", 
   "pcap": "pypcap" 
}
This toolkit can be used against the pcap (packet capture) files, which is usually recorded during the incidents or during the alert. These pcap files is either created by libpcap on Linux platform or WinPcap on Windows platform.
Scapy is a Python-based tool used to analyze and manipulate the network traffic. Following is the link for Scapy toolkit −
http://www.secdev.org/projects/scapy/
This toolkit is used to analyze packet manipulation. It is very capable to decode packets of a wide number of protocols and capture them. Scapy differs from the Dshell toolkit by providing a detailed description to the investigator about network traffic. These descriptions have been recorded in real time.
Scapy has the ability to plot using third-party tools or OS fingerprinting.
Consider the following example.
import scapy, GeoIP #Imports scapy and GeoIP toolkit 
from scapy import * 
geoIp = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) #locates the Geo IP address 
def locatePackage(pkg): 
src = pkg.getlayer(IP).src #gets source IP address 
dst = pkg.getlayer(IP).dst #gets destination IP address 
srcCountry = geoIp.country_code_by_addr(src) #gets Country details of source 
dstCountry = geoIp.country_code_by_addr(dst) #gets country details of destination 
print src+"("+srcCountry+") >> "+dst+"("+dstCountry+")\n"
This script gives the detailed description of the country details in the network packet, who are communicating with each other.
The above script will produce the following output.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to create Python dictionary from JSON input?

You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content
{
   "id": "file",
   "value": "File",
   "popup": {
      "menuitem": [
         {"value": "New", "onclick": "CreateNewDoc()"},
         {"value": "Open", "onclick": "OpenDoc()"},
         {"value": "Close", "onclick": "CloseDoc()"}
      ]
   }
}
You can load it in your python program and loop over its keys in the following way:
import json
f = open('data.json')
data = json.load(f)
f.close()
# Now you can use data as a normal dict:
for (k, v) in data.items():
print("Key: " + k)
print("Value: " + str(v))
This will give the output:
Key: id
Value: file
Key: value
Value: File
Key: popup
Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
How to extract the attribute value of an element in Selenium?

We can extract the attribute value of an element in Selenium with the help of getAttribute() method. Once we locate the element, this method is used to get the attribute value of the element and assigned to a variable.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class AttributeType {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //Using id tagname attribute combination for css expression
      WebElement button = driver.findElement(By.cssSelector("input[name=’search’]"));
      // getting the type attribute and printing in console
      String buttontype = button.getAttribute(“type”);
      System.out.println(“Attribute value is “ + buttontype);
      driver.close();
   }
}
Convert decimal point numbers to percentage using filters in Vue.js - GeeksforGeeks

17 Mar, 2021
Vue is a progressive framework for building user interfaces. The core library is focused on the view layer only and is easy to pick up and integrate with other libraries. Vue is also perfectly capable of powering sophisticated Single-Page Applications in combination with modern tooling and supporting libraries.
Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js template.
The conversion from a decimal number to percentage values can be done using filters. The logic of the filter will first check if the number is less than or equal to 1. When the user provides a number that is greater than 1, a message is displayed asking the user to enter a valid number, otherwise, we will multiply the number by 100 and return it by appending a percentage sign (%).
index.html
<html><head>    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">    </script></head><body>    <div id='parent'>        <p><strong>Decimal1: </strong>          {{dec1}}        </p>        <p><strong>Percentage : </strong>          {{ dec1 | percent }}        </p>        <p><strong>Decimal2: </strong>          {{dec2}}        </p>        <p><strong>Percentage : </strong>          {{ dec2 | percent }}        </p>        <p><strong>Decimal3: </strong>          {{dec3}}        </p>        <p><strong>Percentage : </strong>          {{ dec3 | percent }}        </p>        <p><strong>Decimal4: </strong>          {{dec4}}        </p>        <p><strong>Percentage : </strong>          {{ dec4 | percent }}        </p>      </div>    <script src='app.js'></script></body></html>
app.js
const parent = new Vue({    el: '#parent',    data: {        dec1: 0.1,        dec2: 0.023,        dec3: 0.47,        dec4: 13    },      filters: {        percent: function(dec) {            if (dec <= 1) {                return dec * 100 + "%";            }            return 'Please enter number less than or equal to 1'        }    }})
Output:
Decimal to percentage using filter
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Create Password Protected Zip of a file using Python - GeeksforGeeks

24 Jan, 2021
ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep related files together.
In this article, we will learn how to Create Password-Protected Zip of a file using Python. For this, we are using pyminizip module from python.
 The pyminizip module can be installed using the below command:
pip install pyminizip
For creating zip, we are using compress() method from pyminizip. So, we discuss first its syntax and arguments.
pyminizip.compress(“/srcfile/path.txt”, “file_path_prefix”, “/distfile/path.zip”, “password”, int(compress_level))
Arguments:
src file path (string)
src file prefix path (string) or None (path to prepend to file)
dst file path (string)
password (string) or None (to create no-password zip)
compress_level(int) between 1 to 9, 1 (more fast) <—> 9 (more compress) or 0 (default) 
Return value: Always returns None
Input file:
Program:
Python3
# importing moduleimport pyminizip  # input file pathinpt = "./Text.txt"  # prefix pathpre = None  # output zip file pathoupt = "./output.zip"  # set password valuepassword = "GFG"  # compress levelcom_lvl = 5  # compressing filepyminizip.compress(inpt, None, oupt,                   password, com_lvl)
Output:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
MySQL query to get the current date records wherein one of the columns displays current date

To achieve this, following is the syntax wherein we have used DATE(NOW()) −
select *from yourTableName where DATE(yourColumnName)=DATE(NOW());
Let us first create a table −
mysql> create table DemoTable706 (
   UserId varchar(100),
   UserName varchar(100),
   UserSignupDate datetime
);
Query OK, 0 rows affected (0.57 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable706 values('John1@gmail.com','John','2019-01-31 12:45:22');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable706 values('Chris123@gmail.com','Chris','2019-07-22 10:05:02');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable706 values('12Robert@gmail.com','Robert','2019-06-22 11:25:22');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable706 values('DavidM@gmail.com','David','2019-07-22 00:00:02');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable706;
This will produce the following output -
+--------------------+----------+---------------------+
| UserId             | UserName | UserSignupDate      |
+--------------------+----------+---------------------+
| John1@gmail.com    | John     | 2019-01-31 12:45:22 |
| Chris123@gmail.com | Chris    | 2019-07-22 10:05:02 |
| 12Robert@gmail.com | Robert   | 2019-06-22 11:25:22 |
| DavidM@gmail.com   | David    | 2019-07-22 00:00:02 |
+--------------------+----------+---------------------+
4 rows in set (0.00 sec)
Following is the query to get records wherein one of the columns displays current date −
mysql> select *from DemoTable706 where DATE(UserSignupDate)=DATE(NOW());
This will produce the following output -
+--------------------+----------+---------------------+
| UserId             | UserName | UserSignupDate      |
+--------------------+----------+---------------------+
| Chris123@gmail.com | Chris    | 2019-07-22 10:05:02 |
| DavidM@gmail.com   | David    | 2019-07-22 00:00:02 |
+--------------------+----------+---------------------+
2 rows in set (0.00 sec)
Extract all integers from string in C++

Here we will see how to extract all integers from strings in C++. We can put a string where numbers and no-numbers are present. We will extract all numeric values from it.
To solve this problem, we will use the stringstream class in C++. We will cut the string word by word and then try to convert it into integer type data. if the conversion is done, then it is integer and print the value.
Input: A string with some numbers “Hello 112 World 35 75”
Output: 112 35 75
Step 1:Take a number string
Step 2: Divide it into different words
Step 3: If a word can be converted into integer type data, then it is printed
Step 4: End
 Live Demo
#include<iostream>
#include<sstream>
using namespace std;
void getNumberFromString(string s) {
   stringstream str_strm;
   str_strm << s; //convert the string s into stringstream
   string temp_str;
   int temp_int;
   while(!str_strm.eof()) {
      str_strm >> temp_str; //take words into temp_str one by one
      if(stringstream(temp_str) >> temp_int) { //try to convert string to int
         cout << temp_int << " ";
      }
      temp_str = ""; //clear temp string
   }
}
main() {
   string my_str = "Hello 112 World 35 75";
   getNumberFromString(my_str);
}
112 35 75
Change Spacing of Axis Tick Marks in Base R Plot - GeeksforGeeks

28 Apr, 2021
In this article, we are going to see how to modify the space between axis tick marks of a Base R plot in R programming.
It can be done in the following ways:
Using xaxp & yaxp method.Using axis() Function.
Using xaxp & yaxp method.
Using axis() Function.
Method 1: Using  xaxp & yaxp method
The first tick mark, last tick, and a number of tick mark parameters are given represented by a,b,c shown in the below syntax. These parameters are put into used to change in spacing between axis ticks in the base plot.
Syntax: plot(x, y, xaxp = c(a,b,c), yaxp = c(a,b,c))
Parameters :
a= first tick mark
b= last  tick mark
c= Number of tick marks
Example:
R
# Create example datay <- 1:80x <- 1:80     # Change axis ticks with xaxp & yaxpplot(x, y,             xaxp = c(1, 80, 4),     yaxp = c(1, 80, 10)) 
Output:
Method 2: Using axis function.
In this method, first, there is a need to create a plot without axis ticks. Then, add ticks by applying the axis() function. Different ticks are added in the way as represented by a, b, c parameters in syntax. So, this is one such method to change the spacing between axis ticks in Base R Plot.
Syntax:
plot(x, y, xaxt = “n”,yaxt = “n”)
axis(side = 1, at = c(a, b, c....))
axis(side = 2, at = c(a, b, c.....))
Parameters:
a, b, c = values of axis ticks
Example:
R
# Create example datay <- 1:120x <- 1:120   # Change axis ticks with axis functionplot(x, y,             xaxt = "n",     yaxt = "n")axis(side = 1, at = c(10, 40, 80))axis(side = 2, at = c(15, 50, 75, 100))
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
How to change the order of bars in bar chart in R ?