code-rag-bench/online-tutorials huggingface dataset:
How to print an Array in Java without using Loop - GeeksforGeeks

26 Aug, 2019
Given an array arr in Java, the task is to print the contents of this array.
Loop method: The first thing that comes to mind is to write a for loop from i = 0 to n, and print each element by arr[i].
for(int i = 0; i < Array.length; i++)
        System.out.println(Array[i]);

This article tells how to print this array in Java without the use of any loop.
For this, we will use toString() method of Arrays class in the util package of Java. This method helps us to get the String representation of the array. This string can be easily printed with the help of print() or println() method.
Example 1: This example demonstrate how to get the String representation of an array and print this String representation.
// Java program to get the String// representation of an array and print it  import java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {          // Get the array        int arr[]            = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };          // Get the String representation of array        String stringArr = Arrays.toString(arr);          // print the String representation        System.out.println("Array: " + stringArr);    }}
Array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Example 2: This array can also be printed directly without creating a string.
// Java program to print an array// without creating its String representation  import java.io.*;import java.util.*;  class GFG {    public static void main(String[] args)    {          // Get the array        int arr[]            = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };          // Print the array        System.out.println("Array: "                           + Arrays.toString(arr));    }}
Array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Java-Array-Programs
Arrays
Java Programs
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Biopython - Pairwise Alignment - GeeksforGeeks

24 Oct, 2020
Pairwise Sequence Alignment is a process in which two sequences are compared at a time and the best possible sequence alignment is provided. Pairwise sequence alignment uses a dynamic programming algorithm. Biopython has a special module Bio.pairwise2 which identifies the alignment sequence using pairwise method. Biopython provides the best algorithm to find alignment sequence as compared to other software.
Let’s take two simple and hypothetical sequences as an example for using pairwise module.
Python3
# Import librariesfrom Bio import pairwise2from Bio.Seq import Seq  # Creating sample sequencesseq1 = Seq("TGTGACTA")seq2 = Seq("CATGGTCA")  # Finding similaritiesalignments = pairwise2.align.globalxx(seq1, seq2)  # Showing resultsfor match in alignments:    print(match)
Output: 
Here, the globalxx method does the main work, it follows the convention <alignment type>XX where XX is a code having two characters indicating the parameters it takes. First character indicates the matching and mismatching score while the second indicates the parameter for the gap penalty.
Match parameters :
gap penalty parameters :
For a nice printout Bio.pairwise2 provides format_alignment() method:
Python3
# Import librariesfrom Bio import pairwise2from Bio.Seq import Seqfrom Bio.pairwise2 import format_alignment  # Creating sqmple sequencesseq1 = Seq("TGTGACTA")seq2 = Seq("CATGGTCA")  # Finding similaritiesalignments = pairwise2.align.globalxx(seq1, seq2)  # Showing resultsfor alignment in alignments:    print(format_alignment(*alignment))
Output: 
There is another module provided by Biopython to do the pairwise sequence alignment. Align module has a PairwiseAligner() for this purpose. It has various APIs to set the parameters like mode, match score, algorithm, gap penalty, etc. Below is a simple implementation of the method:
Python3
# Import librariesfrom Bio import Alignfrom Bio.Seq import Seq  # Creating sample sequencesseq1 = Seq("TGTGACTA")seq2 = Seq("CATGGTCA")  # Calling methodaligner = Align.PairwiseAligner()  # Showing method attributesprint(aligner)  # Finding similaritiesalignments = aligner.align(seq1, seq2)  # Showing resultsfor alignment in alignments:    print(alignment)
Output:
Python-BioPython
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python
PyQt5 - Changing color of pressed Push Button - GeeksforGeeks

22 Apr, 2020
In this article we will see how to make a push button react when it is pressed. When button get releases it comes back to its original color, by default when button get clicked it becomes light blue color although we can change this color.
In order to change pressed button color we have to change the style sheet of pressed button, below is the style sheet code which is used with push button object.
QPushButton::clicked
{
background-color : red;
}

Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating push button widget        button = QPushButton("Button ", self)          # setting geometry        button.setGeometry(200, 100, 100, 40)          # adding background color to button        # and background color to pressed button        button.setStyleSheet("QPushButton"                             "{"                             "background-color : lightblue;"                             "}"                             "QPushButton::pressed"                             "{"                             "background-color : red;"                             "}"                             )      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
Print lists in Python (4 Different Ways)
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
ArangoDB - Web Interface

