code-rag-bench/online-tutorials huggingface dataset:
turtle.setx() function in Python

07 Jul, 2021
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 set the turtle’s first coordinate to x, leave the second coordinate unchanged. Here, whatever the position of the turtle is, it set the x coordinate to given input keeping y coordinate unchanged. 
Syntax : turtle.setx(x) 
Parameter: 
x: a number (integer or float), it is the only one required argument.
Below is the implementation of the above method with some examples : 
Example 1 :
Python3
# import packageimport turtle  # check the turtle positionprint(turtle.position()) # set the x coordinateturtle.setx(30) # check the turtle positionprint(turtle.position()) # set the x coordinateturtle.setx(-50) # check the turtle positionprint(turtle.position())
 
 
Output :
 
(0.0, 0.0)
(30.0, 0.0)
(-50.0, 0.0)
 
Example 2 :
 
Python3
# import packageimport turtle  # set turtle directionturtle.left(90) # loop for patternfor i in range(4):     # motion  turtle.forward(100)  turtle.right(90)  turtle.forward(20)  turtle.right(90)  turtle.forward(100)     # set the x coordinate  turtle.up()  turtle.setx(40*(i+1))  turtle.down()     # change the direction  turtle.left(180)
 
 
Output :
 
 
ruhelaa48
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTTP | PUT

31 Oct, 2019
The HTTP PUT request method is used to create a new resource or overwrite a representation of the target resource that is known by the client. Calling this method once is similar to calling it multiple times successively as it has the same effect. Though it is idempotent, we cannot cache its response.
Syntax:
PUT /html file HTTP/1.1
Example:REQUEST:
PUT /example.html HTTP/1.1
Host: sample.com
Content-type: text/html
Content-length: 20

<p>New File</p>
RESPONSE: If the PUT request successfully creates a new resource, then the server informs the user by sending 201(Created) response.Output:
HTTP/1.1 201 Created
Content-Location: /example.html
If the target resource already has a representation and it is successfully modified by the request then the server must send either a 200(OK) or 204(No Content) response indicating that the response is successful.Output:
HTTP/1.1 204 No Content
Content-Location: /newexample.html 
Supported Browsers: The browsers supported by HTTP | PUT are listed below:
Google Chrome 6.0+
Internet Explorer 9.0+
Firefox 4.0+
Apple Safari 5.0
Opera 11.1
HTTP-headers
Picked
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js | erase() Function

24 Apr, 2020
The erase() function in p5.js is used to subtract all the drawings that would be done after the use of this function. The subtracted drawing area would reveal the webpage below the canvas. The effect of this function can be canceled by using the noErase() function.
It does not affect the drawings done by the image() and background() functions.
Syntax:
erase( [strengthFill], [strengthStroke] )
Parameters: This function accept two parameters as mentioned above and described below.
strengthFill: It is a number in the range of 0 to 255, which denotes the strength of the erasing shape’s fill. It is an optional value. The default value is 255, which denotes the full strength of the shape’s fill.
strengthStroke: It is a number in the range of 0 to 255, which denotes the strength of the erasing shape’s stroke. It is an optional value. The default value is 255, which denotes the full strength of the shape’s stroke.
Below examples illustrate the erase() function in p5.js:
Example 1:
function setup() {  createCanvas(600, 400);  textSize(20);    fill('black');  text("Move the slider below to change fill strength", 20, 30);    fillStrengthSlider = createSlider(0, 255, 128, 1);  fillStrengthSlider.position(30, 50);    text("Move the slider below to change stroke strength", 20, 100);    strokeStrengthSlider = createSlider(0, 255, 128, 1);  strokeStrengthSlider.position(30, 120);}  function draw() {  fill('red');  rect(50, 200, 200, 200);    erase(fillStrengthSlider.value(), strokeStrengthSlider.value());  circle(100, 300, 200);  noErase();  }
Output:
Example 2:
let eraseEnable = false;  function setup() {  createCanvas(600, 400);  textSize(20);    fill('black');  text("Click the button to see the effects of"         + " the erase() function", 20, 30);    toggleBtn = createButton("Toggle erase");  toggleBtn.position(30, 60);  toggleBtn.mouseClicked(toggleErase);}  function toggleErase() {  if (eraseEnable) {    noErase();    eraseEnable = false;  }  else {    erase();    eraseEnable = true;  }}  function mouseMoved() {  fill('red');  noStroke();  circle(mouseX, mouseY, 50);}
Output:
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/erase
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Product of all pairwise consecutive elements in an Arrays in C++

