code-rag-bench/online-tutorials huggingface dataset:
Python os.mkdir() Method

Python method mkdir() create a directory named path with numeric mode mode. The default mode is 0777 (octal). On some systems, mode is ignored. Where it is used, the current umask value is first masked out.
Following is the syntax for mkdir() method −
os.mkdir(path[, mode])

path − This is the path, which needs to be created.
path − This is the path, which needs to be created.
mode − This is the mode of the directories to be given.
mode − This is the mode of the directories to be given.
This method does not return any value.
The following example shows the usage of mkdir() method.
#!/usr/bin/python

import os, sys

# Path to be created
path = "/tmp/home/monthly/daily/hourly"

os.mkdir( path, 0755 );

print "Path is created"
When we run above program, it produces following result −
Path is created


    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
Scala - Arithmetic Operators

Try the following example program to understand all the arithmetic operators available in Scala Programming Language.
object Demo {
   def main(args: Array[String]) {
      var a = 10;
      var b = 20;
      var c = 25;
      var d = 25;
      
      println("a + b = " + (a + b) );
      println("a - b = " + (a - b) );
      println("a * b = " + (a * b) );
      println("b / a = " + (b / a) );
      println("b % a = " + (b % a) );
      println("c % a = " + (c % a) );
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

a + b = 30
a - b = -10
a * b = 200
b / a = 2
b % a = 0
c % a = 5


    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
SAS | COALESCE Function with Examples - GeeksforGeeks

30 Jul, 2019
The COALESCE function is employed to pick the first non-missing value in a list of variables. In other words, it returns the first non-blank value of each row.
Let’s produce a sample dataset in SAS to know how COALESCE perform.
Example:
data temp;    input roll_no a1-a4;    cards;12 . 98 52 .         23 79 . 67 .         14 90 82 88 85 ;run;
Output:
COALESCE : First Non-Missing Valuedata exam;set temp;first_non_miss_val = coalesce(of a1 - a4);run;If you examine the output shown within the image below, you’d realize COALESCE returns 98 in first observation which is the first non-missing value among a1 = ., a2 = 98, a3 = 52, a4 =.
data exam;set temp;first_non_miss_val = coalesce(of a1 - a4);run;
If you examine the output shown within the image below, you’d realize COALESCE returns 98 in first observation which is the first non-missing value among a1 = ., a2 = 98, a3 = 52, a4 =.
COALESCE : Last Non-Missing ValueLet us suppose you want to find out last non-missing value instead of first. For that, there is no such function available which will return last non-missing value but to achieve that we can reverse the list of variables and calculate the first non-missing value which would be equivalent to last non-missing value. Indirectly, we are considering to evaluate variables from right to left instead of left to right.data exam;set temp;last_non_miss_val = coalesce(of a4-a1);run;Output:Note: coalesce(of a4-a1) is equivalent to coalesce(a4, a3, a2, a1).
Let us suppose you want to find out last non-missing value instead of first. For that, there is no such function available which will return last non-missing value but to achieve that we can reverse the list of variables and calculate the first non-missing value which would be equivalent to last non-missing value. Indirectly, we are considering to evaluate variables from right to left instead of left to right.
data exam;set temp;last_non_miss_val = coalesce(of a4-a1);run;
Output:
Note: coalesce(of a4-a1) is equivalent to coalesce(a4, a3, a2, a1).
SAS Programming
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Programming Languages to Learn in 2022
Shallow Copy and Deep Copy in C++
Difference between Shallow and Deep copy of a class
Kotlin Array
C# | Data Types
Advantages and Disadvantages of OOP
Java Swing | JComboBox with examples
Top 10 Fastest Programming Languages
Use of FLAG in programming
Prolog | An Introduction
How to clear HTML form fields with jQuery?

With jQuery, you can easily clear HTML form fields. For this, jQuery: reset Selector is used. This will clear the HTML form fields.
You can try to run the following code to clear form fields with jQuery −
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(){
            $(":reset").css("background-color", "#F98700");
         });
      </script>
   </head>
   <body>
      <form action="">
         Student Name<br><input type="text" name="sname"><br>
         Student Subject<br><input type="password" name="ssubject"><br>
         <input type="submit" value="Submit"><br>
         <input type="reset" value="Reset">
      </form>
   </body>
</html>
How to install python modules and their dependencies easily?

The best and recommended way to install Python modules is to use pip, the Python package manager. It automatically installs dependencies of the module as well.
If you have Python 2 >=2.7.9 or Python 3 >=3.4 installed from python.org, you will already have pip and setup tools, but will need to upgrade to the latest version:
On Linux or macOS:
pip install -U pip setuptools
On Windows:
python -m pip install -U pip setuptools
If you’re using a Python install on Linux that’s managed by the system package manager (e.g "yum", "apt-get" etc...), and you want to use the system package manager to install or upgrade pip, then see: https://packaging.python.org/guides/installing-using-linux-tools/
Otherwise:
Download get-pip.py from https://bootstrap.pypa.io/get-pip.py. Run python get-pip.py. This will install or upgrade pip.
Now you can use pip to install python packages. For example, To install the latest version of "SomeProject":
$ pip install 'SomeProject'
To install a specific version:
$ pip install 'SomeProject==1.4'
To install greater than or equal to one version and less than another:
$ pip install 'SomeProject>=1,<2'
RAII and smart pointers in C++

RAII (Resource Acquisition Is Initialization) is C++ technique which control the life cycle of resource. It is a class variant and is tied to object life time.
It encapsulates several resources into class where resource allocation is done by constructor during object creation and resource deallocation is done by destructor during object destruction.
Resource is guaranteed to be held till the object is alive.
void file_write {
   Static mutex m; //mutex to protect file access
   lock_guard<mutex> lock(m); //lock mutex before accessing file
   ofstream file("a.txt");
   if (!file.is_open()) //if file is not open
   throw runtime_error("unable to open file");
   // write text to file
   file << text << stdendl;
}
Smart Pointers in C++ & minus;
Smart pointer is an abstract data type by using which we can make a normal pointer in such way that it can be used as memory management like file handling, network sockets etc., also it can do many things like automatic destruction, reference counting etc.
Smart pointer in C++, can be implemented as template class, which is overloaded with * and -> operator. auto_ptr, shared_ptr, unique_ptr and weak_ptr are the forms of smart pointer can be implemented by C++ libraries.
 Live Demo
#include <iostream>
using namespace std;
// A generic smart pointer class
template <class T>
class Smartpointer {
   T *p; // Actual pointer
   public:
      // Constructor
      Smartpointer(T *ptr = NULL) {
         p = ptr;
      }
   // Destructor
   ~Smartpointer() {
      delete(p);
   }
   // Overloading de-referencing operator
   T & operator * () {
      return *p;
   }
   // Over loading arrow operator so that members of T can be accessed
   // like a pointer
   T * operator -> () {
      return p;
   }
};
int main() {
   Smartpointer<int> p(new int());
   *p = 26;
   cout << "Value is: "<<*p;
   return 0;
}
Value is: 26
What are different methods of passing parameters in C#?

When a method with parameters is called, you need to pass the parameters to the method using any of the following three methods -
This method copies the reference to the memory location of an argument into the formal parameter. This means that changes made to the parameter affect the argument.
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.
In Value parameters, when a method is called, a new storage location is created for each value parameter. The values of the actual parameters are copied into them. Hence, the changes made to the parameter inside the method have no effect on the argument.
Let us see an example for Value Parameters in C# −
 Live Demo
using System;

namespace CalculatorApplication {
   class NumberManipulator {
      public void swap(int x, int y) {
         int temp;

         temp = x; /* save the value of x */
         x = y; /* put y into x */
         y = temp; /* put temp into y */
      }

