code-rag-bench/online-tutorials huggingface dataset:
ReactJS componentDidCatch() Method - GeeksforGeeks

10 Aug, 2021
The componentDidCatch() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the commit phase, so unlike getDerivedStateFromError() which was called during the render phase, side-effects are allowed in this method. This method is also used to log errors.
Syntax:
componentDidCatch(error, info)
Parameters: It accepts two parameters i.e, error, and info as described below:
error: It is the error that was thrown by the descendant component.
info: It stores the componentStack trace of which component has thrown this error.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Project Structure: It will look like the following.
Project Structure
Example: Program to demonstrate the use of componentDidCatch() method.
Filename: App.js:  
Javascript
import React, { Component } from 'react'; export default class App extends Component {  // Initializing the state  state = {    error: false,  };   componentDidCatch(error) {    // Changing the state to true    // if some error occurs    this.setState({      error: true    });  }   render() {    return (      <React.StrictMode>        <div>          {this.state.error ? <div>Some error</div> : <GFGComponent />}        </div>      </React.StrictMode>    );  }} class GFGComponent extends Component {   // GFGComponent throws error as state of  // GFGCompnonent is not defined     render() {    return <h1>{this.state.heading}</h1>;  }}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
output
Reference: https://reactjs.org/docs/react-component.html#componentdidcatch
saurabh1990aror
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Top 10 Angular Libraries For Web Developers
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
How to Insert Form Data into Database using PHP ?
How to redirect to another page in ReactJS ?
How to execute PHP code using command line ?
How to pass data from child component to its parent in ReactJS ?
Java program to calculate the product of two numbers

The * operator in Java is used to multiply two numbers. Read required numbers from the user using Scanner class and multiply these two integers using the * operator.
import java.util.Scanner;
public class MultiplicationOfTwoNumbers {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the value of the first number ::");
      int a = sc.nextInt();
      System.out.println("Enter the value of the first number ::");
      int b = sc.nextInt();
      int result = a*b;
      System.out.println("Product of the given two numbers is ::"+result);
   }
}
Enter the value of the first number ::
55
Enter the value of the first number ::
66
Product of the given two numbers is ::3630
Basic calculator program using C#

To create a calculator program in C#, you need to use Web Forms. Under that create buttons from 1-9, addition, subtraction, multiplication, etc.
Let us see the code for addition, subtraction, and multiplication. Firstly, we have declared two variables −
static float x, y;
Now, we will see how to set codes for calculation on individual button click: Our result textbox is tbResult since we have used Windows Form as well to display the calculator −
protected void add_Click(object sender, EventArgs e) {
   x = Convert.ToInt32(tbResult.Text);
   tbResult.Text = "";
   y = '+';
   tbResult.Text += y;
}
protected void sub_Click(object sender, EventArgs e) {
   x = Convert.ToInt32(tbResult.Text);
   tbResult.Text = "";
   y = '-';
   tbResult.Text += y;
}
protected void mul_Click(object sender, EventArgs e) {
   x = Convert.ToInt32(tbResult.Text);
   tbResult.Text = "";
   y = '*';
   tbResult.Text += y;
}
The following is the equal button code −
protected void eql_Click(object sender, EventArgs e) {
   z = Convert.ToInt32(tbResult.Text);
   tbResult.Text = "";
   if (y == '/') {
      p = x / z;
      tbResult.Text += p;
      x = d;
   } else if (y == '+') {
      p = x + z;
      tbResult.Text += p;
      a = d;
   } else if (y == '-') {
      p = x - z;
      tbResult.Text += p;
      x = p;
   } else {
      p = x * z;
      tbResult.Text += p;
      x = p;
   }
}
How to write JavaScript in an External File?

Create external JavaScript file with the extension .js. After creating, add it to the HTML file in the script tag. The src attribute is used to include that external JavaScript file.
If you have more than one external JavaScript file, then add it in the same web page to increase performance of the page.
Let’s say the following new.js is our external JavaScript file −
function display() {
   alert("Hello World!");
}
Now add the external JavaScript file to the HTML web page −
<html>
   <body>
      <form>
      <input type="button" value="Result" onclick="display()"/>
      </form>
      <script src="new.js">
      </script>
   </body>
</html>
How to convert negative values in an R data frame to positive values?

Sometimes we need to use absolute values but few values in the data set are negative, therefore, we must convert them to positive. This can be done by using abs function. For example, if we have a data frame df with many columns and each of them having some negative values then those values can be converted to positive values by just using abs(df).
Consider the below data frame −
 Live Demo
set.seed(41)
x1<-sample(-1:1,20,replace=TRUE)
x2<-sample(-5:1,20,replace=TRUE)
df1<-data.frame(x1,x2)
df1
  x1 x2
1  1 -2
2 -1 -4
3  0  1
4  0  0
5 -1 -2
6  0   0
7  0  -4
8  0  -4
9   0 -2
10  1 -2
11  0 -1
12  1 -3
13 -1 -5
14  -1 0
15  0 -3
16 -1 -3
17  0 -5
18 -1 -2
19 -1 -5
20 -1 -4
Converting all the values in df1 to positive values −
> abs(df1)
  x1 x2