In this chapter, we will learn how to enable/disable the Authentication, and how to bind the ArangoDB to the Public Network Interface.
# arangosh --server.endpoint tcp://127.0.0.1:8529 --server.database "_system"

It will prompt you for the password saved earlier −
Please specify a password:

Use the password you created for root, at the configuration.
You can also use curl to check that you are actually getting HTTP 401 (Unauthorized) server responses for requests that require authentication −
# curl --dump - http://127.0.0.1:8529/_api/version

HTTP/1.1 401 Unauthorized
X-Content-Type-Options: nosniff
Www-Authenticate: Bearer token_type = "JWT", realm = "ArangoDB"
Server: ArangoDB
Connection: Keep-Alive
Content-Type: text/plain; charset = utf-8
Content-Length: 0

To avoid entering the password each time during our learning process, we will disable the authentication. For that, open the configuration file −
# vim /etc/arangodb3/arangod.conf

You should change the color scheme if the code is not properly visible.
:colorscheme desert

Set authentication to false as shown in the screenshot below.
Restart the service −
# service arangodb3 restart

On making the authentication false, you will be able to login (either with root or created user like Harry in this case) without entering any password in please specify a password.
Let us check the api version when the authentication is switched off −
# curl --dump - http://127.0.0.1:8529/_api/version

HTTP/1.1 200 OK
X-Content-Type-Options: nosniff
Server: ArangoDB
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
Content-Length: 60
{"server":"arango","version":"3.1.27","license":"community"}

 Print
 Add Notes
 Bookmark this page
Close specific Web page using Selenium in Python - GeeksforGeeks

04 Jan, 2021
Prerequisites: Selenium Basics, Selenium close() and quit() 
Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python.
The close() method is a web driver command which closes the browser window. During the automation process, if there are multiple browser windows opened, then the close() command will close the current browser window that is having attention at that time. 
Requirements:
You need to install chromedriver and set path. Click here to download.for more information follows this link.
Step-by-step Approach:
Import required modules
Python3
# import modulesfrom selenium import webdriverfrom selenium.webdriver.support.ui import Selectimport time
Taking any URL.
Python3
# assign web page urldriver.get("http://demo.automationtesting.in/Windows.html")
We want the child window of this web page then click on any button.
 Copy XPath.
Use the find_element_by_xpath() method to find XPath.
Python3
# find XPathdriver.find_element_by_xpath('//*[@id="Tabbed"]/a/button').click()
Create a handles variable who store all handles value of the open browser window.
Then the specified condition of the closing web page.
Python3
# return all handles value of open browser windowhandles = driver.window_handles  for i in handles:    driver.switch_to.window(i)      # close specified web page    if driver.title == "Frames & windows":        time.sleep(2)        driver.close()
The close() method closes current window page. Some pages are used for a long time some pages used for  short time. If we want to close a specific web page, we need to use some condition.
Implementation:
Python3
# import modulesfrom selenium import webdriverfrom selenium.webdriver.support.ui import Selectimport time  # use chrome driverdriver = webdriver.Chrome()  # assign web page urldriver.get("http://demo.automationtesting.in/Windows.html")  # find XPathdriver.find_element_by_xpath('//*[@id="Tabbed"]/a/button').click()  # return all handles value of open browser windowhandles = driver.window_handles  for i in handles:    driver.switch_to.window(i)      # close specified web page    if driver.title == "Frames & windows":        time.sleep(2)        driver.close()
Output:
Python Selenium-Exercises
Python-selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Connectivity, Distance, and Spanning Trees