Given an array arr[n] of n number of integers, the task is to find the product of all pairwise consecutive elements.
Consecutive elements in an array arr[] are, if we are at ith element, i.e. arr[i] then its consecutive element will be either arr[i+1] or arr[i-1], so the product will be arr[i] * arr[i+1] or arr[i] * arr[i-1].
Input 
arr[] = {1, 2, 3, 4}
Output 
2, 6, 12
Explanation 
Splitting into pairs {1,2}, {2, 3}, {3, 4}
Their results will be 1*2 = 2, 2*3 = 6, 3*4 = 12
Input 
arr[] = {9, 5, 1, 2, 6, 10}
Output 
45, 5, 2, 12, 60
Explanation 
Splitting into pairs {9, 5}, {5, 1}, {1, 2}, {2, 6}, {6, 10}
Their results will be 9*5 = 45, 5*1 = 5, 1*2 = 2, 2*6=12, 6*10=60
Start the loop from 0th element of an array till it is less than n-1.
Start the loop from 0th element of an array till it is less than n-1.
For every i check its i+1, product every i and i+1 print the result.
For every i check its i+1, product every i and i+1 print the result.
Start
Step 1→ Declare function to calculate product of consecutive elements
   void product(int arr[], int size)
      Declare int product = 1
      Loop For int i = 0 and i < size – 1 and i++
         Set product = arr[i] * arr[i + 1]
         Print product
      End
Step 2 → In main()
   Declare int arr[] = {2, 4, 6, 8, 10, 12, 14 }
   Declare int size = sizeof(arr) / sizeof(arr[0])
   Call product(arr, size)
Stop
 Live Demo
#include <iostream>
using namespace std;
//functio to find the product of consecutive pairs
void product(int arr[], int size){
   int product = 1;
   for (int i = 0; i < size - 1; i++){
      product = arr[i] * arr[i + 1];
      printf("%d ", product);
   }
}
int main(){
   int arr[] = {2, 4, 6, 8, 10, 12, 14 };
   int size = sizeof(arr) / sizeof(arr[0]);
   printf("product is : ");
   product(arr, size);
   return 0;
}
If run the above code it will generate the following output −
product is : 8 24 48 80 120 168
Shell Script To Show Names of All Sub-Directories Present in Current Directory

09 Apr, 2021
In this given program, we are required to write a shell script to print the list of all the sub-directories present in the current directory. Currently, when we are running this program, the terminal is opened at the root directory location and hence, we are getting a list of sub-directories present at the root level. Moreover, this script comes in handy when we only want to list the sub-directories and not any other files present at the same level of hierarchy.
Approach:
Go to the root directory or any target directory where you want to get its sub-directories.Type in the following program.We are using ‘echo’ so that we get a simplified output.‘ls’ command in Linux lists all the files and directories.‘-d’ option in ls command specifies that we need to list only the directories.We are using the expression ‘*/’ so that we get only the directories under the current directory level and not going any level in depth further.
Go to the root directory or any target directory where you want to get its sub-directories.
Type in the following program.
We are using ‘echo’ so that we get a simplified output.
‘ls’ command in Linux lists all the files and directories.
‘-d’ option in ls command specifies that we need to list only the directories.
We are using the expression ‘*/’ so that we get only the directories under the current directory level and not going any level in depth further.
Program:
# Shell Script to list all sub-directories
# present in a current folder

# echo prints a message for user on screen
echo "List of sub-directories present in this Folder - "

# Following command lists all sub directories
# '*/' will only match directories under the current directory
    
ls -d */
Output:
Listing all sub-directories at root level
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
chmod command in Linux with examples
nohup Command in Linux with Examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
Python | Functions | Question 1

28 Jun, 2021
What will be the output of the following code :
print type(type(int))
(A) type ‘int’
(B) type ‘type’
(C) Error(D) 0Answer: (B)Explanation: The type() function returns the class of the argument the object belongs to. Thus, type(int) returns which is of the type ‘type’ object.Quiz of this Question
Functions
Python-Quizzes
Python-Quizzes-Functions
Python-Quizzes
Functions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Path getFileSystem() method in Java with Examples

16 Jul, 2019
The Path interface was added to Java NIO in Java 7. The Path interface is located in the java.nio.file package, so the fully qualified name of the Java Path interface is java.nio.file.Path. A Java Path instance represents a path in the file system. A path can use to locate either a file or a directory.path of an entity could be of two types one is an absolute path and other is a relative path. The absolute path is the location address from the root to the entity while the relative path is the location address which is relative to some other path.
getFileSystem() method of java.nio.file.Path used to return the file system that created this Path object.
Syntax:
FileSystem getFileSystem()

