code-rag-bench/online-tutorials huggingface dataset:
PyQt5 – rect() method

26 Mar, 2020
rect() method belongs to QtCore.QRect class, this method is used to get the geometry of the window or any widget. It returns the object of type QRect which tells the property of the rectangle.
Syntax : widget.rect()
Argument : It takes no argument.
Return : It returns the rectangle of the widget
Code :
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          # setting geometry        self.setGeometry(100, 100, 600, 400)          # creating a label widget        self.label_1 = QLabel("new border ", self)          # moving position        self.label_1.move(100, 100)                  # printing window geometry        print(self.rect())               # printing label geometry        print(self.label_1.rect())                  # setting up the border        self.label_1.setStyleSheet("border :3px solid black;")          # show all the widgets        self.update()        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
PyQt5.QtCore.QRect(0, 0, 600, 400)
PyQt5.QtCore.QRect(0, 0, 100, 30)

Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert an Integer to a String in Julia – string() Function

21 Nov, 2021
The string() is an inbuilt function in julia which is used to convert a specified integer to a string in the given base. 
Syntax: string(n::Integer; base::Integer, pad::Integer)Parameters:  
n::Integer: Specified integer.
base::Integer: Specified base in which conversion are going to be performed.
pad::Integer: It is number of characters present in the returned string.
Returns: It returns the converted string in the given base.  
Example 1:  
Python
# Julia program to illustrate# the use of String string() method  # Conversion of integer to a string# in the given basePrintln(string(10, base = 5, pad = 5))Println(string(10, base = 5, pad = 3))Println(string(5, base = 10, pad = 2))Println(string(8, base = 9, pad = 4))
Output:  
 : Example 2:  
Python
# Julia program to illustrate# the use of String string() method  # Creation of a single string using# all the argumentsPrintln(string("A", 5, true))Println(string("A", 10, false))Println(string("B", 6, true))Println(string("C", 12, false))
Output:  
 
anikakapoor
simmytarika5
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tuples in Julia
Working with DataFrames in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Cell Arrays in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Taking Input from Users in Julia
Random Numbers Ecosystem in Julia - The Pseudo Side
Creating array with repeated elements in Julia - repeat() Method
Matching of regular expression in string in Julia - match() and eachmatch() Methods
Functions in Julia
Ruby | Time strftime() function

07 Jan, 2020
Time#strftime() is a Time class method which returns the time format according to the directives in the given format string.
Syntax: Time.strftime()
Parameter: Time values
Return: time format according to the directives in the given format string.
Example #1 :
# Ruby code for Time.strftime() method  # loading libraryrequire 'time'  # declaring time a = Time.new(2019)  # declaring timeb = Time.new(2019, 10)  # declaring timec = Time.new(2019, 12, 31)  # Time puts "Time a : #{a}\n\n"puts "Time b : #{b}\n\n"puts "Time c : #{c}\n\n\n\n"    # strftime form puts "Time a strftime form : #{a.strftime("at %I:%M %p")}\n\n"puts "Time b strftime form : #{b.strftime("Is published on %m/%d/%Y")}\n\n"puts "Time c strftime form : #{c.strftime("at %I:%M %p")}\n\n"
Output :
Time a : 2019-01-01 00:00:00 +0000

Time b : 2019-10-01 00:00:00 +0000

Time c : 2019-12-31 00:00:00 +0000



Time a strftime form : at 12:00 AM

Time b strftime form : Is published on 10/01/2019

Time c strftime form : at 12:00 AM

Example #2 :
# Ruby code for Time.strftime() method  # loading libraryrequire 'time'  # loading libraryrequire 'time'  # declaring time a = Time.now  # declaring timeb = Time.new(1000, 10, 10)  # declaring timec = Time.new(2020, 12)  # Time puts "Time a : #{a}\n\n"puts "Time b : #{b}\n\n"puts "Time c : #{c}\n\n\n\n"    # strftime form puts "Time a strftime form : #{a.strftime("at %I:%M %p")}\n\n"puts "Time b strftime form : #{b.strftime("Is published on %m/%d/%Y")}\n\n"puts "Time c strftime form : #{c.strftime("at %I:%M %p")}\n\n"
Output :
Time a : 2019-08-27 12:04:41 +0000

Time b : 1000-10-10 00:00:00 +0000

Time c : 2020-12-01 00:00:00 +0000



Time a strftime form : at 12:04 PM

Time b strftime form : Is published on 10/10/1000

Time c strftime form : at 12:00 AM


Ruby Time-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tensorflow.js tf.cast() Function

12 May, 2021
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.
The tf.cast() function is used to cast a specified Tensor to a new data type.
Syntax:
tf.cast (x, dtype)
Parameters: This function accepts two parameters which are illustrated below:
x: The input tensor which is being casted.
dtype: The data type in which input tensor is going to be casted.
Return Value: It returns a casted tensor of new data type.
Example 1:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Initializing a tensor of some valuesconst x = tf.tensor1d([2.3, 1.7, 5, 0, 1, 0.5]);  // Calling the .cast() function over the // above tensor to cast in "int32" data typetf.cast(x, 'int32').print();
Output:
 Tensor
   [2, 1, 5, 0, 1, 0]