One simple definition is that a tree is a connected graph associated with no cycles, where a cycle let's us go from a node to itself without repeating an edge.
A spanning tree for a connected graph G is defined as a tree containing all the vertices of G.
Spanning trees are often implemented for Internet routing Algorithms. In the Internet, computers (nodes) are often connected with many redundant physical connections.
Total number of Spanning Trees in a Graph. If a graph is a complete graph with n no. of vertices, then total number of spanning trees is n(n-2)
where n is denoted as the number of nodes in the graph. In complete graph, the task is equal to counting different labelled trees with n nodes for which have Cayley's formula.
In mathematics and computer science, connectivity is one of the basic concepts of graph theory
it requires the minimum number of elements (nodes or edges) that required to be removed to separate the remaining nodes into isolated subgraphs.
It is closely related to the theory of network flow problems.
This graph becomes disconnected when the dashed edge is eliminated.
Vertex Connectivity. The vertex connectivity of a graph is the at least number of nodes whose deletion disconnects it.
Vertex connectivity is sometimes denoted as "point connectivity" or simply "connectivity."
Edge Connectivity. The at least number of edges whose deletion from a graph disconnects, also denoted as the line connectivity.
The edge connectivity of a disconnected graph is 0, while that of a connected graph associated with a graph bridge is 1.
The distance between two nodes can be calculated in terms of lowest common ancestor. Following is the formula.
Dist(d1, d2) = Dist(root, d1) + Dist(root, d2) - 2*Dist(root, lca)
'd1' and 'd2' are the two given keys
'root' is root of given Binary Tree.
'lca' is lowest common ancestor of d1 and d2
Dist(d1, d2) is the distance between d1 and d2.
How to Add One Side Left Border to TextView in Android using XML?

This example demonstrate about How to Add One Side Left Border to TextView in Android using XML.
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"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app = "http://schemas.android.com/apk/res-auto"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <LinearLayout
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content"
      android:background = "@drawable/text_style"
      app:layout_constraintBottom_toBottomOf = "parent"
      app:layout_constraintLeft_toLeftOf = "parent"
      app:layout_constraintRight_toRightOf = "parent"
      app:layout_constraintTop_toTopOf = "parent">
      <TextView
         android:layout_width = "match_parent"
         android:layout_height = "wrap_content"
         android:layout_marginLeft = "10dp"
         android:text = "Hello World!"
         android:textSize = "30sp" />
   </LinearLayout>
</android.support.constraint.ConstraintLayout>
In the above code we have taken textview and linear layout. In Linear layout we have added background as text_style. So create a file called text_style.xml in drawable as shown below –
<?xml version = "1.0" encoding = "utf-8"?>
<layer-list xmlns:android = "http://schemas.android.com/apk/res/android">
   <item>
      <shape android:shape = "rectangle">
         <solid android:color = "#FFEB3B"/>
      </shape>
   </item>
   <item android:left = "4dp">
      <shape android:shape = "rectangle">
         <solid android:color = "#FFF"/>
      </shape>
   </item>
</layer-list>
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
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 –
In the above code, it shown one side border for textview.
Click here to download the project code
Delete only specific rows in a table with MySQL

To delete only specific rows, use MySQL NOT IN(). Let us first create a table −
mysql> create table DemoTable1830
     (
     StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
     StudentName varchar(20)
     )AUTO_INCREMENT=101;
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1830(StudentName) values('Chris');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1830(StudentName) values('David');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1830(StudentName) values('Mike');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1830(StudentName) values('Sam');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1830(StudentName) values('Bob');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1830;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       101 | Chris       |
|       102 | David       |
|       103 | Mike        |
|       104 | Sam         |
|       105 | Bob         |
+-----------+-------------+
5 rows in set (0.00 sec)
Here is the query to delete only specific rows −
mysql> delete from DemoTable1830
     where StudentId NOT IN('101','103','105');
Query OK, 2 rows affected (0.00 sec)
Let us check the table records once again:
mysql> select * from DemoTable1830;
This will produce the following output −
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
|       101 | Chris       |
|       103 | Mike        |
|       105 | Bob         |
+-----------+-------------+
3 rows in set (0.00 sec)
Pyspark — wrap your feature engineering in a pipeline | by Alexandre Wrg | Towards Data Science