1  1 2
2  1 4
3  0 1
4  0 0
5  1 2
6  0 0
7  0 4
8  0 4
9  0 2
10 1 2
11 0 1
12 1 3
13 1 5
14 1 0
15 0 3
16 1 3
17 0 5
18 1 2
19 1 5
20 1 4
Let’s have a look at another example −
 Live Demo
y1<-sample(-10:10,20,replace=TRUE)
y2<-sample(-100:1,20)
y3<-sample(-100:-91,20,replace=TRUE)
y4<-sample(c(-100,-50,0,50,100),20,replace=TRUE)
df2<-data.frame(y1,y2,y3,y4)
df2
   y1  y2 y3  y4
1   8 -12 -99 100
2  -2 -37 -93 -50
3  -5 -85 -93 -100
4   6 -16 -93   0
5   2 -51 -91 50
6  -5 -50 -94 100
7   0 -38 -92 100
8  -3 -20 -95 -50
9   1 -42 -96 100
10 -8 -31 -94 -50
11 -4 -75 -100 0
12 -5 -80 -94 100
13  0 -1  -95   0
14  2 -99 -99  50
15  9 -45 -97 -50
16 -6 -79 -93  50
17 -2 -52 -94  0
18  9 -82 -96  50
19  8 -32 -95  0
20  4 -11 -99 -100
Converting all the values in df2 to positive values −
abs(df2)
  y1 y2 y3 y4
1  8 12 99 100
2  2 37 93 50
3  5 85 93 100
4  6 16 93 0
5  2 51 91 50
6  5 50 94 100
7  0 38 92 100
8  3 20 95 50
9  1 42 96 100
10 8 31 94 50
11 4 75 100 0
12 5 80 94 100
13 0 1 95 0
14 2 99 99 50
15 9 45 97 50
16 6 79 93 50
17 2 52 94 0
18 9 82 96 50
19 8 32 95 0
20 4 11 99 100
First uppercase letter in a string (Iterative and Recursive) in C++

In this tutorial, we are going to learn how find the first uppercase letter in the given string. Let's see an example.
Input −Tutorialspoint
Output −T
Let's see the steps to solve the problem using iterative method.
Initialize the string.
Initialize the string.
Iterate over the string.
Iterate over the string.
Check whether the current character is uppercase or not using isupper method.
Check whether the current character is uppercase or not using isupper method.
If the character is uppercase than return the current character.
If the character is uppercase than return the current character.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
char firstUpperCaseChar(string str) {
   for (int i = 0; i < str.length(); i++)
      if (isupper(str[i])) {
         return str[i];
      }
      return 0;
   }
   int main() {
      string str = "Tutorialspoint";
      char result = firstUpperCaseChar(str);
      if (result == 0) {
         cout << "No uppercase letter" << endl;
      }
      else {
         cout << result << endl;
      }
   return 0;
}
If you run the above code, then you will get the following result.
T
Let's see the steps to solve the problem using recursive method.
Initialize the string.
Initialize the string.
Write a recursive function which accepts two parameter string and index.
Write a recursive function which accepts two parameter string and index.
If the current character is end of the string then return.
If the current character is end of the string then return.
If the current character is uppercase then return the current character.
If the current character is uppercase then return the current character.
Let's see the code.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
char firstUpperCaseChar(string str, int i = 0) {
   if (str[i] == '\0') {
      return 0;
   }
   if (isupper(str[i])) {
      return str[i];
   }
   return firstUpperCaseChar(str, i + 1);
}
int main() {
   string str = "Tutorialspoint";
   char result = firstUpperCaseChar(str);
   if (result == 0) {
      cout << "No uppercase letter";
   }
   else {
      cout << result << endl;
   }
   return 0;
}
If you run the above code, then you will get the following result.
T
If you have any queries in the tutorial, mention them in the comment section.
Graphs and its traversal algorithms

In this section we will see what is a graph data structure, and the traversal algorithms of it.
The graph is one non-linear data structure. That is consists of some nodes and their connected edges. The edges may be director or undirected. This graph can be represented as G(V, E). The following graph can be represented as G({A, B, C, D, E}, {(A, B), (B, D), (D, E), (B, C), (C, A)})
The graph has two types of traversal algorithms. These are called the Breadth First Search and Depth First Search.
The Breadth First Search (BFS) traversal is an algorithm, which is used to visit all of the nodes of a given graph. In this traversal algorithm one node is selected and then all of the adjacent nodes are visited one by one. After completing all of the adjacent vertices, it moves further to check another vertices and checks its adjacent vertices again.
bfs(vertices, start)
Input: The list of vertices, and the start vertex.
Output: Traverse all of the nodes, if the graph is connected.
Begin
   define an empty queue que
   at first mark all nodes status as unvisited
   add the start vertex into the que
   while que is not empty, do
      delete item from que and set to u
      display the vertex u
      for all vertices 1 adjacent with u, do
         if vertices[i] is unvisited, then
            mark vertices[i] as temporarily visited
            add v into the queue
         mark
      done
      mark u as completely visited
   done
