code-rag-bench/online-tutorials huggingface dataset:
Ints indexOf() function | Guava | Java - GeeksforGeeks

15 Nov, 2018
Guava’s Ints.indexOf(int[] array, int target) method returns the index of the first appearance of the value target in array.
Syntax:
public static int indexOf(int[] array, int target)

Parameters: This method accepts the following parameters:
array: An array of int values, possibly empty.
target: A primitive int value.
Return Value: This method returns the least index i for which array[i] == target, or -1 if no such index exists.
Example 1:
// Java code to show implementation of// Guava's Ints.indexOf() method  import com.google.common.primitives.Ints;import java.util.Arrays;  class GFG {      // Driver's code    public static void main(String[] args)    {          // Creating an integer array        int[] arr = { 1, 2, 3, 4, 3, 5 };          int target = 3;          // Using Ints.indexOf(int[] array, int target)        // method to get the index of first appearance        // of a given element in array and return -1        // if element is not found in the array        int index = Ints.indexOf(arr, target);          if (index != -1) {            System.out.println("Target is present at index "                               + index);        }        else {            System.out.println("Target is not present"                               + " in the array");        }    }}
Target is present at index 2

Example 2:
// Java code to show implementation of// Guava's Ints.indexOf() method  import com.google.common.primitives.Ints;import java.util.Arrays;  class GFG {      // Driver's code    public static void main(String[] args)    {          // Creating an integer array        int[] arr = { 3, 5, 7, 11, 13 };          int target = 17;          // Using Ints.indexOf(int[] array, int target) method        // to get the index of first appearance of a        // given element in array and return -1 if        // element is not found in the array        int index = Ints.indexOf(arr, target);          if (index != -1) {            System.out.println("Target is present at index "                               + index);        }        else {            System.out.println("Target is not present"                               + " in the array");        }    }}
Target is not present in the array

Reference: https://google.github.io/guava/releases/22.0/api/docs/com/google/common/primitives/Ints.html#indexOf-int:A-int-
java-guava
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
ArrayList in Java
How to iterate any Map in Java
Multidimensional Arrays in Java
LinkedList in Java
Stack Class in Java
Overriding in Java
function command in Linux with examples - GeeksforGeeks

04 Aug, 2021
Function is a command in linux which is used to create functions or methods. 
 
1.using function keyword : A function in linux can be declared by using keyword function before the name of the function. Different statements can be separated by a semicolon or a new line. SYNTAX  
function name { COMMANDS ; }
 
 
2.using parenthesis : A function can also be declared by using parenthesis after the name of the function. Different statements can be separated by a semicolon or a new line. SYNTAX  
name () { COMMANDS ; }
 
 
3.Parameterised function :  
$1 will displays the first argument that will be sent and $2 will display the second ans so on...  
4.help function : It displays help information.  
 
 
nidhi_biet
sagar0719kumar
linux-command
Linux-misc-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Thread functions in C/C++
Basic Operators in Shell Scripting
nohup Command in Linux with Examples
Array Basics in Shell Scripting | Set 1
Named Pipe or FIFO with example C program
chown command in Linux with Examples
mv command in Linux with examples
Docker - COPY Instruction
Start/Stop/Restart Services Using Systemctl in Linux
SED command in Linux | Set 2
Scala - Currying Functions

Currying transforms a function that takes multiple parameters into a chain of functions, each taking a single parameter. Curried functions are defined with multiple parameter lists, as follows −
def strcat(s1: String)(s2: String) = s1 + s2

Alternatively, you can also use the following syntax to define a curried function −
def strcat(s1: String) = (s2: String) => s1 + s2

Following is the syntax to call a curried function −
strcat("foo")("bar")

You can define more than two parameters on a curried function based on your requirement. Try the following example program to show currying concept.
object Demo {
   def main(args: Array[String]) {
      val str1:String = "Hello, "
      val str2:String = "Scala!"
      
      println( "str1 + str2 = " +  strcat(str1)(str2) )
   }