      static void Main(string[] args) {
         NumberManipulator n = new NumberManipulator();

         /* local variable definition */
         int a = 7;
         int b = 10;

         Console.WriteLine("Before swap, value of a : {0}", a);
         Console.WriteLine("Before swap, value of b : {0}", b);

         /* calling a function to swap the values */
         n.swap(a, b);

         Console.WriteLine("After swap, value of a : {0}", a);
         Console.WriteLine("After swap, value of b : {0}", b);

         Console.ReadLine();
      }
   }
}
Before swap, value of a : 7
Before swap, value of b : 10
After swap, value of a : 7
After swap, value of b : 10
How to substitute an environment variable using sed on Linux?

An Environment variable is a dynamic-named value. Generally, these are variables are exported in a single terminal using a command shown below
export $SOMEVARIABLE=value
or they are stored inside the bash files, so that they remain available in all the terminals once the file is sourced. If we want to change an environment variable we can simply change the above command’s value field and then source the file, but if we want to do that with the help of the sed command then we need to know a little bit about the sed command.
Let’s explore the sed command, which is short for stream editor. This command is used to perform different functions like find, replace, insert and many more on a particular file.
sed [OPTIONS]... [SCRIPT] [INPUTFILE...]
Considering we have a simple text file where we want to replace a string that is present in the file to another string, we can make use of the grep command in that case.
immukul@192 linux% cat somefile.txt

this is a test file and it is used for testing and is not available for anything else so
please stop asking, lionel messi
Now we want to replace the string “it” with “litt” in the above file. The command to do that is shown below −
sed ‘s/it/litt’ somefile.txt
immukul@192 linux% cat somefile.txt

this is a test file and litt is used for testing and is not available for anything else so
please stop asking, lionel messi
Now let’s see how to exchange an environment variable’s value inside a bash script with the help of the sed command.
There’s an environment variable TUTS whose value is equal to /Users. In order to change that value in a bash script, we can add these lines to the script.
sed 's@PPP@'"$TUTS"'@'
Now if we run the above script, and type PPP, then instead of printing PPP back, we will be able to print the value of the environment variable.
immukul@192 linux-questions-code % ./sss.sh
PPP
/Users
Find the union of two NumPy arrays - GeeksforGeeks

05 Sep, 2020
To find union of two 1-dimensional arrays we can use function numpy.union1d() of Python Numpy library. It returns unique, sorted array with values that are in either of the two input arrays.
Syntax:
numpy.union1d(array1, array2)

Note The arrays given in input are flattened if they are not 1-dimensional.
Let’s see examples of how to find union of two arrays.
Example 1:
# import librariesimport numpy as np    arr1 = np.array([10, 20, 30, 40])print("array1 ", arr1)  arr2 = np.array([20, 40, 60, 80])print("array2 ", arr2)  # print union of the two arraysprint("Union of two arrays :", np.union1d(arr1, arr2))
Output:
Example 2:Let’s see example of finding union of a 2-d and a 1-d array. As discussed earlier, if array passed as arguments to function numpy.union1d is 2-dimensional, then they are flattened to 1-dimension.
# import librariesimport numpy as np    # 2-d arrayarr1 = np.array([[1, 2, 3], [4, 5, 6]])print("array1 ")print(arr1)  arr2 = np.array([0, 5, 10])print("array2 ", arr2)  # print union of 2-d array and 1-d arrayprint("Union of two arrays", np.union1d(arr1, arr2))
Output:
Example3:If we want to find union of more than two arrays, then we can find that by using functools.reduce function.
# code to find union of more than two arrays# import librariesimport numpy as npfrom functools import reduce    array = reduce(np.union1d, ([1, 2, 3], [1, 3, 5],                            [2, 4, 6], [0, 0, 0]))print("Union ", array)
Output:
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Split string into list of characters
Redis - Keys Del Command

Redis DEL command is used to delete the existing key in Redis.
Number of keys that were removed.
Following is the basic syntax of Redis DEL command.
redis 127.0.0.1:6379> DEL KEY_NAME 

First, create a key in Redis and set some value in it.
redis 127.0.0.1:6379> SET tutorialspoint redis 
OK

Now, delete the previously created key.
redis 127.0.0.1:6379> DEL tutorialspoint 
(integer) 1


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
What are the loop control statements in C language? Explain with flow chart and program

Loop control statements are used to repeat set of statements. They are as follows −
for loop
while loop
do-while loop
The syntax is as follows −
for (initialization ; condition ; increment / decrement){
   body of the loop
}
The flow chart for loop is as follows −
Initialization is usually an assignment statement that is used to set the loop control variable.
Initialization is usually an assignment statement that is used to set the loop control variable.
The condition is a relational expression that determines when the loop will exit.
The condition is a relational expression that determines when the loop will exit.
The increment/decrement part defines how the loop control variable will change each time loop is repeated.
The increment/decrement part defines how the loop control variable will change each time loop is repeated.
Loop continues to execute as long as the condition is true.
Loop continues to execute as long as the condition is true.
Once the condition is false, program continues with the next statement after for loop.
Once the condition is false, program continues with the next statement after for loop.
Following is the C program for loop control statement −
 Live Demo
#include<stdio.h>
main( ){
   int k;
   for (k = 1; k<=5; k++){
      printf ("%d",k);
   }
}
When the above program is executed, it produces the following result −
1 2 3 4 5
The syntax is as follows −
while (condition){
   body of the loop
}
The flow chart for while loop is as follows −
Initialization is done before the loop.
Loop continues as long as the condition is true.
Increment and decrement part is done within the loop.
Following is the C program for while loop control statement −
 Live Demo
#include<stdio.h>
main( ){
   int k;
   k = 1;
   while (k<=5){
      printf ("%d",k);
      k++;
   }
}
When the above program is executed, it produces the following result −
1 2 3 4 5
The syntax is as follows −
Initialization
do{
   body of the loop
   inc/ dec
} while (condition);
The flow chart for do-while loop is as follows −
Following is the C program for do-while loop control statement −
 Live Demo
#include<stdio.h>
main( ){
   int k;
   k = 1;
   do{
      printf ("%d",k);
      k++;
   }
   while (k <= 5);
}
When the above program is executed, it produces the following result −
1 2 3 4 5
Erlang - Maps

A map is a compound data type with a variable number of key-value associations. Each key-value association in the map is called an association pair. The key and value parts of the pair are called elements. The number of association pairs is said to be the size of the map.
An example of how the Map data type can be used is shown in the following program.
Here we are defining a Map M1 which has 2 mappings. The map_size is an inbuilt function defined in Erlang which can be used to determine the size of the map.
-module(helloworld). 
-export([start/0]). 

start() -> 
   M1 = #{name=>john,age=>25}, 
   io:fwrite("~w",[map_size(M1)]).
The output of the above program will be as follows.
2

Some of the other methods available for maps are as follows.
from_list
This method is used to generate a map from a list.
find
This method is used to find if a particular key exists in the map.
get
This method is used to get the value of a particular key in the map.
is_key
This method is used to determine if a particular key is defined as a key in the map.
keys
This method is used to return all the keys from a map.
merge
This method is used to merge 2 maps.
put
This method is used to add a key value pair to the map.
values
This method is used to return all the values from a map.
remove
This method is used to remove a key value from the map.
 Print
 Add Notes
 Bookmark this page
Asynchronisation Usage in PySimpleGUI - GeeksforGeeks

27 Jul, 2020
We use this design pattern for projects that actually will need to poll or output something on a regular basis. In this case, we’re indicating we want a timeout=10 in our window.readcall. Also, this will cause the call to return a “timeout key” as the event every 10 milliseconds has passed without some GUI thing happening first. The timeout key is PySimpleGUI.TIMEOUT_KEY which is usually written as sg.TIMEOUT_KEY in normal PySimpleGUI code.
Please be cautious when you are using windows with a timeout. You will rarely need to use a timeout=0 . A zero value is a non-blocking call, so we need not try to abuse this design pattern.A short note about timers is that this is not a good design for a stopwatch as it can easily drift. This would never pass for a nice solution in a bit of commercial code. For better accuracy, we should always get the actual time from a reputable source, maybe from the operating system. We can use that as what you use to measure and display the time.
To understand it, we will implement a Stopwatch in Python using PySimpleGUI.
import PySimpleGUI as sg  sg.theme('SandyBeach')  layout = [  [sg.Text('Stopwatch', size =(20, 2), justification ='center')],            [sg.Text(size =(10, 2), font =('Arial', 20), justification ='center', key ='-OUTPUT-')],            [sg.T(' ' * 5), sg.Button('Start / Stop', focus = True), sg.Quit()]]  window = sg.Window('Stopwatch Timer', layout)  timer_running, counter = True, 0  # Event Loopwhile True:        # Please try and use as high of a timeout value as you can                                   event, values = window.read(timeout = 10)       # if user closed the window using X or clicked Quit button    if event in (None, 'Quit'):                     break    elif event == 'Start / Stop':        timer_running = not timer_running    if timer_running:        window['-OUTPUT-'].update('{:02d}:{:02d}.{:02d}'.format((counter // 100) // 60,                                                  (counter // 100) % 60, counter % 100))        counter += 1window.close()
Output
Python-gui
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
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
File Handling in Objective-C

File handling is made available with the help of class NSFileManager. These examples won't work on online compiler.
 The list of the methods used for accessing and manipulating files is listed below. Here, we have to replace the FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action.
NSFileManager *fileManager = [NSFileManager defaultManager];

//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];

if ([fileManager fileExistsAtPath:@""] == YES) {
   NSLog(@"File exists");
}    
if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
   NSLog(@"Same content");
}
if ([fileManager isWritableFileAtPath:@"FilePath"]) {
   NSLog(@"isWritable");
}

