code-rag-bench/online-tutorials huggingface dataset:
Const member functions in C++

The const member functions are the functions which are declared as constant in the program. The object called by these functions cannot be modified. It is recommended to use const keyword so that accidental changes to object are avoided.
A const member function can be called by any type of object. Non-const functions can be called by non-const objects only.
Here is the syntax of const member function in C++ language,
datatype function_name const();
Here is an example of const member function in C++,
 Live Demo
#include<iostream>
using namespace std;
class Demo {
   int val;
   public:
   Demo(int x = 0) {
      val = x;
   }
   int getValue() const {
      return val;
   }
};
int main() {
   const Demo d(28);
   Demo d1(8);
   cout << "The value using object d : " << d.getValue();
   cout << "\nThe value using object d1 : " << d1.getValue();
   return 0;
}
The value using object d : 28
The value using object d1 : 8
How to generate prime twins using Python?

Twin primes are pairs of primes which differ by two. The first twin primes are {3,5}, {5,7}, {11,13} and {17,19}. You can generate prime twins in python by running a for loop and checking for primality of the numbers as you do so. 
def is_prime(n):
   for i in range(2, n):
      if n % i == 0:
         return False
   return True

def generate_twins(start, end):
   for i in range(start, end):
      j = i + 2
      if(is_prime(i) and is_prime(j)):
         print("{:d} and {:d}".format(i, j))

generate_twins(2, 100)
This will give the output −
3 and 5
5 and 7
11 and 13
17 and 19
29 and 31
41 and 43
59 and 61
71 and 73
Python | Test if all elements are present in list - GeeksforGeeks

27 Sep, 2019
Sometimes, while working with Python list, we have a problem in which we need to check for a particular list of values and want to be sure if a target list contains all the given values. This has it’s application in web development domain when required some type of filtering. Let’s discuss a way in which this task can be performed.
Method : Using list comprehension + all()This task can be performed using the inbuilt functionality of all(). The all() can be fed with list comprehension logic to check if element of test list is present in target list and rest is done by all().
# Python3 code to demonstrate working of# Test if all elements are present in list# Using list comprehension + all()  # initializing listtarget_list = [6, 4, 8, 9, 10]  # initializing test list test_list = [4, 6, 9]  # printing listsprint("The target list : " + str(target_list))print("The test list : " + str(test_list))  # Test if all elements are present in list# Using list comprehension + all()res = all(ele in target_list for ele in test_list)  # Printing resultprint("Does every element of test_list is in target_list ? : " + str(res))
 
The target list : [6, 4, 8, 9, 10]
The test list : [4, 6, 9]
Does every element of test_list is in target_list ? : True

Python list-programs
Python
Python Programs
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 dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Python | Convert a list to dictionary
How to extract correlation coefficient value from correlation test in R?

To perform the correlation test in R, we need to use cor.test function with two variables and it returns so many values such as test statistic value, degrees of freedom, the p-value, the confidence interval, and the correlation coefficient value. If we want to extract the correlation coefficient value from the correlation test output then estimate function could be used as shown in below examples.
 Live Demo
x1<-rnorm(20,5,2)
y1<-rnorm(20,5,1)
cor.test(x1,y1)
Pearson's product-moment correlation
data: x1 and y1
t = -0.13423, df = 18, p-value = 0.8947
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.4675990 0.4167308
sample estimates:
cor
-0.03162132
cor.test(x1,y1)$estimate cor -0.08194057
 Live Demo
x2<-runif(5000,2,5)
y2<-runif(5000,2,10)
cor.test(x2,y2)
Pearson's product-moment correlation
data: x2 and y2
t = -1.4823, df = 4998, p-value = 0.1383
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.048653479 0.006760764
sample estimates:
cor
-0.02096246
cor.test(x2,y2)$estimate cor 0.01301688
 Live Demo
x3<-runif(50,2,5)
y3<-runif(50,2,10)
cor.test(x3,y3)
Pearson's product-moment correlation
data: x3 and y3
t = -0.80709, df = 48, p-value = 0.4236
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
-0.3817626 0.1680496
sample estimates:
cor
-0.1157106
cor.test(x3,y3)$estimate cor 0.1031475
 Live Demo
x4<-rexp(500,2.1)
y4<-rexp(500,5.75)
cor.test(y4,y4)
Pearson's product-moment correlation
data: y4 and y4
t = Inf, df = 498, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
1 1
sample estimates:
cor
1
cor.test(y4,y4)$estimate cor 1
 Live Demo
x5<-rpois(100000,2)
y5<-rpois(100000,5)
cor.test(y5,y5)
Pearson's product-moment correlation
data: y5 and y5
t = 1.5006e+10, df = 99998, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
1 1
sample estimates:
cor
1
cor.test(y5,y5)$estimate cor 1
C# ToTuple() Method