In order to have a cleaner and more industrializable code, it may be useful to create a pipeline object that handles feature engineering. suppose we have this type of dataframe:
df.show()+----------+-----+|      date|sales|+----------+-----+|2018-12-22|   17||2017-01-08|   22||2015-08-25|   48||2015-03-12|  150|+----------+-----+
Then we want to create variables derived from the date. Most of the time, we’ll do something like this:
Now, we want to integrate the creation of these variables into a spark’s pipeline and, in addition, put some safeguards in place before their calculations. To do this, we will create a class that will inherit of the Transformermethod of spark’s pipelines and we will add a function that will check the inputs before the calculation.
Our class inherited the properties of the Spark Transformer which allows us to insert it into a pipeline.
this function allows us to make our object identifiable and immutable within our pipeline by assigning it a unique ID
defaultCopy Tries to create a new instance with the same UID. Then it copies the embedded and extra parameters over and returns the new instance.
Then the check_input_type function is used to check that the input field is in the right format and finally we simply implement the SQL Functions F.day of month to return our columns.
we will reuse this skeleton to create the other variables we need, the only change to make will be the ID and the _transform function
We have defined MonthQuarterExtractor that have the same skeleton, it may seem like a verbose compared to the withColumn method but much cleaner!
Finally we do the same for the year variable.
Now let’s integrate them into our pipeline.
df.show()+----------+-----+----------+----+------------+|      date|sales|dayofmonth|year|monthquarter|+----------+-----+----------+----+------------+|2018-12-22|   17|        22|2018|           2||2017-01-08|   22|         8|2017|           0||2015-08-25|   48|        25|2015|           3||2015-03-12|  150|        12|2015|           1|+----------+-----+----------+----+------------+
The trick is done, we created a “customs” transformer and inserted it into a spark pipeline. It is also possible to insert them into a pipeline with other objects, a vector assembler, a string indexer or other.
Spark pipelines are a very powerful tool, we can manage almost the entirety of a data science project in a single pipeline while keeping the traceability of each object and allows a simpler industrialization of the code, do not hesitate to abuse it!
Thank you for reading me, if you are interested in more tips | tutorial on Pyspark do not hesitate to leave a comment. (You can find the code here : https://github.com/AlexWarembourg/Medium)
Tryit Editor v3.7

HTML Form attributes
Tryit: The formenctype attribute
Using Iterations in Python Effectively

In this article, we will learn about how to implement iterators and their effective implementation in Python 3.x. Or earlier. Let’ s take a look at various methods available in python which implements iterators.
 Live Demo
genre = ("Python","C","C++","Java")
print("The topic available on Tutorial's Point are:")
i = 0
while (i < len(genre)):
   print (genre[i])
   i += 1
Due to its less compact structure, this method is not favored. Error Handling is also difficult in this case . Large-scale programs or designs doesn’t use this approach.
The topic available on Tutorial's Point are:
Python
C
C++
Java
 Live Demo
genre = ("Python","C","C++","Java")
print("The topic available on Tutorial's Point are:")
for i in range(len(genre)):
   print (genre[i])
This is the most favoured method used by programmers. Here range() functions serves as a medium to increment or decrement the iterator. By default, it increments the iterator by 1. In case we specify the step of incrementation or decrementation, it works according to the step value provided.
The topic available on Tutorial's Point are:
Python
C
C++
Java
 Live Demo
genre = ("Python","C","C++","Java")
print("The topic available on Tutorial's Point are:")
for i in genre:
   print (i)
This method is usually favoured in linear data structures like lists, dictionary, tuples, n dimensional-arrays, etc. The iterator traversed each component of the specified structure and displays data to the console. Incrementation is automatic in this type.
The topic available on Tutorial's Point are: Python C C++ Java
 Live Demo
genre = ("Python","C","C++","Java")
iterator = enumerate(genre)
print("The topic available on Tutorial's Point are:")
for i,v in iterator:
   print (v,end="\t")
In this case enumerate helps us to create a dictionary in which indexes serves as keys and values in the list as their corresponding values. Here we have to specify two iterators; one for the index and another for the value to be displayed.
The topic available on Tutorial's Point are:
PythonCC++Java
 Live Demo
genre = ("Python","C","C++","Java")
extras = ["C#","Dart","Erlang","Go"]
print("The topic available on Tutorial's Point are:")
for i, j in zip(genre,extras):
   print (i, j,sep="\t")
Here we specify two linear data structure i.e. list, array or tuple with the help two iterators. To do this we take the help of zip function which comes very handy while handling various scenarios. It takes up the data structure with a shorter length and skips the content of the larger data structure.
The topic available on Tutorial's Point are:
PythonC#
CDart
C++Erlang
JavaGo
In this article, we learnt how to implement the Stack & Queue data structure in Python 3.x. Or earlier. You can implement the same algorithm to implement a stack/queue detector program in any other programming language.
JavaScript - The Math Object

The math object provides you properties and methods for mathematical constants and functions. Unlike other global objects, Math is not a constructor. All the properties and methods of Math are static and can be called by using Math as an object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument.
The syntax to call the properties and methods of Math are as follows
var pi_val = Math.PI;
var sine_val = Math.sin(30);

Here is a list of all the properties of Math and their description.
Euler's constant and the base of natural logarithms, approximately 2.718.
Natural logarithm of 2, approximately 0.693.
Natural logarithm of 10, approximately 2.302.
Base 2 logarithm of E, approximately 1.442.
Base 10 logarithm of E, approximately 0.434.
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
Square root of 2, approximately 1.414.
In the following sections, we will have a few examples to demonstrate the usage of Math properties.
Here is a list of the methods associated with Math object and their description
Returns the absolute value of a number.
Returns the arccosine (in radians) of a number.
Returns the arcsine (in radians) of a number.
Returns the arctangent (in radians) of a number.
Returns the arctangent of the quotient of its arguments.
Returns the smallest integer greater than or equal to a number.
Returns the cosine of a number.
Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm.
Returns the largest integer less than or equal to a number.
Returns the natural logarithm (base E) of a number.
Returns the largest of zero or more numbers.
Returns the smallest of zero or more numbers.
Returns base to the exponent power, that is, base exponent.
Returns a pseudo-random number between 0 and 1.
Returns the value of a number rounded to the nearest integer.
Returns the sine of a number.
Returns the square root of a number.
Returns the tangent of a number.
Returns the string "Math".
In the following sections, we will have a few examples to demonstrate the usage of the methods associated with Math.

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Redux - Actions

Actions are the only source of information for the store as per Redux official documentation. It carries a payload of information from your application to store.
As discussed earlier, actions are plain JavaScript object that must have a type attribute to indicate the type of action performed. It tells us what had happened. Types should be defined as string constants in your application as given below −
const ITEMS_REQUEST = 'ITEMS_REQUEST';

Apart from this type attribute, the structure of an action object is totally up to the developer. It is recommended to keep your action object as light as possible and pass only the necessary information.
To cause any change in the store, you need to dispatch an action first by using store.dispatch() function. The action object is as follows −
{ type: GET_ORDER_STATUS , payload: {orderId,userId } }
{ type: GET_WISHLIST_ITEMS, payload: userId }

Action creators are the functions that encapsulate the process of creation of an action object. These functions simply return a plain Js object which is an action. It promotes writing clean code and helps to achieve reusability.
Let us learn about action creator which lets you dispatch an action, ‘ITEMS_REQUEST’ that requests for the product items list data from the server. Meanwhile, the isLoading state is made true in the reducer in ‘ITEMS_REQUEST’ action type to indicate that items are loading, and data is still not received from the server.
Initially, the isLoading state was false in the initialState object assuming nothing is loading. When data is received at browser, isLoading state will be returned as false in ‘ITEMS_REQUEST_SUCCESS’ action type in the corresponding reducer. This state can be used as a prop in react components to display loader/message on your page while the request for data is on. The action creator is as follows −
const ITEMS_REQUEST = ‘ITEMS_REQUEST’ ;
const ITEMS_REQUEST_SUCCESS = ‘ITEMS_REQUEST_SUCCESS’ ;
export function itemsRequest(bool,startIndex,endIndex) {
   let payload = {
      isLoading: bool,
      startIndex,
      endIndex
   }
   return {
      type: ITEMS_REQUEST,
      payload
   }
}
export function itemsRequestSuccess(bool) {
   return {
      type: ITEMS_REQUEST_SUCCESS,
      isLoading: bool,
   }
}
To invoke a dispatch function, you need to pass action as an argument to dispatch function.
dispatch(itemsRequest(true,1, 20));
dispatch(itemsRequestSuccess(false));

You can dispatch an action by directly using store.dispatch(). However, it is more likely that you access it with react-Redux helper method called connect(). You can also use bindActionCreators() method to bind many action creators with dispatch function.

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    63 Lectures 
     9.5 hours 

 TELCOMA Global

    129 Lectures 
     19.5 hours 

 Ghulam Abbas

    31 Lectures 
     3 hours 

 Saumitra Vishal

    55 Lectures 
     4 hours 

 Saumitra Vishal
 Print
 Add Notes
 Bookmark this page
Area of a circle inscribed in a regular hexagon?

The circle inscribed in a regular hexagon has 6 points touching the six sides of the regular hexagon.
To find the area of inscribed circle we need to find the radius first. For the regular hexagon the radius is found using the formula, a(√3)/2.
Now area of the circle inscribed is 3πa*a/4
Side of hexagon − 4
Area = 37.68
 Live Demo
#include <stdio.h>
int main(void) {
   int a = 14;
   float pie = 3.14;
   float area = (float)(3*a*a*pie/4);
   printf("The area of circle inscribed in the hexagon of side %d is %f", a, area);
   return 0;
}
The area of circle inscribed in the hexagon of side 14 is 461.580017
switch statement examples:

C - Programming HOME
C - Basic Introduction
C - Program Structure
C - Reserved Keywords
C - Basic Datatypes
C - Variable Types
C - Storage Classes
C - Using Constants
C - Operator Types
C - Control Statements
C - Input and Output
C - Pointing to Data
C - Using Functions
C - Play with Strings
C - Structured Datatypes
C - Working with Files
C - Bits Manipulation
C - Pre-Processors
C - Useful Concepts
C - Built-in Functions
C - Useful Resources
Computer Glossary
Who is Who
Copyright © 2014 by tutorialspoint
Try following example to understand switch statement. You can put the following code into a test.c file and then compile it and then run it .
#include <stdio.h>

main()
{
     int  Grade = 'A';

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
        case 'B' : printf( "Good\n" );
        case 'C' : printf( "OK\n" );
        case 'D' : printf( "Mmmmm....\n" );
        case 'F' : printf( "You must do better than this\n" );    
        default  : printf( "What is your grade anyway?\n" );
     }	
}