Example 2:
Javascript
// Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs"  // Using a tensor of some values// as the parameter for .cast() function to// cast into bool data typetf.cast(tf.tensor1d([0, 1, -3]), 'bool').print();
Output:
Tensor
   [false, true, true]
Reference: https://js.tensorflow.org/api/latest/#cast
Picked
Tensorflow
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Date to Numeric in R?

19 Dec, 2021
In this article, we will discuss how to convert date to numeric in R Programming Language.
This function is used to convert date into numeric
Syntax:
as.numeric(date)
where the date is the input date.
Example:
R
data = as.POSIXct("1/1/2021  1:05:00 AM",                  format="%m/%d/%Y  %H:%M:%S %p")  # displayprint(data)  # convert to numericprint(as.numeric(data))
Output:
[1] "2021-01-01 01:05:00 UTC"
[1] 1609463100
If we want to get the number of days from the number, divide the number by 86400.
as.numeric(date)/86400
If we want to get the number of years from date, then divide it by 365.
as.numeric(date)/86400/365
Example: R program to convert dates into days and years
R
data = as.POSIXct("1/1/2021  1:05:00 AM",                   format="%m/%d/%Y  %H:%M:%S %p")  # displayprint(data)  # convert to numericprint(as.numeric(data))  # convert to numeric and get daysprint(as.numeric(data)/86400)  # convert to numeric and get yearsprint((as.numeric(data)/86400)/365)
Output:
[1] "2021-01-01 01:05:00 UTC"
[1] 1609463100
[1] 18628.05
[1] 51.03574
Here, By using this module, we can get the day, month, year, hour, minute, and second separately in integer format.
Syntax:
day:
day(date)

month:
month(date)

year:
year(date)

hour:
hour(date)

minute:
minute(date)

second:
second(date)
Example:
R
# load the librarylibrary("lubridate")  # create datedata = as.POSIXct("1/1/2021  1:05:00 AM",                   format="%m/%d/%Y  %H:%M:%S %p")  # displayprint(data)  # get the dayprint(day(data))  # get the monthprint(month(data))  # get the yearprint(year(data))  # get the hourprint(hour(data))  # get the minuteprint(minute(data))  # get the secondprint(second(data))
Output:
[1] "2021-01-01 01:05:00 UTC"
[1] 1
[1] 1
[1] 2021
[1] 1
[1] 5
[1] 0
Picked
R-DateTime
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 Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Python | Replace substring in list of strings

07 Jun, 2019
While working with strings, one of the most used application is replacing the part of string with another. Since string in itself is immutable, the knowledge of this utility in itself is quite useful. Here the replacement of a substring in list of string is performed. Let’s discuss certain ways in which this can be performed.
Method #1 : Using list comprehension + replace()The replace method can be coupled with the list comprehension technique to achieve this particular task. List comprehension performs the task of iterating through the list and replace method replaces the section of substring with another.
# Python3 code to demonstrate# Replace substring in list of strings# using list comprehension + replace()  # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks']  # printing original list  print("The original list : " + str(test_list ))  # using list comprehension + replace()# Replace substring in list of stringsres = [sub.replace('4', '1') for sub in test_list]      # print resultprint("The list after substring replacement : " + str(res))
The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']
The list after substring replacement : ['1', 'kg', 'butter', 'for', '10', 'bucks']

 
Method #2 : Using map() + lambda + replace()The combination of these functions can also be used to perform this particular task. The map and lambda help to perform the task same as list comprehension and replace method is used to perform the replace functionality. But this method is poor when it comes to performance than method above.
# Python3 code to demonstrate# Replace substring in list of strings# using list comprehension + map() + lambda  # initializing list test_list = ['4', 'kg', 'butter', 'for', '40', 'bucks']  # printing original list  print("The original list : " + str(test_list ))  # using list comprehension + map() + lambda# Replace substring in list of stringsres = list(map(lambda st: str.replace(st, "4", "1"), test_list))      # print resultprint("The list after substring replacement : " + str(res))
The original list : ['4', 'kg', 'butter', 'for', '40', 'bucks']
The list after substring replacement : ['1', 'kg', 'butter', 'for', '10', 'bucks']

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
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
ZoneId getAvailableZoneIds() method in Java with Examples

19 Aug, 2019
The getAvailableZoneIds() method of the ZoneId class used to get the set of available zone IDs.This set includes all available region-based IDs.The ID can be passed to of(String) to create a ZoneId.The set of zone IDs can increase over time, although in a typical application the set of IDs is fixed.
Syntax:
public static Set getAvailableZoneIds()