Let’s say you have a ValueTuple and would like to convert it to a tuple, then use the ToTuple() method.
With C#, we can easily convert a ValueTuple to a Tuple using ToTuple() method.
Note − Add System.ValueTuple package to run ValueTuple program.
Let’s see how to add it −
Go to your project
Right click on the project in the solution explorer
Select “Manage NuGet Packages”
You will reach the NuGet Package Manager.
Now, click the Browse tab and find “ValueTuple”
Finally, add System.ValueTuple package
Let us see an example to implement ToTuple() method.
using System;
class Program {
   static void Main() {
      var val = (1, 2, 3);
      //Add System.ValueTuple package to run this program
      // ValueTuple
      Console.WriteLine(“ValueTuple: ” val);
      // Tuple
      Tuple<int, int, int> myTuple = val.ToTuple();
      Console.WriteLine(“Tuple: ”+myTuple);
   }
}
ValueTuple: (1, 2, 3)
Tuple: (1, 2, 3)
C Program for Minimum number of jumps to reach the end

We are given, an array of non-negative integers denoting the maximum number of
steps that can be made forward from that element. The pointer is initially positioned at the first index [0 index] of the array. Your goal is to reach the last
index of the array in the minimum number of steps. If it is not possible to reach the
end of the array then print the maximum integer.
naive approach is to begin from initial{the primary} component and recursively call for all the components accessible from the first element. The minimum range of jumps to reach the end from first is calculated using the minimum range of jumps required to achieve end from the elements accessible from first.
minJumps(start, end) = Min ( minJumps(k, end) )
for all k accessible from the start
Here we’ll use the top-down approach of dynamic programming. We’ll use Hashmap to store the subproblem results and whenever we create a solution, first check if the subproblem is already resolved, if yes then use it.
Input: { 1, 2, 4, 1, 2, 2, 1, 1, 3, 8 }
Output: Minimum number of steps = 6 {1-->2-->4-->1-->3-->8}
The first element is 1, so it can only go to 2. The second element is
2, so can make at most 2 steps eg to 4 or 1. It goes to 4 from where it reaches 1 and
so on.
The complexity of dynamic programming approach to find the minimum number
of jumps to reach the end of an array is O(n^2) with space complexity of O(n)
 Live Demo
#include<stdio.h>
#include<limits.h>
int min_steps (int arr[], int n){
   int steps[n];
   int i, j;
   if (n == 0 || arr[0] == 0)
      return INT_MAX;
   steps[0] = 0;
   for (i = 1; i < n; i++){
      steps[i] = INT_MAX;
      for (j = 0; j < i; j++){
         if (i <= j + arr[j] && steps[j] != INT_MAX){
            steps[i] = (steps[i] < (steps[j] + 1)) ? steps[i] : steps[j] + 1;
            break;
         }
      }
   }
   return steps[n - 1];
}
int main (){
   int arr[100];
   int n;
   printf ("Enter size of the array:");
   scanf ("%d", &n);
   printf ("Enter elements in the array:");
   for (int i = 0; i < n; i++){
      scanf ("%d", &arr[i]);
   }
   printf ("Minimum number of steps : %d", min_steps (arr, n));
   return 0;
}
Enter size of array : 7
Enter elements in the array :2 1 1 5 2 1 1
Minimum number of steps : 3
MongoDB query to find documents whose array contains a string that is a substring of a specific word