This will produce following result:
Excellent
Good
OK
Mmmmm....
You must do better than this    
What is your grade anyway?

You can come out of the switch block if your condition is met. This can be achieved using break statement. Try out following example:
#include <stdio.h>

main()
{
     int  Grade = 'B';

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
                   break;
        case 'B' : printf( "Good\n" );
                   break;
        case 'C' : printf( "OK\n" );
                   break;
        case 'D' : printf( "Mmmmm....\n" );
                   break;
        case 'F' : printf( "You must do better than this\n" );
                   break;
        default  : printf( "What is your grade anyway?\n" );
                   break;
     }
}


This will produce following result:
Good

If none of the conditions is met then default condition is executed. Try out following example to understand default condition.
#include <stdio.h>

main()
{
     int  Grade = 'L';

     switch( Grade )
     {
        case 'A' : printf( "Excellent\n" );
                   break;
        case 'B' : printf( "Good\n" );
                   break;
        case 'C' : printf( "OK\n" );
                   break;
        case 'D' : printf( "Mmmmm....\n" );
                   break;
        case 'F' : printf( "You must do better than this\n" );
                   break;
        default  : printf( "What is your grade anyway?\n" );
                   break;
     }
}


This will produce following result:
What is your grade anyway?


Advertisements


    6 Lectures 
     1.5 hours 

 Mr. Pradeep Kshetrapal

    41 Lectures 
     5 hours 

 AR Shankar

    11 Lectures 
     58 mins

 Musab Zayadneh

    59 Lectures 
     15.5 hours 

 Narendra P

    11 Lectures 
     1 hours 

 Sagar Mehta

    39 Lectures 
     4 hours 

 Vikas Yadav
 Print
 Add Notes
 Bookmark this page