End
The Depth First Search (DFS) is a graph traversal algorithm. In this algorithm one starting vertex is given, and when an adjacent vertex is found, it moves to that adjacent vertex first and try to traverse in the same manner.
dfs(vertices, start)
Input: The list of all vertices, and the start node.
Output: Traverse all nodes in the graph.
Begin
   initially make the state to unvisited for all nodes
   push start into the stack
   while stack is not empty, do
      pop element from stack and set to u
      display the node u
      if u is not visited, then
         mark u as visited
         for all nodes i connected to u, do
            if ith vertex is unvisited, then
               push ith vertex into the stack
               mark ith vertex as visited
         done
   done
End
Assertions in C/C++

Here we will see what is assertions in C/C++. The C library macro void assert(int expression) allows diagnostic information to be written to the standard error file. In other words, it can be used to add diagnostics in your C program.
Following is the declaration for assert() Macro.
void assert(int expression);
The parameter of this assert() is expression − This can be a variable or any C expression. If expression evaluates to TRUE, assert() does nothing. If expression evaluates to FALSE, assert() displays an error message on stderr (standard error stream to display error messages and diagnostics) and aborts program execution.
#include <assert.h>
#include <stdio.h>
int main () {
   int a;
   char str[50];
   printf("Enter an integer value: ");
   scanf("%d", &a);
   assert(a >= 10);
   printf("Integer entered is %d\n", a);
   printf("Enter string: ");
   scanf("%s", &str);
   assert(str != NULL);
   printf("String entered is: %s\n", str);
   return(0);
}
Enter an integer value: 11
Integer entered is 11
Enter string: tutorialspoint
String entered is: tutorialspoint
Query for documents where array size is greater than 1 in MongoDB?