Parameters: This method does not accepts any parameter.
Return value: This method returns Set which are a modifiable copy of the set of zone IDs.
Below programs illustrate the getAvailableZoneIds() method:Program 1:
// Java program to demonstrate// ZoneId.getAvailableZoneIds() method  import java.time.*;import java.util.Set;  public class GFG {    public static void main(String[] args)    {          // get available zones using zoneIds()        Set<String> zoneIds = ZoneId.getAvailableZoneIds();          // print first record        System.out.println("First ZoneId in list:" + zoneIds.iterator().next());    }}
First ZoneId in list:Asia/Aden

Program 2:
// Java program to demonstrate// ZoneId.getAvailableZoneIds() method  import java.time.*;import java.util.*;  public class GFG {    public static void main(String[] args)    {          // get available zones using zoneIds()        Set<String> allZones = ZoneId.getAvailableZoneIds();          // create ArrayList from Set        List<String> zoneList = new ArrayList<String>(allZones);        Collections.sort(zoneList);          // printing first 5 zoneid with offset        LocalDateTime dt = LocalDateTime.now();        for (int i = 0; i < 5; i++) {              // get zoneid then ZonedDateTime and offset            // from that ZoneId            String s = zoneList.get(i);            ZoneId zoneid = ZoneId.of(s);            ZonedDateTime zoneddate = dt.atZone(zoneid);            ZoneOffset offset = zoneddate.getOffset();            System.out.println("ZoneId = " + zoneid + " offset = " + offset);        }    }}
ZoneId = Africa/Abidjan offset = Z
ZoneId = Africa/Accra offset = Z
ZoneId = Africa/Addis_Ababa offset = +03:00
ZoneId = Africa/Algiers offset = +01:00
ZoneId = Africa/Asmara offset = +03:00

References:https://docs.oracle.com/javase/10/docs/api/java/time/ZoneId.html#getAvailableZoneIds(java.lang.Object)
Akanksha_Rai
Java-Functions
Java-time package
Java-ZoneId
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Character arithmetic in C and C++

30 Jun, 2022
As already known character range is between -128 to 127 or 0 to 255. This point has to be kept in mind while doing character arithmetic. 
What is Character arithmetic ?
Character arithmetic is used to implement arithmetic operations like addition, subtraction ,multiplication ,division on characters in C and C++ language. In character arithmetic character converts into integer value to perform task. For this ASCII value is used.It is used to perform action the strings.
To understand better let’s take an example.
C
// C program to demonstrate character arithmetic.#include <stdio.h> int main(){    char ch1 = 125, ch2 = 10;    ch1 = ch1 + ch2;    printf("%d\n", ch1);    printf("%c\n", ch1 - ch2 - 4);    return 0;}
-121
y
So %d specifier causes an integer value to be printed and %c specifier causes a character value to printed. But care has to taken that while using %c specifier the integer value should not exceed 127. So far so good.But for c++ it plays out a little different.
Look at this example to understand better. 
C++
// A C++ program to demonstrate character// arithmetic in C++.#include <bits/stdc++.h>using namespace std; int main(){    char ch = 65;    cout << ch << endl;    cout << ch + 0 << endl;    cout << char(ch + 32) << endl;    return 0;}
Output: 
A
65
a
Without a ‘+’ operator character value is printed. But when used along with ‘+’ operator behaved differently. Use of ‘+’ operator implicitly typecasts it to an ‘int’. So to conclude, in character arithmetic, typecasting of char variable to ‘char’ is explicit and to ‘int’ it is implicit. 
let’s take one more example.
C
#include <stdio.h>// driver codeint main(void){    char value1 = 'a';    char value2 = 'b';    char value3 = 'z';    // perform character arithmetic    char num1 = value1 + 3;    char num2 = value2 - 1;    char num3 = value3 + 2;    // print value    printf("numerical value=%d\n", num1);    printf("numerical value=%d\n", num2);    printf("numerical value=%d\n", num3);    return 0;}
Output:
numerical value=100  
numerical value=97
numerical value=124
This article is contributed by Parveen Kumar. 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. 
parasmadan15
reshmapatil2772
sagartomar9927
cpp-data-types
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Python | Convert an HTML table into excel

25 Jun, 2019
MS Excel is a powerful tool for handling huge amounts of tabular data. It can be particularly useful for sorting, analyzing, performing complex calculations and visualizing data. In this article, we will discuss how to extract a table from a webpage and store it in Excel format.
Step #1: Converting to Pandas dataframePandas is a Python library used for managing tables. Our first step would be to store the table from the webpage into a Pandas dataframe. The function read_html() returns a list of dataframes, each element representing a table in the webpage. Here we are assuming that the webpage contains a single table.
# Importing pandasimport pandas as pd  # The webpage URL whose table we want to extracturl = "https://www.geeksforgeeks.org/extended-operators-in-relational-algebra/"  # Assign the table data to a Pandas dataframetable = pd.read_html(url)[0]  # Print the dataframeprint(table)
Output
         0       1        2           3    4