For such evaluations, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo90.insertOne(
... {"words": ["john", "jace"]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c1ada79799acab037af56")
}
> db.demo90.insertOne(
... {"words": ["sam", "adam"]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2c1adb79799acab037af57")
}
Display all documents from a collection with the help of find() method −
> db.demo90.find();
This will produce the following output −
{ "_id" : ObjectId("5e2c1ada79799acab037af56"), "words" : [ "john", "jace" ] }
{ "_id" : ObjectId("5e2c1adb79799acab037af57"), "words" : [ "sam", "adam" ] }
Following is the query to find documents whose array contains a string that is a substring of specific word −
> db.demo90.aggregate([ { $match: { $expr: { $anyElementTrue: { $map: { input: "$words", as: "j", in: { $ne: [ -1, { $indexOfBytes: [ "john", "$$j" ] } ] } } } } } } ]);
This will produce the following output −
{ "_id" : ObjectId("5e2c1ada79799acab037af56"), "words" : [ "john", "jace" ] }
Appending data to a MySQL field that already has data in it?

You can append data to a MySQL database field with the help of in-built CONCAT() function.
The syntax is as follows −
update yourTableName set yourColumnName = CONCAT(yourColumnName,’AppendValue’);
To understand the above concept, let us create a table. The query to create a table −
mysql> create table AppendingDataDemo
   −> (
   −> FirstNameAndLastName varchar(200)
   −> );
Query OK, 0 rows affected (0.59 sec)
Insert some records in the table with the help of insert command. The query is as follows −
mysql> insert into AppendingDataDemo values('John');
Query OK, 1 row affected (0.27 sec)

mysql> insert into AppendingDataDemo values('Bob');
Query OK, 1 row affected (0.20 sec)

mysql> insert into AppendingDataDemo values('Carol');
Query OK, 1 row affected (0.30 sec)
Display all records with the help of select statement −
mysql> select *from AppendingDataDemo;
The following is the output −
+----------------------+
| FirstNameAndLastName |
+----------------------+
| John                 |
| Bob                  |
| Carol                |
+----------------------+
3 rows in set (0.00 sec)
Here is the query to append the data ”Taylor” to the data already in the column. Therefore, the data will get appended.
The query is as follows −
mysql> update AppendingDataDemo set FirstNameAndLastName = concat(FirstNameAndLastName,' Taylor');
Query OK, 3 rows affected (0.10 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Now you can check with select statement that data has been appended or not. The query is as follows −
mysql> select *from AppendingDataDemo;
The following is the output −
+----------------------+
| FirstNameAndLastName |
+----------------------+
| John Taylor          |
| Bob Taylor           |
| Carol Taylor         |
+----------------------+
3 rows in set (0.00 sec)
Program for Area Of Square in C++

We are given with a side of a rectangle and our task is to print the area of the square from that side.
Square is 2-D plain figure which have 4 sides and forms 4 angles of 90degree each and all the sides are of equal shape. In other words we can say that the square is a form of rectangle with equal sides.
Given below is representation of a square −
The Area of square is Side x Side
Input: 6
Output: 36
As the side is 6 so the output is 6*6=36
Input: 12
Output: 144
START
   Step 1-> Declare a function int area(int side)
   In function area
      Declare a variable area and set it as side * side
      Return area
   End
   Step 2 -> Declare a function int main()
   In main Function
   Declare a variable side and Set a Value
   Call function area(side)
   End
STOP
#include <iostream>
using namespace std;
//funcion to calculate area of square
int area(int side){
   int area = side * side;
   return area;
}
// Driver Code
int main(){
   int side = 40;
   cout <<"area of square is :"<<area(side);
   return 0;
}
area of square is :1600
Python 3 - dictionary fromkeys() Method

The method fromkeys() creates a new dictionary with keys from seq and values set to value.
Following is the syntax for fromkeys() method −
dict.fromkeys(seq[, value]))

seq − This is the list of values which would be used for dictionary keys preparation.
seq − This is the list of values which would be used for dictionary keys preparation.
value − This is optional, if provided then value would be set to this value
value − This is optional, if provided then value would be set to this value
This method returns the list.
The following example shows the usage of fromkeys() method.
#!/usr/bin/python3

seq = ('name', 'age', 'sex')

dict = dict.fromkeys(seq)
print ("New Dictionary : %s" %  str(dict))

dict = dict.fromkeys(seq, 10)
print ("New Dictionary : %s" %  str(dict))
When we run above program, it produces the following result −
New Dictionary : {'age': None, 'name': None, 'sex': None}
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Java Examples - Find an object in Array

How to find an object or a string in an Array?
Following example uses Contains method to search a String in the Array.
import java.util.ArrayList;

public class Main {
   public static void main(String[] args) {
      ArrayList objArray = new ArrayList();
      ArrayList objArray2 = new ArrayList();
      objArray2.add(0,"common1");
      objArray2.add(1,"common2");
      objArray2.add(2,"notcommon");
      objArray2.add(3,"notcommon1");
      objArray.add(0,"common1");
      objArray.add(1,"common2");
      System.out.println("Array elements of array1"+objArray);
      System.out.println("Array elements of array2"+objArray2);
      System.out.println("Array 1 contains String common2?? "
         +objArray.contains("common1"));
      System.out.println("Array 2 contains Array1?? "
         +objArray2.contains(objArray) );
   }
}
The above code sample will produce the following result.
Array elements of array1[common1, common2]
Array elements of array2[common1, common2, notcommon, notcommon1]
Array 1 contains String common2?? true
Array 2 contains Array1?? false

 Print
 Add Notes
 Bookmark this page
Example and usage of JOINS in DB2

Problem: How will you find the ORDER_ID, TRANSACTION_ID and TRANSACTION_STATUS from ORDERS and TRANSACTIONS DB2 table using joins?
We can find ORDER_ID, TRANSACTION_ID and TRANSACTION_STATUS from ORDERS and TRANSACTIONS table using the INNER JOIN query.
For example, if we have below 2 ORDERS table.
 
We can use an inner join query as below.
SELECT ORDER_ID, TRANSACTION_ID, TRANSACTION_STATUS FROM ORDERS INNER JOIN TRANSACTIONS ON
ORDERS.TRANSACTION_ID = TRANSACTIONS.TRANSACTION_ID
The above query will return the result below.
gzip.decompress(s) in Python - GeeksforGeeks

26 Mar, 2020
With the help of gzip.decompress(s) method, we can decompress the compressed bytes of string into original string by using gzip.decompress(s) method.
Syntax : gzip.decompress(string)Return : Return decompressed string.
Example #1 :In this example we can see that by using gzip.decompress(s) method, we are able to decompress the compressed string in the byte format of string by using this method.
# import gzip and decompressimport gzips = b'This is GFG author, and final year student.'s = gzip.compress(s)  # using gzip.decompress(s) methodt = gzip.decompress(s)print(t)
Output :
b’This is GFG author, and final year student.’
Example #2 :
# import gzip and compressimport gzips = b'GeeksForGeeks@12345678's = gzip.compress(s)  # using gzip.decompress(s) methodt = gzip.decompress(s)print(t)
Output :
b’GeeksForGeeks@12345678′
Python-gzip
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
React Native - Images

In this chapter, we will understand how to work with images in React Native.
Let us create a new folder img inside the src folder. We will add our image (myImage.png) inside this folder.
We will show images on the home screen.
import React from 'react';
import ImagesExample from './ImagesExample.js'

const App = () => {
   return (
      <ImagesExample />
   )
}
export default App
Local image can be accessed using the following syntax.
import React, { Component } from 'react'
import { Image } from 'react-native'

const ImagesExample = () => (
   <Image source = {require('C:/Users/Tutorialspoint/Desktop/NativeReactSample/logo.png')} />
)
export default ImagesExample
React Native offers a way to optimize images for different devices using @2x, @3x suffix. The app will load only the image necessary for particular screen density.
The following will be the names of the image inside the img folder.
my-image@2x.jpg
my-image@3x.jpg

When using network images, instead of require, we need the source property. It is recommended to define the width and the height for network images.
import React from 'react';
import ImagesExample from './image_example.js'

const App = () => {
   return (
      <ImagesExample />
   )
}
export default App
import React, { Component } from 'react'
import { View, Image } from 'react-native'

const ImagesExample = () => (
   <Image source = {{uri:'https://pbs.twimg.com/profile_images/486929358120964097/gNLINY67_400x400.png'}}
   style = {{ width: 200, height: 200 }}
   />
)
export default ImagesExample

    20 Lectures 
     1.5 hours 

 Anadi Sharma

    61 Lectures 
     6.5 hours 

 A To Z Mentor

    40 Lectures 
     4.5 hours 

 Eduonix Learning Solutions

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    62 Lectures 
     4.5 hours 

 Senol Atac

    67 Lectures 
     4.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How can I check the version of MySQL Server?

With the help of ‘mysqladmin’ program we would be able to know about the version of our MySQL server. To get the version we should have to write the following command on command line −
C:\mysql\bin>mysqladmin -u root version
mysqladmin Ver 8.42 Distrib 5.7.20, for Win64 on x86_64
Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.
Server version       5.7.20
Protocol version     10
Connection           localhost via TCP/IP
TCP port             3306
Uptime:              12 min 54 sec
Threads: 1 Questions: 5 Slow queries: 0 Opens: 105 Flush tables: 1 Open tables: 98 Queries per second avg: 0.0060
Basic Calculator Program Using Java - GeeksforGeeks

17 Nov, 2020
Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input.
Example :
Enter the numbers: 
2
2
Enter the operator (+,-,*,/)
+
The final result:
2.0 + 2.0 = 4.0
Approach Used:
Take two numbers using the Scanner class. The switch case branching is used to execute a particular section.
Using a switch case to evaluate respective operations.
Java
// Java program for simple calculator  import java.io.*;import java.lang.*;import java.lang.Math;import java.util.Scanner;public class BasicCalculator {      public static void main(String[] args)    {        // stores two numbers        double num1, num2;          // Take input from the user        Scanner sc = new Scanner(System.in);          System.out.println("Enter the numbers");          // take the inputs        num1 = sc.nextDouble();          num2 = sc.nextDouble();          System.out.println("Enter the operator (+,-,*,/)");          char op = sc.next().charAt(0);          double o = 0;          switch (op) {          // case to add two numbers        case '+':              o = num1 + num2;              break;          // case to subtract two numbers        case '-':              o = num1 - num2;              break;          // case to multiply two numbers        case '*':              o = num1 * num2;              break;          // case to divide two numbers        case '/':              o = num1 / num2;              break;          default:              System.out.println("You enter wrong input");              break;        }          System.out.println("The final result:");          System.out.println();          // print the final result        System.out.println(num1 + " " + op + " " + num2                           + " = " + o);    }}
Output:
Enter the numbers:
2
2
Enter the operator (+,-,*,/)
+
The final result:
2.0 + 2.0 = 4.0
Time Complexity: O(1)
Auxiliary Space: O(1)
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
Generics in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
AngularJS - Services

AngularJS supports the concept of Separation of Concerns using services architecture. Services are JavaScript functions, which are responsible to perform only specific tasks. This makes them individual entities which are maintainable and testable. The controllers and filters can call them on requirement basis. Services are normally injected using the dependency injection mechanism of AngularJS.
AngularJS provides many inbuilt services. For example, $http, $route, $window, $location, etc. Each service is responsible for a specific task such as the $http is used to make ajax call to get the server data, the $route is used to define the routing information, and so on. The inbuilt services are always prefixed with $ symbol.
There are two ways to create a service −
Factory
Service
In this method, we first define a factory and then assign method to it.
var mainApp = angular.module("mainApp", []);
mainApp.factory('MathService', function() {
   var factory = {};
   
   factory.multiply = function(a, b) {
      return a * b
   }
   
   return factory;
}); 

In this method, we define a service and then assign method to it. We also inject an already available service to it.
mainApp.service('CalcService', function(MathService) {
   this.square = function(a) {
      return MathService.multiply(a,a);
   }
});

The following example shows use of all the above mentioned directives −
<html>
   <head>
      <title>Angular JS Services</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
      </script>
   </head>
   
   <body>
      <h2>AngularJS Sample Application</h2>
      
      <div ng-app = "mainApp" ng-controller = "CalcController">
         <p>Enter a number: <input type = "number" ng-model = "number" /></p>
         <button ng-click = "square()">X<sup>2</sup></button>
         <p>Result: {{result}}</p>
      </div>
      
      <script>
         var mainApp = angular.module("mainApp", []);
         
         mainApp.factory('MathService', function() {
            var factory = {};
            
            factory.multiply = function(a, b) {
               return a * b
            }
            return factory;
         });
         mainApp.service('CalcService', function(MathService) {
            this.square = function(a) {
               return MathService.multiply(a,a);
            }
         });
         mainApp.controller('CalcController', function($scope, CalcService) {
            $scope.square = function() {
               $scope.result = CalcService.square($scope.number);
            }
         });
      </script>
      
   </body>
</html>
Open the file testAngularJS.htm in a web browser and see the result.
Enter a number: 
X2

Result: {{result}}

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    40 Lectures 
     2.5 hours 

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Python - Tuples

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also.
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing −
tup1 = ();

To write a tuple containing a single value you have to include a comma, even though there is only one value −
tup1 = (50,);

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.
To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index.
#!/usr/bin/python

tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5, 6, 7 );
print "tup1[0]: ", tup1[0];
print "tup2[1:5]: ", tup2[1:5];
When the above code is  executed, it produces the following result −
tup1[0]:  physics
tup2[1:5]:  [2, 3, 4, 5]

Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates −
#!/usr/bin/python

tup1 = (12, 34.56);
tup2 = ('abc', 'xyz');

# Following action is not valid for tuples
# tup1[0] = 100;

# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print tup3;
When the above code is executed, it produces the following result −
(12, 34.56, 'abc', 'xyz')

Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement.
#!/usr/bin/python

tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;
Note − an exception raised, this is because after del tup tuple does not exist anymore.
Note − an exception raised, this is because after del tup tuple does not exist anymore.
This produces the following result −
('physics', 'chemistry', 1997, 2000)
After deleting tup :
Traceback (most recent call last):
   File "test.py", line 9, in <module>
      print tup;
NameError: name 'tup' is not defined

Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the prior chapter.

    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to upload a file in Selenium with no text box?

We can upload a file in Selenium with no text box. This is achieved with the help of the sendKeys method. It is applied on the web element which performs the task of selecting the path of the file to be uploaded.
As we make an attempt to upload, we shall click on the Browse button. If we investigate the HTML code for this, we shall be able to locate the attribute type having the value file. Moreover, the file path to be uploaded should be accurate.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class FileUpload{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String u = "https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
      driver.get(u);
      driver.manage().timeouts().implicitlyWait(6, TimeUnit.SECONDS);
      // identify element
      WebElement m=driver.findElement(By.xpath("//input[@name='photo']"));
      // file selection field with file path
      m.sendKeys("C:\\Users\\ghs6kor\\Tulips.jpg");
   }
}
Java String substring() Method example.

