code-rag-bench/online-tutorials huggingface dataset:
Send Chrome Notification Using Python - GeeksforGeeks

29 Jun, 2021
In this article, we are going to see how to send a Chrome notification from your PC to a phone or several devices in this article. We may send messages, links, and other content. For this, we’ll use Python’s notify2 module and its various capabilities, which will help us in delivering messages to many devices.
notify2 is a Python module that is used to deliver notifications and may be used for a variety of applications. For example, if we are creating a news notifier and you want to view the changes on your smartphone rather than your local workstation, we can easily use this module.
pip install notify2
Step 1: Create a program that takes you to subscribe to the webapps.
Python3
from notify_run import Notify  notify = Notify()notify.register()
Output:
You will be given a link and a QR code; click on the link or scan the QR code to proceed.
Step 2: When you click on the link, you will be presented with the following interface:
Step 3: Simply click on the subscribe on this device button, and if you want alerts on other devices, the link is provided at the bottom; simply go to your device’s chrome, copy this URL, and then click on the subscribe on this device button.
Step 4: Now write a Python program to send the notification.
For sending alerts, the send function is utilized. Simply write a message within the send function and execute the script; you will be alerted by Chrome as well as any devices to which you have subscribed.
Python3
from notify_run import Notify  notify = Notify()notify.send("Any Message you want to send")
Output: 
You will notify by Chrome after you run the script
After you run the script, the message will also be shown on the web:
Other devices, like the phone:
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
What are the most important tags for an HTML Document?

HTML has various tags to format content, heading, align content, add sections, etc to a website. The most important tags for an HTML document is doctype, <html>, <head> and <body>.
doctypedoctype is the doctype declaration type. It is used for specifying which version of HTML the document is using.
<!DOCTYPE html>
<html>
The HTML <html> tag is the container for all other HTML elements except for the
<!DOCTYPE html> tag, which is located before the opening <html> tag. All other HTML elements are nested between the <html> and </html> tags.<head>The HTML <head> tag is used for indicating the head section of the HTML document. Tags included inside head tags are not displayed on browser window. The <title>...</title> tag goes inside the <html>...</html>
<head>
   <title>HTML Document</title>
</head>
<body> 
The HTML <body> tag shows the main content section of the HTML document.
PHP ob_get_clean() Function - GeeksforGeeks

17 Mar, 2021
The ob_get_clean() function is an in-built PHP function that is used to clean or delete the current output buffer. It’s also used to get the output buffering again after cleaning the buffer. The ob_get_clean() function is the combination of both ob_get_contents() and ob_end_clean().
Syntax:
string|false ob_get_clean();
Parameters: It does not accept any parameter.
Return value: This function returns the contents of the output buffer and end output buffering. If output buffering is not active, then it returns false.
Example 1: Below is a simple example of ob_get_clean() functionality.
PHP
<?php   // Create an output bufferob_start();  echo "Welcome to GeeksforGeeks";  $out = ob_get_clean();$out = strtolower($out);  var_dump($out);?>
Output:
string(24) "Welcome to GeeksforGeeks"
Example 2:
PHP
<?php  // Declare a class class GFG {    public function GFG_Funcion() {        $variable = array(            "A" => "Welcome",            "B" => "GeeksforGeeks",            "C" => "Geeks"        );          foreach ($variable as $key => $value) {            echo $key . " => " . $value;            echo "<br/>";        }    }}  ob_start();  // Creating an object of class GFG$object = new GFG();  // Calling function$object -> GFG_Funcion();  $saved_ob_level = ob_get_level();  $start_ob_level="";  while (ob_get_level() > $start_ob_level) {    ob_end_flush();}  // Now, it is the final output buffer$content = ob_get_clean();  ?>
Output:
A => Welcome
B => GeeksforGeeks
C => Geeks
Reference: https://www.php.net/manual/en/function.ob-get-clean.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
How to generate PDF file using PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
Java Program for Recursive Bubble Sort

Following is the Java Program for Recursice Bubble Sort −
 Live Demo
import java.util.Arrays;
public class Demo{
   static void bubble_sort(int my_arr[], int len_arr){
      if (len_arr == 1)
      return;
      for (int i=0; i<len_arr-1; i++)
      if (my_arr[i] > my_arr[i+1]){
         int temp = my_arr[i];
         my_arr[i] = my_arr[i+1];
         my_arr[i+1] = temp;
      }
      bubble_sort(my_arr, len_arr-1);
   }
   public static void main(String[] args){
      int my_arr[] = {45, 67, 89, 31, 63, 0, 21, 12};
      bubble_sort(my_arr, my_arr.length);
      System.out.println("The array after implementing bubble sort is ");
      System.out.println(Arrays.toString(my_arr));
   }
}
The array after implementing bubble sort is
[0, 12, 21, 31, 45, 63, 67, 89]
A function named 'Demo' contains the function to perform bubble sort. If the length of the array is 1, then the array is returned. Otherwise, the array is iterated over and if the element at the first place is greater than the element at the next position, the elements are swapped.
After the first pass, the largest element would have been fixed, and the bubble sort is called on all elements except the largest once. In the main function, the array is defined and it is passed as a parameter to the bubble sort function.
How to image copy the entire DB2 table TAB1 into a dataset?