   def strcat(s1: String)(s2: String) = {
      s1 + s2
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

str1 + str2 = Hello, Scala!


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Groovy - If/Else Statement

The next decision-making statement we will see is the if/else statement. The general form of this statement is −
if(condition) { 
   statement #1 
   statement #2 
   ... 
} else{ 
   statement #3 
   statement #4  
}

The general working of this statement is that first a condition is evaluated in the if statement. If the condition is true it then executes the statements thereafter and stops before the else condition and exits out of the loop. If the condition is false it then executes the statements in the else statement block and then exits the loop. The following diagram shows the flow of the if statement.
Following is an example of a if/else statement −
class Example { 
   static void main(String[] args) { 
      // Initializing a local variable 
      int a = 2
		
      //Check for the boolean condition 
      if (a<100) { 
         //If the condition is true print the following statement 
         println("The value is less than 100"); 
      } else { 
         //If the condition is false print the following statement 
         println("The value is greater than 100"); 
      } 
   } 
}
In the above example, we are first initializing a variable to a value of 2. We are then evaluating the value of the variable and then deciding on which println statement should be executed. The output of the above code would be
The value is less than 100.
Differences between ArrayList and Vector in Java

Both ArrayList and Vector are implementation of List interface in Java. Both classes keeps the insertion order. But there are certain differences as well.
Following are the important differences between ArrayList and Vector method.
import java.util.ArrayList;
import java.util.Vector;
import java.util.List;
public class JavaTester {
   public static void main(String args[]) {
      List<String> list = new ArrayList<>();
      list.add("A");
      list.add("B");
      list.add("C");
      list.add("D");
      List<String> list1 = new Vector<>();
      list1.add("A");
      list1.add("B");
      list1.add("C");
      list1.add("D");
      System.out.println(list);
      System.out.println(list1);
   }
}
[A, B, C, D]
[A, B, C, D]
How to remove timezone information from DateTime object in Python

09 Dec, 2021
Timezone is defined as a geographical area or region throughout which standard time is observed. It basically refers to the local time of a region or country. Most of the time zones are offset from Coordinated Universal Time (UTC), the world’s standard for time zone.
In this article, we will discuss how to remove timezone information from the DateTime object.
datetime.now(tz=None): Returns the current local date and time.
datetime.replace(): Returns a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.
To remove timestamp, tzinfo has to be set None when calling replace() function.
First, create a DateTime object with current time using datetime.now(). The DateTime object was then modified to contain the timezone information as well using the timezone.utc. The DateTime object with timezone information is then manipulated using the .replace() method to remove the timezone information using the tzinfo parameter.
Syntax:
replace(tzinfo=None)
Example:
Python
from datetime import datetime, timezone # Get the datetime object using datetime# moduledt_obj_w_tz = datetime.now()print(dt_obj_w_tz) # Add timezone information to the datetime# objectdt_obj_w_tz = dt_obj_w_tz.replace(tzinfo=timezone.utc)print(dt_obj_w_tz) # Remove the timezone information from the datetime# objectdt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None)print(dt_obj_wo_tz)
Output: 
2021-08-10 12:51:42.093388
2021-08-10 12:51:42.093388+00:00
2021-08-10 12:51:42.09338
However, the datetime object with timestamp can be created by providing tz parameter.
Example:
Python
from datetime import datetime, timezone # Get the datetime object with timezone# informationdt_obj_w_tz = datetime.now(tz=timezone.utc)print(dt_obj_w_tz) # Remove the timezone information from the# datetime objectdt_obj_wo_tz = dt_obj_w_tz.replace(tzinfo=None)print(dt_obj_wo_tz)
Output:
2021-08-10 07:21:57.838856+00:00
2021-08-10 07:21:57.838856
surindertarika1234
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove all occurrences of a character from a string using STL

21 Dec, 2021
Given a string S and a character C, the task is to remove all the occurrences of the character C from the given string.
Examples:
Input:vS = “GFG IS FUN”, C = ‘F’ Output:GG IS UN Explanation: Removing all occurrences of the character ‘F’ modifies S to “GG IS UN”. Therefore, the required output is GG IS UN
Input: S = “PLEASE REMOVE THE SPACES”, C = ‘ ‘ Output: PLEASEREMOVETHESPACES Explanation: Removing all occurrences of the character ‘ ‘ modifies S to “GG IS UN”.  
Approach: The idea is to use erase() method and remove() function from C++ STL. Below is the syntax to remove all the occurrences of a character from a string.
S.erase(remove(S.begin(), S.end(), c), S.end())
Below is the implementation of the above approach:
C++
// C++ program of the above approach#include <algorithm>#include <iostream>using namespace std; // Function to remove all occurrences// of C from the string Sstring removeCharacters(string S, char c){     S.erase(remove(                S.begin(), S.end(), c),            S.end());     return S;} // Driver Codeint main(){     // Given String    string S = "GFG is Fun";    char C = 'F';    cout << "String Before: " << S << endl;     // Function call    S = removeCharacters(S, C);     cout << "String After: " << S << endl;    return 0;}
String Before: GFG is Fun
String After: GG is un
 
Time Complexity: O(N2)Auxiliary Space: O(1)
chhabradhanvi
cpp-strings-library
STL
Strings
Strings
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create Stacked bar chart in Python-Plotly?

29 Oct, 2020
Plotly is a Python library which is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library.
A stacked bar chart or  graph is a chart that uses bars to demonstrate comparisons between categories of data, but with ability to impart and compare parts of a whole. Each bar in the chart represents a whole and segments which represent different parts or categories of that whole.
Example 1: Using iris dataset
Python3
import plotly.express as px df = px.data.iris() fig = px.bar(df, x="sepal_width", y="sepal_length", color="species",            hover_data=['petal_width'], barmode = 'stack') fig.show()
  
Output:
 
 
Example 2: Using tips dataset
 
Python3
import plotly.express as px df = px.data.tips() fig = px.bar(df, x="total_bill", y="day",             color="sex", barmode = 'stack') fig.show()
  
Output:
 
 
Example 3: Using graph_objects class
 
Python3
import plotly.graph_objects as pximport numpy as np  # creating random data through randomint# function of numpy.randomnp.random.seed(42) random_x= np.random.randint(1,101,100)random_y= np.random.randint(1,101,100) x = ['A', 'B', 'C', 'D'] plot = px.Figure(data=[go.Bar(    name = 'Data 1',    x = x,    y = [100, 200, 500, 673]   ),                       go.Bar(    name = 'Data 2',    x = x,    y = [56, 123, 982, 213]   )]) plot.update_layout(barmode='stack')                  plot.show()
  
Output:
 
 
barissenyerli
Python-Plotly
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum profit by buying and selling a share at most twice

In a trading, one buyer buys and sells the shares, at morning and the evening respectively. If at most two transactions are allowed in a day. The second transaction can only start after the first one is completed. If stock prices are given, then find the maximum profit that the buyer can make.
Input:
A list of stock prices. {2, 30, 15, 10, 8, 25, 80}
Output:
Here the total profit is 100. As buying at price 2 and selling at price 30.
so profit 28. Then buy at price 8 and sell it again at price 80.
So profit 72. So the total profit 28 + 72 = 100
findMaxProfit(pricelist, n)
Input − List of all prices, number of items in the list.
Output − Maximum Profit.
Begin
   define profit array of size n and fill with 0
   maxPrice := pricelist[n-1]          //last item is chosen

   for i := n-2 down to 0, do
      if pricelist[i] > maxPrice, then
         maxPrice := pricelist[i]
      profit[i] := maximum of profit[i+1] and maxProfit – pricelist[i]
   done

   minProce := pricelist[0]           //first item is chosen
   for i := 1 to n-1, do
      if pricelist[i] < minPrice, then
         minPrice := pricelist[i]
      profit[i] := maximum of profit[i-1] and (profit[i]+(pricelist[i] - minPrice))
   done

   return profit[n-1]
End


#include<iostream>
using namespace std;

int max(int a, int b) {
   return (a>b)?a:b;
}

int findMaxProfit(int priceList[], int n) {
   int *profit = new int[n];
   for (int i=0; i<n; i++)            //initialize profit list with 0
      profit[i] = 0;

   int maxPrice = priceList[n-1];        //initialize with last element of price list

   for (int i=n-2;i>=0;i--) {
      if (priceList[i] > maxPrice)
         maxPrice = priceList[i];

      profit[i] = max(profit[i+1], maxPrice - priceList[i]);     //find the profit for selling in maxPrice
   }

   int minPrice = priceList[0];            //first item of priceList as minimum

   for (int i=1; i<n; i++) {
      if (priceList[i] < minPrice)
         minPrice = priceList[i];

      profit[i] = max(profit[i-1], profit[i] + (priceList[i]- minPrice) );
   }

   int result = profit[n-1];
   return result;
}

int main() {
   int priceList[] = {2, 30, 15, 10, 8, 25, 80};
   int n = 7;
   cout << "Maximum Profit = " << findMaxProfit(priceList, n);
}
Maximum Profit = 100
C++ Program to Find Factorial of a Number using Dynamic Programming

The factorial of a positive integer n is equal to 1*2*3*...n. Factorial of a negative number does not exist. Here a C++ program is given to find out the factorial of a given input using dynamic programming.
Begin
   fact(int n):
      Read the number n
      Initialize
      i = 1, result[1000] = {0}
      result[0] = 1
      for i = 1 to n
         result[i] = I * result[i-1]
   Print result
End
#include <iostream>
using namespace std;
int result[1000] = {0};
int fact(int n) {
   if (n >= 0) {
      result[0] = 1;
      for (int i = 1; i <= n; ++i) {
         result[i] = i * result[i - 1];
      }
      return result[n];
   }
}
int main() {
   int n;
   while (1) {
      cout<<"Enter integer to compute factorial (enter 0 to exit): ";
      cin>>n;
      if (n == 0)
      break;
      cout<<fact(n)<<endl;
   }
   return 0;
}
Enter integer to compute factorial (enter 0 to exit): 2
2
Enter integer to compute factorial (enter 0 to exit): 6
720
Enter integer to compute factorial (enter 0 to exit): 7
5040
Enter integer to compute factorial (enter 0 to exit): 10
3628800
Enter integer to compute factorial (enter 0 to exit): 0
How to swap two arrays without using temporary variable in C language?

Swap two arrays without using Temp variable. Here, we are going to use Arithmetic Operators and Bitwise Operators instead of third variable.
The logic to read the first array is as follows −
printf("enter first array ele:\n");
for(i = 0; i < size; i++){
   scanf("%d", &first[i]);
}
The logic to read the second array is as follows −
printf("enter first array ele:\n");
for(i = 0; i < size; i++){
   scanf("%d", &first[i]);
}
The logic to swap the two arrays without using a third variable is as follows −
for(i = 0; i < size; i++){
   first[i] = first[i] + sec[i];
   sec[i] = first[i] - sec[i];
   first[i] = first[i] - sec[i];
}
Following is the C program to swap two arrays without using the Temp variable −
 Live Demo
#include<stdio.h>
int main(){
   int size, i, first[20], sec[20];
   printf("enter the size of array:");
   scanf("%d", &size);
   printf("enter first array ele:\n");
   for(i = 0; i < size; i++){
      scanf("%d", &first[i]);
   }
   printf("enter second array ele:\n");
   for(i = 0; i < size; i ++){
      scanf("%d", &sec[i]);
   }
   //Swapping two Arrays
   for(i = 0; i < size; i++){
      first[i] = first[i] + sec[i];
      sec[i] = first[i] - sec[i];
      first[i] = first[i] - sec[i];
   }
   printf("\n first array after swapping %d elements\n", size);
   for(i = 0; i < size; i ++){
      printf(" %d \t ",first[i]);
   }
   printf("sec array after Swapping %d elements\n", size);
   for(i = 0; i < size; i ++){
      printf(" %d \t ",sec[i]);
   }
   return 0;
}
When the above program is executed, it produces the following result −
enter the size of array:5
enter first array ele:
11 12 13 14 15
enter second array ele:
90 80 70 60 50
first array after swapping 5 elements
90 80 70 60 50
sec array after Swapping 5 elements
11 12 13 14 15
Golang Program to Print the Sum of all the Positive Numbers and Negative Numbers in a List

Read a number of elements to be in a list.
Take the elements from the user using a for loop and append to a list.
Using a for loop, get the elements one by one from the list and check if it is positive or negative.
If it is positive, check if it is odd or even and find the individual sum.
Find the individual sum of negative numbers.
Print all the sums.
 Live Demo
package main
import "fmt"
func main() {
   fmt.Printf("Enter the number of elements to be in the list:")
   var size int
   fmt.Scanln(&size)
   var arr = make([]int, size)
   for i:=0; i<size; i++ {
      fmt.Printf("Enter %d element: ", i)
      fmt.Scanf("%d", &arr[i])
   }
   sum1:=0
   sum2:=0
   sum3:=0
   for i:=0; i<size; i++{
      fmt.Println(i)
      if arr[i] > 0{
         if arr[i]%2==0 {
            sum1=sum1+arr[i]
         }else{
            sum2=sum2+arr[i]
         }
      } else {
         sum3=sum3+arr[i]
      }
   }
   fmt.Println("Sum of all positive even numbers:", sum1)
   fmt.Println("Sum of all positive odd numbers:", sum2)
   fmt.Println("Sum of all negative numbers:", sum3)
}
Enter the number of elements to be in the list:4
Enter 0th element: -12
Enter 1 element: 34
Enter 2 element: 35
Enter 3 element: 89
0
1
2
3
Sum of all positive even numbers: 34
Sum of all positive odd numbers: 124
Sum of all negative numbers: -12
How do we use file.readlines() to read multiple lines using Python?

The read function reads the whole file at once. You can use the readlines function to read the file line by line.
You can use the following to read the file line by line:
f = open('my_file.txt', 'r+')
for line in f.readlines():
    print line
f.close()
You can also use the with...open statement to open the file and read line by line. For example,
with open('my_file.txt', 'r+') as f:
    for line in f.readlines():
        print line
Difference between Opening and Closing in Digital Image Processing - GeeksforGeeks

16 Jan, 2020
Opening and Closing are dual operations used in Digital Image Processing for restoring an eroded image. Opening is generally used to restore or recover the original image to the maximum possible extent. Closing is generally used to smoother the contour of the distorted image and fuse back the narrow breaks and long thin gulfs. Closing is also used for getting rid of the small holes of the obtained image.
The combination of Opening and Closing is generally used to clean up artifacts in the segmented image before using the image for digital analysis.
Some of the differences between Opening and Closing are:
Properties of Opening are:
    1. XoY is a subset (subimage of X)
    2. If X is a subset of Z then XoY  is a subset of ZoY
    3.(XoY)oY = XoY

Properties of Closing are:
    1. X is a subset subimage of X.Y
    2. (X.Y).Y = X.Y

Image-Processing
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Process and Thread
Stack vs Heap Memory Allocation
Difference Between Spark DataFrame and Pandas DataFrame
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Difference between Clustered and Non-clustered index
Differences between JDK, JRE and JVM
Differences between Procedural and Object Oriented Programming
Difference between Primary Key and Foreign Key
Differences between IPv4 and IPv6
Python | Corner Detection with Shi-Tomasi Corner Detection Method using OpenCV

22 Aug, 2019
What is a Corner?A corner can be interpreted as the junction of two edges (where an edge is a sudden change in image brightness).
Shi-Tomasi Corner Detection was published by J.Shi and C.Tomasi in their paper ‘Good Features to Track‘. Here the basic intuition is that corners can be detected by looking for significant change in all direction.
We consider a small window on the image then scan the whole image, looking for corners.
Shifting this small window in any direction would result in a large change in appearance, if that particular window happens to be located on a corner.
Flat regions will have no change in any direction.
If there’s an edge, then there will be no major change along the edge direction.
For a window(W) located at (X, Y) with pixel intensity I(X, Y), formula for Shi-Tomasi Corner Detection is –
f(X, Y) = Σ (I(Xk, Yk) - I(Xk + ΔX, Yk + ΔY))2  where (Xk, Yk) ε W
According to the formula:If we’re scanning the image with a window just as we would with a kernel and we notice that there is an area where there’s a major change no matter in what direction we actually scan, then we have a good intuition that there’s probably a corner there.Calculation of f(X, Y) will be really slow. Hence, we use Taylor expansion to simplify the scoring function, R.
R = min(λ1, λ2)
where λ1, λ2 are eigenvalues of resultant matrix
Using goodFeaturesToTrack() function –
Syntax : cv2.goodFeaturesToTrack(gray_img, maxc, Q, minD)
Parameters :gray_img – Grayscale image with integral valuesmaxc – Maximum number of corners we want(give negative value to get all the corners)Q – Quality level parameter(preferred value=0.01)maxD – Maximum distance(preferred value=10)
# Python program to illustrate # corner detection with # Shi-Tomasi Detection Method    # organizing imports import cv2import numpy as npimport matplotlib.pyplot as plt%matplotlib inline  # path to input image specified and  # image is loaded with imread commandimg = cv2.imread('chess.png')  # convert image to grayscalegray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # Shi-Tomasi corner detection function# We are detecting only 100 best corners here# You can change the number to get desired result.corners = cv2.goodFeaturesToTrack(gray_img, 100, 0.01, 10)  # convert corners values to integer# So that we will be able to draw circles on themcorners = np.int0(corners)  # draw red color circles on all cornersfor i in corners:    x, y = i.ravel()    cv2.circle(img, (x, y), 3, (255, 0, 0), -1)  # resulting imageplt.imshow(img)  # De-allocate any associated memory usage  if cv2.waitKey(0) & 0xff == 27:     cv2.destroyAllWindows()
Input :
Output :
hachiman_20
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Numpy numpy.ndarray.__add__()

06 Mar, 2019
With the help of Numpy numpy.ndarray.__add__(), we can add a particular value that is provided as a parameter in the ndarray.__add__() method. Value will be added to each and every element in a numpy array.
Syntax: ndarray.__add__($self, value, /)
Return: self+value
Example #1 :In this example we can see that each and every element in an array is added with the value given as a parameter in method ndarray.__add__(). Remember one thing it wouldn’t work for double type values.
# import the important module in pythonimport numpy as np   # make an array with numpygfg = np.array([1, 2, 3, 4, 5])   # applying ndarray.__add__() methodprint(gfg.__add__(5))
[ 6  7  8  9  10]

Example #2 :
# import the important module in pythonimport numpy as np   # make an array with numpygfg = np.array([[1, 2, 3, 4, 5],                [6, 5, 4, 3, 2]])   # applying ndarray.__add__() methodprint(gfg.__add__(5))
[[ 6  7  8  9  10]
 [11  10  9  8  7]]

Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to invert case for all letters in a string in Python?

String class has a method called swapcase() for swapping case of all letters. You can use it as follows:
>>> 'Hello World 123'.swapcase()
'hELLO wORLD 123'
>>> 'Make America Great Again'.swapcase()
'mAKE aMERICA gREAT aGAIN'
turtle.pos() method in Python

01 Aug, 2020
The Turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to find the turtle’s current location (x, y), as a Vec2D-vector. This method has the Aliases: pos | position.
Syntax: turtle.pos() or  turtle.position()
Return: turtle’s current location in terms of (x, y) coordinate
This function does not require any argument and returns the current position of the turtle in the format (x,y) where x and y represent the 2D vector. The default value is (0.0, 0.0).
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import turtle packageimport turtle   # print the default # position i.e; (0.0, 0.0)print(turtle.pos())  # forward turtle by 150 pixelsturtle.forward(150)  # print current position # i.e; (150.0, 0.0)print(turtle.pos())  # forward turtle by 150 pixels# after taking turn right# by 90 degreesturtle.right(90)turtle.forward(150)  # print position (after next move)# i.e; (150.0, -150.0)print(turtle.pos())
Output:
(0.0, 0.0)
(150.0, 0.0)
(150.0, -150.0)

Example 2:
Python3
# import turtle packageimport turtle   # print position (by default)# i.e; (0.0, 0.0)print(turtle.pos())  # turtle move forward # by 40 pixelsturtle.forward(40)  # print position (after move)# i.e; (150.0, 0.0)print(turtle.position())  # turtle move forward by 40 pixels# after taking right turn # by 45 degreesturtle.right(45)turtle.forward(40)  # print position# (after next move) print(turtle.pos())  # turtle move forward by 80 # pixels after taking left# turn by 90 degreesturtle.left(90)turtle.forward(80)  # print position# (after next move) print(turtle.pos())  # turtle move forward # by 40 pixels after taking # right turn by 90 degreesturtle.right(90)turtle.forward(40)  # print position (after next move) print(turtle.position())  # turtle move forward by # 40 pixels after taking # left turn by 45 degreesturtle.left(45)turtle.forward(40)  # print position # (after final move) print(turtle.pos())
Output :
(0.0, 0.0)
(40.0, 0.0)
(68.2842712475, -28.2842712475)
(124.852813742, 28.2842712475)
(153.13708499, 0.0)
(193.13708499, 0.0)

Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to add a column to a MySQL table in Python?

It may be sometimes required to add a new column in a existing table. Suppose we have a “Students” table with columns such as Name, Age, Roll no. We want to add a new column “Address” into our existing table.
This can be done by using the ALTER command. The ALTER command is used to modify, drop or update columns in the database. This can also be used to add a new column into the table using ADD clause.
ALTER TABLE table_name
ADD new_column_name column_definition
[FIRST | AFTER exisiting_column]
Here, table_name refers to the name of the table, new_column_name refers to the name of the column to be added, column_definition refers to the datatype of the column.
The FIRST AND AFTER clause are optional.This are used to specify the particular position at which you want to add the new column. The FIRST will insert the new column at the first position. The AFTER existing_column will insert a new column after the existing_column.
By default, the new column is inserted at the end of the table.
import MySQL connector
import MySQL connector
establish connection with the connector using connect()
establish connection with the connector using connect()
create the cursor object using cursor() method
create the cursor object using cursor() method
create a query using the appropriate mysql statements
create a query using the appropriate mysql statements
execute the SQL query using execute() method
execute the SQL query using execute() method
close the connection
close the connection
Suppose, we have a table named “Students”. We want to add a new column named “Address” of type VARCHAR(100) in the table.
import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")

cursor=db.cursor()

query="ALTER TABLE Students ADD Address VARCHAR(100)"
cursor.execute(query)
db.commit()
print("NEW COLUMN ADDED..")

db.close()
The above code adds a new column named “Address” into the table. The column is inserted at the last of the existing columns.
NEW COLUMN ADDED..
Explain the evaluation of relational algebra expression(DBMS)

SQL queries are decomposed into query blocks. One query block contains a single SELECT-FROM-WHERE expression, as well as GROUP BY and HAVING clause (if any). Nested queries are split into separate query blocks.
Consider an example given below −
Select lastname, firstname from employee where salary>(select max(salary) from employee where deptname =CSE ;
C=(select max(salary) from employee where deptname=CSE); // inner block
Select lastname, firstname from employee where salary>c; //outer block
Where C represents the result returned from the inner block.
The relation algebra for the inner block is Ģmax(salary) (σdname=CSE(employee))
The relation algebra for the inner block is Ģmax(salary) (σdname=CSE(employee))
The relation algebra for the outer blocks is Πlastname, firstname(σsalary>c(employee))
The relation algebra for the outer blocks is Πlastname, firstname(σsalary>c(employee))
The query optimizer would then choose an execution or evaluation plan for each block.
Materialized evaluation − Evaluate one operation at a time. Evaluate the expression in a bottom-up manner and stores intermediate results to temporary files.
Store the result of A ⋈ B in a temporary file.
Store the result of C ⋈ D in a temporary file.
Finally, join the results stored in temporary files.
The overall cost=sum of costs of individual operations + cost of writing intermediate results to disk, cost of writing results to results to temporary files and reading them back is quite high.
Pipelined evaluation − Evaluate several operations simultaneously. Result of one operation is passed to the next operation. Evaluate the expression in a bottom-up manner and don’t store intermediate results to temporary files.
Don’t store the result of A ⋈ B in a temporary file. Instead the result is passed directly for projection with C and so on.
BabylonJS - Scaling

Scaling basically means increasing or decreasing the size of the object at a uniform scale. Let us now consider an example where we will increase/decrease the size of the object along the x or y or z-axis.
<!doctype html>
<html>
   <head>
      <meta charset = "utf-8">
      <title>BabylonJs - Basic Element-Creating Scene</title>
      <script src = "babylon.js"></script>
      <style>
         canvas {width: 100%; height: 100%;}
      </style>
   </head>

   <body>
      <canvas id = "renderCanvas"></canvas>
      <script type="text/javascript">
         var canvas = document.getElementById("renderCanvas");
         var engine = new BABYLON.Engine(canvas, true);
         var createScene  = function() {
            var scene = new BABYLON.Scene(engine);
            scene.clearColor = new BABYLON.Color3(0, 1, 0);
            
            var camera = new BABYLON.ArcRotateCamera("Camera", 1, 0.8, 10, new BABYLON.Vector3(0, 0, 0), scene);
            scene.activeCamera.attachControl(canvas);
            
            var light = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 100, 100), scene);

            var boxa = BABYLON.Mesh.CreateBox("BoxA", 1.0, scene);
            boxa.position = new BABYLON.Vector3(0,0.5,0);

            var boxb = BABYLON.Mesh.CreateBox("BoxB", 1.0, scene);
            boxb.position = new BABYLON.Vector3(3,0.5,0);		
            boxb.scaling = new BABYLON.Vector3(2,1,2);

            var boxc = BABYLON.Mesh.CreateBox("BoxC", 1.0, scene);
            boxc.position = new BABYLON.Vector3(-3,0.5,0);
            boxc.scaling = new BABYLON.Vector3(2,1,2);

            var boxd = BABYLON.Mesh.CreateBox("BoxD", 1.0, scene);
            boxd.position = new BABYLON.Vector3(0,0.5,3);
            boxd.scaling = new BABYLON.Vector3(2,1,2);

            var boxe = BABYLON.Mesh.CreateBox("BoxE", 1.0, scene);
            boxe.position = new BABYLON.Vector3(0,0.5,-3);
            boxe.scaling = new BABYLON.Vector3(2,1,2);

            var ground = BABYLON.Mesh.CreateGround("ground1", 10, 6, 2, scene);
            ground.position = new BABYLON.Vector3(0,0,0);
            return scene;
         };
         var scene = createScene();
         engine.runRenderLoop(function() {
            scene.render();
         });
      </script>
   </body>
</html>
We have scaled in x, y and z direction with values as 2, 1,2 and used new BABYLON.Vector3(2,1,2) for scaling.
 Print
 Add Notes
 Bookmark this page
How to add a new list element under a <ul> using jQuery?

To add a new list element under a ul element, use the jQuery append() method
Set input type text initially
Value: <input type="text" name="task" id="input">
Now on the click of a button, add a new list element using the val() and append() methods in jQuery:
$('button').click(function() {
   var mylist = $('#input').val();
   $('#list').append('<li>'+mylist+'</li>');
   return false;
});
You can try to run the following code to learn how to add a new list element using jQuery:<./p>
 Live Demo
<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         $('button').click(function() {
            var mylist = $('#input').val();
               $('#list').append('<li>'+mylist+'</li>');
               return false;
            });
         });
   </script>