Parameters: This method accepts nothing.
Return value: This method returns the file system that created this Path object.
Below programs illustrate getFileSystem() method:Program 1:
// Java program to demonstrate// java.nio.file.Path.getFileSystem() method  import java.io.IOException;import java.nio.file.FileSystem;import java.nio.file.Path;import java.nio.file.Paths;  public class GFG {    public static void main(String[] args)        throws IOException    {          // create object of Path        Path path            = Paths.get("D:/workspace/AmanCV.docx");          // call getFileSystem()        // and get FileSystem object        FileSystem fs = path.getFileSystem();          // print separator of FileSystem        System.out.println("Separator used for FileSystem: "                           + fs.getSeparator());    }}
Separator used for FileSystem: /

Program 2:
// Java program to demonstrate// java.nio.file.Path.getFileSystem() method  import java.io.IOException;import java.nio.file.FileSystem;import java.nio.file.Path;import java.nio.file.Paths;  public class GFG {    public static void main(String[] args)        throws IOException    {          // create object of Path        Path path = Paths.get("D:/Resume.pdf");          // call getFileSystem()        // and get FileSystem object        FileSystem fs = path.getFileSystem();          // print FileSystem is ReadOnly or not        System.out.println("FileSystem is ReadOnly: "                           + fs.isReadOnly());    }}
FileSystem is ReadOnly: false

References: https://docs.oracle.com/javase/10/docs/api/java/nio/file/Path.html#getFileSystem()
Java-Functions
Java-Path
java.nio.file package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reversing the order of a ggplot2 legend - GeeksforGeeks

02 Jul, 2021
In this article, we will see how to Reverse the order of Legend Items of ggplot2 plots in the R programming language.
First, load the ggplot2 package by using the library() function. If you have not installed it yet, you can simply install it by writing the below command in R Console.
install.packages("ggplot2")
Let us first create a regular plot, so that the difference is apparent.
Example:
R
# Load Packagelibrary("ggplot2") # Create a DataFramedata <- data.frame(Xdata = rnorm(7),                                          Ydata = rnorm(7),                   LegendData = c("ld-01", "ld-02",                                  "ld-03", "ld-04",                                  "ld-05", "ld-06",                                  "ld-07")) # Create a Scatter Plotggplot(data, aes(Xdata, Ydata, color = LegendData)) +    geom_point(size = 10)
Output:
Scatterplot with legend in Default Order
To Reverse the order of Legend, we have to add guides() and guide_legend() functions to the geom_point() function. Inside guides() function, we take the parameter color, which will call guide_legend() guide function as value. Inside guide_legend() function, we take an argument called reverse, which is a logical parameter. If “reverse = TRUE”, the order of legends is reversed otherwise it will remain as it was.
Syntax : guides(...)
Parameter :
... : either a string or call to a guide function. here we call guide_legend() guide function.
Return : each scale can be set scale-by-scale 
Syntax : guide_legend(reverse = TRUE)
Parameter :
reverse : It is a logical parameter that specify the order of plot legend.
Return : Legend Guides for various scales
Example:
R
# Load Packagelibrary("ggplot2") # Create a DataFramedata <- data.frame(Xdata = rnorm(7),                                          Ydata = rnorm(7),                   LegendData = c("ld-01", "ld-02",                                  "ld-03", "ld-04",                                  "ld-05",  "ld-06",                                  "ld-07")) # Create a Scatter Plot and change# the size of legendggplot(data, aes(Xdata, Ydata, color = LegendData)) +    geom_point(size = 10)+  guides(color = guide_legend(reverse=TRUE))
Output: 
Scatterplot with legend in Reverse Order
saurabh1990aror
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to import an Excel File into R ?
How to filter R DataFrame by values in a column?
Time Series Analysis in R
R - if statement
Logistic Regression in R Programming
Informatica Coding Round Question - GeeksforGeeks

