code-rag-bench/online-tutorials huggingface dataset:
Python program to print even length words in a string

29 May, 2022
Given a string. The task is to print all words with even length in the given string.
Examples: 
Input: s = "This is a python language"
Output: This
              is
              python
              language
Input: s = "i am laxmi"
Output:     am
Method: Finding even length words using for loop and if statement and without using the def function. First split the given string using the split() function and then iterate the words of a string using for loop. Calculate the length of each word using the len() function. If the length is even, then print the word.
Python3
# Python code# To print even length words in string #input stringn="This is a python language"#splitting the words in a given strings=n.split(" ")for i in s:  #checking the length of words  if len(i)%2==0:    print(i) # this code is contributed by gangarajula laxmi
This
is
python
language

Approach: Split the string using split() function. Iterate in the words of a string using for loop. Calculate the length of the word using len() function. If the length is even, then print the word. Below is the Python implementation of the above approach: 
Python3
# Python3 program to print# even length words in a string def printWords(s):         # split the string    s = s.split(' ')         # iterate in words of string    for word in s:                 # if length is even        if len(word)%2==0:            print(word)  # Driver Codes = "i am muskan"printWords(s)
am
muskan

ankthon
laxmigangarajula03
Python string-programs
python-basics
python-string
Python
Python Programs
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
What is the purpose of a function prototype in C/C++?

Here we will see what are the purpose of using function prototypes in C or C++. The function prototypes are used to tell the compiler about the number of arguments and about the required datatypes of a function parameter, it also tells about the return type of the function. By this information, the compiler cross-checks the function signatures before calling it. If the function prototypes are not mentioned, then the program may be compiled with some warnings, and sometimes generate some strange output.
If some function is called somewhere, but its body is not defined yet, that is defined after the current line, then it may generate problems. The compiler does not find what is the function and what is its signature. In that case, we need to function prototypes. If the function is defined before then we do not need prototypes.
#include<stdio.h>
main() {
   function(50);
}
void function(int x) {
   printf("The value of x is: %d", x);
}
The value of x is: 50
This shows the output, but it is showing some warning like below:
[Warning] conflicting types for 'function'
[Note] previous implicit declaration of 'function' was here
Now using function prototypes, it is executing without any problem.
#include<stdio.h>
void function(int); //prototype
main() {
   function(50);
}
void function(int x) {
   printf("The value of x is: %d", x);
}
The value of x is: 50
Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function

20 Oct, 2018
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space.
Examples:
Input :  [1, 2, 3, 2, 3, 1, 3]
Output :  3

We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solve this problem in python quickly using Reduce(expression, iterable) method.
# Python program to Find the Number # Occurring Odd Number of Times# using Lambda expression and reduce function  from functools import reduce  def oddTimes(input):     # write lambda expression and apply     # reduce function over input list     # until single value is left     # expression reduces value of a ^ b into single value     # a starts from 0 and b from 1     # ((((((1 ^ 2)^3)^2)^3)^1)^3)     print (reduce(lambda a, b: a ^ b, input))  # Driver programif __name__ == "__main__":    input = [1, 2, 3, 2, 3, 1, 3]    oddTimes(input)
Output:
3

python-lambda
python-string
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
Java program to find the sum of elements of an array

To find the sum of elements of an array.
create an empty variable. (sum)
Initialize it with 0 in a loop.
Traverse through each element (or get each element from the user) add each element to sum.
Print sum.
import java.util.Arrays;
import java.util.Scanner;
public class SumOfElementsOfAnArray {
   public static void main(String args[]){
      System.out.println("Enter the required size of the array :: ");
      Scanner s = new Scanner(System.in);
      int size = s.nextInt();
      int myArray[] = new int [size];
      int sum = 0;
      System.out.println("Enter the elements of the array one by one ");

      for(int i=0; i<size; i++){
         myArray[i] = s.nextInt();
         sum = sum + myArray[i];
      }
      System.out.println("Elements of the array are: "+Arrays.toString(myArray));
      System.out.println("Sum of the elements of the array ::"+sum);
   }
}
Enter the required size of the array ::
5
Enter the elements of the array one by one
45
12
55
78
445
Elements of the array are: [45, 12, 55, 78, 445]
Sum of the elements of the array ::635
Set two Matplotlib imshow plots to have the same colormap scale