You can use length to query for documents where array size is greater than 1:
db.yourCollectionName.find({$where:"this.yourArrayDocumentName.length > 1"}).pretty();
To understand the above syntax, let us create a collection with some documents. The query is
as follows to create a collection with documents:
>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Larry","StudentTechnicalSubje
ct":["Java","C","C++"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6d6c4c0c3d5054b766a76a")
}
>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Maxwell","StudentTechnicalSu
bject":["MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6d6c660c3d5054b766a76b")
}
>db.arrayLengthGreaterThanOne.insertOne({"StudentName":"Maxwell","StudentTechnicalSu
bject":["MySQL","SQL Server","PL/SQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c6d6c800c3d5054b766a76c")
}
Display all documents from a collection with the help of find() method. The query is as follows:
> db.arrayLengthGreaterThanOne.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c6d6c4c0c3d5054b766a76a"),
   "StudentName" : "Larry",
   "StudentTechnicalSubject" : [
      "Java",
      "C",
      "C++"
   ]
}
{
   "_id" : ObjectId("5c6d6c660c3d5054b766a76b"),
   "StudentName" : "Maxwell",
   "StudentTechnicalSubject" : [
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5c6d6c800c3d5054b766a76c"),
   "StudentName" : "Maxwell",
   "StudentTechnicalSubject" : [
      "MySQL",
      "SQL Server",
      "PL/SQL"
   ]
}
Here is the query for documents where array size is greater than 1. The below query will give all documents where array size is greater than 1:
> db.arrayLengthGreaterThanOne.find({$where:"this.StudentTechnicalSubject.length > 1"}).pretty();
The following is the output:
{
   "_id" : ObjectId("5c6d6c4c0c3d5054b766a76a"),
   "StudentName" : "Larry",
   "StudentTechnicalSubject" : [
      "Java",
      "C",
      "C++"
   ]
}
{
   "_id" : ObjectId("5c6d6c800c3d5054b766a76c"),
   "StudentName" : "Maxwell",
   "StudentTechnicalSubject" : [
      "MySQL",
      "SQL Server",
      "PL/SQL"
   ]
}
Java Generics - List

Java has provided generic support in List interface.
List<T> list = new ArrayList<T>();

Where
list − object of List interface.
list − object of List interface.
T − The generic type parameter passed during list declaration.
T − The generic type parameter passed during list declaration.
The T is a type parameter passed to the generic interface List and its implemenation class ArrayList.
Create the following java program using any editor of your choice.
package com.tutorialspoint;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class GenericsTester {
   public static void main(String[] args) {

      List<Integer> integerList = new ArrayList<Integer>();
  
      integerList.add(Integer.valueOf(10));
      integerList.add(Integer.valueOf(11));

      List<String> stringList = new ArrayList<String>();
  
      stringList.add("Hello World");
      stringList.add("Hi World");
 

      System.out.printf("Integer Value :%d\n", integerList.get(0));
      System.out.printf("String Value :%s\n", stringList.get(0));

      for(Integer data: integerList) {
         System.out.printf("Integer Value :%d\n", data);
      }

      Iterator<String> stringIterator = stringList.iterator();

      while(stringIterator.hasNext()) {
         System.out.printf("String Value :%s\n", stringIterator.next());
      }
   }  
}
This will produce the following result −
Integer Value :10
String Value :Hello World
Integer Value :10
Integer Value :11
String Value :Hello World
String Value :Hi World


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Unix / Linux - Shell Basic Operators

There are various operators supported by each shell. We will discuss in detail about Bourne shell (default shell) in this chapter.
We will now discuss the following operators −
Arithmetic Operators
Relational Operators
Boolean Operators
String Operators
File Test Operators
Bourne shell didn't originally have any mechanism to perform simple arithmetic operations but it uses external programs, either awk or expr.
The following example shows how to add two numbers −
#!/bin/sh

val=`expr 2 + 2`
echo "Total value : $val"
The above script will generate the following result −
Total value : 4

The following points need to be considered while adding −
There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2.
There must be spaces between operators and expressions. For example, 2+2 is not correct; it should be written as 2 + 2.
The complete expression should be enclosed between ‘ ‘, called the backtick.
The complete expression should be enclosed between ‘ ‘, called the backtick.
The following arithmetic operators are supported by Bourne Shell.
Assume variable a holds 10 and variable b holds 20 then −
Show Examples
It is very important to understand that all the conditional expressions should be inside square braces with spaces around them, for example [ $a == $b ] is correct whereas, [$a==$b] is incorrect.
All the arithmetical calculations are done using long integers.
Bourne Shell supports the following relational operators that are specific to numeric values. These operators do not work for string values unless their value is numeric.
For example, following operators will work to check a relation between 10 and 20 as well as in between "10" and "20" but not in between "ten" and "twenty".
Assume variable a holds 10 and variable b holds 20 then −
Show Examples
It is very important to understand that all the conditional expressions should be placed inside square braces with spaces around them. For example, [ $a <= $b ] is correct whereas, [$a <= $b] is incorrect.
The following Boolean operators are supported by the Bourne Shell. 
Assume variable a holds 10 and variable b holds 20 then −
Show Examples
The following string operators are supported by Bourne Shell.
Assume variable a holds "abc" and variable b holds "efg" then −
Show Examples
We have a few operators that can be used to test various properties associated with a Unix file.
Assume a variable file holds an existing file name "test" the size of which is 100 bytes and has read, write and execute permission on −
Show Examples
Following link will give you a brief idea on C Shell Operators −
C Shell Operators
Following link helps you understand Korn Shell Operators −
Korn Shell Operators

    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Java Stream findAny() with examples

The findAny() method of the Java Stream returns an Optional for some element of the stream or an empty Optional if the stream is empty. Here, Optional is a container object which may or may not contain a non-null value.
Following is an example to implement the findAny() method in Java −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String[] args){
      List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);
      Optional<Integer> res = list.stream().findAny();
      if (res.isPresent()) {
         System.out.println(res.get());
      } else {
         System.out.println("None!");
      }
   }
}
10
Let us see another example with list of strings −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      List<String> myList = Arrays.asList("Kevin", "Jofra","Tom", "Chris", "Liam");
      Optional<String> res = myList.stream().findAny();
      if (res.isPresent()) {
         System.out.println(res.get());
      } else {
         System.out.println("None!");
      }
   }
}
Kevin
How to strip down all the punctuation from a string in Python?

The fastest way to strip all punctuation from a string is to use str.translate(). You can use it as follows:
import string
s = "string. With. Punctuation?"
print s.translate(None, string.punctuation)
This will give us the output:
string With Punctuation
If you want a more readable solution, you can explicitly iterate over the set and ignore all punctuation in a loop as follows:
import string
s = "string. With. Punctuation?"
exclude = set(string.punctuation)
s = ''.join(ch for ch in s if ch not in exclude)
print s
This will give us the output:
string With Punctuation
Counting elements of an array using a recursive function in JS?

The recursive function calls itself with some base condition. Let’s say the following is our array
with marks −
var listOfMarks=[56,78,90,94,91,82,77];
Following is the code to get the count of array elements −
function countNumberOfElementsUsingRecursive(listOfMarks) {
   if (listOfMarks.length == 0) {
      return 0;
   }
   return 1 +
   countNumberOfElementsUsingRecursive(listOfMarks.slice(1));
}
var listOfMarks=[56,78,90,94,91,82,77];
console.log("The array=");
console.log(listOfMarks);
var numberOfElements=countNumberOfElementsUsingRecursive(listOfMarks);
console.log("The Number of elements = "+numberOfElements);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo110.js.
This will produce the following output −
PS C:\Users\Amit\JavaScript-code> node demo110.js
The array=[
   56, 78, 90, 94,
   91, 82, 77
]
The Number of elements = 7
.NET Core - SDK

In this chapter, we will understand the upcoming features in .NET Core. We will start with the .NET command line tools by opening the following Url in browser https://github.com/dotnet/cli
To know more about the progress, you can download the latest version of .NET Core SDK by scrolling down and you will see the Installer and Binaries section.
You can see the latest version of preview tools for different operating systems, let us select the Installer as per your operating system.
We are working on preview 1 of .NET Core 2.0.
Let us now look at our current tooling by opening the command prompt and execute the following command.
dotnet --info 