</head>
<body>
   <form>
      Value: <input type="text" name="task" id="input">
      <button>Submit</button>
      <br>

      <p>Add a value above and click Submit to add a new list.</p>
      <ul id="list">
      </ul>
   </form>
</body>
</html>
Different ways of writing functions in JavaScript - GeeksforGeeks

09 Jul, 2021
What is a Function ?
A Function is a block of code that is designed to perform a task and executed when it is been called or invoked.
There are 3 ways of writing a function in JavaScript:
Function Declaration
Function Expression
Arrow Function
1. Function Declaration: Function Declaration is the traditional way to define a function. It is somehow similar to the way we define a function in other programming languages. We start declaring using the keyword “function”. Then we write the function name and then parameters.
Below is the example that illustrate the use of Function Declaration.
Javascript
// Function declarationfunction add(a, b) {            console.log(a + b);} // Calling a functionadd(2, 3);
After defining a function, we call it whenever the function is required.
Output:
5
2. Function Expression: Function Expression is another way to define a function in JavaScript. Here we define a function using a variable and store the returned value in that variable.
Below is the example that illustrate the use of Function Expression.
Javascript
// Function Expressionconst add = function(a, b) {    console.log(a+b);} // Calling functionadd(2, 3);
  
Here, the whole function is an expression and the returned value is stored in the variable. We use the variable name to call the function.
 
