code-rag-bench/online-tutorials huggingface dataset:
C program to sort an array in descending order

Sort the given array in descending or ascending order based on the code that has been written.
An array is a group of related data items which share’s a common name. A particular value in an array is identified with the help of its "index number".
The syntax for declaring an array is as follows −
datatype array_name [size];
For example,
float marks [50]
It declares ‘marks’ to be an array containing 50 float elements.
int number[10]
It declares the ‘number’ as an array to contain a maximum of 10 integer constants.
Each element is identified by using an "array index".
Accessing array elements is easy by using the array index.
Following is the C program to sort an array in descending order −
 Live Demo
#include <stdio.h>
void main (){
   int num[20];
   int i, j, a, n;
   printf("enter number of elements in an array\n");
   scanf("%d", &n);
   printf("Enter the elements\n");
   for (i = 0; i < n; ++i)
      scanf("%d", &num[i]);
   for (i = 0; i < n; ++i){
      for (j = i + 1; j < n; ++j){
         if (num[i] < num[j]){
            a = num[i];
            num[i] = num[j];
            num[j] = a;
         }
      }
   }
   printf("The numbers in descending order is:\n");
   for (i = 0; i < n; ++i){
      printf("%d\n", num[i]);
   }
}
When the above program is executed, it produces the following result −
enter number of elements in an array
4
Enter the elements
11
34
67
89
The numbers in descending order is:
89
67
34
11
How to place text over an image with HTML and CSS?