if ([fileManager isReadableFileAtPath:@"FilePath"]) {
   NSLog(@"isReadable");
}

if ( [fileManager isExecutableFileAtPath:@"FilePath"]) {
   NSLog(@"is Executable");
}
if([fileManager moveItemAtPath:@"FilePath1" 
   toPath:@"FilePath2" error:NULL]) {
      NSLog(@"Moved successfully");
   }
if ([fileManager copyItemAtPath:@"FilePath1" 
   toPath:@"FilePath2"  error:NULL]) {
      NSLog(@"Copied successfully");
   }
if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
   NSLog(@"Removed successfully");
}
NSData *data = [fileManager contentsAtPath:@"Path"];
[fileManager createFileAtPath:@"" contents:data attributes:nil];
We have successfully learnt on the various file access and manipulation techniques and it's now your time to do various operations on the files and know the usage of files.

    18 Lectures 
     1 hours 

 PARTHA MAJUMDAR

    6 Lectures 
     25 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
MySQL stored procedure to return a column value?

Let us first create a table −
mysql> create table DemoTable
   -> (
   -> Id int,
   -> Score int
   -> );
Query OK, 0 rows affected (0.69 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1,858858686);
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable values(2,9900554);
Query OK, 1 row affected (0.22 sec)

mysql> insert into DemoTable values(3,646565667);
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+-----------+
| Id   | Score     | 
+------+-----------+
| 1    | 858858686 |
| 2    | 9900554   |
| 3    | 646565667 |
+------+-----------+
3 rows in set (0.00 sec)
Following is the MySQL stored procedure −
mysql> DELIMITER //
mysql> CREATE PROCEDURE Test_StoredProcedure(in id INT, OUT scoreValue INT)
-> BEGIN
-> SELECT Score
-> INTO scoreValue
-> FROM DemoTable tbl
-> WHERE tbl.Id = id;
-> END
-> //
Query OK, 0 rows affected (0.18 sec)
mysql> DELIMITER ;
Now, call the stored procedure with the help of call command and store the output into a variable name called ‘@result’ −
mysql> call Test_StoredProcedure(2,@result);
Query OK, 1 row affected (0.00 sec)
Now display the variable value using select statement −
mysql> select @result;
This will produce the following output −
+---------+
| @result |
+---------+
| 9900554 |
+---------+
1 row in set (0.00 sec)
C library function - fseek()