To set two matplotlib imshow() plots to have the same colormap scale, we can take the following
Set the figure size and adjust the padding between and around the subplots.
Create d1 and d2 matrices using Numpy.
Get the resultant matrix to get the maximum and minmum value.
Use amin and amax methods for minimum and maximum values.
Create a new figure or activate an existing figure.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement, with nrows=1,
ncols=2 at index 1
Using imshow() method with vmin and vmax, define the data range that the colormap covers.
Repeat steps 6 and 7 with data
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data1 = np.random.randn(4, 4)
data2 = np.random.randn(4, 4)

resultant = np.array([data1, data2])
min_val, max_val = np.amin(resultant), np.amax(resultant)
fig = plt.figure()

ax = fig.add_subplot(1, 2, 1)
ax.imshow(data1, cmap="plasma", vmin=min_val, vmax=max_val)

ax2 = fig.add_subplot(1, 2, 2)
ax2.imshow(data2, cmap="plasma", vmin=min_val, vmax=max_val)

plt.show()
MySQL Tryit Editor v1.0

SELECT MIN(Price) AS SmallestPrice
FROM Products; 
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Matplotlib.pyplot.subplots() in Python

11 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
Sample Code
# sample codeimport matplotlib.pyplot as plt     plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() 
Output:
The subplots() function in pyplot module of matplotlib library is used to create a figure and a set of subplots.
Syntax: matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
Parameters: This method accept the following parameters that are described below:
nrows, ncols : These parameter are the number of rows/columns of the subplot grid.
sharex, sharey : These parameter controls sharing of properties among x (sharex) or y (sharey) axes.
squeeze : This parameter is an optional parameter and it contains boolean value with default as True.
num: This parameter is the pyplot.figure keyword that sets the figure number or label.
subplot_kwd: This parameter is the dict with keywords passed to the add_subplot call used to create each subplot.
gridspec_kw: This parameter is the dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on.
Returns: This method return the following values.
fig : This method return the figure layout.
ax : This method return the axes.Axes object or array of Axes objects.
Below examples illustrate the matplotlib.pyplot.subplots() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  # First create some toy data:x = np.linspace(0, 2 * np.pi, 400)y = np.sin(x**2)  fig, ax = plt.subplots()ax.plot(x, y)ax.set_title('Simple plot')    fig.suptitle('matplotlib.pyplot.subplots() Example')plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt  # First create some toy data:x = np.linspace(0, 1.5 * np.pi, 100)y = np.sin(x**2)+np.cos(x**2)  fig, axs = plt.subplots(2, 2,                        subplot_kw = dict(polar = True))axs[0, 0].plot(x, y)axs[1, 1].scatter(x, y)  fig.suptitle('matplotlib.pyplot.subplots() Example')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Difference between Docker Image and Container

12 Jul, 2022
1. Docker Image: The concept of Images and Container is like class and object in which object is an instance of class and class is the blueprint of the object. Images are different in Virtual Machines and Docker, in virtual machines images, are just snapshots of running virtual machines at different points of time but Docker images are a little bit different from them, and the most important and major difference is that Docker images are immutable that is they can not be changed. In the real world, it happens a lot that software works on one computer but it does not works on others due to different environments, this issue is completely solved by docker images and using this, the application will work same on everyone’s PC. Every developer on a team will have exact same development instance. Each testing instance is exactly the same as the development instance. Your production instance is exactly the same as the testing instance. Also, Developers around World can share their Docker Images on a Platform called Docker HUB. 
2. Docker Container: They are actually Docker Virtual Machines but are commonly called Docker Containers. If a Docker image is a map of the house, then Docker Container is actual build house or in other words, we can call it an instance of an image. As per the official website, containers are runnable instance of an image. You can create, start, stop, move, or delete a container using Docker API or CLI. You can connect a container to one or more networks, attach storage to it, or even create a new image based on its current state. An application runs using a cluster of containers which are self isolated from one another and also from host machine where they are running example if a backend application is running on a docker container at port 8000 and you tried to access it from host machine, you will not be able to access as containers are self-isolated and in that case you have to explicitly expose your application at a certain port and connect your machine port to that port.
Example:
docker run --publish 8000:8080 --detach --name alias_name application_name:1.0 
Here application running at port 8080 in container is connected to port 8000 at the host machine. Now it can access application using URL localhost:8000
Difference between Docker Image and Docker Container:
khushb99
Difference Between
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Tkinter ttk.Checkbutton and comparison with simple Checkbutton

