code-rag-bench/online-tutorials huggingface dataset:
Check multiple conditions in if statement - Python - GeeksforGeeks

26 Mar, 2020
If-else conditional statement is used in Python when a situation leads to two conditions and one of them should hold true.
Syntax:
if (condition):
    code1
else:
    code2

[on_true] if [expression] else [on_false]
Note: For more information, refer to Decision Making in Python (if , if..else, Nested if, if-elif)
Here we’ll study how can we check multiple conditions in a single if statement. This can be done by using ‘and’ or ‘or’ or BOTH in a single statement.
Syntax:
if (cond1 AND/OR COND2) AND/OR (cond3 AND/OR cond4):
    code1
else:
    code2

and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn’t check the second one. If the first condition is true and the compiler moves to the second and if the second comes out to be false, false is returned to the if statement.
or Comparison = for this to work normally either condition needs to be true. The compiler checks the first condition first and if that turns out to be true, the compiler runs the assigned code and the second condition is not evaluated. If the first condition turns out to be false, the compiler checks the second, if that is true the assigned code runs but if that fails too, false is returned to the if statement.
The following examples will help understand this better:PROGRAM 1: program that grants access only to kids aged between 8-12
age = 18  if ((age>= 8) and (age<= 12)):    print("YOU ARE ALLOWED. WELCOME !")else:    print("SORRY ! YOU ARE NOT ALLOWED. BYE !")
Output:
SORRY ! YOU ARE NOT ALLOWED. BYE !

PROGRAM 2:
program that checks the agreement of the user to the terms
var = 'N'  if (var =='Y' or var =='y'):    print("YOU SAID YES")elif(var =='N' or var =='n'):    print("YOU SAID NO")else:    print("INVALID INPUT")
Output:
YOU SAID NO

PROGRAM 3: program to compare the entered three numbers
a = 7b = 9c = 3    if((a>b and a>c) and (a != b and a != c)):    print(a, " is the largest")elif((b>a and b>c) and (b != a and b != c)):    print(b, " is the largest")elif((c>a and c>b) and (c != a and c != b)):    print(c, " is the largest")else:    print("entered numbers are equal")
Output:
9  is the largest
Not just two conditions we can check more than that by using ‘and’ and ‘or’.PROGRAM 4:
a = 1b = 1c = 1if(a == 1 and b == 1 and c == 1):    print("working")else:    print("stopped")
Output:
working
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions
*args and **kwargs in Python
sum() function in Python
How to create a SnackBar service?