set::clear in C++ STL

22 Jan, 2018
Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.
clear() function is used to remove all the elements of the set container, thus making its size 0.
Syntax :
setname.clear()
Parameters :
No parameters are passed.
Result :
All the elements of the set are
removed ( or destroyed )
Examples:
Input  : set{1, 2, 3, 4, 5};
         set.clear();
Output : set{}

Input  : set{};
         set.clear();
Output : set{}

Errors and Exceptions
1. It has a no exception throw guarantee.2. Shows error when a parameter is passed.
// INTEGER SET// CPP program to illustrate// Implementation of clear() function#include <iostream>#include <set>using namespace std;  int main(){    set<int> myset{ 1, 2, 3, 4, 5 };      myset.clear();    // Set becomes empty      // Printing the Set    for (auto it = myset.begin();         it != myset.end(); ++it)        cout << ' ' << *it;    return 0;}
Output:
No Output

// CHARACTER SET// CPP program to illustrate// Implementation of clear() function#include <iostream>#include <set>using namespace std;  int main(){    set<char> myset{ 'A', 'b', 'd', 'e' };      myset.clear();    // Set becomes empty      // Printing the Set    for (auto it = myset.begin();         it != myset.end(); ++it)        cout << ' ' << *it;    return 0;}
Output:
No Output