23 Jul, 2021
Given an array with n elements and an integer k. Divide the array into subarrays, each of them containing k elements.For example: Input: arr[]={1, 32, 5, 6, 9, 3} and k=2
The subarrays will have elements:{132}, {56}, {93}.
Now sort these subarrays as {56}, {93}, {132}. Merge these subarrays together and display them as the elements of original array in sorted order asFinal output: arr[]={5, 6, 9, 3, 1, 32} 
Examples: 
Input : 
arr[]={1, 32, 5, 6, 9, 3} 
k=2 
Output : 
arr[]={5, 6, 9, 3, 1, 32}
Below is the implementation of the above idea:
CPP
// C++ Program implementation of the above idea #include <bits/stdc++.h>using namespace std;void subarray_k(vector<int> v, int n, int k){    int sum = 0;    int index;    string str = "";    vector<pair<int, int> > arr;    for (int i = 0; i < n - 1; i++)    {        index = i;        str = to_string(v[i]);        i++;        for (int j = 0; j < k - 1; j++)        {            // Conversion of array elements(integers) to            // string for easy concatenation            string temp = to_string(v[i]);            str += temp;            if (j != k - 2)                i++;        }        stringstream check(str);        int s = 0;         // Conversion of concatenated string to integer        check >> s;        arr.push_back(make_pair(s, index));        index++;    }    int u = 0;       // Sorting of array    sort(arr.begin(), arr.end());    vector<int> v2;    for (int i = 0; i < (n / k); i++) {        u = 0;        int j = arr[i].second;        while (u < k) {            int a = v[j];            v2.push_back(a);            u++;            j++;        }    }       // print    for (int i = 0; i < n; i++)    {        cout << v2[i] << " ";    }} // Driver codeint main(){    int n = 6;    vector<int> v = { 1, 32, 5, 6, 9, 3 };    int k = 2;     // Function call    subarray_k(v, n, k);    return 0;    // This code is contributed by Siddhant Thapliyal}
5 6 9 3 1 32 
Informatica
Interview Experiences
Informatica
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Amazon Interview Experience
Amazon Interview Experience for SDE-1
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience (Off-Campus) 2022
Amazon Interview Experience for SDE-1 (On-Campus)
Infosys Interview Experience for DSE 2022
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
EPAM Interview Experience (Off-Campus)
Area Chart with Altair in Python - GeeksforGeeks

29 Sep, 2021
Prerequisite: Introduction to Altair in Python
An Area Graph shows the change in a quantitative quantity with respect to some other variable. It is simply a line chart where the area under the curve is colored/shaded. It is best used to visualize trends over a period of time, where you want to see how the value of one variable changes over a period of time or with respect to another variable and do not care about the exact data values. Some modifications of the area chart are the stacked area chart and streamgraph.
Area Graph is readily available in Altair and can be applied using the mark_area() function.
To make an area chart, simply select suitable variables from the dataset and map them to the x and y encoding, where the quantitative variable should be mapped to the x encoding.
The dataset used in this article is from the Vega_datasets library.
Code:
Python3
# Python3 program to illustrate # How to make an area chart# using the altair library     # Importing altair and vega_datasets import altair as alt from vega_datasets import data      # Selecting the sp500 datasetsp500 = data.sp500()     # Making the area graph# using the mark_area functionalt.Chart(sp500).mark_area().encode(        # Map the date to x-axis    x = 'date',       # Map the price to y-axis    y = 'price')
Output: 
Simple Area Chart using Altair
The following simple customizations can be done on an area chart: 
Area Color: You can change the default color of the area color by setting the color parameter of the mark_area() method.
Opacity: You can change the default opacity of the area by setting the opacity parameter of the mark_area() method. It ranges from 0 to 1.
Line Color: You can also change the color of the actual line plot by specifying the value of the color key in the line dictionary parameter of the mark_area() method.
Example: 
Python3
# Python3 program to illustrate # How to make an area chart# using the altair library     # Importing altair and vega_datasets import altair as alt from vega_datasets import data      # Selecting the sp500 datasetsp500 = data.sp500()     # Making the area graph alt.Chart(sp500).mark_area(color = 'green',                           opacity = 0.5,                           line = {'color':'darkgreen'}).encode(       # Map the date to x-axis    x = 'date',       # Map the price to y-axis    y = 'price')
Output: 
Customized Area Chart using Altair
 
sooda367
Python-Altair
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
ES6 -  Array Method forEach()

forEach() method calls a function for each element in the array.
array.forEach(callback[, thisObject]);  

callback − Function to test for each element.
callback − Function to test for each element.
thisObject − Object to use as this when executing callback.
thisObject − Object to use as this when executing callback.
Returns created array.
var nums = new Array(12,13,14,15)  
console.log("Printing original array......")  

nums.forEach(function(val,index) { 
   console.log(val) 
})  
nums.reverse()  //reverses the array element 
console.log("Printing Reversed array....")  

nums.forEach(function(val,index){ 
   console.log(val) 
})  
Printing Original Array.... 
12 
13 
14 
15 
Printing Reversed array... 
15 
14 
13 
1


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
jQuery - filter( selector ) Method

The filter( selector ) method filters all elements from the set of matched elements that do not match the specified selector(s).
Here is the simple syntax to use this method −
selector.filter( selector )