The substring(int beginIndex, int endIndex) method of the String class. It returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Live Demo
import java.lang.*;

public class StringDemo {
public static void main(String[] args) {
String str = "This is tutorials point";
String substr = "";

// prints the substring after index 8 till index 17
substr = str.substring(8, 17);
System.out.println("substring = " + substr);

// prints the substring after index 0 till index 8
substr = str.substring(0, 8);
System.out.println("substring = " + substr);
}
}
substring = tutorials
substring = This is
Tryit Editor v3.7

Tryit: Using justify-content: flex-end
Apache Pig - Execution

In the previous chapter, we explained how to install Apache Pig. In this chapter, we will discuss how to execute Apache Pig.
You can run Apache Pig in two modes, namely, Local Mode and HDFS mode.
In this mode, all the files are installed and run from your local host and local file system. There is no need of Hadoop or HDFS. This mode is generally used for testing purpose.
MapReduce mode is where we load or process the data that exists in the Hadoop File System (HDFS) using Apache Pig. In this mode, whenever we execute the Pig Latin statements to process the data, a MapReduce job is invoked in the back-end to perform a particular operation on the data that exists in the HDFS.
Apache Pig scripts can be executed in three ways, namely, interactive mode, batch mode, and embedded mode.
Interactive Mode (Grunt shell) − You can run Apache Pig in interactive mode using the Grunt shell. In this shell, you can enter the Pig Latin statements and get the output (using Dump operator).
Interactive Mode (Grunt shell) − You can run Apache Pig in interactive mode using the Grunt shell. In this shell, you can enter the Pig Latin statements and get the output (using Dump operator).
Batch Mode (Script) − You can run Apache Pig in Batch mode by writing the Pig Latin script in a single file with .pig extension.
Batch Mode (Script) − You can run Apache Pig in Batch mode by writing the Pig Latin script in a single file with .pig extension.
Embedded Mode (UDF) − Apache Pig provides the provision of defining our own functions (User Defined Functions) in programming languages such as Java, and using them in our script.
Embedded Mode (UDF) − Apache Pig provides the provision of defining our own functions (User Defined Functions) in programming languages such as Java, and using them in our script.
You can invoke the Grunt shell in a desired mode (local/MapReduce) using the −x option as shown below.
Command −
$ ./pig –x local
Command −
$ ./pig -x mapreduce
Output −
Output −
Either of these commands gives you the Grunt shell prompt as shown below.
grunt>
You can exit the Grunt shell using ‘ctrl + d’.
After invoking the Grunt shell, you can execute a Pig script by directly entering the Pig Latin statements in it.
grunt> customers = LOAD 'customers.txt' USING PigStorage(',');
You can write an entire Pig Latin script in a file and execute it using the –x command. Let us suppose we have a Pig script in a file named sample_script.pig as shown below.
student = LOAD 'hdfs://localhost:9000/pig_data/student.txt' USING
   PigStorage(',') as (id:int,name:chararray,city:chararray);
  