Time complexity: Linear i.e. O(n)
cpp-set
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL
How to solve “Process out of Memory Exception” in Node.js ?

02 Jul, 2021
In this article, we will learn how to solve the ProcessOutOfMemory exception in NodeJS. Process out of Memory Exception is an exception that occurs when your node.js program gets out of memory. This happens when the default memory allocated to our program gets exceeded by our program while execution. 
This exception can be solved by increasing the default memory allocated to our program to the required memory by using the following command.
Syntax:
node --max-old-space-size=<SPACE_REQD> index.js
Parameters: 
SPACE_REQD: Pass the increased memory space (in Megabytes).
Example: First, let’s recreate this exception then we will understand the reason behind this exception.
index.js
let items = [];  for (let i = 0; i < 99999995; i++) {    items.push(i);}  console.log(items);
Run the index.js file using the following command.
node index.js
Output: We will get a FATAL ERROR saying FatalProcessOutOfMemory as shown below.
Note: The default memory allocated to a node.js program is 512MB on 32-bit systems and 1024MB on 64-bit systems (Above program was run on a 64-bit system).
Example 1: In the below example, we have increased the memory space requirements to 2048MB or 2GB. Use the following command to run the JS file(index.js in my case).
Syntax: 
node --max-old-space-size=2048 index.js
Now we can see, that our program is running perfectly without any exceptions. If you run the below code by using the standard “node index.js” command, it will throw the same exception: FatalProcessOutOfMemory, because our program exceeds the default memory space allocated to it.
So we use the –max-old-space-size command to increase the allocated memory space, so our program won’t run out of memory.
index.js
let items = [];  for (let i = 0; i < 99999995; i++) {    items.push(i);}  console.log(items);
Output:
Example 2: In the below example, we have increased the memory space requirements to 3072MB or 3GB. Use the following command to run the JS file(index.js in my case).
Syntax: 
node --max-old-space-size=3072 index.js
If you run the below code by using the standard “node index.js” command, it will throw the same exception: FatalProcessOutOfMemory, because our program exceeds the default memory space allocated to it. 
So we use the –max-old-space-size command to increase the allocated memory space, so our program won’t run out of memory.
index.js
let items = [];  for (let i = 0; i < 90000000; i++) {    items.push("GeeksforGeeks");}  console.log(items);
Output:
Exception Handling
NodeJS-Questions
Picked
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Check whether a given column is present in a Pandas DataFrame or not

29 Jul, 2021
Consider a Dataframe with 4 columns : ‘ConsumerId’, ‘CarName’, CompanyName, and ‘Price’.  We have to determine whether a particular column is present in the DataFrame or not. 
In this pandas program, we are using Dataframe.columns attribute That return the column labels of the given Dataframe.
Syntax: Dataframe.columns
Parameter: None
Returns: column names
Let’s create a Dataframe:Code: 
Python
# import pandas libraryimport pandas as pd # dictionaryd = {'ConsumerId': [1, 2, 3,                    4, 5],     'CarName': ['I3', 'S4', 'J3',                 'Mini', 'Beetle'],     'CompanyName': ['BMW','Mercedes', 'Jeep',                     'MiniCooper', 'Volkswagen'],     'Price': [1200, 1400, 1500,               1650, 1750]    } # create a dataframedf = pd.DataFrame(d) # show the dataframedf
Output: 
Example 1: To check whether the ‘ConsumerId’ column exists in Dataframe or not. 
Python
if 'ConsumerId' in df.columns :  print('ConsumerId column is present')    else:  print('ConsumerId column is not present')
  Output:  
ConsumerId column is present
Example 2: To check whether the ‘CarName’ column exists in Dataframe or not.
Python
if 'CarName' in df.columns:  print('CarName column is present')    else:  print('CarName column is not present')
 Output:  
CarName column is present
 Example 3: To check whether the ‘CarType’ column exists in Dataframe or not. 
Python
if 'CarType' in df.columns:  print('CarType column is present')    else:  print('CarType column is not present')
Output: 
CarType column is not present
surindertarika1234
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Python | os.rename() method