Output:
 
5
 
3. Arrow Functions: Arrow functions are been introduced in the ES6 version of JavaScript. It is used to shorten the code. Here we do not use the “function” keyword and use the arrow symbol.
 
Below is the example that illustrate the use of Arrow Function.
 
Example:
 
Javascript
// Single line of codelet add = (a, b) => a + b; console.log(add(3, 2));
This shortens the code to a single line compared to other approaches. In a single line of code, the function returns implicitly.
Output:
5
Note: When there is a need to include multiple lines of code we use brackets. Also, when there are multiple lines of code in the bracket we should write return explicitly to return the value from the function.
Example:
Javascript
// Multiple line of codeconst great = (a, b) => {    if (a > b)        return "a is greater";    else        return "b is greater";} console.log(great(3,5));
Output:
b is greater
gulshankumarar231
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
How to get selected value in dropdown list using JavaScript ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Rexx - Logical Operators

Logical Operators are used to evaluate Boolean expressions. Following are the logical operators available in Rexx.
The following program shows how the various operators can be used.
/* Main program*/ 
say 1 & 0 
say 1 | 0 
say 1 && 0 
say \1 
The output of the above program will be −
0
1
1
0

 Print
 Add Notes
 Bookmark this page
Tryit Editor v3.6 - Show React

import { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom/client";

function App() {
  const [inputValue, setInputValue] = useState("");
  const count = useRef(0);

  useEffect(() => {
    count.current = count.current + 1;
  });

  return (
    <>
      <input
        type="text"
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
      />
      <h1>Render Count: {count.current}</h1>
    </>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

/*
Try typing in the input field, and you will
see the application render conut increase.
*/




<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport"
      content="width=device-width, initial-scale=1" />
Iterating C# StringBuilder in a foreach loop

Firstly, set a string array and StringBuilder −
// string array
string[] myStr = { "One", "Two", "Three", "Four" };
StringBuilder str = new StringBuilder("We will print now...").AppendLine();
Now, use foreach loop to iterate −
foreach (string item in myStr) {
   str.Append(item).AppendLine();
}
The following is the complete code −
 Live Demo
using System;
using System.Text;

public class Demo {
   public static void Main() {
      // string array
      string[] myStr = { "One", "Two", "Three", "Four" };
      StringBuilder str = new StringBuilder("We will print now...").AppendLine();

      // foreach loop to append elements
      foreach (string item in myStr) {
         str.Append(item).AppendLine();
      }
      Console.WriteLine(str.ToString());
      Console.ReadLine();
   }
}
We will print now...
One
Two
Three
Four
jQuery Effect - Highlight Effect

The Highlight effect can be used with effect() method. This highlights the element's background with a specific color, default is yellow.
Here is the simple syntax to use this effect −
selector.effect( "highlight", {arguments}, speed );

Here is the description of all the arguments −
color − Highlight color. Default is "#ffff99".
color − Highlight color. Default is "#ffff99".
mode − The mode of the effect. Can be "show", "hide". Default is "show".
mode − The mode of the effect. Can be "show", "hide". Default is "show".
Following is a simple example a simple showing the usage of this effect −
<html>
   <head>
      <title>The jQuery Example</title>
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
		
      <script type = "text/javascript" 
         src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js">
      </script>
		
      <script type = "text/javascript" language = "javascript">
   
         $(document).ready(function() {

            $("#button").click(function(){
               $(".target").effect( "highlight", {color:"#669966"}, 3000 );
            });
         });
			
      </script>
		
      <style>
         p {background-color:#bca; width:200px; border:1px solid green;}
         div{ width:100px; height:100px; background:red;}
      </style>
   </head>
	
   <body>
      <p>Click the button</p>
      <button id = "button"> Highlight </button>

      <div class = "target">
      </div>
   </body>
</html>
This will produce following result −
Click the button

    27 Lectures 
     1 hours 

 Mahesh Kumar

    27 Lectures 
     1.5 hours 

 Pratik Singh

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    60 Lectures 
     9 hours 

 Eduonix Learning Solutions

    17 Lectures 
     2 hours 

 Sandip Bhattacharya

    12 Lectures 
     53 mins

 Laurence Svekis
 Print
 Add Notes
 Bookmark this page
cauchy_distribution a() in C++ with Examples - GeeksforGeeks

16 Oct, 2018
The cauchy_distribution::a() function is an inbuilt function in C++ STL which is used to returns the distribution parameter associated with Cauchy distribution. The class cauchy_distribution is present in header file random. Before going to the syntax of the function, brief introduction to Cauchy Distribution.
Cauchy Distribution A random variable X is said to follow Cauchy Distribution with parameter a and b if it has the probability density function of the form,
Where a is the location parameter specifying the location of peak of the distribution and b is the scale parameter specifying the half-width at half-maximum. Mean and Variance of the distribution is not defined, but its median and mode both exists and equals to a.
Syntax:
cauchy_distribution_name.a()
Parameters: This function does not accepts any parameter.
Return Value: The function returns the distribution parameter associated with the distribution. This parameter is known as the peak location parameter of the Cauchy distribution, which determines the shift to either side of the distribution shape. The parameter is set on construction.
Below programs illustrates the cauchy_distribution::a() function in C++ STL:
Program 1:
// CPP program to illustrate// cauchy_distribution::a()#include <iostream>#include <random>using namespace std;  // Driver programint main(){    default_random_engine generator;    cauchy_distribution<double> d(0.78, 1.45);      // prints the first value    cout << "Cauchy distribution: " << d.a();      return 0;}
Cauchy distribution: 0.78

Program 2:
// CPP program to illustrate// cauchy_distribution::a()#include <iostream>#include <random>using namespace std;  // Driver programint main(){    default_random_engine generator;      // Define a cauchy distribution with default     // parameters a=0.0 and b=1.0    cauchy_distribution<double> d;      // prints the first value    cout << "Cauchy distribution: " << d.a();      return 0;}
Cauchy distribution: 0

cpp-math
STL
C Language
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
UDP Server-Client implementation in C
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
C++ Classes and Objects
BabylonJS - Environment Setup

In this chapter, we will learn how to set up the environment for BabylonJS.
To start with the setup, visit the official website of Babylon.js − www.babylonjs.com. Go to the download section and choose the latest version of Babylon.js and store in your folder.
The screenshot for the same is as follows −
You can also go to GITHUB and clone the babylonjs project −
Babylon.js
In your command line type  −
git clone https://github.com/BabylonJS/Babylon.js.git
go to cd BabylonJS/
npm install

The required files will be available in the BabylonJS folder.
You can use the VSCode (Microsoft Visual Studio Code) for editing.The code comes with builtin functionalities like highlighting if any error, hightlighting the syntax, etc. You can use the editor of your choice and it is not mandatory to use only VSCode.
 Print
 Add Notes
 Bookmark this page