27 Mar, 2019
Tkinter is a GUI (Graphical User Interface) module which comes along with the Python itself. This module is widely used to create GUI applications. tkinter.ttk is used to create the GUI applications with the effects of modern graphics which cannot be achieved using only tkinter. Checkbutton is used to select multiple options.
Checkbuttons can be created using following snippet.
chkbtn = ttk.Checkbutton(master, option=value, ...)
Code #1:
# importing tkinter.ttkfrom tkinter import *from tkinter.ttk import *   # creating rootroot = Tk()  # label textLabel(root, text ='Select Programming language of your choice').place(x = 20, y = 0)  # check buttonsjava = Checkbutton(root, text ='Java',                   takefocus = 0).place(x = 40, y = 30)  cpp = Checkbutton(root, text ='C++',                  takefocus = 0).place(x = 40, y = 50)  python = Checkbutton(root, text ='Python',                     takefocus = 0).place(x = 40, y = 70)  c = Checkbutton(root, text ='C',                takefocus = 0).place(x = 40, y = 90)  root.mainloop()
Output:
Code #2: Difference between simple Checkbutton and ttk.Checkbutton
# importing tkinter and ttkfrom tkinter import * from tkinter import ttk  # rootroot = Tk()  # This will depict the features of Simple CheckbuttonLabel(root, text ='Simple Checkbutton').place(x = 10, y = 10)chkbtn1 = Checkbutton(root, text ='Checkbutton1',             takefocus = 0).place(x = 10, y = 40)chkbtn2 = Checkbutton(root, text ='Checkbutton2',             takefocus = 0).place(x = 10, y = 60)    # This will depict the features of ttk.CheckbuttonLabel(root, text ='ttk.Checkbutton').place(x = 140, y = 10)chkbtn1 = ttk.Checkbutton(root, text ='Checkbutton1',                takefocus = 0).place(x = 140, y = 40)chkbtn2 = ttk.Checkbutton(root, text ='Checkbutton2',                 takefocus = 0).place(x = 140, y = 60)  root.mainloop()
Output:
Notice the difference in the appearance of both the Checkbuttons which is all due to the modern graphics. In the above Code when mouse is being hovered over the ttk.Checkbutton you may see a blue color effect (effect may change from os from os). When we hover mouse over Simple Checkbutton you may not experience any such kind of effects.
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Query to Update All Rows in a Table

10 Oct, 2021
The Update statement is a SQL keyword to update data in the database. We can update all the rows in the database or some values with the help of conditions.  The update is a SQL keyword and it falls under Data Manipulation Language(DML),  as the name suggests it is used to manipulate the data. There are many DML keywords that fall under this:
UPDATE
INSERT
DELETE
SELECT
SQL is a case insensitive language i.e SELECT * FROM PRODUCTS is the same as select * from products. But we write keywords in capital letters and tables, column names in small letters as a convention.
Step 1: CREATE DATABASE
Syntax:
CREATE DATABASE database_name;
Step 2: TO CREATE TABLE(PRODUCTS)
Query:
CREATE TABLE products(product_id int 
primary key, product_name varchar(45),
 product_cost float);