You will see information about the currently installed version of .NET Command Line Tools on your system as shown below.
You can see that currently we have preview 2 tooling. Let us now run the following command to see about the new command.
dotnet help new

For new command language of project, you can select like C# and F# and the type of project, etc.
Let us now see the changes in the latest version of .NET Core. Once the installer is downloaded, double-click on it to install it. Click on Install.
The following screenshot shows the installation process.
It will start the installation process. One the installation is finished, Close this dialog.
Open the command prompt and execute the following command.
dotnet --info

You will see information of currently installed version of .NET Command Line Tools on your system as shown below.
You can now see that we have preview1 tooling of .NET Core 2. Let us now run the following code in the command prompt to see about the new command in .NET Core 2 preview1.
dotnet help new

The command helps you download packages as well to the package cache.
The command opens the following webpage which contains information about the new command in .NET Core 2 preview1.
Let us scroll down, you can now see that we can create the .NET Core application with more templates.
We can now create mstest, web, mvc and webapi projects as well using the command line.
 Print
 Add Notes
 Bookmark this page
C# | Get a collection of values in the StringDictionary - GeeksforGeeks

01 Feb, 2019
StringDictionary.Values property is used to get a collection of values in the StringDictionary.
Syntax:
public virtual System.Collections.ICollection Values { get; }

Return Value: An ICollection that provides the values in the StringDictionary.
Example 1:
// C# code to get a collection// of values in the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized;  class GFG {      // Driver code    public static void Main()    {          // Creating a StringDictionary named myDict        StringDictionary myDict = new StringDictionary();          // Adding key and value into the StringDictionary        myDict.Add("A", "Apple");        myDict.Add("B", "Banana");        myDict.Add("C", "Cat");        myDict.Add("D", "Dog");          // Getting a collection of values        // in the StringDictionary        foreach(string val in myDict.Values)        {            Console.WriteLine(val);        }    }}
Output:
Dog
Banana
Cat
Apple

Example 2:
// C# code to get a collection// of values in the StringDictionaryusing System;using System.Collections;using System.Collections.Specialized;  class GFG {      // Driver code    public static void Main()    {          // Creating a StringDictionary named myDict        StringDictionary myDict = new StringDictionary();          // Adding key and value into the StringDictionary        myDict.Add("3", "prime & odd");        myDict.Add("2", "prime & even");        myDict.Add("4", "non-prime & even");        myDict.Add("9", "non-prime & odd");          // Getting a collection of values        // in the StringDictionary        foreach(string val in myDict.Values)        {            Console.WriteLine(val);        }    }}
Output:
prime & even
prime & odd
non-prime & odd
non-prime & even

Note:
The order of the values in the ICollection is unspecified, but it is the same order as the associated keys in the ICollection returned by the Keys method.
The returned ICollection is not a static copy. Instead, the ICollection refers back to the values in the original StringDictionary. Therefore, changes to the StringDictionary continue to be reflected in the ICollection.
Retrieving the value of this property is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringdictionary.values?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Specialized-Namespace
CSharp-Specialized-StringDictionary
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 50 C# Interview Questions & Answers
Extension Method in C#
HashSet in C# with Examples
Partial Classes in C#
C# | Inheritance
Convert String to Character Array in C#
Linked List Implementation in C#
C# | How to insert an element in an Array?
C# | List Class
Difference between Hashtable and Dictionary in C#
What are the packages in Python?

To understand packages, you also need to know about modules. Any Python file is a module, its name being the file's base name/module's __name__ property without the .py extension. A package is a collection of Python modules, i.e., a package is a directory of Python modules containing an additional __init__.py file. The __init__.py distinguishes a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.
When you import a module or a package, the corresponding object created by Python is always of type module. This means that the distinction between module and package is just at the file system level. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules.
For example, in the DateTime module, there is a submodule called date. When you import DateTime, it won't be imported. You'll need to import it separately.
>>> import datetime
>>> date.today()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'date' is not defined
>>> from datetime import date
>>> date.today()
datetime.date(2017, 9, 1)
How to modify properties of a nested object in JavaScript?

There are two methods to modify properties of nested objects. One is Dot method and the other is Bracket method. The functionality is same for both the methods, but the only difference is their notation. 
lets' discuss them in detail.
In the following example initially the value of property country is England. But using Dot notation the value is changed to India.
Live Demo
<html>
<body>
<script>
   var person;
   var txt = '';
   person = {
      "name":"Ram",
      "age":27,
      "address": {
         "houseno":123,
         "streetname":"Baker street",
         "country":"England"
      }
   }
   document.write("Before change : " + " " + person.address.country);
   person.address.country = "India";
   document.write("</br>");
   document.write("After change : " + " " + person.address.country);
