code-rag-bench/online-tutorials huggingface dataset:
Difference between isset() and array_key_exists() Function in PHP

09 Oct, 2018
isset() function
The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.
Syntax:
bool isset( $var, mixed )
Parameters: This function accepts more than one parameters. The first parameter of this function is $var. This parameter is used to store the value of variable.
Program:
<?php   // Declare an array$array = array();  // Use isset functionecho isset($array['geeks']) ? 'array is set.' :     'array is not set.';?>
array is not set.

array_key_exists() Function
This is also a predefined function in PHP which checks whether an index or a particular key exists in an array or not. It does not evaluate the value of the key for any null values. It returns false if it does not find the key in the array and true in all other possible cases.
Syntax:
bool array_key_exists( $key, $array )
Parameters: This function accepts two parameters as mentioned above and described below:
$key: This parameter is used to store the value to be check.
$array: This parameter is used to store an array with keys to check.
Program:
<?php   // Create an array$array = array(     'name' => null,);  // Use array_key_exists functionecho array_key_exists('name', $array) ? 'array key exists' : 'array key does not exist';?>
array key exists

Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null. Also isset() doesn’t render error when array/variable does not exist, while array_key_exists does.
PHP-function
Picked
PHP
PHP Programs
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 QDateEdit – Getting Input Date

25 May, 2021
In this article we will see how we can get the input date of the QDateEdit. User can set date to the date edit with the help of cursor and the keyboard but sometimes there is a need of setting initial date or date programmatically for showing date in the records, which can be done with the help of setDate method.In order to do this we use date method with the QDateEdit object  
Syntax : date.date()Argument : It takes no argumentReturn : It returns QDate object  
Below is the implementation  
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 500, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating a QDateEdit widget        date = QDateEdit(self)         # setting geometry of the date edit        date.setGeometry(100, 100, 150, 40)                 # date        d = QDate(2020, 6, 10)         # setting date to the date edit        date.setDate(d)                 # creating a label        label = QLabel("GeeksforGeeks", self)         # setting geometry        label.setGeometry(100, 150, 200, 60)         # making label multiline        label.setWordWrap(True)                 # getting current date        value = date.date()                 # setting text to the label        label.setText("Date : " + str(value))   # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :  
 
sweetyty
Python PyQt-QDateEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
lzma.LZMACompressor() in Python

26 Mar, 2020
With the help of lzma.LZMACompressor() method, we can get compressor to compress the bytes of string by using lzma.LZMACompressor() method.
Syntax : lzma.LZMACompressor()Return : Return compressed string.
Example #1 :In this example we can see that by using lzma.LZMACompressor() method, we are able to compress the string in the byte format by using this method.
# import lzma and compressimport lzma  s = b'This is GFG author, and final year student.'print(len(s))  # using lzma.LZMACompressor() methodcompressor = lzma.LZMACompressor()t = compressor.compress(s)print(len(t))
Output :
4324
Example #2 :
# import lzma and compressimport lzma  s = b'GeeksForGeeks@12345678'print(len(s))  # using lzma.LZMACompressor() methodcompressor = lzma.LZMACompressor()t = compressor.compress(s)print(len(t))
Output :
2224
Python-lzma
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
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 | Get unique values from a list
Python | datetime.timedelta() function
Python - IMAP

IMAP is an email retrieval protocol which does not download the emails. It just reads them and displays them. This is very useful in low bandwidth condition. Python’s client side library called imaplib is used for accessing emails over imap protocol.
IMAP stands for Internet Mail Access Protocol. It was first proposed in 1986.
Key Points:
IMAP allows the client program to manipulate the e-mail message on the server without downloading them on the local computer.
IMAP allows the client program to manipulate the e-mail message on the server without downloading them on the local computer.
The e-mail is hold and maintained by the remote server.
The e-mail is hold and maintained by the remote server.
It enables us to take any action such as downloading, delete the mail without reading the mail.It enables us to create, manipulate and delete remote message folders called mail boxes.
It enables us to take any action such as downloading, delete the mail without reading the mail.It enables us to create, manipulate and delete remote message folders called mail boxes.
IMAP enables the users to search the e-mails.
IMAP enables the users to search the e-mails.
It allows concurrent access to multiple mailboxes on multiple mail servers.
It allows concurrent access to multiple mailboxes on multiple mail servers.
The following table describes some of the IMAP commands:
 In the below example we login to a gmail server with user credentials. Then we choose to display the messages in the inbox. A for loop is used to display the fetched messages one by one and finally the connection is closed. 
import imaplib
import pprint

imap_host = 'imap.gmail.com'
imap_user = 'username@gmail.com'
imap_pass = 'password'