Step 3: TO INSERT VALUES IN TABLE
Query: 
INSERT INTO products VALUES
(1001,'Colgate Toothpaste', 2.25),
(1002, 'Sensodyne Toothpaste', 2.30),
(1003, 'Listrine Mouthwash', 1.75), 
(1004, 'T-Shirt', 1.75),
(1005, 'Pants', 2.35);
Step 4: Now let’s see the data inside the table we created.
Query:
SELECT * FROM products;
Output:
Step 5: TO UPDATE ALL DATA
Syntax:  
UPDATE table_name SET column_name1 = new_value1, 
column_name2 = new_value2 ----  ;
Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value. Let’s look at an example. 
Now our task is to update the product_cost to 4,  for all product_id(s), so let’s see how it is done.
Query:
UPDATE products SET product_cost = 4;
Output:
As you can see product_cost for all product_id(s)  is changed to 4.
Syntax:
UPDATE table_name SET column_name1 = new_value1, 
column_name2 = new_value2 ----  WHERE condition;
Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value, WHERE is used to filter for specific data.
Let’s look at an example.  
Now our task is to update the product_cost to 4,  for product_id 1001, so let’s see how it is done.
Query:
UPDATE products SET product_cost 
= 4 WHERE product_id = 1001;
Output:
As you can see product_cost for product_id 1001 is changed to 4.
Picked
SQL-Query
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
SQL | GROUP BY
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
Static Keyword in C++

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name.
Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block. The default value of static variable is zero. The static variables are alive till the execution of the program.
Here is the syntax of static keyword in C++ language,
static datatype variable_name = value;      // Static variable
static return_type function_name {             // Static functions
   ...
}

Here,
datatype − The datatype of variable like int, char, float etc.
variable_name − This is the name of variable given by user.
value − Any value to initialize the variable. By default, it is zero.
return_type − The datatype of function to return the value.
function_name − Any name to the function.
Here is an example of static variable in C++ language,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Base {
   public : static int val;
   static int func(int a) {
      cout << "\nStatic member function called";
      cout << "\nThe value of a : " << a;
   }
};
int Base::val=28;
int main() {
   Base b;
   Base::func(8);
   cout << "\nThe static variable value : " << b.val;
   return 0;
}
Static member function called
The value of a : 8
The static variable value : 28

In the above program, a static variable is declared and a static function is defined in the class Base as shown below −
public : static int val;
static int func(int a) {
   cout << "\nStatic member function called";
   cout << "\nThe value of a : " << a;
}
After the class and before main(), the static variable is initialized as follows −
int Base::val=28;

In the function main(), object of Base class is created and static variable is called. The static function is also called without using object of Base class as follows −
Base b;
Base::func(8);
cout << "\nThe static variable value : " << b.val;
Java program to calculate the percentage

Percent means percent (hundreds), i.e., a ratio of the parts out of 100. The symbol of a percent is %. We generally count the percentage of marks obtained, return on investment etc. The percentage can go beyond 100% also.
For Example, assuming that we have total and a part. So we say what part is what percent of total and should be calculated as −
percentage = ( part / total ) × 100
1. Collect values for part and total
2. Apply formula { percentage = ( part / total ) × 100 }
3. Display percentage
import java.util.Scanner;
public class Percentage {
   public static void main(String args[]){
      float percentage;
      float total_marks;
      float scored;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your marks ::");
      scored = sc.nextFloat();

      System.out.println("Enter total marks ::");
      total_marks = sc.nextFloat();

      percentage = (float)((scored / total_marks) * 100);
      System.out.println("Percentage ::"+ percentage);
   }
}
Enter your marks ::
500
Enter total marks ::
600
Percentage ::83.33333
BabelJS - CLI

Babel comes with a built-in command line interface, which can be used to compile the code.
Create a directory wherein you would be working. Here, we have created directory called babelproject. Let us make use of nodejs to create the project details.
We have used npm init to create the project as shown below −
Here is the project structure that we created.
Now to work with Babel we need to instal Babel cli, Babel preset, Babel core as shown below −
Execute the following command to install babel-cli −
npm install --save-dev babel-cli

Execute the following command to install babel-preset −
npm install --save-dev babel-preset-env

Execute the following command to install babel-core −
npm install --save-dev babel-core

After installation, here are the details available in package.json −
We have installed babel plugins local to the project. This is done so that we can use babel differently on our projects based on the project requirements and also different versions of babeljs. Package.json gives the version details of babeljs used.
In order to make use of babel in our project, we need to specify the same in package.json as follows −
Babel is mainly used to compile JavaScript code, which will have backward compatibility. Now, we will write our code in ES6 -> ES5 or ES7 -> ES5 also ES7->ES6, etc.
To provide instructions to Babel on the same, while executing, we need to create a file called .babelrc in the root folder. It contains a json object with details of the presets as shown below −
We will create the JavaScript file index.js and compile it to es2015 using Babel. Before that, we need to install the es2015 preset as follows −
In index.js, we have created a function using the arrow function which is a new feature added in es6. Using Babel, we will compile the code to es5.
To execute to es2015, following command is used −
npx babel index.js