14 May, 2020
MatSnackBar is an angular directive that’s used for showing a notification bar specifically on the mobile devices.These types of UI components are generally used several times.So to avoid the repetition of code, a service can simply be created to use SnackBar in different components.
Approach:
To create a service you have to use the following command:ng g s snackBar
ng g s snackBar
Now import MatSnackBar from @angular/core and define the function openSnackBar (you can always use a different name).import { Injectable } from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar';  @Injectable({  providedIn: 'root'})export class SnackBarService {  //create an instance of MatSnackBar    constructor(private snackBar:MatSnackBar) { }  /* It takes three parameters     1.the message string     2.the action     3.the duration, alignment, etc. */    openSnackBar(message: string, action: string) {    this.snackBar.open(message, action, {       duration: 2000,    });  }}
import { Injectable } from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar';  @Injectable({  providedIn: 'root'})export class SnackBarService {  //create an instance of MatSnackBar    constructor(private snackBar:MatSnackBar) { }  /* It takes three parameters     1.the message string     2.the action     3.the duration, alignment, etc. */    openSnackBar(message: string, action: string) {    this.snackBar.open(message, action, {       duration: 2000,    });  }}
Import the snackBarService and inject it inside the constructor of the component, in which you want to use the Snackbar. This will create an instance of the service say snackBService.Now call the openSnackBar function wherever it is required, with the help of snackBService.import { Component, OnInit } from '@angular/core';import {SnackBarService} from '../snack.service';    @Component({  selector: 'app-profile',  templateUrl: './snackBar.html',  styleUrls: ['./snackBar.css']})export class SnackBar {    // create an instance of SnackBarService     constructor(private snackBService:SnackBarService) { }    //defining method for display of SnackBar    trigger(message:string, action:string)  {   this.snackBService.openSnackBar(message, action);  }  }
import { Component, OnInit } from '@angular/core';import {SnackBarService} from '../snack.service';    @Component({  selector: 'app-profile',  templateUrl: './snackBar.html',  styleUrls: ['./snackBar.css']})export class SnackBar {    // create an instance of SnackBarService     constructor(private snackBService:SnackBarService) { }    //defining method for display of SnackBar    trigger(message:string, action:string)  {   this.snackBService.openSnackBar(message, action);  }  }
By repeating these steps we can use the snackBar inside any component.Example:<button  (click)="trigger('This is a ', 'SnackBar')">    SnackBarButton</button>
<button  (click)="trigger('This is a ', 'SnackBar')">    SnackBarButton</button>
Output:
AngularJS-Misc
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Implement Token Authentication using Django REST Framework

19 Nov, 2021
Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.This article revolves about implementing token authentication using Django REST Framework to make an API. The token authentication works by providing token in exchange for exchanging usernames and passwords. 
django : 
pip install django
crispy_forms : 
 pip install --upgrade django-crispy-forms 
django rest_framework : 
pip install djangorestframework
HTTPie : 
pip install httpie
and a project to add API, here we are using Sign Up and log in 
Go to user folder in given project and make a api folder to keep all api related files  
 cd user && mkdir api 
Now, make user/api/serializers.py and user/api/viewsets.py in api folder
 cd user/api && touch serializers.py viewsets.py 
now edit user/api/serializers.py 
Python3
from rest_framework import serializersfrom django.contrib.auth.models import User  class userSerializers(serializers.ModelSerializer):     class Meta:        model = User        fields =  '__all__'
also edit user/api/viewsets.py 
Python3
from rest_framework import viewsetsfrom .serializers import userSerializersfrom django.contrib.auth.models import User  class userviewsets(viewsets.ModelViewSet):    queryset = User.objects.all()    serializer_class = userSerializers
Edit settings.pyadd rest_framework and rest_framework.authtoken in INSTALLED_APPS in setting.py
Edit rest_framework settings as below 
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
               'rest_framework.authentication.TokenAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES':(
                'rest_framework.permissions.IsAuthenticated',
    ),

}
Creating router goto project/ and create router.py 
 cd project/ && touch router.py 
edit project/router.py, 
Python3
from user.api.viewsets import userviewsetsfrom rest_framework import routers router = routers.DefaultRouter()router.register('user', userviewsets, base_name ='user_api')
Editing url.pygoto to project/urls.pyand edit it Import router and rest_framework.authtoken for token authentication 
Python3
from .router import routerfrom rest_framework.authtoken import views
add API related paths 
Python3
path('api/', include(router.urls)),path('api-token-auth/', views.obtain_auth_token, name='api-token-auth'),
Testing API first, migrate models  
python manage.py migrate 
start server using below command  
python manage.py runserver
open another terminal and let us check our API using HTTP POST request for a token and paste username and password. 
http POST http://localhost:8081/api-token-auth/ username='your_username' password="your_password"
now use this token to get data from API, place your API token 
http http://localhost:8081/api/user/ "Authorization: Token API_KEY_HERE"
varshagumber28
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add color picker in a form using HTML ?

05 Oct, 2021
In this article. we will learn how to add a color picker in a form using HTML.  As we know, a color picker is also known as a color-chooser. It is an interface in which a user can select a single color from multiple collections of background colors.  
Approach:
First, we create an HTML document that contains an <input> tag.
Use the type attribute with the <input> element.
Set the type attribute to value “color”.
Syntax
<input type="color">
Example: 
HTML
<!DOCTYPE html><html>  <head>    <title>        How to add a color picker         in form using HTML?    </title></head>  <body style="text-align: center;">    <h1>        GeeksForGeeks    </h1>      <h2>        How to add a color picker         in Form using HTML?    </h2>          <form>        <label>First Name</label>        <input type="text" name="fname"><br /><br>        <label>Last name</label>        <input type="text" name="lname"><br />        <p>            Select your favorite color:            <input type="color" value="red" id="color" />        </p>        <input type="submit" value="submit">    </form></body>  </html>
 
Output:
HTML-Attributes
HTML-Questions
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Select statement in MS SQL Server

04 Jun, 2020
In this article, the most basic statement used in SQL is being discussed.
Basic statement: select
There are large amounts of data available everywhere.The data is stored in a sequential order in form of a table.Each table consists of a row which represents a unique record and column represents a field.Schemas are used to arrange the tables in a logical order.In order to extract particular data from the tables, queries are being used which is written in Structured Query Language(SQL).To query data, select statement is used.
There are large amounts of data available everywhere.
The data is stored in a sequential order in form of a table.
Each table consists of a row which represents a unique record and column represents a field.
Schemas are used to arrange the tables in a logical order.
In order to extract particular data from the tables, queries are being used which is written in Structured Query Language(SQL).
To query data, select statement is used.
Syntax:
select 
select_list;
from
schema_name.table.name; 
In order to retrieve all the columns from a table, select* is being used.
Syntax -
select*
from
table_name; 
Points to remember:
In the real time databases, select* isn’t recommended for use because it retrieves the data more than your requirements.It results in slow functioning of the application.In case, the user adds more columns to the table, the select* statement retrieves all the columns including the new ones resulting in crashing of the application.
In the real time databases, select* isn’t recommended for use because it retrieves the data more than your requirements.
It results in slow functioning of the application.
In case, the user adds more columns to the table, the select* statement retrieves all the columns including the new ones resulting in crashing of the application.
Example:
If the user wants to retrieve the name of the student pursuing Computer Science, the query is as follows:
select 
name 
from
course.student
where course='cse' 
Note that course is the name of the schema and student is the name of the table.
The output will be retrieved as follows:
Note –To retrieve the query, another statement where is being used which will be discussed in further articles.
SQL-Server
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to define a rectangular array in C#?

Multi-dimensional arrays are also called rectangular array. You can define a 3-dimensional array of integer as −
int [ , , ] a;
Let us see how to define a two-dimensional array −
Int[,] a = new[3,3]
The following is an example showing how to work with a multi-dimensional i.e. rectangular array in C# −
 Live Demo
using System;

namespace Demo {

   class Program {
      static void Main(string[] args) {

         int[,] a = new int[3, 3];
         a[0,1]= 1;
         a[0,2]= 2;
         a[1,0]= 3;
         a[1,1]= 4;
         a[1,2]= 5;
         a[2,0]= 6;
         a[2,1]= 7;
         a[2,2]= 8;

         int i, j;

         for (i = 0; i < 3; i++) {
            for (j = 0; j < 3; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }
         }
         Console.ReadKey();
      }
   }
}
a[0,0] = 0
a[0,1] = 1
a[0,2] = 2
a[1,0] = 3
a[1,1] = 4
a[1,2] = 5
a[2,0] = 6
a[2,1] = 7
a[2,2] = 8
Python String istitle() Method

Python string  method istitle() checks whether all the case-based characters in the string following non-casebased letters are uppercase and all other case-based characters are lowercase.
Following is the syntax for istitle() method −
str.istitle()

NA
NA
This method returns true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones.It returns false otherwise.
The following example shows the usage of istitle() method.
#!/usr/bin/python

str = "This Is String Example...Wow!!!";
print str.istitle()

str = "This is string example....wow!!!";
print str.istitle()
When we run above program, it produces following result −
True
False


    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
Python | Convert String to Binary - GeeksforGeeks

16 Feb, 2021
Data conversion have always been widely used utility and one among them can be conversion of a string to it’s binary equivalent. Let’s discuss certain ways in which this can be done.
Method #1 : Using join() + ord() + format()The combination of above functions can be used to perform this particular task. The ord function converts the character to it’s ASCII equivalent, format converts this to binary number and join is used to join each converted character to form a string.
# Python3 code to demonstrate working of# Converting String to binary# Using join() + ord() + format()  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + str(test_str))  # using join() + ord() + format()# Converting String to binaryres = ''.join(format(ord(i), '08b') for i in test_str)  # printing result print("The string after binary conversion : " + str(res))
The original string is : GeeksforGeeks
The string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011
 
Method #2 : Using join() + bytearray() + format()This method is almost similar to the above function. The difference here is that rather than converting the character to it’s ASCII using ord function, the conversion at once of string is done by bytearray function.
# Python3 code to demonstrate working of# Converting String to binary# Using join() + bytearray() + format()  # initializing string test_str = "GeeksforGeeks"  # printing original string print("The original string is : " + str(test_str))  # using join() + bytearray() + format()# Converting String to binaryres = ''.join(format(i, '08b') for i in bytearray(test_str, encoding ='utf-8'))  # printing result print("The string after binary conversion : " + str(res))
The original string is : GeeksforGeeks
The string after binary conversion : 01000111011001010110010101101011011100110110011001101111011100100100011101100101011001010110101101110011

Python string-programs
Python
Python Programs
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Element-wise concatenation of two NumPy arrays of string - GeeksforGeeks

04 Jan, 2022
In this article, we will discuss how to concatenate element-wise two arrays of string 
Example :
Input :
A = ['Akash', 'Ayush', 'Diksha', 'Radhika']
B = ['Kumar', 'Sharma', 'Tewari', 'Pegowal']

Output :
A + B = [AkashKumar, AyushSharma, 'DikshTewari', 'RadhikaPegowal']
We will be using the numpy.char.add() method.
Syntax : numpy.char.add(x1, x2)Parameters :
x1 : first array to be concatenated (concatenated at the beginning)
x2 : second array to be concatenated (concatenated at the end)
Returns : Array of strings or unicode
Example 1: String array with a single element.
Python3
# importing library numpy as npimport numpy as np # creating array as first_namefirst_name = np.array(['Geeks'],                      dtype = np.str)print("Printing first name array:")print(first_name) # creating array as last namelast_name = np.array(['forGeeks'],                     dtype = np.str)print("Printing last name array:")print(last_name) # concat first_name and last_name# into new array named as full_namefull_name = np.char.add(first_name, last_name)print("\nPrinting concatenate array as full name:")print(full_name)
  Output : 
Printing first name array:
['Geeks']
Printing last name array:
['forGeeks']

Printing concatenate array as full name:
['GeeksforGeeks']
Example 2: String array with multiple elements.
Python3
# importing library numpy as npimport numpy as np # creating array as first_namefirst_name = np.array(['Akash', 'Ayush', 'Diksha',                       'Radhika'], dtype = np.str)print("Printing first name array:")print(first_name) # creating array as last namelast_name = np.array(['Kumar', 'Sharma', 'Tewari',                      'Pegowal'], dtype = np.str)print("Printing last name array:")print(last_name) # concat first_name and last_name# into new array named as full_namefull_name = np.char.add(first_name, last_name)print("\nPrinting concatenate array as full name:")print(full_name)
  Output : 
Printing first name array:
['Akash' 'Ayush' 'Diksha' 'Radhika']
Printing last name array:
['Kumar' 'Sharma' 'Tewari' 'Pegowal']

Printing concatenate array as full name:
['AkashKumar' 'AyushSharma' 'DikshaTewari' 'RadhikaPegowal']
varshagumber28
Python numpy-String Operation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Converting an image from colour to grayscale using OpenCV

In this program, we will change the color scheme of an image from rgb to grayscale
Step 1: Import OpenCV.
Step 2: Read the original image using imread().
Step 3: Convert to grayscale using cv2.cvtcolor() function.
import cv2
image = cv2.imread('colourful.jpg')
cv2.imshow('Original',image)
grayscale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayscale', grayscale)
Original Image:
Grayscale Image:
Product of non-repeating (distinct) elements in an Array in C++

We are given with an array of repeating or duplicate elements and the task is to find the product of all those elements which are non-repeating or distinct in the given array and display the results.
Input-: arr[] = {2, 1, 1, 2, 3, 4, 5, 5 }
Output-: 120
Explanation-: Since 1, 2 and 5 are repeating more than once so we will take them into 
consideration for their first occurrence. So result will be 1 * 2 * 3 * 4 * 5 = 120
Input-: arr[] = {1, 10, 9, 4, 2, 10, 10, 45, 4 }
Output-: 32400
Explanation-: Since 10 and 4 are repeating more than once so we will take them into consideration 
for their first occurrence. So result will be 1 * 10 * 9 * 4 * 2 * 45  = 32400
Approach used in the below program is as follows −
Input the duplicate elements in an array
For the better approach sort the elements of an array in ascending order such that it would be easy to determine which array element is repeating and don’t consider it for the product
Find all the distinct elements in an array and keep multiplying them by storing the result
Display the final result as the product of all the distinct elements in an array
Start
Step 1-> Declare function to find the product of all the distinct elements in an array
   int find_Product(int arr[], int size)
   Declare and set int prod = 1
   Create variable as unordered_set<int> s
   Loop For  i = 0 and i < size and i++
      IF s.find(arr[i]) = s.end()
         Set  prod *= arr[i]
         Call s.insert(arr[i])
      End
   End
   return prod
Step 2 -: In main()
   Declare and set int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 }
   Calculate the size of an array int size = sizeof(arr) / sizeof(int)
   Call find_Product(arr, size)