26 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.rename() method in Python is used to rename a file or directory.This method renames a source file/ directory to specified destination file/directory.
Syntax: os.rename(source, destination, *, src_dir_fd = None, dst_dir_fd = None)
Parameters:source: A path-like object representing the file system path. This is the source file path which is to renamed.destination: A path-like object representing the file system path.src_dir_fd (optional): A file descriptor referring to a directory.dst_dir_fd (optional): A file descriptor referring to a directory.
Return Type: This method does not return any value.
# Python program to explain os.rename() method   # importing os module import os    # Source file pathsource = 'GeeksforGeeks/file.txt'  # destination file pathdest = 'GeekforGeeks/newfile.txt'    # Now rename the source path# to destination path# using os.rename() methodos.rename(source, dest)print("Source path renamed to destination path successfully.")
Source path renamed to destination path successfully.

# Python program to explain os.rename() method   # importing os module import os    # Source file pathsource = './GeeksforGeeks/file.txt'  # destination file pathdest = './GeeksforGeeks/dir'    # try renaming the source path# to destination path# using os.rename() method  try :    os.rename(source, dest)    print("Source path renamed to destination path successfully.")  # If Source is a file # but destination is a directoryexcept IsADirectoryError:    print("Source is a file but destination is a directory.")  # If source is a directory# but destination is a fileexcept NotADirectoryError:    print("Source is a directory but destination is a file.")  # For permission related errorsexcept PermissionError:    print("Operation not permitted.")  # For other errorsexcept OSError as error:    print(error)
Source is a file but destination is a directory.

Reference: https://docs.python.org/3/library/os.html#os.rename
python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Lex program to check whether given number is armstrong number or not

09 May, 2019
Problem: Lex program to check whether given number is armstrong number or not.
Explanation:Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Description:An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits. For example, 153 is an Armstrong number,
(1^3) + (5^3) + (3^3) = 153 
Examples:
Input: 153 
Output: 153 is a Armstrong number

Input: 250
Output: 250 is not a Armstrong number 
Implementation:
/* Lex program to check whether given     - number is armstrong number or not */%{/* Definition section */#include <math.h>#include <string.h>    void check(char*);    %}  /* Rule Section */% %        [0 - 9]    + check(yytext);% %   int main(){    /* yyin as pointer of File type */    extern FILE* yyin;    yyin = fopen("num", "r");      // The function that starts the analysis    yylex();      return 0;}void check(char* a){    int len = strlen(a), i, num = 0;    for (i = 0; i < len; i++)        num = num * 10 + (a[i] - '0');      int x = 0, y = 0, temp = num;    while (num > 0) {        y = pow((num % 10), len);        x = x + y;        num = num / 10;    }      if (x == temp)        printf("%d is armstrong number \n", temp);    else        printf("%d is not armstrong number\n", temp);}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | canvas drawImage() Method

09 Jun, 2021
In HTML5, canvas drawImage() function is used to display an image or video on canvas. This function can be used to display the whole image or just a small part of the image. But, image has to be loaded first to load it further on canvas. 
Syntax: 
context.drawImage(img, x, y, swidth, sheight, sx, sy, width, height);
Parameter Values:  
img: It indicates the image or video to draw on canvas.
x: It indicates the x-coordinate where image has to be placed.
y: It indicates the y-coordinate where image has to be placed.
swidth: It is optional parameter and indicates the width of the clipped image.
sheight: It is optional parameter and indicates the height of the clipped image.
sx: It is optional parameter and indicates x-coordinate where to start the clipping.
sy: It is optional parameter and indicates y-coordinate where to start the clipping.
width: It is optional parameter and indicates the width of the image to use.
height: It is optional parameter and indicates the height of the image to use.
Example:  
HTML
<!DOCTYPE html><html> <head>    <title>        HTML | canvas drawImage() Method    </title></head> <body>     <p>Image:</p>     <img id="GFG" width="480" height="240"        src="canvas drawImage.png" alt="The Scream" />      <p>Canvas:</p>      <canvas id="myGFGCanvas" width="520" height="300"            style="border: 1px solid #d3d3d3;">        Your browser is not supported        for HTML5 canvas tag.    </canvas>     <script>        window.onload = function () {            var c = document.getElementById("myGFGCanvas");            var ctx = c.getContext("2d");            var img = document.getElementById("GFG");            ctx.drawImage(img, 20, 20);        };    </script></body> </html>
Output: 
 
sagar0719kumar
HTML-Methods
HTML5
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
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
REST API (Introduction)