The image copy allows us to download or copy the DB2 table into a mainframe dataset. There are two types of Image copy i.e. Full image copy and Incremental image copy. The full image copy is used to take the backup of the entire table. The incremental image copy refers to the differential backup. In order to take the full image copy of the DB2 table we can use the below JCL step.
//STEP1 EXEC DSNUPROC
//SYSCOPY DD DSN=TEST.TAB1.COPY,UNIT=SYSDA,VOL=SER=CPY01I,
// SPACE=(CYL,(15,1)),DISP=(NEW,CATLG,CATLG)
//SYSOUT DD SYSOUT=*
//SYSIN DD *
COPY TABLESPACE TAB1SPAC
/*
We can use the utility DSNUPROC for this purpose. The SYSCOPY will have the dataset in which we want to take the backup of the table. The SYSIN is populated with the parameter COPY TABLESPACE which is followed by the name of tablespace where the table TAB1 resides.
How to implement Dictionary with Python3

Dictionaries in python are a type of data structure that map keys to values as a key-value pair. They are one of the frequently used data structures and have many interesting properties. They are presented by enclosing them in a pair of curly brace like below.
dict = {'day1':'Mon' ,'day2':'Tue','day3':'Wed'}
The elements or key-value pairs in the dictionary are represented within single quotes and separated by a colon.
We create a dictionary by assigning values written in the form of a key.
Dict1 = {'day1':'Mon' ,'day2':'Tue','day3':'Wed'}
print(type(dict1))
print(dict1)

# Using the dict() method
dict2 =dict({('day1','Mon'),('day2','Tue'),('day3','Wed')})
print(type(dict2))
print(dict2)
Running the above code gives us the following result −
{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
Dictionaries can also be nested. Means, we have a dictionary as a value for one of the keys inside another dictionary. In the below example we have Saturday and Sunday marked as elements of an inner dictionary which is nested inside an outer dictionary.
dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed','weekend':{'d1':'Saturday','d2':'Sunday'}}
print(dict)
Running the above code gives us the following result:
{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed', 'weekend': {'d1': 'Saturday', 'd2': 'Sunday'}}
To access the elements of a dictionary, we can use the square brackets along with the key to obtain its value. We can also use the get() method to get the values for the dictionary elements.
dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed','weekend':{'d1':'Saturday','d2':'Sunday'}}
print(dict['day2'])
print(dict['weekend'])
print(dict.get('day3'))
Running the above code gives us the following result:
Tue
{'d1': 'Saturday', 'd2': 'Sunday'}
Wed
We add new elements to a dictionary by adding a new key value pair. We can also add another dictionary as an element to create a nested dictionary.
dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
dict['day4']='Thu'
dict['day5']='Fri'
print(dict)
Running the above code gives us the following result:
{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed', 'day4': 'Thu', 'day5': 'Fri'}
We can update a dictionary by adding a new entry or a key-value pair and modifying an existing entry. We have already seen the addition of new elements to the dictionary above. Now we will see the modification of existing entry.Here we simply take the key and assign the new value to the element.
dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
dict['day1']='Monday'
dict['day2']='Tuesday'
print(dict)
Running the above code gives us the following result:
{'day1': 'Monday', 'day2': 'Tuesday', 'day3': 'Wed'}
The specific elements of a dictionary can be deleted by using the del keyword. It can also be used to delete the entire dictionary. There is also the clear() method which can be used to remove elements from the entire dictionary.
dict = {'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
print(dict)
del dict['day3']
print(dict)
dict.clear()
print(dict)
Running the above code gives us the following result:
{'day1': 'Mon', 'day2': 'Tue', 'day3': 'Wed'}
{'day1': 'Mon', 'day2': 'Tue'}
{}
Python - Create progress bar using tqdm module - GeeksforGeeks

22 Apr, 2020
In this article we will see how to make progress bar with the help of tqdm module. A progress bar is a graphical control element used to visualize the progression of an extended computer operation, such as a download, file transfer, or installation. Sometimes, the graphic is accompanied by a textual representation of the progress in a percent format.
Required Modules :
Tqdm : Tqdm package is one of the more comprehensive packages for progress bars with python and is handy for those instances you want to build scripts that keep the users informed on the status of your application.
pip install tqdm
Time : This module provides various time-related functions, it is part of python’s standard library.
# importing modulesfrom tqdm import trangefrom time import sleep   # creating loopfor i in trange(10, desc ="loop "):                   # slowing the for loop        sleep(0.1)
Output :
Example 2:
# importing modulesfrom tqdm import tnrangefrom time import sleep  # creating loopfor i in tnrange(2, desc ="loop 1"):          # creating nested loop    for j in tnrange(5, desc ="loop 2"):                  # slowing the for loop        sleep(0.2)
Output :
Example 3:
# importing modulesimport timeimport sysfrom tqdm import trange  # random functiondef random_task():    time.sleep(0.5)      # another random functiondef another_random_task():    time.sleep(0.2)  # Outer loopfor i in trange(3, file=sys.stdout, desc='Outer loop'):    random_task()          # inner loop    for j in trange(5,file=sys.stdout, desc='Inner loop'):        another_random_task()
Output :
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
sum() function in Python
*args and **kwargs in Python
C# | Boolean.Equals(Boolean) Method - GeeksforGeeks

28 Jun, 2021
This method is used to return a value indicating whether this instance is equal to a specified Boolean object.Syntax:  
public bool Equals (bool obj);
Here, obj is a boolean value to compare to this instance.Return Value: This method returns true if obj has the same value as this instance otherwise it returns false.Below programs illustrate the use of Boolean.Equals(bool obj) Method:Example 1: 
CSHARP
// C# program to demonstrate// Boolean.Parse(String)// Methodusing System; class GFG {     // Main Method    public static void Main()    {         // passing different values        // to the method to check        check(true, true);        check(true, false);        check(false, true);        check(false, false);    }     // Defining check method    public static void check(bool input1, bool input2)    {         // declaring bool variable        bool val;         // getting parsed value        val = input1.Equals(input2);         // checking the equivalency        if (val == true)            Console.WriteLine("{0} is equal to {1}",                                    input1, input2);         else            Console.WriteLine("{0} is not equal to {1}",                                        input1, input2);    }}
True is equal to True
True is not equal to False
False is not equal to True
False is equal to False
 
Example 2: 
CSHARP
// C# program to demonstrate// Boolean.Parse(String)// Methodusing System; class GFG {     // Main Method    public static void Main()    {         // Declaring the variable        // input1 and input2        bool input1, input2;         // initializing the variables        input1 = true;        input2 = false;         // checking the equality        bool val = input1.Equals(input2);         // checking the equivalency        if (val == true)            Console.WriteLine("input1 is equal to input2");         else            Console.WriteLine("input1 is not equal to input2");    }}
input1 is not equal to input2
 
Note: This method implements the System.IEquatable<T> interface, and performs slightly better than Equals because it does not have to convert the obj parameter to an object.Reference:  
https://docs.microsoft.com/en-us/dotnet/api/system.boolean.equals?view=netframework-4.7.2#System_Boolean_Equals_System_Boolean_
 
sweetyty
CSharp Boolean Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
C# | Constructors
Get MySQL maximum value from 3 different columns?

To get the maximum value from three different columns, use the GREATEST() function.
The syntax is as follows
SELECT GREATEST(yourColumnName1,yourColumnName2,yourColumnName3) AS anyAliasName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows
mysql> create table MaxOfThreeColumnsDemo
   -> (
   -> First int,
   -> Second int,
   -> Third int
   -> );
Query OK, 0 rows affected (0.73 sec)
Insert some records in the table using insert command.
The query is as follows
mysql> insert into MaxOfThreeColumnsDemo values(30,90,60);
Query OK, 1 row affected (0.16 sec)
mysql> insert into MaxOfThreeColumnsDemo values(100,40,50);
Query OK, 1 row affected (0.20 sec)
mysql> insert into MaxOfThreeColumnsDemo values(101,290,150);
Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement.
The query is as follows
mysql> select *from MaxOfThreeColumnsDemo;
The following is the output
+-------+--------+-------+
| First | Second | Third |
+-------+--------+-------+
| 30    | 90     | 60    |
| 100   | 40     | 50    |
| 101   | 290    | 150   |
+-------+--------+-------+
3 rows in set (0.00 sec)
Here is the query to find the greatest of three columns
mysql> select greatest(First,Second,Third) AS MAXValueOfThreeColumns from MaxOfThreeColumnsDemo;
The following is the output
+------------------------+
| MAXValueOfThreeColumns |
+------------------------+
| 90                     |
| 100                    |
| 290                    |
+------------------------+
3 rows in set (0.00 sec)
Data Types in C

Variables in C are associated with data type. Each data type requires an amount of memory and performs specific operations.
There are some common data types in C −
int − Used to store an integer value.
int − Used to store an integer value.
char − Used to store a single character.
char − Used to store a single character.
float − Used to store decimal numbers with single precision.
float − Used to store decimal numbers with single precision.
double − Used to store decimal numbers with double precision.
double − Used to store decimal numbers with double precision.
The following table displays data types in C language −
Here is the syntax of datatypes in C language,
data_type variable_name;
Here is an example of datatypes in C language,
 Live Demo
#include >stdio.h>
int main() {
   // datatypes
   int a = 10;
   char b = 'S';
   float c = 2.88;
   double d = 28.888;
   printf("Integer datatype : %d\n",a);
   printf("Character datatype : %c\n",b);
   printf("Float datatype : %f\n",c);
   printf("Double Float datatype : %lf\n",d);
   return 0;
}
Here is the output,
Integer datatype : 10
Character datatype : S
Float datatype : 2.880000
Double Float datatype : 28.888000
Batch Script - String length

In DOS scripting, there is no length function defined for finding the length of a string. There are custom-defined functions which can be used for the same. Following is an example of a custom-defined function for seeing the length of a string.
@echo off
set str = Hello World
call :strLen str strlen
echo String is %strlen% characters long
exit /b

:strLen
setlocal enabledelayedexpansion

:strLen_Loop
   if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
(endlocal & set %2=%len%)
goto :eof
A few key things to keep in mind about the above program are −
The actual code which finds the length of string is defined in the :strLen block.
The actual code which finds the length of string is defined in the :strLen block.
The length of the string is maintained in the variable len.
The length of the string is maintained in the variable len.
The above command produces the following output.
11

 Print
 Add Notes
 Bookmark this page
How to implement Polymorphism in JavaScript?

Polymorphism is one of the tenets of Object Oriented Programming (OOP). It helps to design objects in such a way that the they can share or override any behavior with the specific provided objects. Polymorphism takes advantage of inheritance in order to make this happen.
In the following example child objects such as 'cricket' and 'tennis' have overridden the 'select' method called from parent object 'game' and returned a new string respectively as shown in the output. Whereas another child object 'football', instead of overriding the select method, shared(inherited) the method and displayed the parent string as shown in the output.
Live Demo
<html>
<body>
<script>
   var game = function () {}
      game.prototype.select = function()
   {
      return " i love games and sports"
   }
   var cricket = function() {}
   cricket.prototype = Object.create(game.prototype);
   cricket.prototype.select = function()                //  overridden the select method to display      {                                                         new string.  
      return "i love cricket"
   }
   var tennis = function() {}
   tennis.prototype = Object.create(game.prototype);  // overridden the select method to display new
   tennis.prototype.select = function()                  string              
   {
      return "i love tennis"
   }
   var football = function() {}
   football.prototype = Object.create(game.prototype);  // shared parent property
   var games = [new game(), new cricket(), new tennis(), new football()];
   games.forEach(function(game){
      document.write(game.select());
    document.write("</br>");
   });
</script>
</body>
</html>
i love games and sports
i love cricket
i love tennis
i love games and sports
MariaDB - SQL Injection Protection

The simple act of accepting user input opens the door to exploits. The problem stems primarily from the logical management of data, but luckily, it is fairly easy to avoid these major flaws.
Opportunities for SQL injection typically occur on users entering data like a name, and the code logic failing to analyze this input. The Code, instead, allows an attacker to insert a MariaDB statement, which will run on the database.
Always consider data entered by users, suspect and are in need of strong validation prior to any processing. Perform this validation through pattern matching. For example, if the expected input is a username, restrict entered characters to alphanumeric chars and underscores, and to a certain length. Review an example given below −
if(check_match("/^\w{8,20}$/", $_GET['user_name'], $matches)) {
   $result = mysql_query("SELECT * FROM system_users WHERE user_name = $matches[0]");
} else {
   echo "Invalid username";
}
Also, utilize the REGEXP operator and LIKE clauses in creating input constraints.
Consider all types of necessary explicit control of input such as −
Control the escape characters used.
Control the escape characters used.
Control the specific appropriate data types for input. Limit input to the necessary data type and size.
Control the specific appropriate data types for input. Limit input to the necessary data type and size.
Control the syntax of entered data. Do not allow anything outside of the needed pattern.
Control the syntax of entered data. Do not allow anything outside of the needed pattern.
Control the terms permitted. Blacklist SQL keywords.
Control the terms permitted. Blacklist SQL keywords.
You may not know the dangers of injection attacks, or may consider them insignificant, but they top the list of security concerns. Furthermore, consider the effect of these two entries −
1=1
-or-
*

Code allowing either of those to be entered along with the right command may result in revealing all user data on the database or deleting all data on the database, and neither injection is particularly clever. In some cases, attackers do not even spend time examining holes; they perform blind attacks with simple input.
Also, consider the pattern matching and regular expression tools provided by any programming/scripting language paired with MariaDB, which provide more control, and sometimes better control.
 Print
 Add Notes
 Bookmark this page
Using ControlAggregation in SAPUI5

“ControlAggregation” refers to the target aggregation to which the mapped view is added.
As Specified in the use case below:
"routing": {
   "config": {
      "routerClass": "sap.m.routing.Router",
      "viewType": "XML",
      "viewPath": "sap.ui.demo.nav.view",
      "controlId": "app",
      "controlAggregation": "dummy",
      "transition": "slide",
      "bypassed": {
         "target": "NA"
      }
The views are defined as follows:
<mvc:View
   controllerName="sap.ui.demo.nav.controller.App"
   xmlns="sap.m"
   xmlns:mvc="sap.ui.core.mvc"
   displayBlock="true">
   <App id="sampleApp"/>
</mvc:View>
So here “controlAggregation” is named as 'dummy' but the app is named as SampleApp.
so the target is 'sap.m.SampleApp' and aggregation is named as 'dummy'. Let us take an example here:
routes :[{ pattern:"employee/{id}",
   name:"employee",
   target:"employee"
},
{
   pattern:"department/{id}",
   name :"department",
   target:"department"
}],
targets:{
   employee:{
      viewName:"Employee",
      controlAggregation:"masterPage"
   },
   department"{
      viewName:"Department",
      controlAggregation:"contentPage"
   }
}
So when a user navigates to employee/3, routing engine finds that 'Employee' is the target for this pattern. Then it tries to find the name of the view for that target i.e. 'Employee'. After this, it will determine the control aggregation for this View if any. Here we have it to be “masterPage”. Now the View Engine will render the view inside the “masterPage”.
postqueue - Unix, Linux Command

postqueue [-v] [-c config_dir] -f

postqueue [-v] [-c config_dir] -p

postqueue [-v] [-c config_dir] -s site


The following options are recognized:


This option implements the traditional "sendmail -q" command,
by contacting the Postfix qmgr(8) daemon.


Warning: flushing undeliverable mail frequently will result in
poor delivery performance of all other mail.


Each queue entry shows the queue file ID, message
size, arrival time, sender, and the recipients that still need to
be delivered.  If mail could not be delivered upon the last attempt,
the reason for failure is shown. This mode of operation is implemented
by executing the postqueue(1) command. The queue ID string
is followed by an optional status character:


This option implements the traditional "sendmail -qRsite"
command, by contacting the Postfix flush(8) daemon.







/var/spool/postfix, mail queue

qmgr(8), queue manager
showq(8), list mail queue
flush(8), fast flush service
sendmail(1), Sendmail-compatible user interface
postsuper(1), privileged queue operations



ETRN_README, Postfix ETRN howto





Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
Java Create and Write To Files

To create a file in Java, you can use the createNewFile() method. This method returns a 
boolean value: true if the file was successfully created, and false if the file 
already exists. Note that the method is enclosed in a try...catch 
block. This is necessary because it throws an IOException if an error occurs (if the 
file cannot be created for some reason):
import java.io.File;  // Import the File class
import java.io.IOException;  // Import the IOException class to handle errors

public class CreateFile {
  public static void main(String[] args) {
    try {
      File myObj = new File("filename.txt");
      if (myObj.createNewFile()) {
        System.out.println("File created: " + myObj.getName());
      } else {
        System.out.println("File already exists.");
      }
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

The output will be:
To create a file in a specific directory (requires permission), specify the path of the file and use double backslashes to escape the "\" character (for Windows). On Mac and Linux you can just write the path, like: /Users/name/filename.txt
File myObj = new File("C:\\Users\\MyName\\filename.txt");


Run Example »

In the 
following example, we use the FileWriter class together with its write() method 
to write some text to the file we created in the example above. Note that when you are done writing to the file, 
you should close it 
with the close() method:
import java.io.FileWriter;   // Import the FileWriter class
import java.io.IOException;  // Import the IOException class to handle errors

public class WriteToFile {
  public static void main(String[] args) {
    try {
      FileWriter myWriter = new FileWriter("filename.txt");
      myWriter.write("Files in Java might be tricky, but it is fun enough!");
      myWriter.close();
      System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
      System.out.println("An error occurred.");
      e.printStackTrace();
    }
  }
}

The output will be:
To read the file above, go to the Java Read Files chapter.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Tryit Editor v3.7

Tryit: class in JavaScript
How to remove event handlers in JavaScript?

Javascript provides removeEventListener() method to remove event handlers. An event is handled through addEvenetListener() method. The removeEventListener() method removes event handlers that have been attached with that addEventListener() method.
Live Demo
<html>
<body>
   <h3 id="add">Hover me </h3>
   <p id="remove"> </p>
   <h3>Click this button to stop hovering effect </h3>
   <input type ="button" id="clickIt" onclick="RespondClick()" value ="remove">
   <script>
      const listener = document.getElementById("add");
      listener.addEventListener("mouseover", RespondMouseOver);
      function RespondMouseOver() {
         document.getElementById("remove").innerHTML += 1+ "</br>";
      }
      function RespondClick() {
         listener.removeEventListener("mouseover", RespondMouseOver);
         document.getElementById("remove").innerHTML += 0;
      }
      </script>
</body>
</html>
When we executed the above code we will get the following displayed on the screen
If we hover on the "Hover me" text then 1's will appear. The number of times we hover, the number of times 1's are produced. When we hover the text for 4 times we get the following executed on the screen.
To stop the event handler, we have to click on the "remove" button. After clicking on the remove button we get '0' displayed on the screen and later on even though we hover on the text no 1's will be produced as shown in the figure.
Multiply Strings in C++

Suppose we have two numbers as a string. We have to multiply them and return the result also in a string. So if the numbers are “26” and “12”, then the result will be “312”
To solve this, we will follow these steps −
Taking two arguments x and y it indicates x divides y
if x < -Infinity and y = 1, then return infinity
a := |x|, b := |y| and ans := 0
while a – b >= 0p := 0while a – (left-shifted b (left-shifted 1 p times)) >= 0p := p + 1a := a – (left shift b, p times)ans := ans + left shift 1 p times
p := 0
while a – (left-shifted b (left-shifted 1 p times)) >= 0p := p + 1
p := p + 1
a := a – (left shift b, p times)
ans := ans + left shift 1 p times
if x > 0 is true and y > 0 is also true, then return ans, otherwise return (– ans)
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   string multiply(string num1, string num2);
};
string Solution::multiply(string nums1, string nums2) {
   int n = nums1.size();
   int m = nums2.size();
   string ans(n + m, '0');
   for(int i = n - 1; i>=0; i--){
      for(int j = m - 1; j >= 0; j--){
         int p = (nums1[i] - '0') * (nums2[j] - '0') + (ans[i + j + 1] - '0');
         ans[i+j+1] = p % 10 + '0';
         ans[i+j] += p / 10 ;
      }
   }
   for(int i = 0; i < m + n; i++){
      if(ans[i] !='0')return ans.substr(i);
   }
   return "0";
}
main(){
   Solution ob;
   cout << ob.multiply("28", "25");
}
"26"
"12"
"312"
Python – Group list by first character of string

30 Jan, 2020
Sometimes, we have a use case in which we need to perform the grouping of strings by various factors, like first letter or any other factor. These type of problems are typical to database queries and hence can occur in web development while programming. This article focuses on one such grouping by first letter of string. Let’s discuss certain ways in which this can be performed.
Method #1 : Using next() + lambda + loopThe combination of above 3 functions is used to solve this particular problem by the naive method. The lambda function performs the task of finding like initial character, and next function helps in forward iteration.
# Python3 code to demonstrate# Initial Character Case Categorization# using next() + lambda + loop  # initializing listtest_list = ['an', 'a', 'geek', 'for', 'g', 'free']  # printing original listprint("The original list : " + str(test_list))  # using next() + lambda + loop# Initial Character Case Categorizationutil_func = lambda x, y: x[0] == y[0]res = []for sub in test_list:    ele = next((x for x in res if util_func(sub, x[0])), [])    if ele == []:        res.append(ele)    ele.append(sub)  # print resultprint("The list after Categorization : " + str(res))
The original list : ['an', 'a', 'geek', 'for', 'g', 'free']
The list after Categorization : [['an', 'a'], ['geek', 'g'], ['for', 'free']]

 
Method #2 : Using sorted() + groupby()This particular task can also be solved using the groupby function which offers a conventional method to solve this problem. The sorted function sorts the elements by initial character to be feed to groupby for the relevant grouping.
# Python3 code to demonstrate# Initial Character Case Categorization# using sorted() + groupby()from itertools import groupby  # initializing listtest_list = ['an', 'a', 'geek', 'for', 'g', 'free']  # printing original listprint("The original list : " + str(test_list))  # using sorted() + groupby()# Initial Character Case Categorizationutil_func = lambda x: x[0]temp = sorted(test_list, key = util_func)res = [list(ele) for i, ele in groupby(temp, util_func)]  # print resultprint("The list after Categorization : " + str(res))
The original list : ['an', 'a', 'geek', 'for', 'g', 'free']
The list after Categorization : [['an', 'a'], ['geek', 'g'], ['for', 'free']]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
How to check whether a column value is less than or greater than a certain value in R?

To check whether a column value is less than or greater than a certain value, we can use with function and the output will be a logical vector representing values with TRUE when the condition is satisfied and FALSE when the condition is not satisfied. For example, if we have a column say x of an R data frame df and we want to check whether any of the values in x is greater than 10 or not then it can be done by using with(df,df$x>10).
Consider the below data frame:
Live Demo
> set.seed(1002)
> x1<-rpois(20,5)
> y1<-rpois(20,8)
> z1<-rpois(20,3)
> df1<-data.frame(x1,y1,z1)
> df1
x1 y1 z1
1 5 6 1
2 7 8 2
3 5 9 2
4 3 4 2
5 4 10 3
6 6 6 1
7 10 8 6
8 6 3 6
9 4 12 1
10 8 13 2
11 6 7 4
12 8 9 3
13 5 8 4
14 5 4 3
15 2 7 5
16 4 7 4
17 6 14 3
18 7 6 2
19 8 7 1
20 5 9 5
Checking the conditions for different values.
> with(df1,df1$x1<5)
[1] FALSE FALSE FALSE TRUE TRUE FALSE FALSE FALSE TRUE FALSE FALSE FALSE
[13] FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE
> with(df1,df1$x1>5)
[1] FALSE TRUE FALSE FALSE FALSE TRUE TRUE TRUE FALSE TRUE TRUE TRUE
[13] FALSE FALSE FALSE FALSE TRUE TRUE TRUE FALSE
> with(df1,df1$y1>6)
[1] FALSE TRUE TRUE FALSE TRUE FALSE TRUE FALSE TRUE TRUE TRUE TRUE
[13] TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE
> with(df1,df1$y1>8)
[1] FALSE FALSE TRUE FALSE TRUE FALSE FALSE FALSE TRUE TRUE FALSE TRUE
[13] FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE
> with(df1,df1$z1>8)
[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
[13] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE
> with(df1,df1$z1<4)
[1] TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE FALSE TRUE
[13] FALSE TRUE FALSE FALSE TRUE TRUE TRUE FALSE
> with(df1,df1$x1>7)
[1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE
[13] FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
Let’s have a look at another example.
Live Demo
> x2<-sample(0:9,20,replace=TRUE)
> y2<-sample(0:9,20,replace=TRUE)
> z2<-sample(0:9,20,replace=TRUE)
> df2<-data.frame(x2,y2,z2)
> df2
x2 y2 z2
1 1 3 4
2 5 9 7
3 5 2 9
4 8 8 7
5 2 8 8
6 1 3 6
7 3 5 6
8 5 5 2
9 6 0 4
10 1 6 9
11 9 6 3
12 0 3 7
13 2 4 3
14 1 6 8
15 5 1 4
16 2 0 7
17 6 7 8
18 9 5 9
19 1 3 8
20 5 4 0
> with(df2,df2$x2>6)
[1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE
[13] FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE
> with(df2,df2$x2>5)
[1] FALSE FALSE FALSE TRUE FALSE FALSE FALSE FALSE TRUE FALSE TRUE FALSE
[13] FALSE FALSE FALSE FALSE TRUE TRUE FALSE FALSE
> with(df2,df2$y2>5)
[1] FALSE TRUE FALSE TRUE TRUE FALSE FALSE FALSE FALSE TRUE TRUE FALSE
[13] FALSE TRUE FALSE FALSE TRUE FALSE FALSE FALSE
> with(df2,df2$y2>3)
[1] FALSE TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE FALSE
[13] TRUE TRUE FALSE FALSE TRUE TRUE FALSE TRUE
> with(df2,df2$y2<3)
[1] FALSE FALSE TRUE FALSE FALSE FALSE FALSE FALSE TRUE FALSE FALSE FALSE
[13] FALSE FALSE TRUE TRUE FALSE FALSE FALSE FALSE
> with(df2,df2$x2<5)
[1] TRUE FALSE FALSE FALSE TRUE TRUE TRUE FALSE FALSE TRUE FALSE TRUE
[13] TRUE TRUE FALSE TRUE FALSE FALSE TRUE FALSE
Control the Size of the Points in a Scatterplot in R - GeeksforGeeks

23 May, 2021
In this article, we are going to see how to control the size of the points in a scatterplot in R Programming language.
We will Control the size of the points in a scatterplot using cex argument of the plot function. In this approach to control the size of the points in a scatterplot, the user needs to call the in-built function plot() and using the cex parameter which will take input value as a float in this function of control the size of the points of the given scatterplot in r language.
Syntax: plot( Data_x, Data_y, cex)
Example 1: Increase the point size in a scatterplot.
In this function, we will be increasing the size of the points of the given scatterplot using the cex argument of the plot function of r language. Here cex will be set to 4 which will increase the size of the points of the scatterplot. 
Python3
x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)y = c(7, 9, 6, 2, 8, 1, 3, 4, 5, 8)    plot(x, y, cex = 4) 
Output:
Example 2: Decreasing the point size in a scatterplot.
In this function, we will be decreasing the size of the points of the given scatterplot using the cex argument of the plot function of r language. Here cex will be set to 0.6 which will decrease the size of the points of the scatterplot. 
R
x = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)y = c(7, 9, 6, 2, 8, 1, 3, 4, 5, 8)  plot( x, y, cex = 0.6) 
Output:
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
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
R - if statement
Time Series Analysis in R
How to use regular expressions with TestNG?

We use regular expressions in TestNG to work with a group of test
methods that are named with a certain pattern.
Testng xml file.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Tutorialspoint Test ">
   <test name = "Test Cycle">
      <classes>
         <class name = "TestRegularExpression" />
         <methods>
            <exclude name= “Payment.*”/>
         </methods>
      </classes>
   </test>
</suite>
All the test methods with starting name Payment will be excluded from the
regression suite.
@Test
public void PaymentHistory(){
   System.out.println("Payment history validation is successful”);
}
@Test
public void Login(){
   System.out.println("Login is successful”);
}
@Test
public void PaymentDefault(){
   System.out.println("Payment default verification is successful”);
}
Login() will be executed, but all the methods starting with name Payment will be excluded from execution. This is achieved using regular expression(Payment.*).
Kotlin - Exception Handling

Exception handling is a very important part of a programming language. This technique restricts our application from generating the wrong output at runtime. In this chapter, we will learn how to handle runtime exception in Kotlin. The exceptions in Kotlin is pretty similar to the exceptions in Java. All the exceptions are descendants of the “Throwable” class. Following example shows how to use exception handling technique in Kotlin.
fun main(args: Array<String>) {
   try {
      val myVar:Int = 12;
      val v:String = "Tutorialspoint.com";
      v.toInt();
   } catch(e:Exception) {
      e.printStackTrace();
   } finally {
      println("Exception Handeling in Kotlin");
   }
}
In the above piece of code, we have declared a String and later tied that string into the integer, which is actually a runtime exception. Hence, we will get the following output in the browser.
val myVar:Int = 12;
Exception Handeling in Kotlin

Note − Like Java, Kotlin also executes the finally block after executing the catch block.

    68 Lectures 
     4.5 hours 

 Arnab Chakraborty

    71 Lectures 
     5.5 hours 

 Frahaan Hussain

    18 Lectures 
     1.5 hours 

 Mahmoud Ramadan

    49 Lectures 
     6 hours 

 Catalin Stefan

    49 Lectures 
     2.5 hours 

 Skillbakerystudios

    22 Lectures 
     1 hours 

 CLEMENT OCHIENG
 Print
 Add Notes
 Bookmark this page
Reset keys of array elements using PHP ?

To reset keys of array elements using PHP, the code is as follows−
 Live Demo
<?php
   $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110");
   var_dump ($arr);
   $res = array_values($arr);
   var_dump ($res);
?>
This will produce the following output−
array(4) {
   ["p"]=>
   string(3) "150"
   ["q"]=>
   string(3) "100"
   ["r"]=>
   string(3) "120"
   ["s"]=>
   string(3) "110"
}
array(4) {
   [0]=>
   string(3) "150"
   [1]=>
   string(3) "100"
   [2]=>
   string(3) "120"
   [3]=>
   string(3) "110"
}
Let us now see another example −
 Live Demo
<?php
   $arr = array( 8=>"Ben", 4=>"Kevin", 7=>"Mark", 3=>"Hanks");
   var_dump ($arr);
   $res = array_values($arr);
   var_dump ($res);
?>
This will produce the following output−
array(4) {
   [8]=>
   string(3) "Ben"
   [4]=>
   string(5) "Kevin"
   [7]=>
   string(4) "Mark"
   [3]=>
   string(5) "Hanks"
}
array(4) {
   [0]=>
   string(3) "Ben"
   [1]=>
   string(5) "Kevin"
   [2]=>
   string(4) "Mark"
   [3]=>
   string(5) "Hanks" 
}
How to create a new data frame for the mean of rows of some columns from an R data frame?

Finding row means help us to identity the average performance of a case if all the variables are of same nature and it is also an easy job. But if some of the columns have different type of data then we have to extract columns for which we want to find the row means. Therefore, we can create a new data frame with row means of the required columns using rowMeans function.
 Live Demo
Consider the below data frame −
set.seed(88)
Group<-LETTERS[1:10]
x1<-rpois(20,2)
x2<-rpois(20,5)
x3<-rpois(20,10)
df<-data.frame(Group,x1,x2,x3)
df
 Group x1 x2 x3
1 A 2 3 10
2 B 0 6 7
3 C 3 7 9
4 D 2 8 9
5 E 6 8 9
6 F 8 6 4
7 G 0 4 5
8 H 3 7 10
9 I 3 5 11
10 J 5 4 10
11 A 2 3 9
12 B 3 7 8
13 C 2 6 6
14 D 1 4 7
15 E 0 7 12
16 F 1 8 9
17 G 0 5 11
18 H 2 6 9
19 I 3 7 5
20 J 3 9 6
Creating a new data frame with column Group as in original df and RowMeans for the mean of columns x1, x2, and x3 −
row_means_df<-data.frame(Group=df[,1],RowMeans=rowMeans(df[,-1]))
row_means_df
Group RowMeans
1 A 5.000000
2 B 4.333333
3 C 6.333333
4 D 6.333333
5 E 7.666667
6 F 6.000000
7 G 3.000000
8 H 6.666667
9 I 6.333333
10 J 6.333333
11 A 4.666667
12 B 6.000000
13 C 4.666667
14 D 4.000000
15 E 6.333333
16 F 6.000000
17 G 5.333333
18 H 5.666667
19 I 5.000000
20 J 6.000000
Creating a new data frame with column Group as in original df and RowMeans for the mean of columns x2 and x3 that is 3 and 4 −
row_means_3.4_cols_df<-data.frame(Group=df[,1],RowMeans=rowMeans(df[,-c(1,2)]))
row_means_3.4_cols_df
Group RowMeans
1 A 6.5
2 B 6.5
3 C 8.0
4 D 8.5
5 E 8.5
6 F 5.0
7 G 4.5
8 H 8.5
9 I 8.0
10 J 7.0
11 A 6.0
12 B 7.5
13 C 6.0
14 D 5.5
15 E 9.5
16 F 8.5
17 G 8.0
18 H 7.5
19 I 6.0
20 J 7.5
DAX Filter - ISCROSSFILTERED function

Returns TRUE when columnName or another column in the same or related table is being filtered.
ISCROSSFILTERED (<columnName>) 

columnName
The name of a column in a table.
It cannot be an expression.
TRUE or FALSE.
A column columnName is said to be cross-filtered when a filter applied to another column in the same table or in a related table affects columnName by filtering it.
A column columnName is said to be cross-filtered when a filter applied to another column in the same table or in a related table affects columnName by filtering it.
A column is said to be filtered directly when the filter or filters apply over the column.
A column is said to be filtered directly when the filter or filters apply over the column.
You can use DAX ISFILTERED function to find if a column is filtered directly.
= ISCROSSFILTERED (Sales) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
How to implement custom JsonAdapter using Gson in Java?

The @JsonAdapter annotation can be used at field or class level to specify the Gson. The TypeAdapter class can be used to convert Java objects to and from JSON. By default, Gson library converts application classes to JSON by using built-in type adapters but we can override it by providing custom type adapters.
@Retention(value=RUNTIME)
@Target(value={TYPE,FIELD})
public @interface JsonAdapter
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class JsonAdapterTest {
   public static void main(String[] args) {
      Gson gson = new Gson();
      System.out.println(gson.toJson(new Customer()));
   }
}
// Customer class
class Customer {
   @JsonAdapter(CustomJsonAdapter.class)
   Integer customerId = 101;
}
// CustomJsonAdapter class
class CustomJsonAdapter extends TypeAdapter<Integer> {
   @Override
   public Integer read(JsonReader jreader) throws IOException {
      return null;
   }
   @Override
   public void write(JsonWriter jwriter, Integer customerId) throws IOException {
      jwriter.beginObject();
      jwriter.name("customerId");
      jwriter.value(String.valueOf(customerId));
      jwriter.endObject();
   }
}
{"customerId":{"customerId":"101"}}