Here is the description of all the parameters used by this method −
selector − It could be a comma-separated list of expressions to apply multiple filters at once (e.g. filter(".class1, .class2")).
selector − It could be a comma-separated list of expressions to apply multiple filters at once (e.g. filter(".class1, .class2")).
Following is an example showing a simple usage of this method −
<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" language = "javascript">
         $(document).ready(function() {
            $("li").filter(".middle").addClass("selected");
         });
      </script>
		
      <style>
         .selected { color:red; }
      </style>
   </head>
	
   <body>
      <div>
         <ul>
            <li class = "top">list item 1</li>
            <li class = "top">list item 2</li>
            <li class = "middle">list item 3</li>
            <li class = "middle">list item 4</li>
            <li class = "bottom">list item 5</li>
            <li class = "bottom">list item 6</li>
         </ul>
      </div>
   </body>
</html>
This will produce following result −
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6
Following is an example showing a simple usage of this method −
<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" language = "javascript">
         $(document).ready(function() {
            $("li").filter(".middle").addClass("selected");
         });
      </script>
		
      <style>
         .selected { color:red; }
      </style>
   </head>
	
   <body>
      <div>
         <ul>
            <li class = "top">list item 1</li>
            <li class = "top">list item 2</li>
            <li class = "selected">list item 3</li>
            <li class = "selected">list item 4</li>
            <li class = "bottom">list item 5</li>
            <li class = "bottom">list item 6</li>
         </ul>
      </div>
   </body>
</html>
This will produce following result −
list item 1
list item 2
list item 3
list item 4
list item 5
list item 6

    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
C program to convert upper case to lower and vice versa by using string concepts

Converting upper to lower and lower to upper is generally termed as toggle.
Toggle each character means, in a given string, the lower letter is print in upper form and upper case is print in lower letter respectively.
The C program to convert upper case to lower and lower case to upper is given below −
 Live Demo
#include <stdio.h>
#define MAX 100
void toggle(char * string);
int main(){
   char string[MAX];
   printf("enter the string need to be toggle :\n");
   gets(string);
   toggle(string);
   printf("final string after toggling is:\n");
   printf("%s\n", string);
   return 0;
}
void toggle(char * string){
   int i=0;
   while(string[i]!='\0'){
      if(string[i] >= 'a' && string[i] <= 'z'){
         string[i] = string[i] - 32;
      }
      else if(string[i] >= 'A' && string[i] <= 'Z'){
         string[i]= string[i] + 32;
      }
      i++;
   }
}
When you run the above mentioned program, you will get the following output −
enter the string need to be toggle :
TutoRialS PoinT C ProgrAmmIng LanGuage
final string after toggling is:
tUTOrIALs pOINt c pROGRaMMiNG lANgUAGE
The C program to convert upper to lower and lower to upper by using the pre-defined function is as follows −
 Live Demo
#include <stdio.h>
int main(){
   int i, length = 0;
   char string[] = "TutORial";
   length = sizeof(string)/sizeof(string[0]);
   for(i = 0; i < length; i++){
      if(isupper(string[i])){
         string[i] = tolower(string[i]);
      }
      else if(islower(string[i])){
         string[i] = toupper(string[i]);
      }
   }
   printf("final string after conversion: %s", string);
   return 0;
}
The output is as follows −
final string after conversion : tUTorIAL
How to Insert custom date into MySQL timestamp field?

The problem with UNIX_TIMESTAMP() function is that it returns an integer while we want to insert custom date i.e. not any integer part to MySQL date.
Do not use UNIX_TIMESTAMP() for your column defined as TIMESTAMP because UNIX_TIMESTAMP() returns an integer.
Check the UNIX_TIMESTAMP. The query is as follows −
mysql> select UNIX_TIMESTAMP( '2019-01-09 15 −48 −23') AS IntegerValue;
The following is the output −
+--------------+
| IntegerValue |
+--------------+
| 1547029103   |
+--------------+
1 row in set (0.00 sec)
Look at the sample output, the UNIX_TIMESTAMP() function returns an integer of corresponding date and time.
The syntax is as follows to insert custom date for your column TIMESTAMP.
INSERT INTO yourTableName(yourColumnName) values('yourCustomDateTime');
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table TimestampDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> yourTimestamp TIMESTAMP,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (2.14 sec)
To insert custom date to MySQL timestamp field, the following is the query −
mysql> insert into TimestampDemo(yourTimestamp) values('2019-01-09 15 −48 −23');
Query OK, 1 row affected (0.37 sec)

mysql> insert into TimestampDemo(yourTimestamp) values('2018-03-14 16 −4 −23');
Query OK, 1 row affected (0.37 sec)