The C library function int fseek(FILE *stream, long int offset, int whence) sets the file position of the stream to the given offset.
Following is the declaration for fseek() function.
int fseek(FILE *stream, long int offset, int whence)
stream − This is the pointer to a FILE object that identifies the stream.
stream − This is the pointer to a FILE object that identifies the stream.
offset − This is the number of bytes to offset from whence.
offset − This is the number of bytes to offset from whence.
whence − This is the position from where offset is added. It is specified by one of the following constants −
whence − This is the position from where offset is added. It is specified by one of the following constants −
SEEK_SET
Beginning of file
SEEK_CUR
Current position of the file pointer
SEEK_END
End of file
This function returns zero if successful, or else it returns a non-zero value.
The following example shows the usage of fseek() function.
#include <stdio.h>

int main () {
   FILE *fp;

   fp = fopen("file.txt","w+");
   fputs("This is tutorialspoint.com", fp);
  
   fseek( fp, 7, SEEK_SET );
   fputs(" C Programming Language", fp);
   fclose(fp);
   
   return(0);
}
Let us compile and run the above program that will create a file file.txt with the following content. Initially program creates the file and writes This is tutorialspoint.com but later we had reset the write pointer at 7th position from the beginning and used puts() statement which over-write the file with the following content −
This is C Programming Language
Now let's see the content of the above file using the following program −
#include <stdio.h>