It displays the index.js code in es5 as shown above.
We can store the output in the file by executing the command as shown below −
npx babel index.js --out-file index_es5.js

Here is the file that we created, index_es5.js −
 Print
 Add Notes
 Bookmark this page
Python OR Operator - GeeksforGeeks

19 Oct, 2021
Python OR Operator takes at least two boolean expressions and returns True if any one of the expressions is True. If all the expressions are False then it returns False.
Python OR operator returns True in any one of the boolean expressions passed is True.
Python3
bool1 = 2>3bool2 = 2<3  print('bool1:', bool1)print('bool2:', bool2)  # or operatorOR = bool1 or bool2print("OR operator:", OR)
bool1: False
bool2: True
OR operator: True
We can use the OR operator in the if statement. We can use it in the case where we want to execute the if block if any one of the conditions becomes if True.
Python3
# or operator with ifdef fun(a):    if a >= 5 or a <= 15:        print('a lies between 5 and 15')    else:        print('a is either less than 5 or greater than 15')    # driver codefun(10)fun(20)fun(5)
a lies between 5 and 15
a lies between 5 and 15
a lies between 5 and 15
In the above output, we can see that the code for the if statement is executed always. This is because for every value of a, one of the boolean expressions will always be True and the else block will never get executed.
The Python Or operator always evaluates the expression until it finds a True and as soon it Found a True then the rest of the expression is not checked. Consider the below example for better understanding.
Python3
# short circuit in Python or operatordef true():    print("Inside True")    return True  def false():    print("Inside False")    return False  case1 = true() or false()print("Case 1")print(case1)print()  case2 = true() or true()print("Case 2")print(case2)print()  case3 = false() or false()print("Case 3")print(case3)print()  case4 = false() or true()print("Case 4")print(case4)
Inside True
Case 1
True

Inside True
Case 2
True

Inside False
Inside False
Case 3
False

Inside False
Inside True
Case 4
True
From the above example, we can see that the short circuit or lazy evaluation is followed. In case1 and case2, the second expression is not evaluated because the first expression returns True, whereas, in case3 and case4 the second expression is evaluated as the first expression does not returns True.
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 | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
How to run JavaScript from PHP?

31 Jul, 2021
JavaScript is the client side scripting language and PHP is the server side scripting language. JavaScript is used as client side to check and verify client details and PHP is server side used to interact with database. In PHP, HTML is used as a string in the code. In order to render it to the browser, we produce JavaScript code as a string in the PHP code.
Example 1: Write JavaScript code within PHP code
<?php echo '<script type="text/JavaScript">      prompt("GeeksForGeeks");     </script>';?>
Output:
Example 2: Write JavaScript code outside of PHP code (in same PHP file)
<?php    // some php stuff?><script type="text/javascript">    alert('GeeksforGeeks!');</script>
Output:
Example 3: JavaScript Function – DOM Manipulation (in same PHP file)
<?php    echo "<div id='demo'></div>";?><script type="text/JavaScript">  // Function is called, return // value will end up in xvar x = myFunction(11, 10);   document.getElementById("demo").innerHTML = x;  // Function returns the product of a and bfunction myFunction(a, b) {    return a * b;             }</script>
Output:
110
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
Picked
Technical Scripter 2018
PHP
PHP Programs
Technical Scripter
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Handling large numbers in C++?