</script>
</body>
</html>
Before change : England
After change : India
In the following example the value of  property 'country' is changed from England to India using Bracket notation. 
Live Demo
<html>
<body>
<script>
   var person;
   var txt = '';
   person = {
      "name":"Ram",
      "age":27,
      "address": {
         "houseno":123,
         "streetname":"Baker street",
         "country":"England"
      }
   }
   document.write("Before change : " + " " + person.address["country"]);
   person.address.country = "India";
   document.write("</br>");
   document.write("After change : " + " " + person.address["country"]);
</script>
</body>
</html>
Before change : England
After change : India
Difference Between malloc() and calloc() with Examples - GeeksforGeeks

21 Jan, 2022
Pre-requisite: Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()The functions malloc() and calloc() are library functions that allocate memory dynamically. Dynamic means the memory is allocated during runtime (execution of the program) from the heap segment.
malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn’t initialize the allocated memory. If you try to read from the allocated memory without first initializing it, then you will invoke undefined behavior, which will usually mean the values you read will be garbage.
calloc() allocates the memory and also initializes every byte in the allocated memory to 0. If you try to read the value of the allocated memory without initializing it, you’ll get 0 as it has already been initialized to 0 by calloc().
malloc() takes a single argument, which is the number of bytes to allocate.
Unlike malloc(), calloc() takes two arguments: 1) Number of blocks to be allocated. 2) Size of each block in bytes.
After successful allocation in malloc() and calloc(), a pointer to the block of memory is returned otherwise NULL is returned which indicates failure. 
C
#include <stdio.h>#include <stdlib.h> int main(){    // Both of these allocate the same number of bytes,    // which is the amount of bytes that is required to    // store 5 int values.     // The memory allocated by calloc will be    // zero-initialized, but the memory allocated with    // malloc will be uninitialized so reading it would be    // undefined behavior.    int* allocated_with_malloc = malloc(5 * sizeof(int));    int* allocated_with_calloc = calloc(5, sizeof(int));     // As you can see, all of the values are initialized to    // zero.      printf("Values of allocated_with_calloc: ");    for (size_t i = 0; i < 5; ++i) {        printf("%d ", allocated_with_calloc[i]);    }    putchar('\n');     // This malloc requests 1 terabyte of dynamic memory,    // which is unavailable in this case, and so the    // allocation fails and returns NULL.    int* failed_malloc = malloc(1000000000000);    if (failed_malloc == NULL) {        printf("The allocation failed, the value of "               "failed_malloc is: %p",               (void*)failed_malloc);    }     // Remember to always free dynamically allocated memory.    free(allocated_with_malloc);    free(allocated_with_calloc);}
Values of allocated_with_calloc: 0 0 0 0 0 
The allocation failed, the value of failed_malloc is: (nil)
chakradharkandula
shubham_singh
Navfal
HarshitHiremath
lennymclennington
C-Dynamic Memory Allocation
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Command line arguments in C/C++
fork() in C
Different methods to reverse a string in C/C++
TCP Server-Client implementation in C
Exception Handling in C++
Function Pointer in C
Structures in C
Substring in C++
'this' pointer in C++
std::string class in C++
SciPy Constants

As SciPy is more focused on scientific implementations, it provides many built-in scientific constants.
These constants can be helpful when you are working with Data Science.
PI is an example of a scientific constant.
Print the constant value of PI:
A list of all units under the constants module can be seen using the dir()
function.
List all constants:
The units are placed under these categories:
Metric
Binary
Mass
Angle
Time
Length
Pressure
Volume
Speed
Temperature
Energy
Power
Force
Return the specified unit in meter (e.g. centi 
  returns 0.01)
Return the specified unit in bytes (e.g. kibi 
  returns 1024)
Return the specified unit in kg (e.g. gram 
  returns 0.001)
Return the specified unit in radians (e.g. degree returns 0.017453292519943295)
Return the specified unit in seconds (e.g. hour returns 3600.0)
Return the specified unit in meters (e.g. nautical_mile returns 1852.0)
Return the specified unit in pascals (e.g. psi returns 6894.757293168361)
Return the specified unit in square meters(e.g. hectare returns 10000.0)
Return the specified unit in cubic meters (e.g. 
liter returns 0.001)
Return the specified unit in meters per second (e.g. 
speed_of_sound returns 340.5)
Return the specified unit in Kelvin (e.g. zero_Celsius returns 273.15)
Return the specified unit in joules (e.g. 
calorie returns 4.184)
Return the specified unit in watts (e.g. horsepower returns 745.6998715822701)
Return the specified unit in newton (e.g. 
kilogram_force returns 9.80665)
Insert the correct syntax for printing the kilometer unit (in meters):
print(constants.)

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to remove a SubList from an ArrayList in Java?

The subList() method of the List interface accepts two integer values representing indexes of the elements and, returns a view of the of the current List object removing the elements between the specified indices.
The clear() method of List interface removes all the elements from the current List object.
Therefore, to remove a specific sub list of an array list you just need to call these two methods on your list object by specifying the boundaries of the sub list you need to remove as −
obj.subList().clear();
 Live Demo
