code-rag-bench/online-tutorials huggingface dataset:
Scala String substring() method with example

23 Oct, 2019
The substring() method is utilized to find the sub-string from the stated String which starts from the index specified.
Method Definition: String substring(int beginIndex)
Return Type: It returns the content from the given String Which starts from the index we specify.
Example: 1#
// Scala program of substring()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying substring method        val result = "GeeksforGeeks".substring(8)                  // Displays output        println(result)          }} 
Geeks

Example: 2#
// Scala program of substring()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying substring method        val result = "GeeksforGeeks".substring(11)                  // Displays output        println(result)              }} 
ks

Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Operators in Scala
Scala Constructors
Enumeration in Scala
How to get the first element of List in Scala
Inheritance in Scala
How to Install Scala with VSCode?
HashMap in Scala
Break statement in Scala
Scala Map get() method with example
PyQt5 QListWidget – Getting Current Selected Row

01 Aug, 2020
In this article we will see how we can get the current selected row of the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. Current row property holds the row of the current item. Depending on the current selection mode, the row may also be selected with the help of setCurrentRow method.
In order to do this we will use currentRow method with the list widget object.
Syntax : list_widget.currentRow()
Argument : It takes no argument
Return : It returns integer
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys    class Window(QMainWindow):      def __init__(self):        super().__init__()          # setting title        self.setWindowTitle("Python ")          # setting geometry        self.setGeometry(100, 100, 500, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()          # method for components    def UiComponents(self):          # creating a QListWidget        list_widget = QListWidget(self)          # setting geometry to it        list_widget.setGeometry(50, 70, 150, 60)          # list widget items        item1 = QListWidgetItem("A")        item2 = QListWidgetItem("B")        item3 = QListWidgetItem("C")          # adding items to the list widget        list_widget.addItem(item1)        list_widget.addItem(item2)        list_widget.addItem(item3)          # setting current row        list_widget.setCurrentRow(2)          # creating a label        label = QLabel("GeesforGeeks", self)          # setting geometry to the label        label.setGeometry(230, 80, 300, 80)          # making label multi line        label.setWordWrap(True)          # getting current selected row        value = list_widget.currentRow()          # setting text to the label        label.setText("Current Selected Row : " + str(value))      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() 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
Convert integer to string in Python
Python OOPs Concepts
Java program to implement selection sort

Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.
The smallest element is selected from the unsorted array and swapped with the leftmost element, and that element becomes a part of the sorted array. This process continues moving unsorted array boundary from one element to the right.
1.Set MIN to location 0
2.Search the minimum element in the list
3.Swap with value at location MIN
4.Increment MIN to point to next element
5.Repeat until the list is sorted
Live Demo
public class SelectionSort {
   public static void main(String args[]){
      int array[] = {10, 20, 25, 63, 96, 57};
      int size = array.length;

      for (int i = 0 ;i< size-1; i++){
         int min = i;

         for (int j = i+1; j<size; j++){
            if (array[j] < array[min]){
            min = j;
            }
         }
         int temp = array[min];
         array[min] = array[i];
         array[i] = temp;
      }

      for (int i = 0 ;i< size; i++){
         System.out.print(" "+array[i]);
      }
   }  
}
How to check if an alert exists using WebDriver?

We can check if an alert exists with Selenium webdriver. An alert is created with the help of Javascript. We shall use the explicit wait concept in synchronization to verify the presence of an alert.
Let us consider the below alert and check its presence on the page. There is a condition called alertIsPresent which we will use to check for alerts. It shall wait for
a specified amount of time for the alert after which it shall throw an exception.
We need to import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait to incorporate expected conditions and WebDriverWait class.
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 org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class VerifyAlert{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String u ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"driver.get(u);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify and click submit
      WebElement t = driver.findElement(By.name("submit"));
      t.click();
      // Explicit wait condition for alert
      WebDriverWait w = new WebDriverWait(driver, 5);
      //alertIsPresent() condition applied
      if(w.until(ExpectedConditions.alertIsPresent())==null)
      System.out.println("Alert not exists");
      else
      System.out.println("Alert exists");
      driver.close();
   }
}
Playit

#myDIV {  background-color:lightblue;  transform:translate(10px);}
Finding word starting with specific letter in JavaScript