Dump student;
Now, you can execute the script in the above file as shown below.
Note − We will discuss in detail how to run a Pig script in Bach mode and in embedded mode in subsequent chapters.

    46 Lectures 
     3.5 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    16 Lectures 
     1 hours 

 Nilay Mehta

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    14 Lectures 
     1 hours 

 Bigdata Engineer

    23 Lectures 
     1 hours 

 Bigdata Engineer
 Print
 Add Notes
 Bookmark this page
DB2 - Roles

A role is a database object that groups multiple privileges that can be assigned to users, groups, PUBLIC or other roles by using GRANT statement.
A role cannot own database objects.
Permissions and roles granted to groups are not considered when you create the following database objects.

Package Containing static SQL
Views
Materialized Query Tables (MQT)
Triggers
SQL Routines


Package Containing static SQL
Views
Materialized Query Tables (MQT)
Triggers
SQL Routines
Syntax: [To create a new role]
db2 create role <role_name> 
Example: [To create a new role named ‘sales’ to add some table to be managed by some user or group]
db2 create role sales 
Output:
DB20000I The SQL command completed successfully. 
Syntax: [To grant permission of a role to a table]
db2 grant select on table <table_name> to role <role_name> 
Example: [To add permission to manage a table ‘shope.books’ to role ‘sales’]
db2 grant select on table shope.books to role sales 
Output:
DB20000I  The SQL command completed successfully. 
Security administrator grants role to the required users. (Before you use this command, you need to create the users.)
Syntax: [To add users to a role]
db2 grant role <role_name> to user <username> 
Example: [To add a user ‘mastanvali’ to a role ‘sales’]
db2 grant sales to user mastanvali  
Output:
DB20000I  The SQL command completed successfully. 
For creating a hierarchies for roles, each role is granted permissions/ membership with another role.
Syntax: [before this syntax create a new role with name of “production”]
db2 grant role <roll_name> to role <role_name>
Example: [To provide permission of a role ‘sales’ to another role ‘production’]
db2 grant sales to role production 

    10 Lectures 
     1.5 hours 

 Nishant Malik

    41 Lectures 
     8.5 hours 

 Parth Panjabi

    53 Lectures 
     11.5 hours 

 Parth Panjabi

    33 Lectures 
     7 hours 

 Parth Panjabi

    44 Lectures 
     3 hours 

 Arnab Chakraborty

    178 Lectures 
     14.5 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Python | sympy.factorint() method - GeeksforGeeks