Stop
include <bits/stdc++.h>
using namespace std;
//function that calculate the product of non-repeating elements
int find_Product(int arr[], int size) {
   int prod = 1;
   unordered_set<int> s;
   for (int i = 0; i < size; i++) {
      if (s.find(arr[i]) == s.end()) {
         prod *= arr[i];
         s.insert(arr[i]);
      }
   }
   return prod;
}
int main() {
   int arr[] = { 2, 1, 1, 2, 3, 4, 5, 5 };
   int size = sizeof(arr) / sizeof(int);
   cout<<"product of all non-repeated elements are : "<<find_Product(arr, size);
   return 0;
}
product of all non-repeated elements are : 120
C | Operators | Question 5 - GeeksforGeeks

16 Sep, 2021
#include <stdio.h>int main(){    int i = 3;    printf("%d", (++i)++);    return 0;}
What is the output of the above program?(A) 3(B) 4(C) 5(D) Compile-time errorAnswer: (D)Explanation: In C, prefix and postfix operators need l-value to perform operation and return r-value. The expression (++i)++ when executed increments the value of variable i(i is a l-value) and returns r-value. The compiler generates the error(l-value required) when it tries to post-increment the value of a r-value.
ankitshaw1112
C-Operators
Operators
C Language
C Quiz
Operators
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Core Dump (Segmentation fault) in C/C++
Function Pointer in C
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
C | File Handling | Question 1
C | Arrays | Question 7
C | Misc | Question 7
Select all except the first character in a string in MySQL?