int main () {
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1) {
      c = fgetc(fp);
      if( feof(fp) ) {
         break;
      }
      printf("%c", c); 
   }
   fclose(fp);
   return(0);
}
Let us compile and run the above program to produce the following result −
This is C Programming Language


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to save a canvas as PNG in Selenium?

We can save a canvas as png in Selenium. We shall first identify the canvas with the help of any locators like xpath, css, and so on. Then obtain the value of src attribute with the getAttribute method.
We shall build an URL in java with the class URL and have a BufferedImage via ImageIOclass. Then utilize the same class to save the canvas with the png extension in a location.
Let us try to save the below image within the project folder.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
public class SaveCanvas{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify canvas
      WebElement l = driver.findElement(By.xpath("//img[@title='Tutorialspoint']"));
      // get src value of element
      String v = l.getAttribute("src");
      // creating URL
      URL i = new URL(v);
      //having BufferedImage with ImageIO class
      BufferedImage s = ImageIO.read(i);
      // save image in location with .png extension
      ImageIO.write(s, "png", new File("Logo.png"));
      driver.close();
   }
}
Logo.png file gets created within the project folder.
Python | Equate two list index elements

20 Mar, 2019
Sometimes we need to link two list from the point of view of their index elements and this kind of problem comes mostly in places where we need to display in formatted form the linkage of two lists with one another. This a very specific problem, but can be useful whenever we need a possible solution. Let’s discuss certain ways in which this can be done.
Method #1 : Using formatting + tuple()The string formatting can be used to specify the way we need to output the list and the task of pairing the like indices can be done with the help of tuple function.
# Python3 code to demonstrate# Equate two list index elements# using formatting + tuple()  # initializing lists test_list1 = ['GeeksforGeeks', 'is', 'best']test_list2 = ['1', '2', '3']  # printing original lists print("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # using formatting + tuple() to# Equate two list index elementstemp = len(test_list1) * '% s = %% s, 'res = temp % tuple(test_list1) % tuple(test_list2)  # printing resultprint ("The paired elements string is : " + res)
The original list 1 is : ['GeeksforGeeks', 'is', 'best']
The original list 2 is : ['1', '2', '3']
The paired elements string is : GeeksforGeeks = 1, is = 2, best = 3, 

 
Method #2 : Using join() + zip()These two methods can also combine to achieve this particular task, the join function can be used to extend the format logic to all indices and construct a string, zip function pairs the like index elements from both the tuples.
# Python3 code to demonstrate# Equate two list index elements# using join() + zip()  # initializing lists test_list1 = ['GeeksforGeeks', 'is', 'best']test_list2 = ['1', '2', '3']  # printing original lists print("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # using join() + zip() to# Equate two list index elementsres = ', '.join('% s = % s' % i for i in zip(test_list1, test_list2))  # printing resultprint ("The paired elements string is : " + res)
The original list 1 is : ['GeeksforGeeks', 'is', 'best']
The original list 2 is : ['1', '2', '3']
The paired elements string is : GeeksforGeeks = 1, is = 2, best = 3, 

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Check if string starts with any element in list