In C++, we can use large numbers by using the boost library. This C++ boost library is widely used library. This is used for different sections. It has large domain of applications. For example, using boost, we can use large number like 264 in C++.
Here we will see some examples of boost library. We can use big integer datatype. We can use different datatypes like int128_t, int256_t, int1024_t etc. By using this we can get precision up to 1024 easily.
At first we are multiplying two huge number using boost library.
#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
int128_t large_product(long long n1, long long n2) {
   int128_t ans = (int128_t) n1 * n2;
   return ans;
}
int main() {
   long long num1 = 98745636214564698;
   long long num2 = 7459874565236544789;
   cout << "Product of "<< num1 << " * "<< num2 << " = " <<
   large_product(num1,num2);
}
Product of 98745636214564698 * 7459874565236544789 =
736630060025131838840151335215258722
Another kind of datatype is that Arbitrary Precision Datatype. So we can use any precision using cpp_int datatype. It automatically assigns precision at runtime.
#include<iostream>
#include <boost/multiprecision/cpp_int.hpp>
using namespace boost::multiprecision;
using namespace std;
cpp_int large_fact(int num) {
   cpp_int fact = 1;
   for (int i=num; i>1; --i)
      fact *= i;
   return fact;
}
int main() {
   cout << "Factorial of 50: " << large_fact(50) << endl;
}
Factorial of 50:
30414093201713378043612608166064768844377641568960512000000000000
ggplot2 - Multi Panel Plots

Multi panel plots mean plot creation of multiple graphs together in a single plot. We will use par() function to put multiple graphs in a single plot by passing graphical parameters mfrow and mfcol.
Here we will use “AirQuality” dataset to implement multi panel plots. Let us understand the dataset first to have a look on creation of multi panel plots. This dataset includes Contains the responses of a gas multi-sensor device deployed on the field in an Italian city. Hourly responses averages are recorded along with gas concentrations references from a certified analyzer.
Understand the par() function to create a dimension of required multi panel plots.
> par(mfrow=c(1,2))
> # set the plotting area into a 1*2 array

This creates a blank plot with dimension of 1*2.
Now create the bar plot and pie chart of the mentioned dataset using following command. This same phenomenon can be achieved with the graphical parameter mfcol.
The only difference between the two is that, mfrow fills in the subplot region row wise while mfcol fills it column wise.
> Temperature <- airquality$Temp
> Ozone <- airquality$Ozone
> par(mfrow=c(2,2))
> hist(Temperature)
> boxplot(Temperature, horizontal=TRUE)
> hist(Ozone)
> boxplot(Ozone, horizontal=TRUE)

The boxplots and barplots are created in single window basically creating a multi panel plots.
Same plot with a change of dimensions in par function would look as follows −
par(mfcol = c(2, 2))

 Print
 Add Notes
 Bookmark this page
Python 3 - Number randrange() Method

The randrange() method returns a randomly selected element from range(start, stop, step).
Following is the syntax for the randrange() method
randrange ([start,] stop [,step])

Note − This function is not accessible directly, so we need to import the random module and then we need to call this function using the random static object.
start − Start point of the range. This would be included in the range. Default is 0
start − Start point of the range. This would be included in the range. Default is 0
stop − Stop point of the range. This would be included in the range. Default is 1
stop − Stop point of the range. This would be included in the range. Default is 1
step − Step point of the range. This would be excluded from the range.
step − Step point of the range. This would be excluded from the range.
This method returns a random item from the given range.
The following example shows the usage of the randrange() method.
#!/usr/bin/python3
import random

# randomly select an odd number between 1-100 
print ("randrange(1,100, 2) : ", random.randrange(1, 100, 2))

# randomly select a number between 0-99 
print ("randrange(100) : ", random.randrange(100))
When we run the above program, it produces the following result −
randrange(1,100, 2) :  83
randrange(100) :  93


    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
Ruby | Array sample() function

06 Dec, 2019
Array#sample() : sample() is a Array class method which returns a random element or n random elements from the array.
Syntax: Array.sample()
Parameter: Array
Return: a random element or n random elements from the array.
Example #1 :
# Ruby code for sample() method  # declaring arraya = [18, 22, 33, nil, 5, 6]  # declaring arrayb = [1, 4, 1, 1, 88, 9]  # declaring arrayc = [18, 22, 50, 6]  # sample method exampleputs "sample() method form : #{a.sample(2)}\n\n"  puts "sample() method form : #{b.sample(1)}\n\n"  puts "sample() method form : #{c.sample(3)}\n\n"
Output :
sample() method form : [6, nil]

sample() method form : [4]

sample() method form : [18, 22, 6]