05 Sep, 2019
With the help of sympy.factorint() method, we can find the factors and their corresponding multiplicities of a given integer. For input less than 2, factorint() behaves as follows:
 – returns the empty factorization {}.
 – returns .
 – adds  to the factors and then factors .
Syntax:factorint(n)
Parameter:n – It denotes an integer.
Returns:Returns a dictionary containing the prime factors of n as keysand their respective multiplicities as values.
Example #1:
# import factorint() method from sympyfrom sympy import factorint  n = 2**3 * 3**4 * 5**6  # Use factorint() method factor_dict = factorint(n)       print("Dictionary containing factors of {} with respective multiplicities : {}".      format(n, factor_dict))
Output:
Dictionary containing factors of 10125000 
with respective multiplicities : {2: 3, 3: 4, 5: 6}

Example #2:
# import factorint() method from sympyfrom sympy import factorint  n = 6**4 * 13  # Use factorint() method factor_dict = factorint(n)       print("Dictionary containing factors of {} with respective multiplicities : {}".      format(n, factor_dict))
Output:
Dictionary containing factors of 16848 
with respective multiplicities : {2: 4, 3: 4, 13: 1}

Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
TimeSpan.FromHours() Method in C#

30 Sep, 2019
This method is used to get a TimeSpan that represents a specified number of hours, accurate to the nearest millisecond.
Syntax: public static TimeSpan FromHours (double value);
Parameter:value: This parameter specifies the number of hours, accurate to the nearest millisecond.
Return Value: It returns a new TimeSpan object that represents the value.
Exceptions:
OverflowException: It occurs when the given double value is smaller than the smallest possible value or greater than the largest possible value or the value is PositiveInfinity or is NegativeInfinity.
ArgumentException: If the value is equal to NaN.
Below programs illustrate the use of TimeSpan.FromHours(Double) Method:
Program 1:
// C# program to demonstrate the// TimeSpan.FromDays(Double) Methodusing System;  class GFG {      // Main Method    public static void Main()    {        try {              TimeSpan interval = TimeSpan.FromHours(12.3459);            Console.WriteLine("The Timespan is : {0}",                                            interval);        }          catch (OverflowException e) {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
The Timespan is : 12:20:45.2400000