0  ROLL_NO    NAME  ADDRESS       PHONE  AGE
1        1     RAM    DELHI  9455123451   18
2        2  RAMESH  GURGAON  9652431543   18
3        3   SUJIT   ROHTAK  9156253131   20
4        4  SURESH    DELHI  9156768971   18

 Step #2: Storing the Pandas dataframe in an excel fileFor this, we use the to_excel() function of Pandas, passing the filename as a parameter.
# Importing pandasimport pandas as pd  # The webpage URL whose table we want to extracturl = "https://www.geeksforgeeks.org/extended-operators-in-relational-algebra/"  # Assign the table data to a Pandas dataframetable = pd.read_html(url)[0]  # Store the dataframe in Excel filetable.to_excel("data.xlsx")
Output:
In case of multiple tables on the webpage, we can change the index number from 0 to that of the required table.
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
Convert integer to string in Python
Difference between static, auto, global and local variable in C++

There are two separate concepts here −
scope, which determines where a name can be accessed - global and local
storage duration, which determines when a variable is created and destroyed - static and auto
Local variables can be used only by statements that are inside that function or block of code. Local variables are not known to functions on their own.
 Live Demo
#include <iostream>
using namespace std;

int main () {
   // Local variable declaration:
   int a, b;
   int c;

   // actual initialization
   a = 10;
   b = 20;
   c = a + b;

   cout << c;
   return 0;
}
This will give the output −
30

Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program. A global variable can be accessed by any function.
 Live Demo
#include <iostream>
using namespace std;

// Global variable declaration:
int g;

int main () {
   // Local variable declaration:
   int a, b;

   // actual initialization
   a = 10;
   b = 20;
   g = a + b;

   cout << g;
   return 0;
}
This will give the output −
30

Automatic variables are local variables whose lifetime ends when execution leaves their scope, and are recreated when the scope is reentered.
for (int i =0 0; i < 5; ++i) {
   int n = 0;
   printf("%d ", ++n); // prints 1 1 1 1 1 - the previous value is lost
}
Static variables have a lifetime that lasts until the end of the program. If they are local variables, then their value persists when execution leaves their scope.
for (int i = 0; i < 5; ++i) {
   static int n = 0;
   printf("%d ", ++n); // prints 1 2 3 4 5 - the value persists
}
Note that the static keyword has various meanings apart from static storage duration. Also, in C++ the auto keyword no longer means automatic storage duration; it now means automatic type, deduced from the variable's initializer.
Python String join() Method

Python string  method join() returns a string in which the string elements of sequence have been joined by str separator.
Following is the syntax for join() method −
str.join(sequence)

sequence − This is a sequence of the elements to be joined.
sequence − This is a sequence of the elements to be joined.
This method returns a string, which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method.
The following example shows the usage of join() method.
#!/usr/bin/python

s = "-";
seq = ("a", "b", "c"); # This is sequence of strings.
print s.join( seq )
When we run above program, it produces following result −
PHP $_POST

$_POST is a predefined variable which is an associative array of key-value pairs passed to a URL by HTTP POST method that uses URLEncoded or multipart/form-data content-type in request.
$HTTP_POST_VARS also contains the same information, but is not a superglobal, and now been deprecated.
Easiest way to send data to server with POST request is specifying method attribute of HTML form as POST. Assuming that the URL in browser is http://localhost/testscript.php, method=POST is set in a HTML form test.html as below −
<form action="testscript.php" method="POST">
   <input type="text" name="name">
   <input type="text" name="age">
   <input type ="submit" value="submit">
</form>
The PHP script is as follows:
<?php
echo "Name : " . $_POST["name"] . "<br>";
echo "Age : " . $_POST["age"];
?>
This will produce following result −
Name : xyz
Age : 20
In following example, htmlspecialchars() function is used to convert characters in HTML entities.
Assuming that the user posted dta as name=xyz and age=20
<?php
echo "Name: " . htmlspecialchars($_POST["name"]) . "<br>";
echo "age: " . htmlspecialchars($_POST["age"]) . "<br>";
?>
This will produce following result −
Name : xyz
Age : 20
Python | Ways to invert mapping of dictionary

18 Feb, 2019
Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning.Let’s discuss a few ways to invert mapping of a dictionary.Method #1: Using Dictionary Comprehension.
# Python code to demonstrate# how to invert mapping # using dict comprehension  # initialising dictionaryini_dict = {101: "akshat", 201 : "ball"}  # print initial dictionaryprint("initial dictionary : ", str(ini_dict))  # inverse mapping using dict comprehensioninv_dict = {v: k for k, v in ini_dict.items()}  # print final dictionaryprint("inverse mapped dictionary : ", str(inv_dict))
initial dictionary :  {201: 'ball', 101: 'akshat'}
inverse mapped dictionary :  {'ball': 201, 'akshat': 101}