Example #2 :
# Ruby code for sample() method  # declaring arraya = ["abc", "nil", "dog"]  # declaring arrayc = ["cat", nil]  # declaring arrayb = ["cow", nil, "dog"]  # sample method exampleputs "sample() method form : #{a.sample(2)}\n\n"  puts "sample() method form : #{b.sample(1)}\n\n"  puts "sample() method form : #{c.sample(3)}\n\n"
Output :
sample() method form : ["dog", "abc"]

sample() method form : ["dog"]

sample() method form : ["cat", nil]


Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Ruby | Array slice() function
Ruby | push() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Array select() function
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | unless Statement and unless Modifier
Python – Convert List of lists to list of Sets

25 Feb, 2021
Given a list containing lists, the task is to write a Python Program to convert it to a list containing sets.
Examples:
Input : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
Output : [{1, 2}, {1, 2, 3}, {2}, {0}]

Input : [[4, 4], [5, 5, 5], [1, 2, 3]]
Output : [{4}, {5}, {1, 2, 3}]
Method 1: Using list comprehension
This can easily be achieved using list comprehension. We just iterate through each list converting the lists to the sets.
Python3
# python3 program to convert list# of lists to a list of sets    # initializing listtest_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]  # printing original listprint("The original list of lists : " + str(test_list))  # using list comprehension# convert list of lists to list of setsres = [set(ele) for ele in test_list]  # print resultprint("The converted list of sets : " + str(res))
Output:
he original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
The converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}]
Method 2 : Using map() + set
We can use the combination of map function and set operator to perform this particular task. The map function binds each list and converts it into the set.
Python3
# Python3 code to demonstrate# convert list of lists to list of sets# using map() + set  # initializing listtest_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]  # printing original listprint("The original list of lists : " + str(test_list))  # using map() + setres = list(map(set, test_list))  # print resultprint("The converted list of sets : " + str(res))
Output:
The original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]
The converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}]
Python list-programs
Python set-programs
Technical Scripter 2020
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
LongSummaryStatistics getCount() method in Java with Examples

27 Jun, 2019
The getCount() method of LongSummaryStatistics class in Java is used to get the count of records in this LongSummaryStatistics.
Syntax:
public long getCount()

Parameter: This method do not accept any value as parameter.
Return Value: This method returns the count of the records in this LongSummaryStatistics.
Program:
// Java program to demonstrate// the above method  import java.util.*;  public class LongSummaryStatisticsDemo {    public static void main(String[] args)    {          LongSummaryStatistics longSummaryStatistics            = new LongSummaryStatistics();          List<Integer> list            = Arrays.asList(10, 20, 30, 40, 50);          Iterator<Integer> iterator = list.listIterator();        while (iterator.hasNext()) {              // Add the integers to the LongSummaryStatistics object            longSummaryStatistics.accept(iterator.next());        }          System.out.println("The count of values is "                           + longSummaryStatistics.getCount());    }}
The count of values is 5

Reference: https://docs.oracle.com/javase/10/docs/api/java/util/LongSummaryStatistics.html#getCount()
Java - util package
Java-Functions
Java-LongSummaryStatistics
Java
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
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
How to read multiple Excel files in R

18 Jul, 2021
In this article, we will discuss how to merge multiple Excel files in the R programming language.
dplyr: The dplyr package in R is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles.
plyr: The “plyr” package in R is used to work with data, including its enhancements and manipulations. 
readxl: This package is used to work with excel files in R
readr: This package is used to read files in R
list.files() function produces a character vector of the names of files or directories in the named directory.
Syntax: list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)
lapply() function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.
Syntax: lapply(X, FUN, ...)
bind_rows() function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one.
Syntax: bind_rows(..., .id = NULL)
Files in use:
gfg_data1.xlsx
gfg_data2.xlsx
gfg_data3.xlsx
Example: Merging Excel using R
R
library("dplyr")                                                library("plyr")                                                 library("readr")  library("readxl")  gfg_data <- list.files(path = "Location/to/folder",                           pattern = "*.xlsx",                       full.names = TRUE) %>%   lapply(read_excel) %>%                                             bind_rows                                                        gfg_data                                                         
Output:
Picked
R-Excel
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
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?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
R - if statement
How to access the JSON fields, arrays and nested objects of JsonNode in Java?