29 Dec, 2019
While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string starts with any of the matching strings. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using filter() + startswith()The combination of the above function can help to perform this particular task. The filter method is used to check for each word and startswith method tests for the prefix logic at target list.
# Python3 code to demonstrate# Prefix tests in Strings# using filter() + startswith()  # initializing string test_string = "GfG is best"  # initializing prefix listpref_list = ['best', 'GfG', 'good']  # printing original string print("The original string : " + str(test_string))  # using filter() + startswith()# Prefix tests in Stringsres = list(filter(test_string.startswith, pref_list)) != []  # print resultprint("Does string start with any prefix list sublist ? : " + str(res))
The original string : GfG is best
Does string start with any prefix list sublist ? : True

 
Method #2 : Using startswith()As improvement to the above method, it is not always necessary to include filter method for comparison. This task can be handled solely by supplying a prefix check list as argument to startswith method as well.
# Python3 code to demonstrate# Prefix tests in Strings# using startswith()  # initializing string test_string = "GfG is best"  # initializing prefix listpref_list = ['best', 'GfG', 'good']  # printing original string print("The original string : " + str(test_string))  # using startswith()# Prefix tests in Stringsres = test_string.startswith(tuple(pref_list))  # print resultprint("Does string start with any prefix list sublist ? : " + str(res))
The original string : GfG is best
Does string start with any prefix list sublist ? : True

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

12 Dec, 2019
Prerequisites:
File Objects in Python
Reading and Writing to files in Python
Truncate() method truncate the file’s size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed. Note that if a specified size exceeds the file’s current size, the result is platform-dependent: possibilities include that the file may remain unchanged, increase to the specified size as if zero-filled, or increase to the specified size with undefined new content.To truncate the file, you can open the file in append mode or write mode.
Syntax:
fileObject.truncate(size)