mysql> insert into TimestampDemo(yourTimestamp) values('2017-12-10 10 −8 −20');
Query OK, 1 row affected (0.16 sec)

mysql> insert into TimestampDemo(yourTimestamp) values('2016-4-05 13 −45 −21');
Query OK, 1 row affected (0.30 sec)
Now you can display all records from the table using select statement. The query is as follows −
mysql> select *from TimestampDemo;
The following is the output −
+----+-----------------------+
| Id | yourTimestamp         |
+----+-----------------------+
| 1  | 2019-01-09 15 −48 −23 |
| 2  | 2018-03-14 16 −04 −23 |
| 3  | 2017-12-10 10 −08 −20 |
| 4  | 2016-04-05 13 −45 −21 |
+----+-----------------------+
4 rows in set (0.00 sec)
Ethical Hacking - Cross-Site Scripting

Cross-site scripting (XSS) is a code injection attack that allows an attacker to execute malicious JavaScript in another user's browser.
The attacker does not directly target his victim. Instead, he exploits a vulnerability in a website that the victim visits, in order to get the website to deliver the malicious JavaScript for him. To the victim's browser, the malicious JavaScript appears to be a legitimate part of the website, and the website has thus acted as an unintentional accomplice to the attacker. These attacks can be carried out using HTML, JavaScript, VBScript, ActiveX, Flash, but the most used XSS is malicious JavaScript.
These attacks also can gather data from account hijacking, changing of user settings, cookie theft/poisoning, or false advertising and create DoS attacks.
Let’s take an example to understand how it works. We have a vulnerable webpage that we got by the metasploitable machine. Now we will test the field that is highlighted in red arrow for XSS.
First of all, we make a simple alert script
<script>  
   alert(‘I am Vulnerable’)  
</script>
It will produce the following output −
XSS attacks are often divided into three types −
Persistent XSS, where the malicious string originates from the website's database.
Persistent XSS, where the malicious string originates from the website's database.
Reflected XSS, where the malicious string originates from the victim's request.
Reflected XSS, where the malicious string originates from the victim's request.
DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code.
DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code.
Generally, cross-site scripting is found by vulnerability scanners so that you don’t have to do all the manual job by putting a JavaScript on it like
<script>  
   alert('XSS') 
</script>
Burp Suite and acunetix are considered as the best vulnerability scanners.
To prevent XSS attacks, keep the following points in mind −
Check and validate all the form fields like hidden forms, headers, cookies, query strings.
Check and validate all the form fields like hidden forms, headers, cookies, query strings.
Implement a stringent security policy. Set character limitation in the input fields.
Implement a stringent security policy. Set character limitation in the input fields.

    36 Lectures 
     5 hours 

 Sharad Kumar

    31 Lectures 
     3.5 hours 

 Abhilash Nelson

    22 Lectures 
     3 hours 

 Blair Cook

    74 Lectures 
     4.5 hours 

 199courses

    75 Lectures 
     4.5 hours 

 199courses

    148 Lectures 
     28.5 hours 

 Joseph Delgadillo
 Print
 Add Notes
 Bookmark this page
Check if some elements of array are equal JavaScript

We have an array of numbers that have got some redundant entries, our job is to write a
function that takes in the array and groups all the identical entries into one subarray and returns
the new array thus formed.
For example −
//If the input array is:
const arr = [1, 3, 3, 1];
//then the output should be:
const output = [[1, 1], [3, 3]];
We will use a HashMap to keep a track of the elements already occurred and iterate over the
array using a for loop, the code for this will be −
const arr = [1, 3, 3, 1];
const groupArray = arr => {
   const map = {};
   const group = [];
   for(let i = 0; i < arr.length; i++){
      if(typeof map[arr[i]] === 'number'){
         group[map[arr[i]]].push(arr[i]);
      } else {
         //the push method returns the new length of array
         //and the index of newly pushed element is length-1
         map[arr[i]] = group.push([arr[i]])-1;
      }
   };
   return group;
}
console.log(groupArray(arr));
The output in the console will be −
[ [ 1, 1 ], [ 3, 3 ] ]
Tryit Editor v3.7

Tryit: A description list
C++ Program to Convert String to Integer - GeeksforGeeks

01 May, 2020
Given a string of digits, the task is to convert the string to an integer.
Examples:
Input : str = "12345"
Output : 12345

Input : str = "876538";
Output : 876538

Input : str = "0028";
Output : 28