To select all except the first character in a string, you can use SUBSTR() method. Let us first create a table −
mysql> create table DemoTable
(
   FirstName varchar(20)
);
Query OK, 0 rows affected (0.63 sec)
Insert records in the table using insert command −
mysql> insert into DemoTable values('Larry');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('David');
Query OK, 1 row affected (0.14 sec)
Display records from the table using select command −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+
| FirstName |
+-----------+
| Larry     |
| Carol     |
| Robert    |
| David     |
+-----------+
4 rows in set (0.00 sec)
Here is the query to select all except the first character in a string −
mysql> select substr(FirstName,2) from DemoTable;
This will produce the following output −
+---------------------+
| substr(FirstName,2) |
+---------------------+
| arry                |
| arol                |
| obert               |
| avid                |
+---------------------+
4 rows in set (0.00 sec)
C program to check if a given string is Keyword or not?

Keyword is a predefined or reserved word which is available in C++ library with a fixed meaning and used to perform an internal operation. C++ Language supports more than 64 keywords.
Every Keyword exists in lower case letters like auto, break, case, const, continue, int etc.
32 Keywords in C++ Language which is also available in the C language.
These are 30 reserved words that were not in C, but added to C++
Input: str=”for”
Output: for is a keyword
Keywords are reserved words which cannot be used as variable names in program.
Keywords are reserved words which cannot be used as variable names in program.
There are 32 keywords in the C programming language.
There are 32 keywords in the C programming language.
Compare the string with each keyword if the string is same then string is keyword
 Live Demo