Program 2: For Overflow Exception
// C# program to demonstrate the// TimeSpan.FromDays(Double) Methodusing System;  class GFG {      // Main Method    public static void Main()    {        try {              TimeSpan interval =                TimeSpan.FromHours(Double.NegativeInfinity);              Console.WriteLine("The Timespan is : {0}",                                            interval);        }          catch (OverflowException e)       {            Console.Write("Exception Thrown: ");            Console.Write("{0}", e.GetType(), e.Message);        }    }}
Exception Thrown: System.OverflowException

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.timespan.fromhours?view=netframework-4.7.2
shubham_singh
CSharp-method
CSharp-TimeSpan-Struct
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML - <td> Tag

The HTML <td> tag is used for specifying a cell or table data within a table.
<!DOCTYPE html>
<html>

   <head>
      <title>HTML td Tag</title>
   </head>

   <body>
      <table border = "1">
         <tr>
            <th>Subject</th>
            <th>Topic</th>
         </tr>
         
         <tr>
            <td>Java</td>
            <td>Threading</td>
         </tr>
         
         <tr>
            <td>C++</td>
            <td>Virtual Functions</td>
         </tr>
         
         <tr>
            <td>Linux</td>
            <td>File Systems</td>
         </tr>
      </table>
   </body>

</html>
This will produce the following result −
This tag supports all the global attributes described in − HTML Attribute Reference
The HTML <td> tag also supports the following  additional attributes −
This tag supports all the event attributes described in − HTML Events Reference

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Dictionary.Keys Property in C#