// C++ program to convert String into Integer#include <bits/stdc++.h>using namespace std;  // function for converting string to integerint stringTointeger(string str){    int temp = 0;    for (int i = 0; i < str.length(); i++) {          // Since ASCII value of character from '0'        // to '9' are contiguous. So if we subtract        // '0' from ASCII value of a digit, we get         // the integer value of the digit.        temp = temp * 10 + (str[i] - '0');    }    return temp;}  // Driver codeint main(){    string str = "12345";    int num = stringTointeger(str);    cout << num;    return 0;}
12345

How to do using library functions?Please refer Converting Strings to Numbers in C/C++ for library methods.
cpp-string
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Program to implement Singly Linked List in C++ using class
Iterative Letter Combinations of a Phone Number
Dynamic _Cast in C++
How to sort an Array in descending order using STL in C++?
Setting up Sublime Text for C++ Competitive Programming Environment
Why it is important to write "using namespace std" in C++ program?
return 0 vs return 1 in C++
Extract string from between quotations - Python - GeeksforGeeks

03 Jan, 2021
In this article, we will learn to extract strings in between the quotations using Python.
Method 1:
To extract strings in between the quotations we can use findall() method from re library.
Python3
import reinputstring = ' some strings are present in between "geeks" "for" "geeks" '  print(re.findall('"([^"]*)"', inputstring))
Output:
['geeks', 'for', 'geeks']
Method 2:
We can extract strings in between the quotations using split() method and slicing.
Python3
inputstring = 'some strings are present in between "geeks" "for" "geeks" '    """here split() method will split the string for every quotation ( " ) .i.e.['some strings are present in between ', 'geeks', ' ', 'for', ' ', 'geeks', ' '].   Then we will be storing all the strings at odd index.  """  result = inputstring.split('"')[1::2]print(result);
Output:
['geeks', 'for', 'geeks']
Here you can learn more about Regular Expressions and list slicing in python.
Picked
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
How can Selenium select each div separately that have the same class?