A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class.
In the below example, we can access JSON fields, arrays and nested objects of JsonNode.
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class ParseJSONNodeTest {
   public static void main(String args[]) {
      String jsonStr = "{ \"name\" : \"Raja\", \"age\" : 30," +
                       " \"technologies\" : [\"Java\", \"Scala\", \"Python\"]," +
                       " \"nestedObject\" : { \"field\" : \"value\" } }";
      ObjectMapper objectMapper = new ObjectMapper();
      try {
         JsonNode node = objectMapper.readValue(jsonStr, JsonNode.class);
         JsonNode nameNode = node.get("name");
         String name = nameNode.asText();
         System.out.println(name);
         JsonNode ageNode = node.get("age");
         int age = ageNode.asInt();
         System.out.println(age);
         JsonNode array = node.get("technologies");
         JsonNode jsonNode = array.get(1);
         String techStr = jsonNode.asText();
         System.out.println(techStr);
         JsonNode child = node.get("nestedObject");
         JsonNode childField = child.get("field");
         String field = childField.asText();
         System.out.println(field);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}
Raja
30
Scala
value
Java Program to check if two dates are equal

Let us first declare objects of LocalDate −
LocalDate dateOne = LocalDate.now();
LocalDate dateTwo = LocalDate.of(dateOne.getYear(), dateOne.getMonth(), dateOne.getDayOfMonth());
Let us now use the equals () method to check if both the dates are same or not −
if (dateOne.equals(dateTwo)) {
   System.out.printf("\nBoth the dates are same!", dateOne, dateTwo);
}
import java.time.LocalDate;
public class Demo {
   public static void main(String[] argv) {
      LocalDate dateOne = LocalDate.now();
      LocalDate dateTwo = LocalDate.of(dateOne.getYear(), dateOne.getMonth(), dateOne.getDayOfMonth());
      System.out.printf("Date One = "+dateOne);
      System.out.printf("\nDate Two = "+dateTwo);
      if (dateOne.equals(dateTwo)) {
         System.out.printf("\nBoth the dates are same!", dateOne, dateTwo);
      }
   }
}
Date One = 2019-04-12
Date Two = 2019-04-12
Both the dates are same!
How to set only numeric value for edittext in Android?

This example demonstrates how do I set only numeric value for editText in Android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/editText"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_centerVertical="true"
      android:ems="10"/>
   <Button
      android:id="@+id/button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/editText"
      android:layout_centerHorizontal="true"
      android:layout_marginTop="26dp"
      android:text="Click Here to set numeric value for
      EditText"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
   Button button;
   EditText editText;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      button = (Button) findViewById(R.id.button);
      editText = (EditText) findViewById(R.id.editText);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            editText.setInputType(InputType.TYPE_CLASS_NUMBER);
         }
      });
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
Python 3 - os.mkfifo() Method

The method mkfifo() create a FIFO named path with numeric mode. The default mode is 0666 (octal).The current umask value is first masked out.
FIFOs are pipes that can be accessed like regular files. FIFOs exist until they are deleted
Following is the syntax for mkfifo() method −
os.mkfifo(path[, mode])

path − This is the path, which needs to be created.
path − This is the path, which needs to be created.
mode − This is the mode of the named path to be given.
mode − This is the mode of the named path to be given.
This method does not return any value.
The following example shows the usage of mkfifo() method.
# !/usr/bin/python3
import os, sys

# Path to be created
path = "/tmp/hourly"
os.mkfifo( path, 0644 )

print ("Path is created")
When we run the above program, it produces the following result −
Path is created


    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
What does Integer.parseInt() method do in Java?

This is a static method of the class named Integer it accepts an integer parameter and Parses it as a signed decimal integer.
 Live Demo
public class IntegerDemo {
   public static void main(String[] args) {
      // parses the string argument
      int a = Integer.parseInt("12");
      int b = Integer.parseInt("26");
      int c = Integer.parseInt("54");
      int m = a * b * c;
      
      System.out.print("Value after multiplying = " + m);
   }
}
Value after multiplying = 16848
Tryit Editor v3.7

Tryit: HTML image map - circle area