Method #2: Using dict.keys() and dict.values()
# Python code to demonstrate# how to invert mapping # using zip and dict functions  # initialising dictionaryini_dict = {101: "akshat", 201 : "ball"}  # print initial dictionaryprint("initial dictionary : ", str(ini_dict))  # inverse mapping using zip and dict functionsinv_dict = dict(zip(ini_dict.values(), ini_dict.keys()))  # print final dictionaryprint("inverse mapped dictionary : ", str(inv_dict))
initial dictionary :  {201: 'ball', 101: 'akshat'}
inverse mapped dictionary :  {'ball': 201, 'akshat': 101}

Method #3: Using map() and reversed
# Python code to demonstrate# how to invert mapping # using map and reversed  # initialising dictionaryini_dict = {101: "akshat", 201 : "ball"}  # print initial dictionaryprint("initial dictionary : ", str(ini_dict))  # inverse mapping using map and reversedinv_dict = dict(map(reversed, ini_dict.items()))  # print final dictionaryprint("inverse mapped dictionary : ", str(inv_dict))
initial dictionary :  {201: 'ball', 101: 'akshat'}
inverse mapped dictionary :  {'akshat': 101, 'ball': 201}

Method #4: Using lambda
# Python code to demonstrate# how to invert mapping # using lambda  # initialising dictionaryini_dict = {101 : "akshat", 201 : "ball"}  # print initial dictionaryprint("initial dictionary : ", str(ini_dict))  # inverse mapping using lambdalambda ini_dict: {v:k for k, v in ini_dict.items()}  # print final dictionaryprint("inverse mapped dictionary : ", str(ini_dict))
initial dictionary :  {201: 'ball', 101: 'akshat'}
inverse mapped dictionary :  {201: 'ball', 101: 'akshat'}

Marketing
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to extract date from a string in dd-mmm-yyyy format in JavaScript ?

09 Dec, 2020
In this article, we will see how to extract date from a given string of format “dd-mmm-yyyy” in JavaScript. We have a string, and we want to extract the date format “dd-mmm-yyyy” from the string.
Example:
// String
str = "India got freedom on 15-Aug-1947"

// Extracted date from given string in 
// "dd-mmm-yyyy" format
date = 15-Aug-1947
Approach:
There is no native format in JavaScript for” dd-mmm-yyyy”. To get the date format “dd-mmm-yyyy”, we are going to use regular expression in JavaScript. 
The regular expression in JavaScript is used to find the pattern in a string. So we are going to find the “dd-mmm-yyyy” pattern in the string using match() method.
Syntax:str.match(/\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/gi);
str.match(/\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/gi);
Example:
HTML
<!DOCTYPE html>  <html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">      <meta http-equiv="X-UA-Compatible"         content="ie=edge"></head>  <body>      <!-- div element -->    <div style="color: red;        background-color: black;        margin: 80px 80px;        padding: 40px 400px;">        India got freedom on 15-Aug-1947.          <p></p>          <button>            Click the button to see date        </button>    </div>      <!-- Link of JQuery cdn -->    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script>      <script>          // After clicking the button it will         // show the height of the div        $("button").click(function () {              // String that contains date            var str = "India got freedom on 15-Aug-1947"              // Find "dd-mmm-yyyy" format in the string            var result =str.match(/\d{2}-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{4}/gi);              // Show date on screen in             // format "dd-mmm-yyyy"            $("p").html(result);        });    </script></body>  </html>
Before clicking the button:
After clicking the button:
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
When is a semicolon after } mandated in C++ Program?

A semicolon after a close brace is mandatory if this is the end of a declaration. In case of braces, they have used in declarations of class, enum, struct, and initialization syntax. At the end of each of these statements, we need to put a semicolon. For example,
class X {};    // same declaration for struct as well
enum Y {};
int z[] = {1,2};
A semicolon by itself is an empty statement, and you'll be able to add additional ones anywhere a statement is legal. Therefore it might be legal to place a semicolon right after the braces following your if, although it wouldn't be related to them if at all.
Add a User in Linux using Python Script - GeeksforGeeks

04 May, 2020
Creating a user via command line in Linux is a tedious task. Every time someone joins your organization and you need to type a long Linux command rather than doing this you can create a python script that can ask for you the username and password and create that user for you.
Examples:
Input : 
Enter Username : John
Password: ****


Output :
User successfully created with given credentials

Below is the Python code –
# importing linraryimport osimport subprocessimport sysimport getpass  # add user functiondef add_user():       # Ask for the input     username = input("Enter Username ")          # Asking for users password     password = getpass.getpass()   4              try:         # executing useradd command using subprocess module         subprocess.run(['useradd', '-p', password, username ])           except:         print(f"Failed to add user.")                              sys.exit(1)  add_user()
Output:
After successfully creating the user type, use this command to get details of new user –
cat /etc/passwd
python-utility
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Convert integer to string in Python
Convert string to integer in Python
Python infinity
How to set input type date in dd-mm-yyyy format using HTML ?
Matplotlib.pyplot.title() in Python
How to append elements in Python tuple?