We are required to write a JavaScript function that takes in an array of string literals as the first argument and a single string character as the second argument.
Then our function should find and return the first array entry that starts with the character specified by the second argument.
The code for this will be −
const names = ['Naman', 'Kartik', 'Anmol', 'Rajat', 'Keshav', 'Harsh', 'Suresh', 'Rahul'];
const firstIndexOf = (arr = [], char = '') => {
   for(let i = 0; i < arr.length; i++){
      const el = arr[i];
      if(el.substring(0, 1) === char){
         return i;
      };
   };
   return -1;
};
console.log(firstIndexOf(names, 'K'));
console.log(firstIndexOf(names, 'R'));
console.log(firstIndexOf(names, 'J'));
And the output in the console will be −
1
3
-1
How to count all child elements of a particular element using JavaScript ? - GeeksforGeeks

24 Jan, 2022
Given an HTML document containing some elements nested elements and the task is to count all the child elements of a particular element. It is very simple to count the number of child elements of a particular element using JavaScript. For example: If you have a parent element consisting of many child elements then you can use HTML DOM childElementCount property to count all the child elements of a particular element.
Syntax
node.childElementCount
Example:
<!DOCTYPE html><html>  <head>    <title>        How to count all child elements of a        particular element using JavaScript?    </title></head>  <body>    <h1 style="color:green">GeeksforGeeks</h1>      <h3>        Click the button to count all<br>        children the div element    </h3>      <h5>Count all child elements of <ul> elements</h5>    <ul id="parentID">        <li>First element</li>        <li>Second element</li>        <li>Third element</li>        <li>Fourth element</li>    </ul>      <button onclick="myGeeks()">        Click Here!    </button>      <h5 id="GFG"></h5>      <script>          // This function count the child elements        function myGeeks() {            var count = document.getElementById(                "parentID").childElementCount;              document.getElementById("GFG").innerHTML                = "Total Number of Child node: "                + count;        }    </script></body>  </html>
Output:
Before Clicking the Button:
After Clicking the Button:
Akanksha_Rai
simmytarika5
HTML-Misc
JavaScript-Misc
HTML
JavaScript
Web Technologies
Web technologies Questions
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
REST API (Introduction)
Form validation using HTML and JavaScript
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
How can we assign a function to a variable in JavaScript?