import java.util.ArrayList;
public class RemovingSubList {
   public static void main(String[] args){
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the Array List: \n"+list);
      //Removing the sub list
      list.subList(4, 9).clear();
      System.out.println("Contents of the Array List after removing the sub list: \n"+list);
   }
}
Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the Array List after removing the sub list:
[JavaFX, Java, WebGL, OpenCV, Mahout, Impala]
The removeRange() method of the AbstractList class method accepts two integer values representing indexes of the elements of the current ArrayList and removes them.
But this is a protected method and to use this you need to
Inherit the ArrayList class (from your class) using the extends keyword.
Inherit the ArrayList class (from your class) using the extends keyword.
Instantiate your class.
Instantiate your class.
Add elements to the obtained object.
Add elements to the obtained object.
Then, remove the desired subList using the removeRange() method.
Then, remove the desired subList using the removeRange() method.
 Live Demo
import java.util.ArrayList;
public class RemovingSubList extends ArrayList<String>{
   public static void main(String[] args){
      RemovingSubList list = new RemovingSubList();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the Array List: \n"+list);
      //Removing the sub list
      list.removeRange(4, 9);
      System.out.println("Contents of the Array List after removing the sub list: \n"+list);
   }
}
Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the Array List after removing the sub list:
[JavaFX, Java, WebGL, OpenCV, Mahout, Impala]
Modular Exponentiation (Power in Modular Arithmetic) in java

The java.math.BigInteger.modPow(BigInteger exponent, BigInteger m) returns a BigInteger whose value is (this<sup>exponent</sup> mod m). Unlike pow, this method permits negative exponents. You can calculate the modular Exponentiation using this method.
Live Demo
import java.math.*;

public class BigIntegerDemo {
   public static void main(String[] args) {
      // create 3 BigInteger objects
      BigInteger bi1, bi2, bi3;
     
      // create a BigInteger exponent
      BigInteger exponent = new BigInteger("2");
      bi1 = new BigInteger("7");
      bi2 = new BigInteger("20");
     
      // perform modPow operation on bi1 using bi2 and exp
      bi3 = bi1.modPow(exponent, bi2);
      String str = bi1 + "^" +exponent+ " mod " + bi2 + " is " +bi3;
     
      // print bi3 value
      System.out.println( str );
   }
}
7^2 mod 20 is 9
Fetch random rows from a table with MySQL

For this, you can use a PREPARE statement. Let us first create a table −
mysql> create table DemoTable(
   FirstName varchar(100),
   CountryName varchar(100)
);
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Adam','US');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Chris','AUS');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Robert','UK');
Query OK, 1 row affected (0.32 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+-------------+
| FirstName | CountryName |
+-----------+-------------+
| Adam      | US          |
| Chris     | AUS         |
| Robert    | UK          | 
+-----------+-------------+
3 rows in set (0.00 sec)
Following is the query to fetch random rows in a single query −
mysql> set @value := ROUND((select count(*) from DemoTable) * rand());
Query OK, 0 rows affected (0.00 sec)
mysql> set @query := CONCAT('select *from DemoTable LIMIT ', @value , ', 1');
Query OK, 0 rows affected (0.00 sec)
mysql> prepare myStatement from @query ;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute myStatement;
+-----------+-------------+
| FirstName | CountryName |
+-----------+-------------+
| Chris     | AUS         |
+-----------+-------------+
1 row in set (0.00 sec)
mysql> deallocate prepare myStatement;
Query OK, 0 rows affected (0.00 sec)
Program to find length of longest strictly increasing then decreasing sublist in Python

Suppose we have a list of numbers called nums. We have to find the length of the longest sublist such that (minimum length 3) its values are strictly increasing and then decreasing.
So, if the input is like nums = [7, 1, 3, 5, 2, 0], then the output will be 5, as the sublist is [2, 4, 6, 3, 1] is strictly increasing then decreasing.
To solve this, we will follow these steps −
i := 0, n := size of a, res := -infinity
while i < n - 2, dost := ilinc := 0, ldec := 0while i < n - 1 and a[i] < a[i + 1], dolinc := linc + 1i := i + 1while i < n - 1 and a[i] > a[i + 1], doldec := ldec + 1i := i + 1if linc > 0 and ldec > 0, thenres := maximum of res and (i - st + 1)while i < n - 1 and a[i] is same as a[i + 1], doi := i + 1
st := i
linc := 0, ldec := 0
while i < n - 1 and a[i] < a[i + 1], dolinc := linc + 1i := i + 1
linc := linc + 1
i := i + 1
while i < n - 1 and a[i] > a[i + 1], doldec := ldec + 1i := i + 1
ldec := ldec + 1
i := i + 1
if linc > 0 and ldec > 0, thenres := maximum of res and (i - st + 1)
res := maximum of res and (i - st + 1)
while i < n - 1 and a[i] is same as a[i + 1], doi := i + 1
i := i + 1
return res if res >= 0 otherwise 0
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, a):
      i, n, res = 0, len(a), float("-inf")
      while i < n - 2:
         st = i
         linc, ldec = 0, 0
         while i < n - 1 and a[i] < a[i + 1]:
            linc += 1
            i += 1
         while i < n - 1 and a[i] > a[i + 1]:
            ldec += 1
            i += 1
         if linc > 0 and ldec > 0:
            res = max(res, i - st + 1)
         while i < n - 1 and a[i] == a[i + 1]:
            i += 1
      return res if res >= 0 else 0