#include <stdio.h>
#include <string.h>
int main() {
   char keyword[32][10]={
      "auto","double","int","struct","break","else","long",
      "switch","case","enum","register","typedef","char",
      "extern","return","union","const","float","short",
      "unsigned","continue","for","signed","void","default",
      "goto","sizeof","voltile","do","if","static","while"
   } ;
   char str[]="which";
   int flag=0,i;
   for(i = 0; i < 32; i++) {
      if(strcmp(str,keyword[i])==0) {
         flag=1;
      }
   }
   if(flag==1)
      printf("%s is a keyword",str);
   else
      printf("%s is not a keyword",str);
}
which is a keyword
Program to find the largest sum of the path between two nodes in a binary tree in Python

Suppose we have a binary tree; we have to find the maximum sum of any path between any two nodes.
So, if the input is like
then the output will be 62 as the nodes are [12,13,14,16,7].
To solve this, we will follow these steps −
Define a function utils() . This will take root
Define a function utils() . This will take root
if root null, thenreturn 0
if root null, then
return 0
return 0
l := utils(left of root)
l := utils(left of root)
r := utils(right of root)
r := utils(right of root)
max_single := maximum of (max of l and r) + value of root) and value of root
max_single := maximum of (max of l and r) + value of root) and value of root
max_top := maximum of max_single and l + r + value of root
max_top := maximum of max_single and l + r + value of root
res := maximum of res and max_top
res := maximum of res and max_top
return max_single
return max_single
From the main method, do the following −
From the main method, do the following −
if root is null, thenreturn 0
if root is null, then
return 0
return 0
res := infinity
res := infinity
utils(root)
utils(root)
return res
return res
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
   def __init__(self, value):
      self.val = value
      self.left = None
      self.right = None
class Solution:
   def solve(self, root):
      if root is None:
         return 0
      self.res = float("-inf")
      self.utils(root)
      return self.res
   def utils(self, root):
      if root is None:
         return 0
      l = self.utils(root.left)
      r = self.utils(root.right)
      max_single = max(max(l, r) + root.val, root.val)
      max_top = max(max_single, l + r + root.val)
      self.res = max(self.res, max_top)
      return max_single
ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
print(ob.solve(root))
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
62
How to replace the values in a matrix with another value based on a condition in R?