Python tuple is an immutable object. Hence any operation that tries to modify it (like append) is not allowed. However, following workaround can be used.
First, convert tuple to list by built-in function list(). You can always append item to list object. Then use another built-in function tuple() to convert this list object back to tuple.
>>> T1=(10,50,20,9,40,25,60,30,1,56)
>>> L1=list(T1)
>>> L1
[10, 50, 20, 9, 40, 25, 60, 30, 1, 56]
>>> L1.append(100)
>>> T1=tuple(L1)
>>> T1
(10, 50, 20, 9, 40, 25, 60, 30, 1, 56, 100)
You can see new element appended to original tuple representation.
How to launch Edge browser with Selenium Webdriver?

We can launch Edge browser with Selenium webdriver by using the Microsoft webdriver. We should also ensure that we are having the machine with the Windows 10 operating system.
Navigate to the below link to download the Microsoft Edge driver executable file − https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
Once the page is launched, scroll down to the Downloads section, then choose and click the link which is compatible with our local Edge browser version.
A zip file gets created, once the download is completed successfully. We have to then unzip the file and save it in a desired location. Then, set the path of the msedgedriver.exe file. This is done by utilizing the System.setProperty method.
Finally we have to create an instance of the EdgeDriver class.
System.setProperty("webdriver.edge.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\msedgedriver.exe");
WebDriver d = new EdgeDriver();
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class EdgeBrwser{
   public static void main(String[] args) {
      //set path of msedgedriver.exe path
      System.setProperty("webdriver.edge.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\msedgedriver.exe");
      //instance of EdgeDriver
      WebDriver driver = new EdgeDriver();
      //URL launch
      driver.get("https://www.tutorialspoint.com/index.htm");
   }
}
C# Program to Convert Integer to String

To convert an integer to string in C#, use the ToString() method.
Set the integer for which you want the string −
int num = 299;
Use the ToString() method to convert Integer to String −
String s;
int num = 299;
s = num.ToString();
You can try to run the following code to convert an integer to string in C# −
Live Demo
using System;
class MyApplication {
   static void Main(string[] args) {
      String s;
      int num = 299;
      s = num.ToString();
      Console.WriteLine("String = "+s);
      Console.ReadLine();
   }
}
String = 299
Julia local Keyword | Creating a local variable in Julia - GeeksforGeeks

02 Sep, 2021
Keywords in Julia are reserved words whose value is pre-defined to the compiler and can not be changed by the user. These words have a specific meaning and perform their specific operation on execution.‘local’ keyword in Julia is used to create a variable of a limited scope whose value is local to the scope of the block in which it is defined. Syntax:  
var1 = value1
loop condition
    statement
    local var1
    statement
end
Example 1:  
Python3
# Julia program to illustrate# the use of local variable for i in 1:10    x = iend # Accessing local variable# from outside of the loopprintln(x)
Output:  
ERROR: LoadError: UndefVarError: x not defined
Above code generates error because the scope of variable x is limited to the scope of for-loop in which it is defined.Example 2:  
Python3
# Julia program to illustrate# the use of local variable # Defining functionfunction check_local()    x = 0    for i in 1:5             # Creating local variable        local x        x = i * 2        println(x)    end    println(x)end # Function callcheck_local()
Output:  
2
4
6
8
10
0
In the above code, it can be seen that when the value of x is printed within the loop, the output is as per condition, but when the value of x is printed outside the scope of for-loop, the value of x is again 0 as assigned earlier. This shows that the scope of the local variable remains limited to the block in which it is defined. 
gulshankumarar231
Julia-keywords
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Reshaping array dimensions in Julia | Array reshape() Method
Storing Output on a File in Julia
Comments in Julia
Manipulating matrices in Julia
while loop in Julia
Formatting of Strings in Julia
Tuples in Julia
Searching in Array for a given element in Julia
What is difference in Python operators != and "is not"?

In Python != is defined as not equal to operator. It returns true if operands on either side are not eual to each other, and returns false if they are equal.
>>> (10+2) != 12                # both expressions are same hence false
False
>>> (10+2)==12                
True
>>> 'computer' != "computer"     # both strings are equal(single and double quotes same)
False
>>> 'computer' != "COMPUTER"   #upper and lower case strings differ
True
Whereas is not operator checks whether id() of two objects is same or not. If same, it returns false and if not same, it returns true
>>> a=10
>>> b=a
>>> id(a), id(b)
(490067904, 490067904)
>>> a is not b
False
>>> a=10
>>> b=20
>>> id(a), id(b)
(490067904, 490068064)
>>> a is not b
True
Java NumberFormat.getCurrencyInstance() method