ob = Solution()
nums = [8, 2, 4, 6, 3, 1]
print(ob.solve(nums))
[[8, 2, 4, 6, 3, 1]
5
A modified game of Nim in C ?

Modified game of Nim is an optimisation games of arrays. This game predicts the winner based on the starting player and optimal moves.
Game Logic − In this game, we are given an array{}, that contains elements. There are generally two players that play the game namly player1 and player2. The aim of both is to make sure that all their numbers are removed from the array. Now, player1 has to remove all the numbers that are divisible by 3 and the player2 has to remove all the numbers that are divisible by 5. The aim is to make sure that they remove all elements optimally and find the winner in this case.
Array : {1,5, 75,2,65,7,25,6}
Winner : playerB.
A removes 75 -> B removes 5 -> A removes 6 -> B removes 65 -> No moves for A, B wins.
The code will find the number of elements that A can remove , number of elements that B can remove and the number of elements that they both can remove. Based on the number of the elements they both can remove the solution is found. As A removes first elements it can win even if he has to remove one element more than B. In normal case, the player with the maximum number of elements to remove wins.
#include <bits/stdc++.h>
using namespace std;
int main() {
   int arr[] = {1,5, 75,2,65,7,25,6};
   int n = sizeof(arr) / sizeof(arr[0]);
   int movesA = 0, movesB = 0, movesBoth = 0;
   for (int i = 0; i < n; i++) {
      if (arr[i] % 3 == 0 && arr[i] % 5 == 0)
         movesBoth++;
      else if (arr[i] % 3 == 0)
         movesA++;
      else if (arr[i] % 5 == 0)
         movesB++;
   }
   if (movesBoth == 0) {
      if (movesA > movesB)
         cout<<"Player 1 is the Winner";
      cout<<"Player 2 is the Winner";
   }
   if (movesA + 1 > movesB)
      cout<<"Player 1 is the Winner";
   cout<<"Player 2 is the Winner"; ;
   return 0;
}
Player 2 is the Winner
How to convert string to array of integers in java?

You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them.
 Live Demo
import java.util.Arrays;
public class StringToIntegerArray {
   public static void main(String args[]) {
      String [] str = {"123", "345", "437", "894"};
      int size = str.length;
      int [] arr = new int [size];
      for(int i=0; i<size; i++) {
         arr[i] = Integer.parseInt(str[i]);
      }
      System.out.println(Arrays.toString(arr));
   }
}
[123, 345, 437, 894]
How should I enable LOAD DATA LOCAL INFILE in my.cnf in MySQL?

We can enable it with the help of the SET command with GLOBAL. The first time, local infile will be off.
The following is the syntax.
mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';

Here is the output.
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | OFF   |
+---------------+-------+
1 row in set (0.01 sec)

We can enable the local infile with the help of ON or boolean value true or numeric value 1. The following is the syntax to enable the local infile.
mysql> SET GLOBAL local_infile = 'ON';
Query OK, 0 rows affected (0.00 sec)

mysql> SET GLOBAL local_infile = 1;
Query OK, 0 rows affected (0.00 sec)

mysql> SET GLOBAL local_infile = true;
Query OK, 0 rows affected (0.00 sec)
In MySQL version 8.0.12, let us check if it is ON or not.
mysql>  SHOW GLOBAL VARIABLES LIKE 'local_infile';
The following is the output.
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| local_infile  | ON    |
+---------------+-------+
1 row in set (0.00 sec)

After restarting MySQL, it will set local infile to ON.
Removing an element from C++ std::vector<> by index?

Remove an element from C++ std::vector<> by index can be done by following way −
 Live Demo
#include<iostream>
#include<vector>
using namespace std;
int main() {
   vector<int> v; //declare vector
   //insert elements into vector
   v.push_back(-10);
   v.push_back(7);
   v.push_back(6);
   // Deletes the first element (v[0])
   v.erase(v.begin() );
   for (int i = 0; i < v.size(); i++)
      cout << v[i] << " ";
}
7 6
How can I iterate through two lists in parallel in Python?

Assuming that two lists may be of unequal length, parallel traversal over common indices can be done using for loop over over range of minimum length
>>> L1
['a', 'b', 'c', 'd']
>>> L2
[4, 5, 6]
>>> l=len(L1) if len(L1)<=len(L2)else len(L2)
>>> l
3
>>> for i in range(l):
    print (L1[i], L2[i])

a 4
b 5
c 6
A more pythonic way is to use zip() function which results in an iterator that aggregates elements from each iterables
>>> for i,j in zip(L1,L2):
    print (i,j)

a 4
b 5
c 6