Example:See the below image for file size.
Let’s change the file size to 100 bytes.
# Python program to demonstrate# truncate() method  fp = open('file1.txt', 'w')  # Truncates the file to specified# sizefp.truncate(100)  # Closing filesfp.close()
Output:
In the above approaches, every time the file is opened it is needed to be closed explicitly. If one forgets to close the file, it may introduce several bugs in the code, i.e. many changes in files do not go into effect until the file is properly closed. To prevent this with statement can be used. with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes code cleaner. There is no need to call file.close() when using with statement. The with statement itself ensures proper acquisition and release of resources.
Let’s change the above file to 50 bytes
# Python program to demonstrate# truncate method using with statement  with open('file1.txt', 'w') as fp:    fp.truncate(50)
Output:
Note: To know more about with statement click here.
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
time.Time.Add() Function in Golang with Examples

19 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Add() function in Go language is used to add the stated time and duration. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func (t Time) Add(d Duration) Time

Here, “t” is the stated time and “d” is the duration that is to be added to the time stated.
Return Value: It returns the result of adding stated t and d.
Example:
// Golang program to illustrate the usage of// Time.Add() function  // Including main packagepackage main  // Importing fmt and timeimport "fmt"import "time"  // Calling mainfunc main() {      // Declaring time in UTC    t := time.Date(2020, 11, 9, 7, 0, 0, 0, time.UTC)      // Declaring durations    d1 := t.Add(time.Second * 4)    d2 := t.Add(time.Minute * 2)    d3 := t.Add(time.Hour * 1)    d4 := t.Add(time.Hour * 22 * 7)      // Prints output    fmt.Printf("%v\n", t)    fmt.Printf("%v\n", d1)    fmt.Printf("%v\n", d2)    fmt.Printf("%v\n", d3)    fmt.Printf("%v", d4)}
Output:
2020-11-09 07:00:00 +0000 UTC
2020-11-09 07:00:04 +0000 UTC
2020-11-09 07:02:00 +0000 UTC
2020-11-09 08:00:00 +0000 UTC
2020-11-15 17:00:00 +0000 UTC

Here, the output returned is in UTC as defined above.
GoLang-time
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js Buffer.write() Method

13 Oct, 2021
The Buffer.write() method writes the specified string into a buffer, at the specified position. If buffer did not contain enough space to fit the entire string, only part of string will be written. However, partially encoded characters will not be written.
Syntax:
buffer.write( string, offset, length, encoding )
Parameters: This method accept four parameters as mentioned above and described below:
string: It holds the string to write into the buffer.
offset: It holds the number of bytes to skip before starting to write the string. Its default value is 0.
length: It holds the number of bytes to write into buffer. The default value is buffer.length-offset.
encoding: It holds the encoding of the value. The default value is ‘utf8’.
Return Value: This method returns a number that represents the number of bytes written.
Example 1:
// Node.js program to demonstrate the  // Buffer.write() method   // Create a buffervar buf = Buffer.from('GeeksforGeeks');  buf.write('EE', 1);   console.log(buf.toString());
Output:
GEEksforGeeks
Example 2:
// Node.js program to demonstrate the  // Buffer.write() method   // Create a bufferconst buf = Buffer.allocUnsafe(100);   const len = buf.write('GeeksforGeeks', 2, 5, 'utf8');   console.log(len.toString());
Output:
5
Note: The above program will compile and run by using the node index.js command.
Reference: https://www.geeksforgeeks.org/node-js-buffer-allocunsafe-method/
Node.js-Buffer-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
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 ?
Differences between Functional Components and Class Components in React
pieslice() function in C

05 Dec, 2019
pieslice() draws and fills a pie slice with center at (x, y) and given radius r. The slice travels from s_angle to e_angle which are starting and ending angles for the pie slice. The angles for pie-slice are given in degrees and are measured counterclockwise.
Syntax :
void pieslice(int x, int y, int s_angle, 
                    int e_angle, int r);

where,
(x, y) is center of the circle.
r is the radius of the circle.
s_angle and e_angle are the starting 
and ending angles respectively.

Examples :
Input : x = 300, y = 300, s_angle = 0 ,
        e_angle = 120, r = 150
Output :

Input : x = 300, y = 300, s_angle = 30 ,
        e_angle = 100, r = 200
Output :

Below is the implementation for the pieslice() function:
// C Implementation for drawing pieslice#include <graphics.h>  // driver codeint main(){    // gm is Graphics mode which     // is a computer display mode     // that generates image using pixels.    // DETECT is a macro defined in    // "graphics.h" header file    int gd = DETECT, gm;      // initgraph initializes the     // graphics system by loading a     // graphics driver from disk    initgraph(&gd, &gm, "");      // pieslice function    pieslice(300, 300, 0, 120, 150);      getch();      // closegraph function closes the     // graphics mode and deallocates all     // memory allocated by graphics system .    closegraph();      return 0;}
Output :