The getCurrencyInstance() method of the NumberFormat class returns the instance of the NumberFormat class. The java.text.NumberFormat class is used for formatting numbers and currencies as per a specific Locale. Number formats varies from country to country
Here, we have considered a locale.
NumberFormat n = NumberFormat.getCurrencyInstance(Locale.FRANCE);
Then, we have formatted a double value with the currency.
double points = 1.78;
System.out.println(n.format(points));
The following is the final example.
 Live Demo
import java.text.NumberFormat;
import java.util.Locale;
public class MainClass {
    public static void main(String[] args) {
       // Currency of France is Euro
       NumberFormat n = NumberFormat.getCurrencyInstance(Locale.FRANCE);
       // points
       double points = 1.78;
       double totalPoints = points * 1000;
       System.out.println(n.format(points));
       System.out.println(n.format(totalPoints));
    }
}
1,78 €
1 780,00 €
How to create an unordered list without bullets in HTML?

To create unordered list in HTML, use the <ul> tag. Unordered list starts with the <ul> tag. The list item starts with the <li> tag and will be marked as disc, square, circle, none, etc. The default is bullets, which is small black circles.
For creating an unordered list without bullets, use CSS property list-style-type. We will be using the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <ul> tag, with the CSS property list-style-type to remove bullets in an unordered list. 
Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet.
You can try to run the following code to create an unordered list without bullets in HTML −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>HTML Unordered List</title>
   </head>
   <body>
      <h1>Developed Countries</h1>
      <p>The list of developed countries :</p>
      <ul style="list-style-type:none">
         <li>US</li>
         <li>Australia</li>
         <li>New Zealand</li>
      </ul>
   </body>
</html>
How to extract the text of a webelement in Selenium?

Selenium extracts the text of a webelement with the help of getText() method.
Code Implementation with getText().
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ExtractText {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      //Using id with # for css expression
      driver.findElement(By.cssSelector("#gsc-i-id1")).sendKeys("Selenium");
      // extracting the text entered in console with getText()
      System.out.println(“The entered text is:” driver.findElement(By.cssSelector("#gsc-i-         id1")).getText());
      driver.close();
   }
}
Explain ‘simple if’ statement in C language

‘if’ keyword is used to execute a set of statements when the logical condition is true.
The syntax is given below −
if (condition){
   Statement (s)
}
The statement inside the if block are executed only when condition is true, otherwise not.
The statement inside the if block are executed only when condition is true, otherwise not.
If we want to execute only one statement when condition is true, then braces ({}) can be removed. In general, we should not omit the braces even if, there is a single statement to execute.
If we want to execute only one statement when condition is true, then braces ({}) can be removed. In general, we should not omit the braces even if, there is a single statement to execute.
When the condition is true the braces ({}) are required to execute more than one statement.
When the condition is true the braces ({}) are required to execute more than one statement.
Given below is the C program to execute If conditional operators −
 Live Demo
#include<stdio.h>
void main (){
   int a=4;
   printf("Enter the value of a: ");
   scanf("%d",&a);
   if(a%2==1){
      printf("a is odd number");
   }
   Return 0;
}
You will see the following output −
Run 1: Enter the value of a: 56
a is even number
Run2: Enter the value of a: 33
Here, if condition becomes false, as a result, statement inside the if block is skipped.
PyQt5 – How to adjust size of ComboBox according to the items size

22 Apr, 2020
In this article we will see how we can adjust the combo box according to the size of item according to item which has maximum size among the item list. By default we use setGeometry method and setSize method to adjust the size but it will not automatically adjust the size according to the item size.
In order to adjust the size according to the maximum length item size we use adjustSize method
Syntax : combo_box.adjustSize()
Argument : It takes no argument
Return : None
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, 600, 400)          # calling method        self.UiComponents()          # showing all the widgets        self.show()      # method for widgets    def UiComponents(self):          # creating a combo box widget        self.combo_box = QComboBox(self)          # setting geometry of combo box        self.combo_box.setGeometry(200, 150, 200, 50)          # geek list        geek_list = ["Sayian", "Super Saiyan", "Super Sayian 2", "Super Sayian Blue"]          # making it editable        self.combo_box.setEditable(True)          # adding list of items to combo box        self.combo_box.addItems(geek_list)          # adjusting the size according to the maximum sized element        self.combo_box.adjustSize()      # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt5-ComboBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
v-for Directive in Vue.js

25 Jun, 2020
v-for directive is a Vue.js directive used to loop over a data usually an array or object. First, we will create a div element with id as app and let’s apply the v-for directive to an element with data. Now we will create this data by initializing a Vue instance with the data attribute containing the value.
Syntax:
v-for="data in datas"
Parameters: This function accepts data which is either an array or object over which we will loop over.
Example: This example uses Vue.js to loop over an array with v-for.
<!DOCTYPE html><html>  <head>    <title>        VueJS | v-for directive    </title>      <!-- Load Vuejs -->    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">    </script></head>  <body>    <div style="text-align: center;        width: 600px;">                  <h1 style="color: green;">            GeeksforGeeks        </h1>                  <b>            VueJS | v-for directive        </b>    </div>      <div id="canvas" style=        "border:1px solid #000000;        width: 600px;height: 200px;">          <div id="app">            <h2 v-for="data in datas">                {{data}}            </h2>        </div>    </div>      <script>        var app = new Vue({            el: '#app',            data: {                datas: [                    'Hello',                     'World',                     'GeeksforGeeks'                ]            }        })    </script></body>  </html>
Output:
Vue.JS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Concatenate Column Values in Pandas DataFrame?