In JavaScript, you can assign a function in a variable using the concept of anonymous functions. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. They are called using the variable name −
This is how JavaScript anonymous functions can be used −
var func = function() {
   alert(‘This is anonymous');
}
func();
Anonymous functions are always loaded using a variable name. Anonymous, as the name suggests, allows creating a function without any names identifier. It can be used as an argument to other functions. Call them using a variable name −
Here’s an example −
//anonymous function
var a = function() {
   return 5;
}
Shading an area between two points in a Matplotlib plot

To shade an area between two points in matplotlib, we can take the following steps−
Create x and y data points using numpy.
Plot x and y data points, with color=red and linewidth=2.
To shade an area parallel to X-axis, initialize two variables, y1 and y2.
To add horizontal span across the axes, use axhspan() method with y1, y2, green as shade color,and alpha for transprency of the shade.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(0, 20, 500)
y = np.cos(3*x) + np.sin(2*x)
plt.plot(x, y, c='red', lw=2)
y1 = 0.5
y2 = -0.5
plt.axhspan(y1, y2, color='green', alpha=0.75, lw=0)
plt.show()
Change current working directory with Python - GeeksforGeeks

07 Sep, 2021
The OS module in Python is used for interacting with the operating system. This module comes under Python’s standard utility module so there is no need to install it externally. All functions in OS module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type but are not accepted by the operating system.To change the current working directory(CWD) os.chdir() method is used. This method changes the CWD to a specified path. It only takes a single argument as a new directory path.Note: The current working directory is the folder in which the Python script is operating. 
Syntax: os.chdir(path)Parameters: path: A complete path of the directory to be changed to the new directory path.Returns: Doesn’t return any value  
Example #1: We will first get the current working directory of the script and then we will change it. Below is the implementation.  
Python3
# Python program to change the# current working directory  import os # Function to Get the current# working directorydef current_path():    print("Current working directory before")    print(os.getcwd())    print()  # Driver's code# Printing CWD beforecurrent_path() # Changing the CWDos.chdir('../') # Printing CWD aftercurrent_path()
Output:  
Current working directory before
C:\Users\Nikhil Aggarwal\Desktop\gfg

Current working directory after
C:\Users\Nikhil Aggarwal\Desktop
Example #2: Handling the errors while changing the directory.  
Python3
# Python program to change the# current working directory  # importing all necessary librariesimport sys, os   # initial directorycwd = os.getcwd()   # some non existing directoryfd = 'false_dir/temp'   # trying to insert to false directorytry:    print("Inserting inside-", os.getcwd())    os.chdir(fd)       # Caching the exception    except:    print("Something wrong with specified directory. Exception- ")    print(sys.exc_info())             # handling with finally          finally:    print()    print("Restoring the path")    os.chdir(cwd)    print("Current directory is-", os.getcwd())
Output: 
Inserting inside- C:\Users\Nikhil Aggarwal\Desktop\gfgSomething wrong with specified directory. Exception- (<class ‘FileNotFoundError’>, FileNotFoundError(2, ‘The system cannot find the path specified’), <traceback object at 0x00000268184630C8>)Restoring the path Current directory is- C:\Users\Nikhil Aggarwal\Desktop\gfg  
 
sumitgumber28
Python directory-program
Python os-module-programs
python-file-handling
python-os-module
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 ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
How to find the rank of a matrix in R?

The rank of a matrix is defined as the maximum number of linearly independent vectors in rows or columns. If we have a matrix with dimensions R x C, having R number of rows and C number of columns, and if R is less than C then the rank of the matrix would be R. To find the rank of a matrix in R, we can use rankMatrix function in Matrix package.
Loading Matrix package −
library(Matrix)
 Live Demo
M1<-matrix(1:9,ncol=3)
M1
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
rankMatrix(M1)
[1] [1] 2
 Live Demo
M2<-matrix(1:36,nrow=6)
M2
    [,1] [,2] [,3] [,4] [,5] [,6]
[1,]  1    7   13   19   25   31
[2,]  2    8   14   20   26   32
[3,]  3    9   15   21   27   33
[4,]  4    10  16   22   28   34
[5,]  5    11  18   24   30   36
rankMatrix(M2)
[1] [1] 2
 Live Demo
M3<-matrix(sample(0:9,100,replace=TRUE),nrow=20)
M3
[,1] [,2] [,3] [,4] [,5]
[1,] 9 8 1 4 1
[2,] 5 3 0 6 1
[3,] 2 6 5 5 4
[4,] 5 8 3 7 5
[5,] 3 1 4 0 3
[6,] 1 5 5 3 5
[7,] 0 3 0 3 5
[8,] 1 9 4 0 4
[9,] 1 4 3 7 6
[10,] 1 3 6 1 4
[11,] 6 9 2 5 9
[12,] 7 0 2 8 1
[13,] 5 9 4 1 1
[14,] 9 1 1 6 4
[15,] 1 4 4 0 7
[16,] 6 0 9 2 7
[17,] 9 3 0 2 1
[18,] 9 6 0 7 2
[19,] 5 2 0 8 5
[20,] 8 8 4 0 4
rankMatrix(M3)
[1] [1] 5
 Live Demo
M4<-matrix(sample(21:50,160,replace=TRUE),nrow=20)
M4
    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 49   35   25 36 31 22 49 42
[2,] 45   33   21 39 37 26 41 37
[3,] 36   30   46 50 26 32 24 49
[4,] 33   39   31 39 37 50 50 32
[5,] 41   38   39 38 40 25 42 30
[6,] 34   49   26 34 24 34 42 26
[7,] 40   44   30 21 27 47 32 47
[8,] 35   27   21 25 37 28 48 27
[9,] 34   50   41 38 39 27 43 40
[10,] 21 41 50 28 32 38 22 25
[11,] 26  46 34 29 24 38 28 39
[12,] 36  41 36 47 49 48 49 31
[13,] 44  50 37 38 33 26 37 45
[14,] 31  22 47 37 47 41 23 45
[15,] 42  39 38 26 35 21 31 31
[16,] 50  29 40 47 48 34 23 29
[17,] 49  21 30 47 24 21 43 47
[18,] 27  22 25 34 45 28 49 45
[19,] 38  39 32 31 29 23 34 45
[20,] 45  37 31 43 40 27 29 36
rankMatrix(M4)
[1] [1] 8
 Live Demo
M5<-matrix(sample(rnorm(20),25,replace=TRUE),nrow=5)
M5
[,1] [,2] [,3] [,4] [,5]
[1,] 0.73475325 -1.2186186 -0.21496111 1.8642877 1.1133489
[2,] -0.09091262 -0.4513579 0.18346741 0.1834674 -0.4513579
[3,] 1.55003168 -0.1454168 0.28244025 0.5674004 1.5706586
[4,] -0.90693971 -1.2186186 -0.09091262 -0.1454168 1.0289755
[5,] -0.45135792 0.5674004 0.28244025 -0.2149611 1.5500317
rankMatrix(M5)
[1] [1] 5
 Live Demo
M6<-matrix(sample(rexp(5,2),20,replace=TRUE),nrow=10)
M6
[,1] [,2]
[1,] 0.2969787 3.5003481
[2,] 0.5462926 3.5003481
[3,] 1.0018821 0.5462926
[4,] 3.5003481 0.2969787
[5,] 1.0018821 0.2969787
[6,] 1.0018821 0.2969787
[7,] 1.0018821 0.5462926
[8,] 0.2133455 0.2133455
[9,] 0.5462926 3.5003481
[10,] 0.2969787 0.2133455
rankMatrix(M6)
[1] [1] 2
Does Java support multiple inheritance? Why? How can we resolve this?

Whenever, you extend a class a copy of superclass’s members is available to the subclass object and, when you can call the method of the superclass using the object of the subclass.
In the following example, we have a class named SuperClass with a method with name demo(). We are extending this class with another class (SubClass).
Now, you create an object of the subclass and call the method demo().
 Live Demo
class SuperClass{
   public void demo() {
      System.out.println("demo method");
   }
}
public class SubClass extends SuperClass {
   public static void main(String args[]) {
      SubClass obj = new SubClass();
      obj.demo();
   }
}
demo method
For suppose, if we have two classes namely, SuperClass1 and SuperClass2 with the same method say demo() (including parameters) as shown below −
class SuperClass1{
   public void demo() {
      System.out.println("demo method");
   }
}
class SuperClass2{
   public void demo() {
      System.out.println("demo method");
   }
}
Now, from another class, if extend both the classes as −
public class SubClass extends SuperClass1, SuperClass2 {
   public static void main(String args[]) {
      SubClass obj = new SubClass();
      obj.demo();
   }
}
According to the basic rule of inheritance, a copy of both demo() methods should be created in the subclass object which leaves the subclass with two methods with the same prototype. Then, if you call the demo() method using the object of the subclass compiler faces an ambiguous situation not knowing which method to call.
Therefore, in Java multiple inheritance is not allowed and, you cannot extend more than one other class. Still, if you try to do so, a compile-time error is generated.
On compiling, the above program generates the following error −
MultipleInheritanceExample.java:9: error: '{' expected
public class MultipleInheritanceExample extends MyInterface1, MyInterface2{
                                                               ^
1 error
In case of multiple interfaces with the same default method. In the concrete class implementing both interfaces, you can implement the common method and call both super methods. thus You can achieve multiple inheritance in Java using interfaces.
 Live Demo
interface MyInterface1{
   public static int num = 100;
   public default void display() {
      System.out.println("display method of MyInterface1");
   }
}
interface MyInterface2{
   public static int num = 1000;
   public default void display() {
      System.out.println("display method of MyInterface2");
   }
}

public class InterfaceExample implements MyInterface1, MyInterface2{
   public void display() {
      System.out.println("This is the implementation of the display method");
   }
   public void show() {
      MyInterface1.super.display();
      MyInterface2.super.display();
   }

   public static void main(String args[]) {
      InterfaceExample obj = new InterfaceExample();
      obj.show();
   }
}
display method of MyInterface1
display method of MyInterface2
Fill between two vertical lines in matplotlib

To fill color between two vertical lines, use the following steps −
Using plt.subplots() method, create a figure and a set of subplots. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call.
Using plt.subplots() method, create a figure and a set of subplots. This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call.
To draw two vertical lines, initialize x = 3 and x = 5.
To draw two vertical lines, initialize x = 3 and x = 5.
Using the created ax, axvspan would help to add vertical span(rectangle) across the axes.This rectangle spans from xmin to xmax horizontally, and, by default, the whole Y-axis vertically.
Using the created ax, axvspan would help to add vertical span(rectangle) across the axes.
This rectangle spans from xmin to xmax horizontally, and, by default, the whole Y-axis vertically.
To show the figure, use the plt.show() method.
To show the figure, use the plt.show() method.
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

line1 = 3 # vertical x = 3
line2 = 5 # vertical x = 5

ax.axvspan(line1, line2, alpha=.5, color='green')

plt.show()
C++ program to append content of one text file to another

This is a C++ program to append the content of one text file to another.
a.txt file contains “Tutorials”
a1.txt file contains “point”
Tutorialspoint
Begin
   Define a fstream class object as fin.
   Open a input file a.txt with input file stream class object fin.
   Open a output file a1.txt with output file stream class object fout
   in append mode.
   Check if the file is not existing then
      Print “File not found”.
   Else append content from fin to fout.
   Open the destination file in read mode.
   Display its content as output. 
End.
 Live Demo
#include <bits/stdc++.h>
#include<fstream>
using namespace std;
int main() {
   fstream f;
   ifstream fin;
      fin.open("a.txt");
      ofstream fout;
      fout.open("a1.txt", ios::app);
   if (!fin.is_open()) {
      cout << "Tutorialspoint";
   } else {
      fout << fin.rdbuf();
   }
   string word;
   f.open("a1.txt");
   while (f >> word) {
      cout << word << " ";
   }
   return 0;
}
Tutorialspoint
How to use enums in C/C++?

Enumeration is a user defined datatype in C language. It is used to assign names to the integral constants, which makes a program easy to read and maintain. The keyword “enum” is used to declare an enumeration.
Here is the syntax of enum in C language,
enum enum_name{const1, const2, ....... };
The enum keyword is also used to define the variables of enum type. There are two ways to define the variables of enum type as follows.
enum week{sunday, monday, tuesday, wednesday, thursday, friday, saturday};
enum week day;
Here is an example of enum in C language,
#include<stdio.h>
enum week{Mon=10, Tue, Wed, Thur, Fri=10, Sat=16, Sun};
enum day{Mond, Tues, Wedn, Thurs, Frid=18, Satu=11, Sund};
int main() {
   printf("The value of enum week: %d\t%d\t%d\t%d\t%d\t%d\t%d\n\n",Mon , Tue, Wed, Thur, Fri, Sat,    Sun);
   printf("The default value of enum day: %d\t%d\t%d\t%d\t%d\t%d\t%d",Mond , Tues, Wedn, Thurs, Frid,    Satu, Sund);
   return 0;
}
The value of enum week: 10111213101617
The default value of enum day: 0123181112
ES6 - Number.MAX_VALUE

The Number.MAX_VALUE property belongs to the static Number object. It represents constants for the largest possible positive numbers that JavaScript can work with.
The actual value of this constant is 1.7976931348623157 x 10308
var val = Number.MAX_VALUE;

var val = Number.MAX_VALUE;
console.log("Value of Number.MAX_VALUE : " + val );
Value of Number.MAX_VALUE : 1.7976931348623157e+308


    32 Lectures 
     3.5 hours 

 Sharad Kumar

    40 Lectures 
     5 hours 

 Richa Maheshwari

    16 Lectures 
     1 hours 

 Anadi Sharma

    50 Lectures 
     6.5 hours 

 Gowthami Swarna

    14 Lectures 
     1 hours 

 Deepti Trivedi

    31 Lectures 
     1.5 hours 

 Shweta
 Print
 Add Notes
 Bookmark this page
How to Run Synchronous Queries using sync-sql Module in Node.js ?

28 Apr, 2020
The sync-sql module is designed to make synchronous queries to the database. Since normal SQL queries are asynchronous in node.js but if you want to run it synchronously, then it is possible using this module. In synchronized SQL, the result set is returned when the query is executed.
Note: Do not use this module in production mode as node.js is designed to be asynchronous.
Installation of sync-sql module:
You can visit the link Install sync-sql module. You can install this package by using this command.npm install sync-sqlAfter installing sync-sql you can check your sync-sql version in command prompt using the command.npm version sync-sqlAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.jsNow open MySQL and create a database for example ‘demo’.
You can visit the link Install sync-sql module. You can install this package by using this command.npm install sync-sql
npm install sync-sql
After installing sync-sql you can check your sync-sql version in command prompt using the command.npm version sync-sql
npm version sync-sql
After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js
node index.js
Now open MySQL and create a database for example ‘demo’.
Filename: index.js
const Mysql = require('sync-mysql')  const connection = new Mysql({    host:'localhost',    user:'root',    password:'password',    database:'demo'})  var result = connection.query('SELECT NOW()')console.log(result)
Steps to run the program:
The project structure will look like this:Make sure you install sync-sql using following commands:npm install sync-sqlRun index.js file using below command:node index.js
The project structure will look like this:
Make sure you install sync-sql using following commands:npm install sync-sql
npm install sync-sql
Run index.js file using below command:node index.js
node index.js
So this is how you can run synchronized SQL queries in node js using sync-sql package.
Node.js-Misc
Node.js
Web Technologies
Web technologies Questions
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
Installation of Node.js on Windows
JWT Authentication with Node.js
How to use an ES6 import 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
Print anagrams together in Python using List and Dictionary

19 Apr, 2022
Given an array of words, print all anagrams together ? Examples:
Input : arr = ['cat', 'dog', 'tac', 'god', 'act']
Output : 'cat tac act dog god'
This problem has existing solution please refer Anagrams and Given a sequence of words, print all anagrams together links. We will solve this problem in python using List and Dictionary data structures. Approach is very simple :
Traverse list of strings.
Sort each string in ascending order and consider this sorted value as Key and original value as Value of corresponding key. Check if key is not present in dictionary that means it is occurring first time, so map a empty list to Key and append value in it, if key is already present then simple append the value.
Now each key will contain list of strings which are anagram together.
Python3
# Function to return all anagrams togetherdef allAnagram(input):         # empty dictionary which holds subsets    # of all anagrams together    dict = {}     # traverse list of strings    for strVal in input:                 # sorted(iterable) method accepts any        # iterable and returns list of items        # in ascending order        key = ''.join(sorted(strVal))                 # now check if key exist in dictionary        # or not. If yes then simply append the        # strVal into the list of it's corresponding        # key. If not then map empty list onto        # key and then start appending values        if key in dict.keys():            dict[key].append(strVal)        else:            dict[key] = []            dict[key].append(strVal)     # traverse dictionary and concatenate values    # of keys together    output = ""    for key,value in dict.items():        output = output + ' '.join(value) + ' '     return output # Driver functionif __name__ == "__main__":    input=['cat', 'dog', 'tac', 'god', 'act']    print (allAnagram(input))
Output:
'cat tac act dog god'
This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nidhi_biet
sumitgumber28
anagram
Python dictionary-programs
Python list-programs
python-dict
python-list
Python
Strings
python-dict
python-list
Strings
anagram
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()
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python | Pandas Series.dt.hour

20 Mar, 2019
Series.dt can be used to access the values of the series as datetimelike and return several properties. Pandas Series.dt.hour attribute return a numpy array containing the hour of the datetime in the underlying data of the given series object.
Syntax: Series.dt.hour
Parameter : None
Returns : numpy array
Example #1: Use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30',                '2010-4-22 09:25', '2019-11-8 02:22'])  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Convert the underlying data to datetime sr = pd.to_datetime(sr)  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object.
# return the hourresult = sr.dt.hour  # print the resultprint(result)
Output :As we can see in the output, the Series.dt.hour attribute has successfully accessed and returned the hour of the datetime in the underlying data of the given series object. Example #2 : Use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(pd.date_range('2012-12-12 12:12',                       periods = 5, freq = 'H'))  # Creating the indexidx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5']  # set the indexsr.index = idx  # Print the seriesprint(sr)
Output :
Now we will use Series.dt.hour attribute to return the hour of the datetime in the underlying data of the given Series object.
# return the hourresult = sr.dt.hour  # print the resultprint(result)
Output :
As we can see in the output, the Series.dt.hour attribute has successfully accessed and returned the hour of the datetime in the underlying data of the given series object.
Python pandas-series-datetime
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
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
How to get the file size using PHP ?

22 Jan, 2021
In this article, we are going to discuss how to get the file size using PHP. PHP is a general-purpose scripting language that is suited for both server and client scripting language for website development. To get the file size, we will use filesize() function. 
The filesize() function returns the size of a file in bytes. This function accepts the filename as a parameter and returns the size of a file in bytes on success and False on failure. 
Syntax:
filesize($filename)
Parameters: The filesize() function in PHP accepts only one parameter i.e. $filename that specifies the filename of the file whose size that you want to check.
Example 1: In this example, we use filesize() function with a file parameter and it returns the size of given file.
PHP
<?php    echo "The File size is: ";  echo filesize("gfg.txt");  ?>
Output:
The File size is: 15
Example 2: In this example, we use filesize() function with a non-existing file parameter then it returns an error message.
PHP
<?php    echo "The File size is: ";  echo filesize("gfg2.txt");?>
Output:
The File size is: 
Warning: filesize(): stat failed for inde1x.php in
C:\xampp\htdocs\gfg.php on line 4
PHP-Misc
Picked
Technical Scripter 2020
PHP
PHP Programs
Technical Scripter
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
How to create admin login page using PHP?
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
How to create admin login page using PHP?
PHP | Ternary Operator
How to send an email using PHPMailer ?
What is tools:context in Android Layout Files?

12 Apr, 2021
Android Studio provides a much richer variety of functions in the form of various XML attributes in the tools namespace which enables design-time features or compile-time behaviors. When the app is being built, the build tools remove these attributes so that there is no effect on runtime behavior or APK size. tools:context is such an attribute that is defined in any root view and declares which activity or fragment the layout is associated with.
This declaration helps in enabling various features in the layout preview which demands the knowledge of the activity such as automatically choosing the necessary theme for preview. Let’s see a small demonstration of the above stated. Now, whenever a project is created in android studio or any activity or fragment is added the following code gets generated automatically in the layout file:
XML
<!--To demonstrate the automatically generated code and usasge of tools:context--><?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="match_parent"          <!--It means that the layout is associated with MainActivity-->    tools:context=".MainActivity">     <!--Other Views-->  </androidx.constraintlayout.widget.ConstraintLayout>
You can also specify the activity class name yourself using the same dot prefix as stated in the manifest file. Another use of the tools:context is in the form of figuring out where to place the onClick handlers (to respond to touch events) when you implement it using the quickfix.
showcasing the use of tools:context in using the quickfix
Now if you were to delete the tools:context attribute then there would be no recommendation for the quickfix. So to summarize, tools:context attribute is declared in the rootview of the layout file and it declares which activity or fragment the layout file is associated with. It is also used for better visualization of the current layout and view. 
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Flutter - Stack Widget
Introduction to Android Development
Activity Lifecycle in Android with Demo App
Fragment Lifecycle in Android
How to Convert a String value to Byte value in Java with Examples

29 Jan, 2020
Given a String “str” in Java, the task is to convert this string to byte type.
Examples:
Input: str = "1"
Output: 1

Input: str = "3"
Output: 3

Approach 1: (Naive Method)One method is to traverse the string and add the numbers one by one to the byte type. This method is not an efficient approach.
Approach 2: (Using Byte.parseByte() method)The simplest way to do so is using parseByte() method of Byte class in java.lang package. This method takes the string to be parsed and returns the byte type from it. If not convertible, this method throws error.
Syntax:
Byte.parseByte(str);

Below is the implementation of the above approach:
Example 1: To show successful conversion
// Java Program to convert string to byte  class GFG {      // Function to convert String to Byte    public static byte convertStringToByte(String str)    {          // Convert string to byte        // using parseByte() method        return Byte.parseByte(str);    }      // Driver code    public static void main(String[] args)    {          // The string value        String stringValue = "1";          // The expected byte value        byte byteValue;          // Convert string to byte        byteValue = convertStringToByte(stringValue);          // Print the expected byte value        System.out.println(            stringValue            + " after converting into byte = "            + byteValue);    }}
1 after converting into byte = 1

Approach 3: (Using Byte.valueOf() method)The valueOf() method of Byte class converts data from its internal form into human-readable form.
Syntax:
Byte.valueOf(str);

Below is the implementation of the above approach:
Example 1: To show successful conversion
// Java Program to convert string to byte  class GFG {      // Function to convert String to Byte    public static byte convertStringToByte(String str)    {          // Convert string to byte        // using valueOf() method        return Byte.valueOf(str);    }      // Driver code    public static void main(String[] args)    {          // The string value        String stringValue = "1";          // The expected byte value        byte byteValue;          // Convert string to byte        byteValue = convertStringToByte(stringValue);          // Print the expected byte value        System.out.println(            stringValue            + " after converting into byte = "            + byteValue);    }}
1 after converting into byte = 1

Java-Byte
Java-Data Types
Java-String-Programs
Java-Strings
Java
Java Programs
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove the first character of string in PHP?

To remove the first character of a string in PHP, the code is as follows−
 Live Demo
<?php
   $str = "Test";
   echo "Before removing the first character = ".$str;
   $res = substr($str, 1);
   echo "\nAfter removing the first character = ".$res;
?>
This will produce the following output −
Before removing the first character = Test
After removing the first character = est
Let us now see another example
 Live Demo
<?php
   $str = "Demo";
   echo "Before removing the first character = ".$str;
   $res = ltrim($str, 'D');
   echo "\nAfter removing the first character = ".$res;
?>
This will produce the following output−
Before removing the first character = Demo 
After removing the first character = emo
CharsetDecoder charset() in Java with examples

23 Jul, 2020
CharsetDecoder.charset() is an in-built method in Java of CharsetDecoder class that returns the charset that created this decoder.
Syntax:
public final Charset charset()

Parameter: The function does not accepts any parameter.
Return value: The function returns the decoder’s charset.
Program below demonstrate the above mentioned function:
Program 1:
// Java program below demonstrate// CharsetDecoder.charset function  import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;  public class Main {    public static void main(String[] argv) throws Exception    {        Charset charset = Charset.forName("ISO-8859-1");          // initialising CharsetDecoder cd        CharsetDecoder cd = charset.newDecoder();        // print charset of decoder cd        System.out.println(cd.charset());    }}
ISO-8859-1

Program 2:
// Java program below demonstrate// CharsetDecoder.charset function  import java.nio.charset.Charset;import java.nio.charset.CharsetDecoder;  public class Main {    public static void main(String[] argv) throws Exception    {        Charset charset = Charset.forName("ISO-8859-2");          // initialising CharsetDecoder cd        CharsetDecoder cd = charset.newDecoder();        // print charset of decoder cd        System.out.println(cd.charset());    }}
ISO-8859-2

nidhi_biet
Java-CharsetDecoder
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Stack Class in Java
Set in Java
Introduction to Java
Constructors in Java
Initializing a List in Java
Speak the meaning of the word using Python

28 Jun, 2022
The following article shows how by the use of two modules named, pyttsx3 and PyDictionary, we can make our system say out the meaning of the word given as input. It is module which speak the meaning when we want to have the meaning of the particular word.
PyDictionary: It is a Dictionary Module for Python 2-3 to get meanings, translations, synonyms and Antonyms of words. It uses WordNet for doing as its functionality suggests and has dependencies on modules named Requests, BeautifulSoup4 and goslate .
pyttsx3: It is a text to speech library. This module is what gives our system voice so that they can communicate with us. Pyttsx3 uses sapi5 in windows and espeak in windows.
Both modules can be installed by using pip in the following way:
pip install PyDictionary
pip install pyttsx3  
As mentioned above, by the combination of two modules we will generate the functionality required and to do that the following steps were taken:
A method is defined to make the system search for the meaning of the word provided as input
Another method is defined to make the system say out loud the output generated corresponding to the input provided.
The output returned in this may be a dictionary, so we have to extract each meaning of the word provided as it will be in a key-value format.
Below is the Implementation.
Python3
import pyttsx3from PyDictionary import PyDictionary  class Speaking:     def speak(self, audio):               # Having the initial constructor of pyttsx3        # and having the sapi5 in it as a parameter        engine = pyttsx3.init('sapi5')                 # Calling the getter and setter of pyttsx3        voices = engine.getProperty('voices')                 # Method for the speaking of the assistant        engine.setProperty('voice', voices[0].id)        engine.say(audio)        engine.runAndWait()  class GFG:    def Dictionary(self):        speak = Speaking()        dic = PyDictionary()        speak.speak("Which word do u want to find the meaning sir")                 # Taking the string input        query = str(input())        word = dic.meaning(query)        print(len(word))                 for state in word:            print(word[state])            speak.speak("the meaning  is" + str(word[state]))  if __name__ == '__main__':    GFG()    GFG.Dictionary(self=None)
Output:
anikakapoor
simmytarika5
python-utility
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 OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python
Python program to copy odd lines of one file to other

23 Aug, 2018
Write a python program to read contents of a file and copy only the content of odd lines into new file.
Examples:
Input : Hello
        World
        Python
        Language
Output : Hello
         Python

Input : Python
        Language
        Is
        Easy
Output : Python
         Is

1) Open file name bcd.txt in read mode and assign it to fn.2) Open file name nfile.txt in write mode and assign it to fn1.3) Read the content line by line of the file fn and assign it to cont.4) Access each element from 0 to length of cont.5) Check if i is not divisible by 2 then write the content in fn1 else pass.6) Close the file fn1.7) Now open nfile.txt in read mode and assign it to fn1.8) Read the content of the file and assign it to cont1.9) Print the content of the file and then close the file fn and fn1 .
# open file in read modefn = open('bcd.txt', 'r')  # open other file in write modefn1 = open('nfile.txt', 'w')  # read the content of the file line by linecont = fn.readlines()type(cont)for i in range(0, len(cont)):    if(i % 2 ! = 0):        fn1.write(cont[i])    else:        pass  # close the filefn1.close()  # open file in read modefn1 = open('nfile.txt', 'r')  # read the content of the filecont1 = fn1.read()  # print the content of the fileprint(cont1)  # close all filesfn.close()fn1.close()
Output : Python
         Is

python-file-handling
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.