The Dictionary.Keys property in C# is used to fetch all the keys in the Dictionary.
Following is the syntax −
public System.Collections.Generic.Dictionary<TKey, TValue>.KeyCollection Keys { get; }
Let us now see an example to implement the Dictionary.Keys property −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "Kagido");
      dict.Add("Two", "Ngidi");
      dict.Add("Three", "Devillers");
      dict.Add("Four", "Smith");
      dict.Add("Five", "Warner");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.Write("\nAll the keys..\n");
      Dictionary<string, string>.KeyCollection allKeys =
      dict.Keys;
      foreach(string str in allKeys){
         Console.WriteLine("Key = {0}", str);
      }
   }
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = Kagido
Key = Two, Value = Ngidi
Key = Three, Value = Devillers
Key = Four, Value = Smith
Key = Five, Value = Warner
All the keys..
Key = One
Key = Two
Key = Three
Key = Four
Key = Five
Let us now see another example to implement the Dictionary.Keys property −
using System;
using System.Collections.Generic;
public class Demo {
   public static void Main(){
      Dictionary<string, string> dict =
      new Dictionary<string, string>();
      dict.Add("One", "Chris");
      dict.Add("Two", "Steve");
      dict.Add("Three", "Messi");
      dict.Add("Four", "Ryan");
      dict.Add("Five", "Nathan");
      Console.WriteLine("Count of elements = "+dict.Count);
      Console.WriteLine("\nKey/value pairs...");
      foreach(KeyValuePair<string, string> res in dict){
         Console.WriteLine("Key = {0}, Value = {1}", res.Key, res.Value);
      }
      Console.WriteLine("Value for key three = "+dict["Three"]);
      dict["Three"] = "Katie";
      Console.WriteLine("Updated value associated with key Three...");
      Console.WriteLine(dict["Three"]);
      Console.Write("\nAll the keys..\n");
      Dictionary<string, string>.KeyCollection allKeys = dict.Keys;
      foreach(string str in allKeys){
         Console.WriteLine("Key = {0}", str);
      }
   }
}
This will produce the following output −
Count of elements = 5
Key/value pairs...
Key = One, Value = Chris
Key = Two, Value = Steve
Key = Three, Value = Messi
Key = Four, Value = Ryan
Key = Five, Value = Nathan
Value for key three = Messi
Updated value associated with key Three...
Katie
All the keys..
Key = One
Key = Two
Key = Three
Key = Four
Key = Five
Program to Parse a comma separated string in C++

24 Oct, 2020
Given a comma-separated string, the task is to parse this string and separate the words in C++.Examples:  
Input: "1,2,3,4,5"
Output: 
1
2
3
4
5

Input: "Geeks,for,Geeks"
Output: 
Geeks
for
Geeks





 
Approach: 
Get the string in stream – stringstream
Create a string vector to store the parsed words
Now till there is a string in stringstream, checked by good() method,Get the substring if the string from starting point to the first appearance of ‘, ‘ using getline() methodThis will give the word in the substringNow store this word in the vectorThis word is now removed from the stream and stored in the vector
Get the substring if the string from starting point to the first appearance of ‘, ‘ using getline() method
This will give the word in the substring
Now store this word in the vector
This word is now removed from the stream and stored in the vector
Below is the implementation of the above approach: 
CPP
// C++ program to parse a comma-separated string #include <bits/stdc++.h>using namespace std; int main(){    string str = "1,2,3,4,5,6";    vector<string> v;     stringstream ss(str);     while (ss.good()) {        string substr;        getline(ss, substr, ',');        v.push_back(substr);    }     for (size_t i = 0; i < v.size(); i++)        cout << v[i] << endl;}
1
2
3
4
5
6





 
danielcrawley1998
C++
C++ Programs
Strings
Strings
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Matplotlib.axes.Axes.quiver() in Python

19 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.barbs() function in axes module of matplotlib library is also used to plot a 2D field of arrows.
Syntax: Axes.quiver(self, *args, data=None, **kw
Parameters: This method accept the following parameters that are described below:
X, Y : These parameter are the x and y coordinates of the arrow locations.
U, V: These parameter are the x and y components of the arrow vector.
C : This parameter contains the numeric data that defines the arrow colors by colormapping via norm and cmap.
pivot : This parameter is the part of the arrow that is anchored to the X, Y grid.
units : This parameter is the arrow dimensions (except for length) are measured in multiples of this unit.
angles : This parameter is the method for determining the angle of the arrows.
scale : This parameter is the number of data units per arrow length unit.
scale_units : This parameter is an optional parameter nad it contains these values ‘width’, ‘height’, ‘dots’, ‘inches’, ‘x’, ‘y’, ‘xy’ .
width : This parameter is the shaft width in arrow units.
headwidth : This parameter is the head width as multiple of shaft width.
headlength : This parameter is the length width as multiple of shaft width.
headwidth : This parameter is the head width as multiple of shaft width.
headaxislength : This parameter is the head length at shaft intersection.
minshaft : This parameter is the length below which arrow scales, in units of head length.
minlength : This parameter is the minimum length as a multiple of shaft width.
color : This parameter is the explicit color(s) for the arrows.
Below examples illustrate the matplotlib.axes.Axes.quiver() function in matplotlib.axes:
Example 1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np      X = np.arange(-20, 20, 0.5)Y = np.arange(-20, 20, 0.5)U, V = np.meshgrid(X, Y)  fig, ax = plt.subplots()q = ax.quiver(X, Y, U, V)  ax.set_title('matplotlib.axes.Axes.quiver()\ Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as np      X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2),                    np.arange(0, 2 * np.pi, .2))U = np.cos(X**2)V = np.sin(Y**2)C = U**2 + V**2  fig, ax = plt.subplots()ax.quiver(X, Y, U, V, C, units ='width')ax.set_title('matplotlib.axes.Axes.quiver() \Example', fontsize = 14, fontweight ='bold')plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.