A matrix has only numeric values and sometimes these values are either incorrectly entered or we might want to replace some of the values in a matrix based on some conditions. For example, if we have few fives in a matrix then we might want to replace all fives to an another number which is greater than 5 or less than 5.
Consider the below matrix −
set.seed(123)
M <-matrix(sample(1:50,25),nrow=5)
M
  [,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 5 8 19
[3,] 14 48 40 41 4
[4,] 3 25 28 7 45
[5,] 42 26 9 10 17
Replacing values based on different conditions −
M[M <5]<-10
M
[,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 5 8 19
[3,] 14 48 40 41 10
[4,] 10 25 28 7 45
[5,] 42 26 9 10 17
M[M=5] <-15
M
  [,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 5 8 19
[3,] 14 48 40 41 10
[4,] 10 25 28 7 45
[5,] 15 26 9 10 17
M[M==5] <-15
M
  [,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 15 8 19
[3,] 14 48 40 41 10
[4,] 10 25 28 7 45
[5,] 15 26 9 10 17
M[M<10&M>5]<-21
M
[,1] [,2] [,3] [,4] [,5]
[1,] 31 43 27 29 36
[2,] 15 37 15 21 19
[3,] 14 48 40 41 10
[4,] 10 25 28 21 45
[5,] 15 26 21 10 17
M[M >30]<-25
M
[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 27 29 25
[2,] 15 25 15 21 19
[3,] 14 25 25 25 10
[4,] 10 25 28 21 25
[5,] 15 26 21 10 17
M[M==14] <-25
M
[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 27 29 25
[2,] 15 25 15 21 19
[3,] 25 25 25 25 10
[4,] 10 25 28 21 25
[5,] 15 26 21 10 17
M[M==17] <-15
M
[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 27 29 25
[2,] 15 25 15 21 19
[3,] 25 25 25 25 10
[4,] 10 25 28 21 25
[5,] 15 26 21 10 15
M[M>25&M <30]<-25
M
[,1] [,2] [,3] [,4] [,5]
[1,] 25 25 25 25 25
[2,] 15 25 15 21 19
[3,] 25 25 25 25 10
[4,] 10 25 25 21 25
[5,] 15 25 21 10 15
PyQt - QLabel Widget

A QLabel object acts as a placeholder to display non-editable text or image, or a movie of animated GIF. It can also be used as a mnemonic key for other widgets. Plain text, hyperlink or rich text can be displayed on the label.
The following table lists the important methods defined in QLabel class −
Given below are the most commonly used methods of QLabel.
setAlignment()
Aligns the text as per alignment constants
Qt.AlignLeft
Qt.AlignRight
Qt.AlignCenter
Qt.AlignJustify
setIndent()
Sets the labels text indent
setPixmap()
Displays an image
Text()
Displays the caption of the label
setText()
Programmatically sets the caption
selectedText()
Displays the selected text from the label (The textInteractionFlag must be set to TextSelectableByMouse)
setBuddy()
Associates the label with any input widget
setWordWrap()
Enables or disables wrapping text in the label
In this example, QLabel objects l2 and l4 have the caption containing hyperlink. setOpenExternalLinks for l2 is set to true. Hence, if this label is clicked, the associated URL will open in the browser. linkHovered signal of l4 is connected to hovered() function. So, whenever the mouse hovers over it, the function will be executed.
QPixmap object prepares offscreen image from python.jpg file. It is displayed as label l3 by using setPixmap() method.
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

def window():
   app = QApplication(sys.argv)
   win = QWidget() 
	
   l1 = QLabel()
   l2 = QLabel()
   l3 = QLabel()
   l4 = QLabel()
	
   l1.setText("Hello World")
   l4.setText("TutorialsPoint")
   l2.setText("welcome to Python GUI Programming")
	
   l1.setAlignment(Qt.AlignCenter)
   l3.setAlignment(Qt.AlignCenter)
   l4.setAlignment(Qt.AlignRight)
   l3.setPixmap(QPixmap("python.jpg"))
	
   vbox = QVBoxLayout()
   vbox.addWidget(l1)
   vbox.addStretch()
   vbox.addWidget(l2)
   vbox.addStretch()
   vbox.addWidget(l3)
   vbox.addStretch()
   vbox.addWidget(l4)
	
   l1.setOpenExternalLinks(True)
   l4.linkActivated.connect(clicked)
   l2.linkHovered.connect(hovered)
   l1.setTextInteractionFlags(Qt.TextSelectableByMouse)
   win.setLayout(vbox)
	
   win.setWindowTitle("QLabel Demo")
   win.show()
   sys.exit(app.exec_())
	
def hovered():
   print "hovering"
def clicked():
   print "clicked"
	
if __name__ == '__main__':
   window()
The above code produces the following output −

    146 Lectures 
     22.5 hours 

 ALAA EID
 Print
 Add Notes
 Bookmark this page
Groovy - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations.
Groovy has the following types of operators −
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
The Groovy language supports the normal Arithmetic operators as any the language. Following are the Arithmetic operators available in Groovy −
Show Example
int x = 5;
x++;
x will give 6
int x = 5;
x--;
x will give 4
Relational operators allow of the comparison of objects. Following are the relational operators available in Groovy −
Show Example
Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy −
Show Example
Groovy provides four bitwise operators. Following are the bitwise operators available in Groovy −
Show Example
&
This is the bitwise “and” operator
|
This is the bitwise “or” operator
^
This is the bitwise “xor” or Exclusive or operator
~
This is the bitwise negation operator
Here is the truth table showcasing these operators.
The Groovy language also provides assignment operators. Following are the assignment operators available in Groovy −
Show Example
def A = 5
A+=3
Output will be 8
def A = 5
A-=3
Output will be 2
def A = 5
A*=3
Output will be 15
def A = 6
A/=3
Output will be 2
def A = 5
A%=3
Output will be 2
Groovy supports the concept of ranges and provides a notation of range operators with the help of the .. notation. A simple example of the range operator is given below.
def range = 0..5 

This just defines a simple range of integers, stored into a local variable called range with a lower bound of 0 and an upper bound of 5.
The following code snippet shows how the various operators can be used.
class Example { 
   static void main(String[] args) { 
      def range = 5..10; 
      println(range); 
      println(range.get(2)); 
   } 
}
When we run the above program, we will get the following result −
From the println statement, you can see that the entire range of numbers which are defined in the range statement are displayed.
The get statement is used to get an object from the range defined which takes in an index value as the parameter.
[5, 6, 7, 8, 9, 10] 
7

The following table lists all groovy operators in order of precedence.
++   --   +   -
pre increment/decrement, unary plus, unary minus
*   /   %
multiply, div, modulo
+   -
addition, subtraction
==   !=   <=>
equals, not equals, compare to
&
binary/bitwise and
^
binary/bitwise xor
|
binary/bitwise or
&&
logical and
||
logical or
=   **=   *=   /=   %=   +=   -=   <<=   >>=   >>>=   &=   ^=   |=
Various assignment operators

    52 Lectures 
     8 hours 

 Krishna Sakinala

    49 Lectures 
     2.5 hours 

 Packt Publishing
 Print
 Add Notes
 Bookmark this page
Java Generics - Map

Java has provided generic support in Map interface.
Set<T> set = new HashSet<T>();

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

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

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

      Map<Integer,Integer> integerMap 
         = new HashMap<Integer,Integer>();
  
      integerMap.put(1, 10);
      integerMap.put(2, 11);

      Map<String,String> stringMap = new HashMap<String,String>();
    
      stringMap.put("1", "Hello World");
      stringMap.put("2","Hi World");
 

      System.out.printf("Integer Value :%d\n", integerMap.get(1));
      System.out.printf("String Value :%s\n", stringMap.get("1"));

      // iterate keys.
      Iterator<Integer> integerIterator   = integerMap.keySet().iterator();

      while(integerIterator.hasNext()) {
         System.out.printf("Integer Value :%d\n", integerIterator.next());
      }

      // iterate values.
      Iterator<String> stringIterator   = stringMap.values().iterator();

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


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
How to check if the string begins with specific substring in Java?

A String class can be used to represent the character strings, all the string literals in a Java program are implemented as an instance of a String class. The Strings are constants and their values cannot be changed (immutable) once created.
We can use the startsWith() method of String class to check whether a string begins with a specific string or not, it returns a boolean, true or false.
public boolean startsWith(String prefix)
public class StringStartsWithSubStringTest {
   public static void main(String[] args) {
      String str = "WelcomeToTutorialsPoint";
      if(str.startsWith("Welcome")) {
         System.out.println("Begins with the specified word!");
      }
      else {
         System.out.println("Does not begin with the specified word!");
      }
   }
}
Begins with the specified word!
GATE | GATE-CS-2016 (Set 1) | Question 25 - GeeksforGeeks

12 Aug, 2021
Consider the following C program.
#include<stdio.h>void mystery(int *ptra, int *ptrb) {   int *temp;   temp = ptrb;   ptrb = ptra;   ptra = temp;}int main() {    int a=2016, b=0, c=4, d=42;    mystery(&a, &b);    if (a < c)       mystery(&c, &a);    mystery(&a, &d);    printf("%d\n", a);}
The output of the program _____________
 Note : This question was asked as Numerical Answer Type.
(A) 2016(B) 0(C) 4(D) 8Answer: (A)Explanation: Note that a and d are not swapped as the function mystery() doesn’t change values, but pointers which are local to the function.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQs 2016 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0021:27 / 1:07:54•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Key2RKhzRGY" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2016 (Set 1)
GATE-GATE-CS-2016 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
Is there a goto statement available in bash on Linux?

Long story short, Linux’s bash doesn’t have goto statements and no information about the control structures exists in the official documentation. It should also be noted that we can make use of the break and continue statement to achieve the same behaviour that goto statement provides us.
A simple behaviour of the goto can be achieved with a few tweaks and using the simple if condition in bash.
The script will look something like this
# ... Code You want to run here ...

if false; then

# ... Code You want to skip here ...

fi

# ... You want to resume here ...
Another idea is to make use of a bash script that is slightly more complicated, then the one mentioned above but works like a charm.
#!/bin/bash

function goto
{
   label=$1
   cmd=$(sed -n "/$label:/{:a;n;p;ba};" $0 | grep -v ':$')
   eval "$cmd"
   exit
}
startFunc=${1:-"startFunc"}

goto $startFunc

startFunc:

x=100
goto foo

mid:
x=101
echo "Not printed!"

foo:
x=${x:-10}
echo x is $x
$ ./sample.sh
x is 100
$ ./sample.sh foo
x is 11
$ ./sample.sh mid
Not printed!
x is 101
Python - Convert Coordinate Dictionary to Matrix - GeeksforGeeks

30 Dec, 2020
Sometimes, while working with Python Matrix, we can have problem in which we have dictionary records with key as matrix position and its value, and we wish to convert that to actual Matrix. This can have applications in many domains including competitive programming and day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop + max() + list comprehensionThe combination of above methods can be used to solve this problem. In this, we use max() to get the dimensions of matrix, list comprehension to create matrix and loop to assign values.
# Python3 code to demonstrate working of # Convert Coordinate Dictionary to Matrix# Using loop + max() + list comprehension  # initializing dictionarytest_dict = { (0, 1) : 4, (2, 2) : 6, (3, 1) : 7, (1, 2) : 10, (3, 2) : 11}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Convert Coordinate Dictionary to Matrix# Using loop + max() + list comprehensiontemp_x = max([cord[0] for cord in test_dict.keys()])temp_y = max([cord[1] for cord in test_dict.keys()])res = [[0] * (temp_y + 1) for ele in range(temp_x + 1)]  for (i, j), val in test_dict.items():    res[i][j] = val  # printing result print("The dictionary after creation of Matrix : " + str(res)) 
The original dictionary is : {(0, 1): 4, (1, 2): 10, (3, 2): 11, (3, 1): 7, (2, 2): 6}The dictionary after creation of Matrix : [[0, 4, 0], [0, 0, 10], [0, 0, 6], [0, 7, 11]]
 
Method #2 : Using list comprehensionThis is yet another way in which this task can be performed. This performs task similar to above function, just the difference is that it is shorthand to above method.
# Python3 code to demonstrate working of # Convert Coordinate Dictionary to Matrix# Using list comprehension  # initializing dictionarytest_dict = { (0, 1) : 4, (2, 2) : 6, (3, 1) : 7, (1, 2) : 10, (3, 2) : 11}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Convert Coordinate Dictionary to Matrix# Using list comprehensiontemp_x, temp_y = map(max, zip(*test_dict))res = [[test_dict.get((j, i), 0) for i in range(temp_y + 1)]                                   for j in range(temp_x + 1)]  # printing result print("The dictionary after creation of Matrix : " + str(res)) 
The original dictionary is : {(0, 1): 4, (1, 2): 10, (3, 2): 11, (3, 1): 7, (2, 2): 6}The dictionary after creation of Matrix : [[0, 4, 0], [0, 0, 10], [0, 0, 6], [0, 7, 11]]
Python dictionary-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Defaultdict in Python
How to Install PIP on Windows ?
Deque in Python
Bar Plot in Matplotlib
Check if element exists in list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python Program for Binary Search (Recursive and Iterative)
Python | Convert a list into a tuple
Python | os.wait() method - GeeksforGeeks

26 Aug, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.wait() method in Python is used by a process to wait for completion of a child process.This method returns a tuple containing its PID and exit status indication. The exit status of child process is indicated by a 16 bit number whose lower byte is the signal number that killed the process and higher byte is the exit status (if the signal number is zero).
Syntax: os.wait()
Parameter: No parameter is required.
Return type: This method returns a tuple which contains terminated child’s PID and exit status indication.
Code: Use of os.wait() method
# Python program to explain os.wait() method   # importing os module  import os   # Create a child process# using os.fork() method pid = os.fork()    # a Non-zero process id (pid)# indicates the parent process if pid :          # Wait for the completion of    # child process using    # os.wait() method        status = os.wait()    print("\nIn parent process-")    print("Terminated child's process id:", status[0])    print("Signal number that killed the child process:", status[1])  else :    print("In Child process-")    print("Process ID:", os.getpid())    print("Hello ! Geeks")    print("Exiting")        # using os.wait() method    # Parent process will wait till # the completion of child process# and then only it will # begin its execution
In Child process-
Process ID: 6276
Hello! Geeks
Exiting

In parent process-
Terminated child's process id: 6276
Signal number that killed the child process: 0

python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()