We can select each div separately that have the same class with the help of the Selenium webdriver. Often in the html code, we find more than one div element having a class attribute with the same value.
Let us see the html code of elements with div tag having the same value set for the class attribute (as highlighted in the image). The value of the class attribute is - colsm-5 col-xs-8 store-details sp-detail paddingR0.
To identify each of these div elements separately, we shall use the method findElements and pass the value of the class attribute as a parameter to this method. The findElements method returns a list of matching elements. We have to iterate through this list and identify each div separately.
List<WebElement> l =
driver.findElements(By.className("store-details"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
public class DivSameCls{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.justdial.com/Bangalore/Bakeries");
      // identify div elements with same class
      List<WebElement> l = driver.findElements(By.className("store-details"));
      // list iteration
      System.out.println("Elements are: ");
      for(int j = 0; j< l.size(); j++) {
         //identify separate div
         String v = l.get(j).getText();
         System.out.println("Elements are: ");
         System.out.println(v);
      }
      //browser close
      driver.close();
   }
}
Python dictionary cmp() Method

Python dictionary  method cmp() compares two dictionaries based on key and values.
Following is the syntax for cmp() method −
cmp(dict1, dict2)

dict1 − This is the first dictionary to be compared with dict2.
dict1 − This is the first dictionary to be compared with dict2.
dict2 − This is the second dictionary to be compared with dict1.
dict2 − This is the second dictionary to be compared with dict1.
This method returns 0 if both dictionaries are equal, -1 if dict1 < dict2 and 1 if dict1 > dic2.
The following example shows the usage of cmp() method.
#!/usr/bin/python

dict1 = {'Name': 'Zara', 'Age': 7};
dict2 = {'Name': 'Mahnaz', 'Age': 27};
dict3 = {'Name': 'Abid', 'Age': 27};
dict4 = {'Name': 'Zara', 'Age': 7};
print "Return Value : %d" %  cmp (dict1, dict2)
print "Return Value : %d" %  cmp (dict2, dict3)
print "Return Value : %d" %  cmp (dict1, dict4)
When we run above program, it produces following result −
Return Value : -1
Return Value : 1
Return Value : 0


    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 – API.send_direct_message() in Tweepy

12 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The send_direct_message() method of the API class in Tweepy module is used to send a direct message as the authenticated user.
Syntax : API.send_direct_message(parameters)
Parameters :
recipient_id : ID of the recipient.
text : text of the direct message.
attachment_type : attachment media or location to be sent.
attachment_media_id : ID of the attachment media to be sent.
Returns : an object of class DirectMessage
Example 1 :
# import the moduleimport tweepy  # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = ""  # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret)  # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret)  # calling the api api = tweepy.API(auth)  # ID of the recipientrecipient_id =   # text to be senttext = "This is a Direct Message."  # sending the direct messagedirect_message = api.send_direct_message(recipient_id, text)  # printing the text of the sent direct messageprint(direct_message.message_create['message_data']['text'])
Output :
This is a Direct Message.

Example 2 : Sending a direct message with the following media attachment :
# ID of the recipientrecipient_id =   # text to be senttext = "This is a Direct Message."  # the ID of the mediaattachment_media_id =   # sending the direct messagedirect_messages = api.send_direct_message(recipient_id, text,                    attachment_media_id = attachment_media_id)
Output :
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Remove items from Set

27 Dec, 2017
In this article, we will try to a way in which the elements can be removed from the set in a sequential manner. Before going into that let’s learn various characteristic of a set. A Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set.
Examples:
Input : set([12, 10, 13, 15, 8, 9])
Output :
{9, 10, 12, 13, 15}
{10, 12, 13, 15}
{12, 13, 15}
{13, 15}
{15}
set()

Input : set(['a','b','c','d','e'])
Output :
{'d', 'c', 'a', 'b'}
{'c', 'a', 'b'}
{'a', 'b'}
{'b'}
set()

Using the pop() methodThe pop() is an inbuilt method in Python that is used to pop out or remove the elements one by one from the set. The element that is the smallest in the set is removed first followed by removing elements in increasing order. In the following program, the while loop goes onto removing the elements one by one, until the set is empty.
# Python program to remove elements from set# Using the pop() methoddef Remove(initial_set):    while initial_set:        initial_set.pop()        print(initial_set)  # Driver Codeinitial_set = set([12, 10, 13, 15, 8, 9])Remove(initial_set)
Output:
{9, 10, 12, 13, 15}
{10, 12, 13, 15}
{12, 13, 15}
{13, 15}
{15}
set()

python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a dialog box or window in HTML ?

05 Jun, 2020
In this article, we will create a dialog box or window using the <dialog> tag in the document. This tag is used to create popup dialog and models on a web page. This tag is new in HTML5.
Syntax:
<dialog open> Contents... </dialog>
Example 1:
<!DOCTYPE html><html>  <head>    <title>        How to define a dialog         box or window?    </title>      <style>        dialog {            color: green;            font-size: 30px;            font-weight: bold;            font-style: italic;        }          body {            text-align: center;        }    </style></head>  <body>    <h1>        <dialog> tag    </h1>    <dialog open>        Welcome to GeeksforGeeks    </dialog></body>  </html>              
Output:
Example 2:
<!DOCTYPE html><html>  <head>    <meta charset="utf-8">    <title>        How to define a dialog        box or window?    </title>      <style>        table,        th,        td {            border: 1px solid red;        }    </style></head>  <body>    <center>        <h2>GeeksForGeeks</h2>        <h2>            How to define a             dialog box or window        </h2>                  <dialog open>            This is an open dialog window        </dialog>    </center></body>  </html>
Output:
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Form validation using jQuery
Design a web page using HTML and CSS
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type
p5.Color setAlpha() Method

28 Jul, 2020
The setAlpha() method in p5.js is used to set the alpha component of a p5.Color object. The range of the alpha value is dependent on the current color mode. In the default RGB color mode, the value can be between 0 and 255.
Syntax:
setAlpha( alpha )

Parameters: This method accepts a single parameter as mentioned above and described below:
alpha: It is a number that denotes the new alpha value.
The example below illustrates the setAlpha() method in p5.js:
Example 1:
Javascript
function setup() {  createCanvas(600, 300);    alphaSlider = createSlider(0, 255, 128);  alphaSlider.position(30, 50);}  function draw() {  clear();  textSize(18);    // Get the alpha value from the slider  let alphaValue = alphaSlider.value();    let newColor = color(128, 255, 128);    // Set the alpha value of the color  newColor.setAlpha(alphaValue);      background(newColor);  fill('black');  text("Move the slider to change the " +       "alpha component of the background color",       20, 20);    }
Output:
Example 2:
Javascript
function setup() {  createCanvas(600, 300);    alphaSlider = createSlider(0, 255, 128);  alphaSlider.position(30, 50);}  function draw() {  clear();  textSize(18);    noFill();  stroke(0);  strokeWeight(50);  ellipse(width / 2, height / 2, 150);  strokeWeight(1);    // Get the alpha value from the slider  let alphaValue = alphaSlider.value();    let newColor = color(255, 128, 128);    // Set the alpha value of the color  newColor.setAlpha(alphaValue);      noStroke();  background(newColor);  fill('black');  text(    "Move the slider to change the " +    "alpha component of the background color",    20, 20);    }
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5.Color/setAlpha
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?