# connect to host using SSL
imap = imaplib.IMAP4_SSL(imap_host)

## login to server
imap.login(imap_user, imap_pass)

imap.select('Inbox')

tmp, data = imap.search(None, 'ALL')
for num in data[0].split():
	tmp, data = imap.fetch(num, '(RFC822)')
	print('Message: {0}\n'.format(num))
	pprint.pprint(data[0][1])
	break
imap.close()
Depending on the mail box configuration, mail is displayed.

    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
Tryit Editor v3.6 - Show Node.js

var http = require('http');
​
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  //Return the url part of the request object:
Work with $push in MongoDB

Let us create a collection with documents −
> db.demo738.insertOne({Subjects:["C","C++"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead696557bb72a10bcf0661")
}
> db.demo738.insertOne({Subjects:["MySQL","PL/SQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ead696657bb72a10bcf0662")
}
Display all documents from a collection with the help of find() method −
> db.demo738.find();
This will produce the following output −
{ "_id" : ObjectId("5ead696557bb72a10bcf0661"), "Subjects" : [ "C", "C++" ] }
{ "_id" : ObjectId("5ead696657bb72a10bcf0662"), "Subjects" : [ "MySQL", "PL/SQL" ] }
Following is the query to push −
>db.demo738.update({_id:ObjectId("5ead696657bb72a10bcf0662")},{$push:{"Subjects":"MongoDB"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo738.find();
This will produce the following output −
{ "_id" : ObjectId("5ead696557bb72a10bcf0661"), "Subjects" : [ "C", "C++" ] }
{ "_id" : ObjectId("5ead696657bb72a10bcf0662"), "Subjects" : [ "MySQL", "PL/SQL", "MongoDB" ] }
How can we set the shortcut key to a JButton in Java?

A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons to a Java Swing application. A JButon can generate an ActionListener interface when the button is pressed or clicked, it can also generate the MouseListener and KeyListener interfaces. We can also set the short cut keys for a JButton using the setMnemonic() method.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonTest extends JFrame {
   private JButton button;
   public JButtonTest() {
      setTitle("JButtonTest");
      button = new JButton("Click or press ALT-C");
      button.setMnemonic('C');
      add(button, BorderLayout.CENTER);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent evt) {
            JOptionPane.showMessageDialog(null, ("Button clicked or pressed"));
         }
      });
      setSize(475, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String args[]) throws Exception {
      new JButtonTest();
   }
}
In the above program, if we click or apply short cut key (Alt+C from the keyboard) on JButton, a new popup window can be generated below
Tryit Editor v3.7

CSS Style Images
Tryit: Create rounded image
count_if() in C++ STL - GeeksforGeeks

31 May, 2021
count_if() function returns the number of elements in a range that satisfy the condition.
Syntax: 
template <class InputT, class UnaryPredicate>
typename iterator_traits <InputT> :: difference_type
    count_if(InputT first, InputT last, UnaryPredicate p);
Examples:  
Input: 0 1 2 3 4 5 6 7 8 9
Output: Total no of even numbers is: 5

Input: 2 3 4 5 6 7 8 9 10 11 12 13
Output: Total no of even numbers is: 6
The count_if function takes three parameters, the first two of which are the first and the last position of the sequence of the elements (where the last position is not included in the range) while the third parameter is an unary predicate ( takes single argument to check the condition and returns true or false ) that takes the element of given sequence one by one as a parameter and returns a boolean value on the basis of condition specified in that function.  One thing we should keep in mind is that type of the predicate should be same as the type of the container. 
Then, count_if() returns the number of elements in the given sequence for which the comparator function (third parameter) returns true. 
CPP
// C++ program to show the working// of count_if()#include <bits/stdc++.h>using namespace std; // Function to check the// number is even or oddbool isEven(int i){    if (i % 2 == 0)        return true;    else        return false;} // Drivers codeint main(){    vector<int> v;    for (int i = 0; i < 10; i++) {        v.push_back(i);    }    int noEven = count_if(v.begin(), v.end(),                                     isEven);     cout << "Total no of even numbers is: "         << noEven;     return 0;}
Total no of even numbers is: 5
 
sohamdas8697
CPP-Functions
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
C++ Classes and Objects
Virtual Function in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
Sorting a Map by value in C++ STL
Shallow Copy and Deep Copy in C++
Python | Get first index values in tuple of strings

01 May, 2019
Yet another peculiar problem which might not be common, but can occur in python programming while playing with tuples. Since tuples are immutable, they are difficult to manipulate and hence knowledge of possible variation solutions always helps. This articles solves problem of extracting only the first index element of each string in tuple. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension
Almost every problem can be solved using list comprehension as a shorthand to naive approach and this problem isn’t an exception. In this, we just iterate through each list picking just the 0th index element to build the resultant list.
# Python3 code to demonstrate# Get first index values in tuple of strings# using list comprehension  # initializing tupletest_tuple = ('GfG', 'for', 'Geeks')  # printing original tuple print("The original tuple : " + str(test_tuple))  # using list comprehsion# Get first index values in tuple of stringsres = list(sub[0] for sub in test_tuple)  # print resultprint("The first index string character list : " + str(res))
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']

 
Method #2 : Using next() + zip()
This particular task can also be performed using the combination of above two in more efficient way, using the iterators to do this task. The zip function can be used bind together the string elements.
# Python3 code to demonstrate# Get first index values in tuple of strings# using next() + zip()  # initializing tupletest_tuple = ('GfG', 'for', 'Geeks')  # printing original tuple print("The original tuple : " + str(test_tuple))  # using next() + zip()# Get first index values in tuple of stringsres = list(next(zip(*test_tuple)))  # print resultprint("The first index string character list : " + str(res))
The original tuple : ('GfG', 'for', 'Geeks')
The first index string character list : ['G', 'f', 'G']

Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Split string into list of characters
How to capture multiple matches in the same line in Java regex

import java.util.regex.*;
class PatternMatcher {
   public static void main(String args[]) {
      int count = 0;
      // String to be scanned to find the pattern.
      String content = "aaa bb aaa";
      String string = "aaa";

      // Create a Pattern object
      Pattern p = Pattern.compile(string);

      // get a matcher object
      Matcher m = p.matcher(content);

      while(m.find()) {
         count++;
         System.out.println("Match no:"+count);
         System.out.println("Found at: "+ m.start()+ " - " + m.end());
      }
   }
}
Match no:1
Found at: 0 - 3
Match no:2
Found at: 7 - 10
start() – This method used for getting the start index of a match that is being found using find() method.
start() – This method used for getting the start index of a match that is being found using find() method.
end() –This method used for getting the end index of a match that is being found using find() method. It returns index of character next to last matching character.
end() –This method used for getting the end index of a match that is being found using find() method. It returns index of character next to last matching character.
Python | Perform Sentence Segmentation Using Spacy

05 Sep, 2020
The process of deciding from where the sentences actually start or end in NLP or we can simply say that here we are dividing a paragraph based on sentences. This process is known as Sentence Segmentation. In Python, we implement this part of NLP using the spacy library.
Spacy is used for Natural Language Processing in Python.
To use this library in our python program we first need to install it.
Command to install this library:
pip install spacy
python -m spacy download en_core_web_sm
Here en_core_web_sm  means core English Language available online of small size.
Example:
we have the following paragraph:
"I Love Coding. Geeks for Geeks helped me in this regard very much. I Love Geeks for Geeks."
here there are 3 sentences.
1. I Love Coding.
2. Geeks for Geeks helped me in this regard very much.
3. I Love Geeks for Geeks
In python, .sents is used for sentence segmentation which is present inside spacy. The output is given by .sents is a generator and we need to use the list if we want to print them randomly.
Code:
#import spacy libraryimport spacy  #load core english librarynlp = spacy.load("en_core_web_sm")  #take unicode string  #here u stands for unicodedoc = nlp(u"I Love Coding. Geeks for Geeks helped me in this regard very much. I Love Geeks for Geeks.")#to print sentencesfor sent in doc.sents:  print(sent)
Output:Now if we try to use doc.sents randomly then what happens:
Code: To overcome this error we first need to convert this generator into a list using list function.
#converting the generator object result in to listdoc1 = list(doc.sents)  #Now we can use it randomly asdoc1[1]
Output:
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.inner()

This function returns the inner product of vectors for 1-D arrays. For higher dimensions, it returns the sum product over the last axes.
import numpy as np 
print np.inner(np.array([1,2,3]),np.array([0,1,0])) 
# Equates to 1*0+2*1+3*0
It will produce the following output −
2

# Multi-dimensional array example 
import numpy as np 
a = np.array([[1,2], [3,4]]) 

print 'Array a:' 
print a 
b = np.array([[11, 12], [13, 14]]) 

print 'Array b:' 
print b 

print 'Inner product:' 
print np.inner(a,b)
It will produce the following output −
Array a:
[[1 2]
[3 4]]

Array b:
[[11 12]
[13 14]]

Inner product:
[[35 41]
[81 95]]

In the above case, the inner product is calculated as −
1*11+2*12, 1*13+2*14 
3*11+4*12, 3*13+4*14 


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Program to count substrings with all 1s in binary string in Python

Suppose we have a binary string s. We have to find the number of substrings that contain only "1"s. If the answer is too large, mod the result by 10^9+7.
So, if the input is like s = "100111", then the output will be 7, because the substrings containing only "1"s are ["1", "1", "1", "1", "11", "11" and "111"]
To solve this, we will follow these steps −
a := 0
count := 0
for i in range 0 to size of s - 1, doif s[i] is same as "0", thena := 0otherwise,a := a + 1count := count + a
if s[i] is same as "0", thena := 0
a := 0
otherwise,a := a + 1count := count + a
a := a + 1
count := count + a
return count
Let us see the following implementation to get better understanding −
def solve(s):
   a = 0
   count = 0
   for i in range(len(s)):
      if s[i] == "0":
         a = 0
      else:
         a += 1
         count += a
   return count

s = "100111"
print(solve(s))
"100111"
7
How to resolve a NullPointerException in Java?

A NullPointerException is a runtime exception thrown by the JVM when our application code, other referenced API or the middleware encounters the following conditions
Attempting to invoke an instance method of a null object.
Attempting to access or modify a particular field of a null object.
Attempting to obtain the length of a null object as an array.
Review the java.lang.NullPointerException stack trace and determine where the Exception is triggered (Application code, third-party API, middleware software and extract the line).
If the problem is at the application code then a code walk-through will be required. If the problem is found from third-party API or middleware, need to first review the referenced code and determine if it could indirectly be the source of the problem, for instance, passing a null value to a third party API method, etc.
If problem found within the application code, then attempt to determine which Object instance is null and causing the problem. We need to modify the code in order to add proper null check validations and proper logging so we can understand the source of the null value as well.
public class NPEDemo {
   private String field1 = null;
   private String field2 = null;
   public String getField1() {
      return field1;
   }
   private void setField1(String field1) {
      this.field1 = field1;
   }
   public String getField2() {
      return field2;
   }
   private void setField2(String field2) {
      this.field2 = field2;
   }
   public static void main(String[] args) {
      try {
         NPEDemo npe = new NPEDemo();
         npe.setField1("field1 value");
         npe = null;
         npe.setField2("field2 Value");
      } catch (Throwable e) {
         System.out.println("Java Error is: "+e );
         e.printStackTrace();
      }
   }
}
Java Error is: java.lang.NullPointerException
java.lang.NullPointerException
at NPEDemo.main(NPEDemo.java:24)
C Program for sum of cos(x) series

We are given with the value of x and n where, x is the angle for cos and n is the number of terms in the cos(x) series.
Cos(x) is a trigonometric function which is used to calculate the value of x angle.
cos⁡(x)=∑k=0∞(−1)k(2k!)x2k
Cos(x) = 1 – (x*2 / 2!) + (x*4 / 4!) – (x*6 / 6!) + (x*8 / 8!)......
Input-: x = 10, n = 3
Output-: 0.984804
Input-: x = 8, n = 2
Output-: 0.990266
Approach used in the below program is as follows −
Input the value of x and n
Apply the formula for calculating cos(x) series
Print the result as the sum of all the series
Start
Step 1 Declare and initialize const double PI = 3.142
Step 2 In function double series_sum(double x, int n)
   Set x = x * (PI / 180.0)
Set result = 1
Set s = 1, fact = 1, pow = 1
    Loop For i = 1 and i < 5 and i++
        Set s = s * -1
        Set fact = fact * (2 * i - 1) * (2 * i)
        Set pow = pow * x * x
        Set result = result + s * pow / fact
     End Loop
    Return result
Step 3 In function int main() s
    Declare and set x = 10
Declare and set n = 3
    Print series_sum(x, n)  
Stop
#include <stdio.h>
const double PI = 3.142;
//will return the sum of cos(x)
double series_sum(double x, int n) {
    x = x * (PI / 180.0);
    double result = 1;
    double s = 1, fact = 1, pow = 1;
    for (int i = 1; i < 5; i++) {
        s = s * -1;
        fact = fact * (2 * i - 1) * (2 * i);
        pow = pow * x * x;
        result = result + s * pow / fact;
    }
    return result;
}
//main function
int main() {
    float x = 10;
    int n = 3;
    printf("%lf\n", series_sum(x, n));  
    return 0;
}
X=10; n=30.984804
X=13; n=80.974363
X=8; n=2 0.990266
C++ Program to Find Fibonacci Numbers using Matrix Exponentiation

The Fibonacci numbers, commonly denoted Fn form a sequence, called the Fibonacci sequence, i.e; each number is the sum of the two preceding ones, starting from 0 and 1. That is −
F0 = 0 and F1 = 1
And
Fn = Fn-1 + Fn-2
for n > 1.
Begin
   Take two 2 dimensional array
   Create a function and Perform matrix multiplication
   Create another function to find out power of matrix
   Create a function then to find out the Fibonacci number
   Multiply(arr1[2][2], arr2[2][2])
   Take 4 variables a, b, c, d
   a = arr1[0][0] * arr2[0][0] + arr1[0][1] * arr2[1][0]
   b= arr1[0][0] * arr2[0][1] + arr1[0][1] * arr2[1][1]
   c = arr1[1][0] * arr2[0][0] + arr1[1][1] * arr2[1][0]
   d = arr1[1][0] * arr2[0][1] + arr1[1][1] * arr2[1][1]
   arr1[0][0] = a
   arr1[0][1] = b
   arr1[1][0] = c
   arr1[1][1] = d
   Power(arr1[2][2], take integer n as input)
   if (n == 0 or n == 1)
      return;
   arr1 [2][2] = {{1,1}, {1,0}}
   power(arr1, n / 2)
   multiply(arr1, arr1)
   if (n mod 2 not equal to 0)
      multiply(arr1, arr2)
   fibonacci_matrix(n)
   arr1[2][2] = {{1,1}, {1,0}}
   if n ==0
      return 0
      power(arr1 n - 1)
   return arr1[0][0]
End
#include <iostream>
using namespace std;
void multiply(int F[2][2], int M[2][2]) {
   int a = F[0][0] * M[0][0] + F[0][1] * M[1][0];
   int b= F[0][0] * M[0][1] + F[0][1] * M[1][1];
   int c = F[1][0] * M[0][0] + F[1][1] * M[1][0];
   int d = F[1][0] * M[0][1] + F[1][1] * M[1][1];
   F[0][0] = a;
   F[0][1] = b;
   F[1][0] = c;
   F[1][1] = d;
}
void power(int F[2][2], int n) {
   if (n == 0 || n == 1)
      return;
   int M[2][2] = {{1,1},{1,0}};
   power(F, n / 2);
   multiply(F, F);
   if (n % 2 != 0)
      multiply(F, M);
}
int fibonacci_matrix(int n) {
   int F[2][2] = {{1,1},{1,0}};
   if (n == 0)
      return 0;
   power(F, n - 1);
   return F[0][0];
}
int main() {
   int n;
   while (1) {
      cout<<"Enter the integer n to find nth fibonacci no. (enter 0 to exit):";
      cin>>n;
      if (n == 0)
         break;
      cout<<fibonacci_matrix(n)<<endl;
   }
   return 0;
}
Enter the integer n to find nth fibonacci no. (enter 0 to exit): 2
1
Enter the integer n to find nth fibonacci no. (enter 0 to exit): 6
8
Enter the integer n to find nth fibonacci no. (enter 0 to exit): 7
13
Enter the integer n to find nth fibonacci no. (enter 0 to exit): 0
Python – Extract elements from Ranges in List

02 Sep, 2020
Given a list, and a list of tuples with ranges, extract all elements in those ranges from list.
Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 6, 10], range_list = [(2, 4), (7, 8)]Output : [4, 6, 7, 5, 6]Explanation : 4, 6, 7 are elements at idx 2, 3, 4 and 5, 6 at idx 7, 8.
Input : test_list = [4, 5, 4, 6, 7, 5, 4, 5, 6, 10], range_list = [(2, 6)]Output : [4, 6, 7, 5, 4]Explanation : Elements from 2-6 index are extracted.
Method #1 : Using loop + list slicing 
In this, we extract each range using list slicing and using loop iterate for each range and keep extending the extracting slices to extending list.
Python3
# Python3 code to demonstrate working of # Extract elements from Ranges in List# Using loop + list slicing   # initializing listtest_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]  # printing original listprint("The original list is : " + str(test_list))  # initializing rangesrange_list = [(2, 4), (7, 8), (10, 12)]  res = []for ele in range_list:          # extending ranges    res.extend(test_list[ele[0] : ele[1] + 1])  # printing result print("Ranges elements : " + str(res))
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
Ranges elements : [4, 6, 7, 5, 4, 4, 6, 9]

Method #2  : Using list comprehension
In this, we apply similar method as above function, difference being that list comprehension is used to solve this in compact form.
Python3
# Python3 code to demonstrate working of # Extract elements from Ranges in List# Using list comprehensionfrom itertools import chain  # initializing listtest_list = [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]  # printing original listprint("The original list is : " + str(test_list))  # initializing rangesrange_list = [(2, 4), (7, 8), (10, 12)]  # using one-liner to solve this problemres = list(chain.from_iterable([test_list[ele[0] : ele[1] + 1] for ele in range_list]))  # printing result print("Ranges elements : " + str(res))
The original list is : [4, 5, 4, 6, 7, 5, 4, 5, 4, 6, 4, 6, 9, 8]
Ranges elements : [4, 6, 7, 5, 4, 4, 6, 9]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
C library function - atan2()

The C library function double atan2(double y, double x) returns the arc tangent in radians of y/x based on the signs of both values to determine the correct quadrant.
Following is the declaration for atan2() function.
double atan2(double y, double x)
x − This is the floating point value representing an x-coordinate.
x − This is the floating point value representing an x-coordinate.
y − This is the floating point value representing a y-coordinate.
y − This is the floating point value representing a y-coordinate.
This function returns the principal arc tangent of y/x, in the interval [-pi,+pi] radians.
The following example shows the usage of atan2() function.
#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main () {
   double x, y, ret, val;

   x = -7.0;
   y = 7.0;
   val = 180.0 / PI;

   ret = atan2 (y,x) * val;
   printf("The arc tangent of x = %lf, y = %lf ", x, y);
   printf("is %lf degrees\n", ret);
  
   return(0);
}
Let us compile and run the above program that will produce the following result −
The arc tangent of x = -7.000000, y = 7.000000 is 135.000000 degrees


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Python | Single Point Crossover in Genetic Algorithm - GeeksforGeeks

13 Oct, 2019
Single Point Crossover in Genetic Algorithm is a form of crossover in which two-parent chromosome are selected and a random/given point is selected and the genes/data are interchanged between them after the given/selected point for example
Examples:
P1: 000011110011 
P2: 101010101010

Point: 4
After Crossover:
C1: 000010101010
C2: 101011110011

The problem is to select a random point for the crossover of two given parents and generate at least five generations of children from the given pair of a chromosome.
# library to generate a random numberimport random  # function for implementing the single-point crossoverdef crossover(l, q):  # converting the string to list for performing the crossover    l = list(l)    q = list(q)  # generating the random number to perform crossover    k = random.randint(0, 15)    print("Crossover point :", k)  # interchanging the genes    for i in range(k, len(s)):        l[i], q[i] = q[i], l[i]    l = ''.join(l)    q = ''.join(q)    print(l)    print(q, "\n\n")    return l, q    # patent chromosomes:  s = '1100110110110011'p = '1000110011011111'print("Parents")print("P1 :", s)print("P2 :", p, "\n")  # function calling and storing the off springs for # next generation crossoverfor i in range(5):    print("Generation ", i+1, "Childrens :")    s, p = crossover(s, p)
Parents
P1 : 1100110110110011
P2 : 1000110011011111 

Generation  1 Childrens :
Crossover point : 2
1100110011011111
1000110110110011 


Generation  2 Childrens :
Crossover point : 7
1100110110110011
1000110011011111 


Generation  3 Childrens :
Crossover point : 0
1000110011011111
1100110110110011 


Generation  4 Childrens :
Crossover point : 7
1000110110110011
1100110011011111 


Generation  5 Childrens :
Crossover point : 2
1000110011011111
1100110110110011

Artificial Intelligence
Genetic Algorithms
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree
Decision Tree Introduction with example
Python | Decision tree implementation
Support Vector Machine Algorithm
ML | Underfitting and Overfitting
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Factorial of Large Number Using boost multiprecision Library - GeeksforGeeks

28 Jan, 2018
We have given a large number now we can easily find out the factorial of this large number using boost multiprevision Library.Boost library has included a new multiprecision library in the current 1.53.0 release for C++ programmers who need more precision than 64 bits.
Examples:
Input : 100
Output :  933262154439441526816992388562667004-
         907159682643816214685929638952175999-
         932299156089414639761565182862536979-
         208272237582511852109168640000000000-
         00000000000000



Input :50
Output : 3041409320171337804361260816606476884-
         4377641568960512000000000000

// CPP program to find factorial of large // number using boost library.#include <bits/stdc++.h>#include <boost/multiprecision/cpp_int.hpp>using boost::multiprecision::cpp_int;using namespace std;  cpp_int Factorial(int number){    cpp_int num = 1;    for (int i = 1; i <= number; i++)        num = num * i;    return num;}  int main(){    int number = 100;    cpp_int fact = Factorial(number);    cout << fact << endl;    return 0;}
Output:-
933262154439441526816992388562667004-
         907159682643816214685929638952175999-
         932299156089414639761565182862536979-
         208272237582511852109168640000000000-
         00000000000000
cpp-boost
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Constructors in C++
Virtual Function in C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
Copy Constructor in C++
Object Oriented Programming in C++
Polymorphism in C++
Clearing input buffer in C/C++

The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.
Here is the syntax of fflush(stdin) to clear the input buffer in C language,
int fflush(FILE *stream);
Here is an example of fflush(stdin) to clear the input buffer in C language,
 Live Demo
#include <stdio.h>
#include<stdlib.h>

int main() {
   char s[20];

   printf("Enter the string : \n", s);
   scanf("%s\n", s);
   printf("The entered string : %s", s);
     
   fflush(stdin);
   return 0;
}
Here is the output
Enter the string : helloworld
The entered string : helloworld
Composition vs Aggregation in C#

Under Composition, if the parent object is deleted, then the child object also loses its status. Composition is a special type of Aggregation and gives a part-of relationship.
For example, A Car has an engine. If the car is destroyed, the engine is destroyed as well.
public class Engine {
   . . .
}
public class Car {
   Engine eng = new Engine();
   .......
}
Aggregation is a directional relation between objects in C#. It is the relationship between objects.
For example, Employee and Address
An Employee is associated with a single Department, whereas a Department can have more than one employee. Let us see an example of Employee and Address.
public class Address {
   . . .
}
public class Employee {
   private Address addr;
   public Employee (Address addr) {
      this.addr = addr;
   }
   . . .
}
Easy way to re-order columns in MySQL?

To re-order columns in MySQL, use the ALTER TABLE MODIFY COLUMN. The syntax is as follows -
ALTER TABLE yourTableName MODIFY COLUMN yourColumnName data type after yourColumnName.
To understand the above syntax, let us first create a table. The query to create a table is as follows.
mysql> create table reOrderColumn
-> (
-> ProductId int,
-> DeliveryDate datetime,
-> ProductName varchar(100)
-> );
Query OK, 0 rows affected (0.76 sec)
Now check the description of the table. The query is as follows.
mysql> desc reOrderColumn;
The following is the output.
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductId | int(11) | YES | | NULL | |
| DeliveryDate | datetime | YES | | NULL | |
| ProductName | varchar(100) | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
3 rows in set (0.10 sec)
Now re-order the column using ALTER MODIFY command. I will reorder the DeliveryDate column after the ProductName column. The query is as follows.
mysql> alter table reOrderColumn modify column DeliveryDate datetime after ProductName;
Query OK, 0 rows affected (1.61 sec)
Records: 0 Duplicates: 0 Warnings: 0
Let us now check the column have been reordered or not. The query is as follows.
mysql> desc reOrderColumn;
The following is the output displaying the columns have been reordered.
+--------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+-------+
| ProductId | int(11) | YES | | NULL | |
| ProductName | varchar(100) | YES | | NULL | |
| DeliveryDate | datetime | YES | | NULL | |
+--------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
Semaphore in C#

The semaphore class lets you set a limit on the number of threads that have access to a critical section. The class is used to control access to a pool of resources. System.Threading.Semaphore is the namespace for Semaphore because it has all the methods and properties required to implement Semaphore.
For using a semaphore in C#, you just need to instantiate an instance of a Semaphore object. It has minimum of two arguments −
−
MSDN
Let us now see an example:
Here, we have used the following Semaphore constructor that initializes a new instance of the Semaphore class, specifying the maximum number of concurrent entries and optionally reserving some entries.
static Semaphore semaphore = new Semaphore(2, 2);
 Live Demo
using System;
using System.Threading;
namespace Program
{
class Demo
   {
      static Thread[] t = new Thread[5];
      static Semaphore semaphore = new Semaphore(2, 2);
      static void DoSomething()
      {
         Console.WriteLine("{0} = waiting", Thread.CurrentThread.Name);
         semaphore.WaitOne();
         Console.WriteLine("{0} begins!", Thread.CurrentThread.Name);
         Thread.Sleep(1000);
         Console.WriteLine("{0} releasing...", Thread.CurrentThread.Name);
         semaphore.Release();
      }
      static void Main(string[] args)
      {
         for (int j = 0; j < 5; j++)
         {
            t[j] = new Thread(DoSomething);
            t[j].Name = "thread number " + j;
            t[j].Start();
         }
         Console.Read();
      }
   }
}
The following is the output
thread number 2 = waiting
thread number 0 = waiting
thread number 3 = waiting
thread number 1 = waiting
thread number 4 = waiting
thread number 2 begins!
thread number 1 begins!
thread number 2 releasing...
thread number 1 releasing...
thread number 4 begins!
thread number 3 begins!
thread number 4 releasing...
thread number 0 begins!
thread number 3 releasing...
thread number 0 releasing...
Equivalent of Java Super Keyword in C#

For super keyword in Java, we have the base keyword in C#.
Super keyword in Java refers immediate parent class instance. It is used to differentiate the members of superclass from the members of subclass, if they have same names. It is used to invoke the superclass constructor from subclass.
C# base keyword is used to access the constructors and methods of base class. Use it within instance method, constructor, etc.
Let us see an example of C# base.
 Live Demo
using System;
public class Animal {
   public string repColor = "brown";
}
public class Reptile: Animal {
   string repColor = "green";
   public void display() {
      Console.WriteLine("Color: "+base.repColor);
      Console.WriteLine("Color: "+repColor);
   }
}
public class Demo {
   public static void Main() {
      Reptile rep = new Reptile();
      rep.display();
   }
}
Color: brown
Color: green
Matcher replaceAll() method in Java with Examples

The java.util.regex.Matcher class represents an engine that performs various match operations. There is no constructor for this class, you can create/obtain an object of this class using the matches() method of the class java.util.regex.Pattern.
The replaceAll() method of this (Matcher) class accepts a string value, replaces all the matched subsequences in the input with the given string value and returns the result.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#%&*]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //Retrieving Pattern used
      System.out.println("The are "+count+" special characters [# % & *] in the given text");
      //Replacing all special characters [# % & *] with ! String result = matcher.replaceAll("!");
      System.out.println("Replaced all special characters [# % & *] with !: \n"+result);
   }
}
Enter input text:
Hello# How # are# you *& welcome to T#utorials%point
The are 7 special characters [# % & *] in the given text
Replaced all special characters [# % & *] with !:
Hello! How ! are! you !! welcome to T!utorials!point
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   public static void main(String args[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression to match spaces (one or more)
      String regex = "\\s+";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      //Replacing all space characters with single space
      String result = matcher.replaceAll(" ");
      System.out.print("Text after removing unwanted spaces: \n"+result);
   }
}
Enter a String
hello this is a sample text with irregular spaces
Text after removing unwanted spaces:
hello this is a sample text with irregular spaces
Convert array to HashSet in Java

Create an array and convert it to List −
Integer[] arr = { 10, 15, 20, 10, 10, 10, 20, 30, 35, 40, 40};
List<Integer> l = Arrays.asList(arr);
Now, let us convert the above array to HashSet −
Set<Integer> s = new HashSet<Integer>(l);
The following is an example to convert array to HashSet −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Integer[] arr = { 10, 15, 20, 10, 10, 10, 20, 30, 35, 40, 40};
      List<Integer> l = Arrays.asList(arr);
      Set<Integer> s = new HashSet<Integer>(l);
      for (Iterator i = s.iterator(); i.hasNext();) {
         Object ele = i.next();
         System.out.println(ele);
      }
   }
}
35
20
40
10
30
15
How can I get the current screen orientation in Android?