Akanksha_Rai
C-Library
computer-graphics
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
'this' pointer in C++
Ways to copy a vector in C++
Understanding "extern" keyword in C
Arrow operator -> in C/C++ with Examples
SVG <g> Element

16 Jun, 2022
The SVG <g> element is a container used to group other SVG elements.
Transformations applied to the <g> element are also performed on its child elements, and its attributes are inherited by its children.
Syntax:
<g attributes="" >
    <elements>
</g>
Attributes:
core Attributes: These attributes are core attributes like id, etc.
styling Attributes: These attributes define styling, exp, class, style.
conditional Attributes: These attributes are condition-based, exp systemLanguage.
presentation Attributes: Attributes used to give presentation effects, exp color,clip-rule, etc.
Example 1: Making green consecutive circles inheriting attributes from the <g> element.
html
<!DOCTYPE html><html> <body>    <svg width="1200" height="1200">        <g fill="white" stroke="green" stroke-width="10">            <circle cx="40" cy="40" r="25" />            <circle cx="80" cy="40" r="25" />            <circle cx="120" cy="40" r="25" />            <circle cx="160" cy="40" r="25" />        </g>    </svg></body> </html>
Output:
 
Example 2: Making rectangles with the same inherited properties. 
html
<!DOCTYPE html><html> <body>    <svg width="1200" height="1200">        <defs>            <linearGradient id="gfgStr">                <stop offset="50%"   stop-color="green" />                <stop offset="100%" stop-color="blue" />            </linearGradient>        </defs>               <g fill="white" stroke="url(#gfgStr)" stroke-width="15">            <rect width="400" height="200" />            <rect width="200" height="200" />            <rect width="200" height="100" />        </g>    </svg></body> </html>
Output:
Browsers Supported: The following browsers are supported by this SVG element:
Chrome 1 and above
Edge 12 and above
Firefox 1.5 and above
Safari 3.1 and above
Internet Explorer 9 and above
Opera 8 and above
kumargaurav97520
HTML-SVG
SVG-Element
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Form validation using jQuery
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
base64.encodestring(s) in Python

22 Apr, 2020
With the help of base64.encodestring(s) method, we can encode the string using base64 encoded data into the binary form.
Syntax : base64.encodestring(string)
Return : Return the encoded string.
Example #1 :In this example we can see that by using base64.encodestring(s) method, we are able to get the encoded string which can be in binary form by using this method.
# import base64from base64 import encodestring  s = b'GeeksForGeeks'# Using base64.encodestring(s) methodgfg = encodestring(s)  print(gfg)
Output :
b’R2Vla3NGb3JHZWVrcw==\n’
Example #2 :
# import base64from base64 import encodestring  s = b'I love python'# Using base64.encodestring(s) methodgfg = encodestring(s)  print(gfg)
Output :
b’SSBsb3ZlIHB5dGhvbg==\n’
Python base64-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Replace values of a Factor in R Programming - recode_factor() Function - GeeksforGeeks

01 Jun, 2020
Factors in R programming are kind of data structures that stores categorical data i.e., levels and can have any type of data (integer, string, etc). recode_factor() function in R Language is used to replace certain values in a factor. To use recode_factor() function, dplyr package is required.
Syntax:recode_factor(x, ..., .ordered = TRUE)
Parameters:x: represents factor object of a vector... :represents replacements.ordered: creates an ordered factor if TRUE.
Example 1:
# Required for recode_factor() functioninstall.packages("dplyr")  # Loading packagelibrary(dplyr)  # Create factor objectf <- as.factor(c("a", "b", "c"))  # Print factor objectcat("Before replacement:\n")print(f)  # Replacing single valuecat("After replacement:\n")print(recode_factor(f, "a" = "x"))
Output:
Before replacement:
[1] a b c
Levels: a b c

After replacement:
[1] x b c
Levels: x b c
Example 2:
# Required for recode_factor() functioninstall.packages("dplyr")  # Loading packagelibrary(dplyr)  # Create factor objectf <- as.factor(c("a", "b", "c"))  # Print factor objectcat("Before replacement:\n")print(f)  # Replacing multiple valuescat("After replacement:\n")print(recode_factor(f, "a" = "x", "b" = "y"))
Output:
Before replacement:
[1] a b c
Levels: a b c

After replacement:
[1] x y c
Levels: x y c
R Factor-Function
R-Factors
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 filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
How to import an Excel File into R ?