Following is the code to place text over an image using HTML and CSS −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
h1{
   text-align: center;
}
.imageContainer {
   margin-left:36%;
   display: inline-block;
   position: relative;
   text-align: center;
   color: rgb(64, 11, 124);
}
.caption{
   font-size: 25px;
   font-weight: bolder;
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
.BL {
   position: absolute;
   bottom: 8px;
   left: 16px;
}
.TL{
   position: absolute;
   top: 8px;
   left: 16px;
}
.TR {
   position: absolute;
   top: 8px;
   right: 16px;
}
.BR {
   position: absolute;
   bottom: 8px;
   right: 16px;
}
.center {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<h1>Place text on image example</h1>
<div class="imageContainer">
<img src="https://i.picsum.photos/id/59/500/500.jpg">
<div class="caption BL">Bottom Left Text</div>
<div class="caption TL" >Top Left Text</div>
<div class="caption TR">Top Right Text</div>
<div class="caption BR">Bottom Right Text</div>
<div class="caption center">Centered Text</div>
</div>
</body>
</html>
The above code will produce the following output −
math.max() function in Lua programming

There are several occurrences when we want to get the max value from a given series of numbers and then use that value later on.
The Maximum value from the series of different numbers is the value that is the maximum of all the numbers that are present in that series.
Lua provides us with a math.max() function that we can use to find the max value out of different numbers that we pass to it as arguments.
Let’s consider a simple example where we will make use of the math.max() function in Lua −
 Live Demo
a = 10
b = 11
c = 12
print(math.max(a,b,c))
12
It should be noted that if we try to pass the same numbers to the math.max() function then the output will be the same number itself.
Consider the example shown below −
 Live Demo
d = 11
e = 11
print(math.max(d,e))
11
We can also pass negative numbers in the math.max() function as an argument.
Consider the example shown below −
 Live Demo
f = -10
g = -5
print(math.max(f,g))
-5
Find the average of an unknown number of inputs in Python

03 Dec, 2021
Prerequisites: *args and **kwargs in PythonThe special syntax *args in function definitions in python is used to pass a variable number of arguments to a function. It is used to pass a non-keyworded, variable-length argument list. The syntax is to use the symbol * to take in a variable number of arguments; by convention, it is often used with the word args. In this article, the task is to find the average of the unknown number of inputs.Examples:  
Input : 1, 2, 3
Output : 2.00

Input : 2, 6, 4, 8
Output: 5.00
Below is the implementation.  
Python3
# function that takes arbitrary# number of inputsdef avgfun(*n):    sums = 0     for t in n:        sums = sums + t     avg = sums / len(n)    return avg      # Driver Coderesult1 = avgfun(1, 2, 3)result2 = avgfun(2, 6, 4, 8) # Printing average of the listprint(round(result1, 2))print(round(result2, 2))
Output: 
2.0
5.0
 
clintra
Python function-programs
Python-Functions
Python
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
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
SQL Clusters

09 Oct, 2020
In this article, we are going to cover the SQL cluster and will also cover some advantages and disadvantages of SQL clusters. Let’s discuss one by one.
Clusters in SQL are used to store data that is from different tables in the same physical data blocks. They are used if records from those tables are frequently queried together. By storing same data blocks, the number of database block reads needed to full fill such queries decreases which improves performance.
Each cluster stores tables data and maintains a clustered index to sort data.
Columns within the cluster index are called clustered keys. These determine the physical placement of rows within the cluster.
Cluster key is usually a foreign key of one table that references the primary key of another table in cluster.
The first cluster is created. Then cluster index is created on cluster key columns. After cluster key index is created, data can be entered into tables stored in clusters. As rows are inserted database stores cluster key and its associated rows in each of the cluster’s blocks.
Syntax :
CREATE CLUSTER <Cluster Name> 
(<Column> <Data Type> 
[, <Column> <Data Type> ] . . . . . )
[<Other Options >]

Example –
create table branch_master 
( 
"branch_code" varchar(10) PRIMARY KEY, 
"branch_name" varchar(15)
);

Now, Consider the above created table and let’s create the cluster for the same.Creating a Cluster :
create cluster branch_info
( 
"branch_code" varchar(10)
);

Advantages of clusters :
Disk I/O is reduced.Access time improves for joins of clustered tables.As all rows in clustered tables use the same columns as common primary key, this yields storage benefit.
Disk I/O is reduced.
Access time improves for joins of clustered tables.
As all rows in clustered tables use the same columns as common primary key, this yields storage benefit.
Disadvantages of clusters :
Reduces performance of INSERT statements as compared to storing the table separately with its own index.Columns that are often updated are not good candidates for cluster key.
Reduces performance of INSERT statements as compared to storing the table separately with its own index.
Columns that are often updated are not good candidates for cluster key.
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | <td> width Attribute

29 Jul, 2021
The HTML <td> width Attribute is used to specify the width of a table cell. If width attribute is not set then it takes default width according to content.
Syntax:
<td width="pixels | %">
Attribute Values:
pixels: It sets the width of table in terms of pixels.
%: It sets the width of table in terms of percentage (%).
Note: The <td> width Attribute is not supported by HTML 5.
Example:
<!DOCTYPE html><html>  <head>    <title>        HTML td width Attribute    </title></head>  <body>    <h1>GeeksforGeeks</h1>      <h2>HTML td width Attribute</h2>      <table border="1"            width="500">        <tr>            <th>NAME</th>            <th>AGE</th>            <th>BRANCH</th>        </tr>          <tr>            <td width="50%">BITTU</td>            <td width="20%">22</td>            <td width="30%">CSE</td>        </tr>          <tr>            <td>RAKESH</td>            <td>25</td>            <td>EC</td>        </tr>    </table></body>  </html>
Output:
Supported Browsers: The browser supported by HTML <td> width Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Reloading modules in Python

27 Oct, 2016
reload() reloads a previously imported module. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object.
Note: The argument should be a module which has been successfully imported.
Usage:
For Python2.x
reload(module)

For above 2.x and <=Python3.3
import imp
imp.reload(module)

For >=Python3.4
import importlib
importlib.reload(module)

For more information, check out reload().
This article is contributed by Sri Sanketh Uppalapati. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
PySpark – Read CSV file into DataFrame

25 Oct, 2021
In this article, we are going to see how to read CSV files into Dataframe. For this, we will use Pyspark and Python.
Files Used:
authors
book_author
books
Here we are going to read a single CSV into dataframe using spark.read.csv and then create dataframe with this data using .toPandas().
Python3
from pyspark.sql import SparkSession spark = SparkSession.builder.appName(    'Read CSV File into DataFrame').getOrCreate() authors = spark.read.csv('/content/authors.csv', sep=',',                         inferSchema=True, header=True) df = authors.toPandas()df.head()
Output:
Here, we passed our CSV file authors.csv. Second, we passed the delimiter used in the CSV file. Here the delimiter is comma ‘,‘. Next, we set the inferSchema attribute as True, this will go through the CSV file and automatically adapt its schema into PySpark Dataframe. Then, we converted the PySpark Dataframe to Pandas Dataframe df using toPandas() method.
To read multiple CSV files, we will pass a python list of paths of the CSV files as string type. 
Python3
from pyspark.sql import SparkSession spark = SparkSession.builder.appName('Read Multiple CSV Files').getOrCreate() path = ['/content/authors.csv',        '/content/book_author.csv'] files = spark.read.csv(path, sep=',',                       inferSchema=True, header=True) df1 = files.toPandas()display(df1.head())display(df1.tail())
Output:
Here, we imported authors.csv and book_author.csv present in the same current working directory having delimiter as comma ‘,‘ and the first row as Header.
To read all CSV files in the directory, we will use * for considering each file in the directory.
Python3
from pyspark.sql import SparkSession spark = SparkSession.builder.appName(    'Read All CSV Files in Directory').getOrCreate() file2 = spark.read.csv('/content/*.csv', sep=',',                    inferSchema=True, header=True) df1 = file2.toPandas()display(df1.head())display(df1.tail())
Output:
This will read all the CSV files present in the current working directory, having delimiter as comma ‘,‘ and the first row as Header.
rahuls66
Blogathon-2021
Picked
Python-Pyspark
Blogathon
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Import JSON Data into SQL Server?
SQL Query to Convert Datetime to Date
Python program to convert XML to Dictionary
Scrape LinkedIn Using Selenium And Beautiful Soup in Python
How to toggle password visibility in forms using Bootstrap-icons ?
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
GATE | GATE-CS-2006 | Question 1

28 Jun, 2021
Consider the polynomial p(x) = a0 + a1x + a2x2 + a3x3 , where ai ≠ 0 ∀i. The minimum number of multiplications needed to evaluate p on an input x is:(A) 3(B) 4(C) 6(D) 9Answer: (A)Explanation:Background Explanation :Horner’s rule for polynomial division is an algorithm used to simplify the process of evaluating a polynomial f(x) at a certain value x = x0 by dividing the polynomial into monomials (polynomials of the 1st degree). Each monomial involves a maximum of one multiplication and one addition processes. The result obtained from one monomial is added to the result obtained from the next monomial and so forth in an accumulative addition fashion. To explain the above, let is re-write the polynomial in its expanded form;
f(x0) = a0 + a1x0+ a2x0^2+ ... + anx0^n
This can, also, be written as:
f(x0) = a0 + x0(a1+ x0(a2+ x0(a3+ ... + (an-1 + anx0)....)
The algorithm proposed by this rule is based on evaluating the monomials formed above startingfrom the one in the inner-most parenthesis and move out to evaluate the monomials in the outerparenthesis.
Solution :Using Horner’s Rule, we can write the polynomial as followinga0 + (a1 + (a2 + a3x)x)x
In the above form, we need to do only 3 multiplications

p = a3 X x    ------------ (1)

q = (a2 + p) X x  ---------(2)

r = (a1 + q) X x  ---------(3)

result = a0 + r 
Reference :https://www.geeksforgeeks.org/horners-method-polynomial-evaluation/This solution is contributed by Nitika Bansal.Quiz of this Question
GATE-CS-2006
GATE-GATE-CS-2006
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | Gate IT 2005 | Question 11
GATE | GATE MOCK 2017 | Question 45
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2000 | Question 2
GATE | GATE CS 2013 | Question 50
GATE | GATE CS 2012 | Question 65
GATE | GATE-CS-2003 | Question 64
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2015 (Set 1) | Question 30
null=True – Django Built-in Field Validation

13 Feb, 2020
Built-in Field Validations in Django models are the default validations that come predefined to all Django fields. Every field comes in with built-in validations from Django validators. One can also add more built-in field validations for applying or removing certain constraints on a particular field. null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database.
Syntax
field_name = models.Field(null = True)
Illustration of null=True 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 models.py file of geeks app. We will be using CharField for experimenting for all field options.
from django.db import modelsfrom django.db.models import Model# Create your models here.  class GeeksModel(Model):    geeks_field = models.CharField(max_length = 200, null = True)
After running makemigrations and migrate on Django and rendering the above model, let us try to create an instance using None from Django shell. To start Django shell, enter the command,
Python manage.py shell
Now let us try to create instance of GeeksModel using None.
# importing required modelfrom geeks.models import GeeksModel  # creating instance of GeeksModels = GeeksModel.objects.create(geeks_field = None)  # saving current model instances.save()
Let us check in admin interface if the instance of model is created.Therefore, null=True modifies the field to accept NULL values or in python’s terms None Values.
Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.
For both string-based and non-string-based fields, one will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).
NaveenArora
Django-models
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to define dimensions of an empty DataFrame in R ?

21 Apr, 2021
An empty data frame in R Programming Language corresponds to the tabular structure where the axes are of length 0, i.e. it does not contain any data items. It is basically a tabular structure organized into rows and columns consisting of all empty data vectors. A data frame can be empty in the following cases : 
A data frame with empty vectors.
Creating a data frame of NULL entries.
An empty data frame can be created by using only 0-length variables for column names. The data types can also be declared for these columns to specify the type of data if we wish to. In this case, the dimensions of the data frame are 0 x number of columns, but the data frame is considered empty, since it doesn’t contain any entries. 
Syntax:
data.frame(column1 = data_type(col1),...)
Example
R
# declaring a data frame with 2 columns and# declaring data type of both the columns data_frame <- data.frame(col1 = character(0), col2 = numeric(0))  # printing data frameprint ("Data Frame : ")print (data_frame)
Output
[1] “Data Frame : “
[1] col1 col2
<0 rows> (or 0-length row.names)
In case, a single type of data type is to be assigned to all the columns of the data frame, the data type can be declared after all the columns are initialized with NA values. 
Example
R
# declaring an empty data framedata_frame1 <- data.frame(col1=NA, col2=NA, col3=NA, col4=NA)[numeric(0), ]  # printing data frameprint ("Data Frame :")print (data_frame1)
Output
[1] “Data Frame : “
[1] col1 col2 col3 col4
<0 rows> (or 0-length row.names)
This is just another way of interpreting empty dataframe. Here, the values it stores will be NULL, but the dimension will be like a regular dataframe with values. A matrix with the required dimensions can be created. It is filled with NA or missing values. Since, the matrices and data frames are interconvertible into each other, it can then be converted to data frame. The dimensions of the data frame are equivalent to the length of the axes declared for matrix. A matrix can be declared using matrix() function in R. 
Example:
R
# declaring a data frame with 2 columns# and declaring data type of both the # columns mat <- matrix(NA, nrow = 5, ncol = 2)  # converting matrix to data framedata_frame <- data.frame(mat)  # printing data frameprint ("Data Frame : ")print (data_frame)  # printing dimensionsdim(data_frame)
Output
[1] “Data Frame : “
 X1 X2
1 NA NA
2 NA NA
3 NA NA
4 NA NA
5 NA NA
[1] 5 2
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame
Convert First letter of every word to Uppercase in R Programming – str_to_title() Function

03 Jun, 2020
str_to_title() Function in R Language is used to convert the first letter of every word of a string to Uppercase and the rest of the letters are converted to lower case.
Note: This function uses 'stringr' library.
Syntax: str_to_title(string)
Parameter:string: string to be converted
Example 1:
# R Program to illustrate # the use of str_to_title function  # Loading Librarylibrary(stringr)  # Creating a stringstr <- "geeks for geeks"  # Calling str_to_title() functionstr_to_title(str) 
Output:
[1] "Geeks For Geeks"

Example 2:
# R Program to illustrate # the use of str_to_title function  # Loading Librarylibrary(stringr)  # Creating a stringstr <- "GEEKS FOR GEEKS"  # Calling str_to_title() functionstr_to_title(str) 
Output:
[1] "Geeks For Geeks"

R String-Functions
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Remove rows with NA in one column of R DataFrame
Dplyr – Groupby on multiple columns using variable names in R

23 Sep, 2021
The group_by() method is used to group the data contained in the data frame based on the columns specified as arguments to the function call. The group_by() function takes as an argument, the across and all of the methods which has to be applied on the specified grouping over all the columns of the data frame. 
Syntax:
group_by(col1, col2,..)
This is followed by the application of summarize() function, which is used to generate summary statistics over the applied column. The column is renamed with the specified new name. The new column can be assigned any of the aggregate methods like mean(), sum(), etc. Let us first look at a simpler approach, and apply groupby to only one column.
Example: Groupby on single column using variable names
R
library(data.table)library(dplyr)  # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2),                         col2 = c(1,1,3,4,5,6),                         col3 = 1                        )  print ("Original DataFrame")print (data_frame)  # deciding the column to group bygrp <- c('col1')  # calculating mean of col2 based on col1 groupdata_frame %>%   group_by(across(all_of(grp))) %>%   summarize(mean_col2 = mean(col2))
Output
[1] "Original DataFrame" 
col1 col2 col3 
1:    A    1    1 
2:    A    1    1 
3:    B    3    1 
4:    B    4    1 
5:    C    5    1 
6:    C    6    1 
# A tibble: 3 x 2   
col1  mean_col2   
<chr>     <dbl> 
1 A           1   
2 B           3.5 
3 C           5.5
Since there are three groups, A, B, and C, the mean is calculated for each of these three groups. 
Example: Applying group_by over multiple columns using the variable name
R
library(data.table)library(dplyr)  # creating first data framedata_frame <- data.table(col1 = rep(LETTERS[1:3],each=2),                         col2 = c(1,1,3,4,5,6),                         col3 = 1                        )  print ("Original DataFrame")print (data_frame)  # deciding the column to group bygrp <- c('col1','col2')  # calculating mean of col2 based on col1 groupdata_frame %>%   group_by(across(all_of(grp))) %>%   summarize(mean_col2 = sum(col2))
Output
# A tibble: 5 x 3 
# Groups:   col1 [3]   
col1   col2 mean_col2   
<chr> <dbl>     <dbl> 
1 A         1         2 
2 B         3         3 
3 B         4         4 
4 C         5         5 
5 C         6         6
Picked
R Dplyr
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tensorflow | tf.data.Dataset.reduce()

03 Oct, 2019
With the help of tf.data.Dataset.reduce() method, we can get the reduced transformation of all the elements in the dataset by using tf.data.Dataset.reduce() method.
Syntax : tf.data.Dataset.reduce()Return : Return combined single result after transformation.
Note :These given examples will demonstrate the use of new version of tensorflow 2.0, so if you want to run these examples please run the following commands in command prompt.
pip install tensorflow==2.0.0-rc2
Example #1 :In this example we can see that by using tf.data.Dataset.reduce() method, we are able to get the reduced transformation of all the elements from the dataset.
# import tensorflowimport tensorflow as tf  # using tf.data.Dataset.reduce() methodgfg = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5])  print(gfg.reduce(0, lambda x, y: x + y).numpy())
Output :
15
Example #2 :
# import tensorflowimport tensorflow as tf  # using tf.data.Dataset.reduce() methodgfg = tf.data.Dataset.from_tensor_slices([[5, 10], [3, 6]])  print(gfg.reduce(0, lambda x, y: x * y).numpy())
Output :
[15, 60]
Tensorflow
Python
Technical Scripter
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
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
Splitting a PDF into many using Java

08 Dec, 2020
Program to split the PDF document into multiple PDFs. Below is the implementation for the same using JAVA. The prerequisite of this topic is that you have already installed apache library 
Approach:
Load the PDF from the computer.Load the PDF using the class called PDDocument.Use load() function of PDdocument class to load the file. 
Load the PDF using the class called PDDocument.
Use load() function of PDdocument class to load the file. 
Run the Splitter Class to split PDF.Splitter is a class used to split PDF.Use Split() function of the splitter class to split the PDF. 
Splitter is a class used to split PDF.
Use Split() function of the splitter class to split the PDF. 
Using Iterator to count pages.Split the pages into many so that count the pages after the split() function, and use that to create a finite number of splits PDF.Save all the PDFs.Close the document.
Split the pages into many so that count the pages after the split() function, and use that to create a finite number of splits PDF.
Save all the PDFs.
Close the document.
Below is the implementation of the above approach:
Java
// Splitting a PDF in to many using Javaimport org.apache.pdfbox.multipdf.Splitter;import org.apache.pdfbox.pdmodel.PDDocument;  import java.io.File;import java.io.IOException;import java.util.List;import java.util.Iterator;  public class SplitPdf {    public static void main(String[] args)        throws IOException    {          // Loading PDF        File pdffile            = new File("C:/Desktop/Java/sample.pdf");        PDDocument document = PDDocument.load(pdffile);          // Splitter Class        Splitter splitting = new Splitter();          // Splitting the pages into multiple PDFs        List<PDDocument> Page = splitting.split(document);          // Using a iterator to Traverse all pages        Iterator<PDDocument> iteration            = Page.listIterator();          // Saving each page as an individual document        int j = 1;        while (iteration.hasNext()) {            PDDocument pd = iteration.next();            pd.save("C:/Desktop/Java/Generated/sample-"                    + j++ + ".pdf");        }        System.out.println("Splitted Pdf Successfully.");        document.close();    }}
Before the execution of the program:
 
After execution of the program:
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array
Plot a Point or a Line on an Image with Matplotlib

17 Dec, 2020
Prerequisites: Matplotlib
Matplotlib and its constituents support a lot of functionality. One such functionality is that we can draw a line or a point on an image using Matplotlib in python.
Import modules
Read the image
Plot the line or point on the image
Display the plot/image.
Image Used:
Implementation using the above approach on the given image is provided below:
Example 1 : Drawing a point on the image.
Attribute used: marker
It is used to define what marker type should the point be displayed in.
Python3
from matplotlib import imagefrom matplotlib import pyplot as plt  # to read the image stored in the working directorydata = image.imread('sunset-1404452-640x480.jpg')  # to draw a point on co-ordinate (200,300)plt.plot(200, 350, marker='v', color="white")plt.imshow(data)plt.show()
Output:
Example 2 : Draw a line on the image
To draw a line we will give the co-ordinates of two points in the plot function.
Attribute used: linewidth
Used to specify the width of the line.
Python3
from matplotlib import imagefrom matplotlib import pyplot as plt  # to read the image stored in the working directorydata = image.imread('sunset-1404452-640x480.jpg')  # to draw a line from (200,300) to (500,100)x = [200, 500]y = [300, 100]plt.plot(x, y, color="white", linewidth=3)plt.imshow(data)plt.show()
Output: 
Example 3 : Draw two intersecting lines crossing each other to make X.
Python3
from matplotlib import imagefrom matplotlib import pyplot as plt  # to read the image stored in the working directorydata = image.imread('sunset-1404452-640x480.jpg')  # to draw first line from (100,400) to (500,100)# to draw second line from (150,100) to (450,400)x1 = [100, 500]y1 = [400, 100]x2 = [150, 450]y2 = [100, 400]plt.plot(x1, y1, x2, y2, color="white", linewidth=3)plt.axis('off')plt.imshow(data)plt.show()
Output : 
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
MariaDB - Transactions

Transactions are sequential group operations. They function as a single unit, and do not terminate until all operations within the group execute successfully. A single failure in the group causes the entire transaction to fail, and causes it to have no impact on the database.
Transactions conform to ACID (Atomicity, Consistency, Isolation, and Durability) −
Atomicity − It ensures the success of all operations by aborting on failures and rolling back changes.
Atomicity − It ensures the success of all operations by aborting on failures and rolling back changes.
Consistency − It ensures the database applies changes on a successful transaction.
Consistency − It ensures the database applies changes on a successful transaction.
Isolation − It enables independent transactions operation of transactions.
Isolation − It enables independent transactions operation of transactions.
Durability − It ensures the persistence of a successful transaction in the event of system failure.
Durability − It ensures the persistence of a successful transaction in the event of system failure.
At the head of a transaction statement is the START TRANSACTION statement followed by COMMIT and ROLLBACK statements −
START TRANSACTION begins the transaction.
START TRANSACTION begins the transaction.
COMMIT saves changes to data.
COMMIT saves changes to data.
ROLLBACK ends the transaction, destroying any changes.
ROLLBACK ends the transaction, destroying any changes.
On a successful transaction, COMMIT acts. On a failure, ROLLBACK acts.
Note − Some statements cause an implicit commit, and they also cause an error when used within transactions. Examples of such statements include, but are not limited to CREATE, ALTER, and DROP.
MariaDB transactions also include options like SAVEPOINT and LOCK TABLES. SAVEPOINT sets a restore point to utilize with ROLLBACK. LOCK TABLES allows controlling access to tables during sessions to prevent modifications during certain time periods.
The AUTOCOMMIT variable provides control over transactions. A setting of 1 forces all operations to be considered successful transactions, and a setting of 0 causes persistence of changes to only occur on an explicit COMMIT statement.
The general structure of a transaction statement consists of beginning with START TRANSACTION. The next step is inserting one or more commands/operations, inserting statements that check for errors, inserting ROLLBACK statements to manage any errors discovered and finally inserting a COMMIT statement to apply changes on successful operations.
Review the example given below −
START TRANSACTION;
SELECT name FROM products WHERE manufacturer = 'XYZ Corp';
UPDATE spring_products SET item = name;
Python - Deque

A double-ended queue, or deque, has the feature of adding and removing elements from either end. The Deque module is a part of collections library.
It has the methods for adding and removing elements which can be invoked directly with arguments. In the below program we import the collections module and declare a deque.
Without need of any class we use the in-built implement these methods directly.


import collections
# Create a deque
DoubleEnded = collections.deque(["Mon","Tue","Wed"])
print (DoubleEnded)

# Append to the right
print("Adding to the right: ")
DoubleEnded.append("Thu")
print (DoubleEnded)

# append to the left
print("Adding to the left: ")
DoubleEnded.appendleft("Sun")
print (DoubleEnded)

# Remove from the right
print("Removing from the right: ")
DoubleEnded.pop()
print (DoubleEnded)

# Remove from the left
print("Removing from the left: ")
DoubleEnded.popleft()
print (DoubleEnded)

# Reverse the dequeue
print("Reversing the deque: ")
DoubleEnded.reverse()
print (DoubleEnded)
When the above code is executed, it produces the following result: 
deque(['Mon', 'Tue', 'Wed'])
Adding to the right: 
deque(['Mon', 'Tue', 'Wed', 'Thu'])
Adding to the left: 
deque(['Sun', 'Mon', 'Tue', 'Wed', 'Thu'])
Removing from the right: 
deque(['Sun', 'Mon', 'Tue', 'Wed'])
Removing from the left: 
deque(['Mon', 'Tue', 'Wed'])
Reversing the deque: 
deque(['Wed', 'Tue', 'Mon'])
How to create an empty matrix in R ?

25 Feb, 2022
The term empty matrix has no rows and no columns. A matrix that contains missing values has at least one row and column, as does a matrix that contains zeros. In this article, we are going to see how to create an empty matrix in R Programming Language.
There are three ways of creating an empty matrix:
Using row and column.
Using only row.
Using only column.
Method 1: Using both row and column:
Here in this, we need to pass both row and column to create an empty matrix:
Syntax: matrix name = matrix(, nrow = value 1, ncol = value2)
Where:
Here matrix name can be any valid identifier
Value 1 is for number of rows.
Value 2 is for number of columns.
Example 1: In the below example, we created a mat variable, After creating mat variable we are using the matrix function to create a matrix and mentioning a number of rows and columns in it.
Below is the implementation:
R
# creating empty matrix,# storing in variable mat and passing# number of rows and columnsmat = matrix(, nrow = 1, ncol = 1) # printing empty matrix.print(mat)
Output: 
Here we got NA as output which means not a number or not available.
Example 2: 
R
# creating empty matrix,# storing in variable mat1 and passing@ number of rows and columnsmat1 = matrix(, nrow = 10, ncol = 10) # printing empty matrix.print(mat1)
Output: 
Method 2: Using only row :
Here we need to pass the only one row to create an empty matrix 
Syntax: matrix name = matrix(, nrow = value 1)
Where,
Here matrix name can be any valid identifier
value 1 is for number of rows.
Example 1: 
R
Mat<-matrix(,nrow=10) # printing empty matrix.print(Mat)
Output:
Method 3: Using only column.
Here we need to pass the only columns to create an empty matrix.
Syntax: matrix name = matrix(, ncol = value 1)
Where,
Here matrix name can be any valid identifier
Value 1 is for number of column.
Below is the implementation:
R
Mat<-matrix(,ncol=10) #printing empty matrix.print(Mat)
Output:
sweetyty
vinayakmraj
Picked
R Matrix-Programs
R-Matrix
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream Ciphers

16 Oct, 2020
In stream cipher, one byte is encrypted at a time while in block cipher ~128 bits are encrypted at a time.
Initially, a key(k) will be supplied as input to pseudorandom bit generator and then it produces a random 8-bit output which is treated as keystream.
The resulted keystream will be of size 1 byte, i.e., 8 bits.
Stream Cipher follows the sequence of pseudorandom number stream.One of the benefits of following stream cipher is to make cryptanalysis more difficult, so the number of bits chosen in the Keystream must be long in order to make cryptanalysis more difficult.By making the key more longer it is also safe against brute force attacks.The longer the key the stronger security is achieved, preventing any attack.Keystream can be designed more efficiently by including more number of 1s and 0s, for making cryptanalysis more difficult.Considerable benefit of a stream cipher is, it requires few lines of code compared to block cipher.
Stream Cipher follows the sequence of pseudorandom number stream.
One of the benefits of following stream cipher is to make cryptanalysis more difficult, so the number of bits chosen in the Keystream must be long in order to make cryptanalysis more difficult.
By making the key more longer it is also safe against brute force attacks.
The longer the key the stronger security is achieved, preventing any attack.
Keystream can be designed more efficiently by including more number of 1s and 0s, for making cryptanalysis more difficult.
Considerable benefit of a stream cipher is, it requires few lines of code compared to block cipher.
Encryption :For Encryption,
Plain Text and Keystream produces Cipher Text (Same keystream will be used for decryption.).
The Plaintext will undergo XOR operation with keystream bit-by-bit and produces the Cipher Text.
Example –
Plain Text : 10011001
Keystream  : 11000011
`````````````````````
Cipher Text : 01011010

Decryption :For Decryption,
Cipher Text and Keystream gives the original Plain Text (Same keystream will be used for encryption.).
The Ciphertext will undergo XOR operation with keystream bit-by-bit and produces the actual Plain Text.
Example –
Cipher Text : 01011010
Keystream   : 11000011
`````````````````````` 
Plain Text  : 10011001

Decryption is just the reverse process of Encryption i.e. performing XOR with Cipher Text.
Diagram of Stream Cipher
cryptography
Network-security
Computer Networks
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Introduction of Mobile Ad hoc Network (MANET)
Advanced Encryption Standard (AES)
Bluetooth
Intrusion Detection System (IDS)
Cryptography and its Types
Difference between FDMA, TDMA and CDMA
How to install Python libraries without using the pip command?

06 Oct, 2021
The most common practice of installing external libraries in your system is by using the Python pip command. However, there is an alternate method of manually installing Python libraries without using the pip command.
In this article, we are going to discuss how to manually install a python package.  
Below is the Step-by-step approach to manually install selenium library in a system. 
Step 1: Downloading the files
Go to the https://pypi.org/ website find the package you want to install
From the menu on the left-hand side click the download files button.
Here I have taken the example of the selenium library.
Make sure to download .tar.gz file
downloading files
.tar.tz
Step 2: Unzip the files downloaded if they are zipped using any unzipping software.
Step 3: Change the current working directory to the file containing Setup.py using the cd command.
cd command
Step 4: Read the installation instructions carefully and install as directed.
Step 5: After changing the current working directory to the file containing Setup.py type the following command:
python setup.py install
setup.py
Final
That’s it, now you are ready to use the installed library and you can import this library in your python program.
how-to-install
python-utility
How To
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
io.WriteString() Function in Golang with Examples - GeeksforGeeks

05 May, 2020
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The WriteString() function in Go language is used to write the contents of the stated string “s” to the writer “w”, which takes a slice of bytes. And if “w” is implemented by StringWriter then its WriteString method is called immediately. Else, w.Write is invoked strictly once. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
Syntax:
func WriteString(w Writer, s string) (n int, err error)

Here, “w” is the writer, and “s” is the string that is written to the writer.
Return value: It returns the total number of bytes of the content of type int and also returns an error if any.
Below examples illustrates the use of above method:
Example 1:
// Golang program to illustrate the usage of// io.WriteString() function  // Including main packagepackage main  // Importing fmt, io, and osimport (    "fmt"    "io"    "os")  // Calling mainfunc main() {      // Defining w using Stdout    w := os.Stdout      // Calling WriteString method with its parameters    n, err := io.WriteString(w, "GfG\n")      // If error is not nil then panics    if err != nil {        panic(err)    }      // Prints output    fmt.Printf("n: %d\n", n)}
Output:
GfG
n: 4

Example 2:
// Golang program to illustrate the usage of// io.WriteString() function  // Including main packagepackage main  // Importing fmt, io, and osimport (    "fmt"    "io"    "os")  // Calling mainfunc main() {      // Defining w using Stdout    w := os.Stdout      // Calling WriteString method with its parameters    n, err := io.WriteString(w, "GeeksforGeeks\nis\na\nCS-Portal.\n")      // If error is not nil then panics    if err != nil {        panic(err)    }      // Prints output    fmt.Printf("n: %d\n", n)}
Output:
GeeksforGeeks
is
a
CS-Portal.
n: 30

Here, in the above example, “Stdout” is used in order to create a default file descriptor where the stated content is written.
Golang-io
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Durations in Golang
How to Parse JSON in Golang?
Strings in Golang
Defer Keyword in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Class and Object in Golang
Loops in Go Language
Rune in Golang
time.Parse() Function in Golang With Examples
Tryit Editor v3.7

Tryit: HTML marked text
Addition of 2 matrices in Java

#include <stdio.h>
int main()
{
   int m, n, c, d, first[10][10], second[10][10], sum[10][10];
   printf("Enter the number of rows and columns of matrix\n");
   scanf("%d%d", &m, &n);
   printf("Enter the elements of first matrix\n");
     for (c = 0; c < m; c++)
      for (d = 0; d < n; d++)
         scanf("%d", &first[c][d]);
     printf("Enter the elements of second matrix\n");
     for (c = 0; c < m; c++)
      for (d = 0 ; d < n; d++)
         scanf("%d", &second[c][d]);
     printf("Sum of entered matrices:-\n");
     for (c = 0; c < m; c++) {
      for (d = 0 ; d < n; d++) {
         sum[c][d] = first[c][d] + second[c][d];
         printf("%d\t", sum[c][d]);
      }
      printf("\n");
   }
     return 0;
}
How to secure database passwords in PHP? - GeeksforGeeks

24 Oct, 2021
Most of the websites are providing sing up and login facility to the user. User has to create a password and use it for login to the website. But it is very important to secure the password of the user. password_hash() function provides the facility to securely store the password of the user to the database.
Syntax  
password_hash(Password, PASSWORD_DEFAULT)
Example: First parameter Password will contain the normal password. The second Parameter will contain PASSWORD_BCRYPT to make secure otherwise it contains PASSWORD_DEFAULT as default. Let’s see the example to understand properly.  
dbconn.php  
php
<?php   $db_host = "localhost";  $db_name = "secure_pass";  $db_pass = "";  $db_user = "root";   $conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);   if (!$conn){    die ('Failed to connect with server');  }   ?>
Signup Form:  
html
<form action="index.php" method="POST">  <label for="username">Username</label>  <input type="text" name="username" required><br><br>   <label for="password">Password</label>  <input type="password" name="password" required><br><br>  <input type="submit" name="submit" value="submit">   </form>
index.php  
php
<?php   //Include database connection file  include 'dbconn.php';   if (isset($_POST['submit'])){    $username = $_POST['username'];     // Normal Password    $pass = $_POST['password'];     // Securing password using password_hash    $secure_pass = password_hash($pass, PASSWORD_BCRYPT);     $sql = "INSERT INTO login_tb (u_username, u_password)    VALUES('$username', '$secure_pass')";    $result = mysqli_query($conn, $sql);  }    // Include HTML sign up form  include 'signup_form.php';?>
Output:Password In Database.  
 
saurabh1990aror
PHP-Misc
Picked
PHP
Web Technologies
Web technologies Questions
Write From Home
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
How to generate PDF file using PHP ?
Different ways for passing data to view in Laravel
How to Install php-curl in Ubuntu ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?