In some situation, we need to find an android activity orientation. This example demonstrates how to integrate Android Login and registration form.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   android:id = "@+id/parent"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity"
   android:gravity = "center"
   android:orientation = "vertical">
   <TextView
      android:id = "@+id/text"
      android:textSize = "28sp"
      android:textAlignment = "center"
      android:layout_width = "match_parent"
      android:layout_height = "wrap_content" />
</LinearLayout>
In the above code, we have taken a text view. According to screen orientation, text view going to update the text.
Step 3 − Add the following code to src/MainActivity.java
package com.example.andy.myapplication;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   int view = R.layout.activity_main;
   TextView textview;
   @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(view);
      textview = findViewById(R.id.text);
      int orientation = this.getResources().getConfiguration().orientation;
      if (orientation = = Configuration.ORIENTATION_PORTRAIT) {
         textview.setText("Portrait mode");
      } else {
         textview.setText("landscape mode");
      }
   }
}
In the above code, we have taken orientation as integer and comparing with configuring orientation as shown below -
int orientation = this.getResources().getConfiguration().orientation;
if (orientation = = Configuration.ORIENTATION_PORTRAIT) {
   textview.setText("Portrait mode");
} else {
   textview.setText("landscape mode");
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
When user keeps mobile as portrait mode, it will show the result as shown above. Now turn the device to landscape mode, it will show the result as shown below -
Click here to download the project code
What is following-sibling in Selenium?

We can use the concept of following-sibling in xpath for identifying elements in Selenium. It identifies the siblings of the context node. The siblings should be located at the equal level of the existing node and should have the same parent.
Let us see an example of an element with ul tag having more than one child with li tag. Then let us try to locate the fifth li element (Effective Resume Writing) from the first li element with class attribute sreading.
//li[@class='sreading']/following-sibling::li[4]
Here, we are locating the fifth child of ul tag, but we have provided li[4] since we are locating the fifth child from the first child element.
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 FollowingSiblingXpath{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      //identify fifth child from first child
      WebElement n = driver.findElement
      (By.xpath("//li[@class='sreading']/following-sibling::li[4]"));
      String s = n.getText();
      System.out.println("Text is: " + s);
      driver.quit();
   }
}