10 Jul, 2020
Many times we need to combine values in different columns into a single column. There can be many use cases of this, like combining first and last names of people in a list, combining day, month, and year into a single column of Date, etc. Now we’ll see how we can achieve this with the help of some examples.
Example 1: In this example, we’ll combine two columns of first name last name to a column name. To achieve this we’ll use the map function.
import pandas as pdfrom pandas import DataFrame    # creating a dictionary of namesNames = {'FirstName':['Suzie','Emily','Mike','Robert'],         'LastName':['Bates','Edwards','Curry','Frost']}   # creating a dataframe from dictionarydf = DataFrame(Names, columns=['FirstName','LastName'])print(df)   print('\n')   # concatenating the columnsdf['Name'] = df['FirstName'].map(str) + ' ' + df['LastName'].map(str)print(df)
Output:
Example 2: Similarly, we can concatenate any number of columns in a dataframe. Let’s see through another example to concatenate three different columns of the day, month, and year in a single column Date.
import pandas as pdfrom pandas import DataFrame   # creating a dictionary of DatesDates = {'Day': [1, 29, 23, 4, 15],         'Month': ['Aug', 'Feb', 'Aug', 'Apr', 'Mar'],         'Year': [1947, 1983, 2007, 2011, 2020]}  # creating a dataframe from dictionarydf = DataFrame(Dates, columns = ['Day', 'Month', 'Year'])print (df)  print('\n')  # concatenating the columnsdf['Date'] = df['Day'].map(str) + '-' + df['Month'].map(str) + '-' + df['Year'].map(str)print (df)
Output:
Example 3:
We can take this process further and concatenate multiple columns from multiple different dataframes. In this example, we combine columns of dataframe df1 and df2 into a single dataframe.
import pandas as pdfrom pandas import DataFrame   # creating a dictionary of DatesDates = {'Day': [1, 1, 1, 1],         'Month': ['Jan', 'Jan', 'Jan', 'Jan'],         'Year': [2017, 2018, 2019, 2020]}   # creating a dataframe from dictionarydf1 = DataFrame(Dates, columns = ['Day', 'Month', 'Year'])   # creating a dictionary of RatesRates = {'GDP': [5.8, 7.6, 5.6, 4.1],          'Inflation Rate': [2.49, 4.85, 7.66, 6.08]}   # creating a dataframe from dictionarydf2 = DataFrame(Rates, columns = ['GDP', 'Inflation Rate'])  # combining columns of df1 and df2df_combined = df1['Day'].map(str) + '-' + df1['Month'].map(str) + '-' + df1['Year'].map(str) + ': ' + 'GDP: ' + df2['GDP'].map(str) + '; ' + 'Inflation: ' + df2['Inflation Rate'].map(str)print (df_combined)
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Longest Valid Parentheses in Python

Suppose we have a string, with opening and closing parentheses. We have to find the longest length of the valid (well-formed) parentheses. So if the input is like “))(())())”, then the result will be 6, as the valid string is “(())()”.
To solve this, we will follow these steps −
Make a stack, and insert -1., set ans := 0
Make a stack, and insert -1., set ans := 0
for i in range 0 to length of stack – 1if s[i] is opening parentheses, then insert i into stackotherwiseif stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, thentop element from stackans := max of ans and i – stack topotherwise insert i into stack
for i in range 0 to length of stack – 1
if s[i] is opening parentheses, then insert i into stack
if s[i] is opening parentheses, then insert i into stack
otherwiseif stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, thentop element from stackans := max of ans and i – stack topotherwise insert i into stack
otherwise
if stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, thentop element from stackans := max of ans and i – stack top
if stack is not empty and top of stack is not -1 and s[stack top] is opening parentheses, then
top element from stack
top element from stack
ans := max of ans and i – stack top
ans := max of ans and i – stack top
otherwise insert i into stack
otherwise insert i into stack
return ans
return ans
Let us see the following implementation to get a better understanding −
 Live Demo
class Solution(object):
   def longestValidParentheses(self, s):
      stack = [-1]
      ans = 0
      for i in range(len(s)):
         if s[i] == "(":
            stack.append(i)
         else:
            if stack and stack[-1]!=-1 and s[stack[-1]] == "(":
               stack.pop()
               ans = max(ans,i - stack[-1])
            else:
            stack.append(i)
      return ans
ob = Solution()
print(ob.longestValidParentheses("))(())())"))
"))(())())"
6