code-rag-bench/online-tutorials huggingface dataset:
Calculating median of an array in JavaScript

Following is the code for calculating median of an array in JavaScript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample {
      color: red;
   }
</style>
</head>
<body>
<h1>Calculating median of an array</h1>
<div><pre class="sample"></pre></div>
<div class="result"></div>
<button class="Btn">Calculate</button>
<h3>Click on the above button to calculate the median of the above array</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let sampleEle = document.querySelector(".sample");
   let arr = [1, 5, 6, 99, 12, 11, 22];
   sampleEle.innerHTML = arr;
   BtnEle.addEventListener("click", () => {
      let middle = Math.floor(arr.length / 2);
      arr = [...arr].sort((a, b) => a - b);
      if (arr.length % 2 !== 0) {
         resEle.innerHTML = "Median = " + arr[middle];
      } else {
         resEle.innerHTML = "Median = " + (arr[middle - 1] + arr[middle]) / 2;
      }
   });
</script>
</body>
</html>
On clicking the ‘Calculate’ button −
How to remove text from a label in Python?

20 Jul, 2021
Prerequisite: Python GUI – tkinter
In this article, the Task is to remove the text from label, once text is initialized in Tkinter. Python offers multiple options for developing GUI (Graphical User Interface) out of which Tkinter is the most preferred means. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest, most reliable and easiest way to create a desired GUI application. 
The Task is to remove the text from label, once text is initialized in Tkinter.
Approach:
Import module
Create a normal Tkinter window.
Add Label and Create One Button
Syntax:
Text(Object Name,text=”Enter Text”, **attr)
For remove the text, we will use config() method in Tkinter
config is used to access an object’s attributes after its initialization.
Syntax:
Object_Name.config(**attr)
Given below is the program to implement the same:
Python3
# Import Modulefrom tkinter import * # Create Objectroot = Tk() # specify size of window.root.geometry("400x400") # Remove text from label def remove_text():    label.config(text="") # Create Labellabel = Label(root, text="Hello World!", font="BOLD")label.pack() # Create Delete ButtonButton(root, text="Delete", command=remove_text).pack() # Execute Tkinterroot.mainloop()
Output:
Output:before clicking delete
Output:after clicking delete
sagartomar9927
Picked
Python-tkinter
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Create a simple Animation using Turtle in Python

20 Jan, 2022
Prerequisites: Turtle Programming in PythonTurtle is a Python feature like a drawing board, which lets us command a turtle to draw all over it! We can use functions like turtle.forward(...) and turtle.right(...) which can move the turtle around. Let’s create a basic animation where different little turtles race around a track created for them. 
 
Turtle Module
Random Module
 
 
Firstly, import the required modules.
There are different shapes of pointer available in the turtle module(like arrow, classic and turtle). As this is a “Turtle Race”, we need the ‘turtle’ and ‘classic’ shape.
We’ll use the classic shape to draw the racing track.
List the specs of the first turtle, enter the turtle in the track and set the turtle ready for the race.
Do the same for the rest of the turtles.
Use the randint() to set the speed of the turtles.
Below is the implementation.  
Python3
# required modulesfrom turtle import * from random import randint       # classic shape turtlespeed(0)penup()goto(-140, 140)  # racing track for step in range(15):    write(step, align ='center')    right(90)         for num in range(8):        penup()        forward(10)        pendown()        forward(10)             penup()    backward(160)    left(90)    forward(20) # first player detailsplayer_1 = Turtle()player_1.color('red')player_1.shape('turtle')  # first player proceeds to racing trackplayer_1.penup()player_1.goto(-160, 100)player_1.pendown()  # 360 degree turnfor turn in range(10):    player_1.right(36) # second player detailsplayer_2 = Turtle()player_2.color('blue')player_2.shape('turtle')  # second player enters in the racing trackplayer_2.penup()player_2.goto(-160, 70)player_2.pendown()  # 360 degree turnfor turn in range(72):    player_2.left(5) # third player detailsplayer_3 = Turtle()player_3.shape('turtle')player_3.color('green')  # third player enters in the racing trackplayer_3.penup()player_3.goto(-160, 40)player_3.pendown()  # 360 degree turnfor turn in range(60):    player_3.right(6) # fourth player detailsplayer_4 = Turtle()player_4.shape('turtle')player_4.color('orange')  # fourth player enters in the racing trackplayer_4.penup()player_4.goto(-160, 10)player_4.pendown()  # 360 degree turnfor turn in range(30):    player_4.left(12) # turtles run at random speedsfor turn in range(100):    player_1.forward(randint(1, 5))    player_2.forward(randint(1, 5))    player_3.forward(randint(1, 5))    player_4.forward(randint(1, 5))
Output: 
 
sumitgumber28
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to find longitude and latitude for a list of Regions or Country using Python

16 Jul, 2020
Geopy is a Python 2 and 3 client for several popular geocoding web services. Geocoding is the process to identify geographic coordinates like latitude and longitude of a given city/country/address. This is very useful during marking position on the map in data visualization. We use geopy.exec, geocodertimedout, geolocators, geopy.geocoder in the below code to fetch the results
This module does not come built-in with Python. To install it type the below command in the terminal.
pip install geopy 

Example: Let’s create a pandas dataframe containing a list of regions or countries.
# Import pandas package  import pandas as pd import numpy as np    # Define a dictionary containing  data data = {'City':['Bangalore', 'Mumbai', 'Chennai', 'Delhi']}     # Convert the dictionary into DataFrame df = pd.DataFrame(data)     # Observe the result df 
Output:
Now Let’s find the latitude and longitude of the following regions or countries.
from geopy.exc import GeocoderTimedOutfrom geopy.geocoders import Nominatim   # declare an empty list to store# latitude and longitude of values # of city columnlongitude = []latitude = []   # function to find the coordinate# of a given city def findGeocode(city):           # try and catch is used to overcome    # the exception thrown by geolocator    # using geocodertimedout      try:                  # Specify the user_agent as your        # app name it should not be none        geolocator = Nominatim(user_agent="your_app_name")                  return geolocator.geocode(city)          except GeocoderTimedOut:                  return findGeocode(city)      # each value from city column# will be fetched and sent to# function find_geocode   for i in (df["City"]):          if findGeocode(i) != None:                   loc = findGeocode(i)                  # coordinates returned from         # function is stored into        # two separate list        latitude.append(loc.latitude)        longitude.append(loc.longitude)           # if coordinate for a city not    # found, insert "NaN" indicating     # missing value     else:        latitude.append(np.nan)        longitude.append(np.nan)
Showing the output produced as dataframe.
# now add this column to dataframedf["Longitude"] = longitudedf["Latitude"] = latitude  df
Output:
nidhi_biet
python-modules
Python-projects
python-utility
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Sum of different length Lists of list

14 May, 2020
Getting the sum of list is quite common problem and has been dealt with and discussed many times, but sometimes, we require to better it and total sum, i.e. including those of nested list as well. Let’s try and get the total sum and solve this particular problem.
Method #1 : Using list comprehension + sum()We can solve this problem using the list comprehension as a potential shorthand to the conventional loops that we may use to perform this particular task. We just iterate and sum the nested list and at end return the cumulative sum using sum function.
# Python3 code to demonstrate# Sum of Uneven Lists of list# Using list comprehension + sum()  # initializing listtest_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension + sum()# Sum of Uneven Lists of listres = sum([ele for sub in test_list for ele in sub])  # print resultprint("The total element sum in lists is : " + str(res))
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element sum in lists is : 80

 
Method #2 : Using chain() + sum()This particular problem can also be solved using the chain function instead of list comprehension in which we use the conventional sum function to check the sum.
# Python3 code to demonstrate# Sum of Uneven Lists of list# Using chain() + sum()from itertools import chain  # initializing listtest_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]  # printing original listprint("The original list : " + str(test_list))  # using chain() + sum()# Sum of Uneven Lists of listres = sum(list(chain(*test_list)))  # print resultprint("The total element sum in lists is : " + str(res))
The original list : [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
The total element sum in lists is : 80

Python list-programs
Python-list-of-lists
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Call a C function in Python

12 Apr, 2021
Have you ever came across the situation where you have to call C function using python? This article is going to help you on a very basic level and if you have not come across any situation like this, you enjoy knowing how it is possible.First, let’s write one simple function using C and generate a shared library of the file. Let’s say file name is function.c. 
C
int myFunction(int num){    if (num == 0)         // if number is 0, do not perform any operation.        return 0;    else        // if number is power of 2, return 1 else return 0          return ((num & (num - 1)) == 0 ? 1 : 0) ; }
Compile this : 
cc -fPIC -shared -o libfun.so function.c
The above statement will generate a shared library with the name libfun.so. Now, let’s see how to make use of it in python. In python, we have one library called ctypes. Using this library we can use C function in python. Let’s say file name is function.py.  
Python3
import ctypesNUM = 16     # libfun loaded to the python file# using fun.myFunction(),# C function can be accessed# but type of argument is the problem.                        fun = ctypes.CDLL("libfun.so") # Or full path to file # Now whenever argument# will be passed to the function                                                       # ctypes will check it.           fun.myFunction.argtypes = [ctypes.c_int] # now we can call this# function using instant (fun)# returnValue is the value# return by function written in C# codereturnVale = fun.myFunction(NUM)       
srishti verma
paulivancristofari
anurag vashisth
Articles
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Time Complexity and Space Complexity
SQL Interview Questions
Understanding "extern" keyword in C
SQL | Views
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Lodash _.forEach() Method

16 Sep, 2020
The _.forEach() method iterates over elements of collection and invokes iteratee for each element.
Syntax:
_.forEach( collection, [iteratee = _.identity] )

Parameters: This method accepts two parameters as mentioned above and described below:
collection: This parameter holds the collection to iterate over.
iteratee: It is the function that is invoked per iteration.
Return Value: This method returns the collection.
Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.  
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Use of _.forEach() method _.forEach(['c', 'cpp', 'java','python'], function(value) {  console.log(value);});
Output:
'c'
'cpp'
'java'
'python'
['c', 'cpp', 'java','python']

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Use of _.forEach() method _.forEach({ 'x': 1, 'y': 2 }, function(value, key) {  console.log(key);});
Output:
'x'
'y'
{ 'x': 1, 'y': 2 }

Note: This will not work in normal JavaScript because it requires the library lodash to be installed. 
Reference: https://lodash.com/docs/4.17.15#forEach
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Roadmap to Learn JavaScript For Beginners
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Seaborn - Visualizing Pairwise Relationship

Datasets under real-time study contain many variables. In such cases, the relation between each and every variable should be analyzed. Plotting Bivariate Distribution for (n,2) combinations will be a very complex and time taking process.
To plot multiple pairwise bivariate distributions in a dataset, you can use the pairplot() function. This shows the relationship for (n,2) combination of variable in a DataFrame as a matrix of plots and the diagonal plots are the univariate plots.
In this section, we will learn what are Axes, their usage, parameters, and so on.
seaborn.pairplot(data,...)
Following table lists down the parameters for Axes −
data
Dataframe
hue
Variable in data to map plot aspects to different colors.
palette
Set of colors for mapping the hue variable
kind
Kind of plot for the non-identity relationships. {‘scatter’, ‘reg’}
diag_kind
Kind of plot for the diagonal subplots. {‘hist’, ‘kde’}
Except data, all other parameters are optional. There are few other parameters which pairplot can accept. The above mentioned are often used params.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('iris')
sb.set_style("ticks")
sb.pairplot(df,hue = 'species',diag_kind = "kde",kind = "scatter",palette = "husl")
plt.show()
We can observe the variations in each plot. The plots are in matrix format where the row name represents x axis and column name represents the y axis.
The diagonal plots are kernel density plots where the other plots are scatter plots as mentioned.
Teradata - JOIN strategies

This chapter discusses the various JOIN strategies available in Teradata.
Teradata uses different join methods to perform join operations. Some of the commonly used Join methods are −
Merge Join
Nested Join
Product Join
Merge Join method takes place when the join is based on the equality condition. Merge Join requires the joining rows to be on the same AMP. Rows are joined based on their row hash. Merge Join uses different join strategies to bring the rows to the same AMP.
If the join columns are the primary indexes of the corresponding tables, then the joining rows are already on the same AMP. In this case, no distribution is required.
Consider the following Employee and Salary Tables.
CREATE SET TABLE EMPLOYEE,FALLBACK ( 
   EmployeeNo INTEGER, 
   FirstName VARCHAR(30) , 
   LastName VARCHAR(30) , 
   DOB DATE FORMAT 'YYYY-MM-DD', 
   JoinedDate DATE FORMAT 'YYYY-MM-DD', 
   DepartmentNo BYTEINT 
) 
UNIQUE PRIMARY INDEX ( EmployeeNo );
CREATE SET TABLE Salary ( 
   EmployeeNo INTEGER, 
   Gross INTEGER,  
   Deduction INTEGER, 
   NetPay INTEGER 
) 
UNIQUE PRIMARY INDEX(EmployeeNo); 
When these two tables are joined on EmployeeNo column, then no redistribution takes place since EmployeeNo is the primary index of both the tables which are being joined.
Consider the following Employee and Department tables.
CREATE SET TABLE EMPLOYEE,FALLBACK (
   EmployeeNo INTEGER, 
   FirstName VARCHAR(30) , 
   LastName VARCHAR(30) , 
   DOB DATE FORMAT 'YYYY-MM-DD', 
   JoinedDate DATE FORMAT 'YYYY-MM-DD', 
   DepartmentNo BYTEINT 
) 
UNIQUE PRIMARY INDEX ( EmployeeNo );
CREATE SET TABLE DEPARTMENT,FALLBACK ( 
   DepartmentNo BYTEINT, 
   DepartmentName CHAR(15) 
) 
UNIQUE PRIMARY INDEX ( DepartmentNo );
If these two tables are joined on DeparmentNo column, then the rows need to be redistributed since DepartmentNo is a primary index in one table and non-primary index in another table. In this scenario, joining rows may not be on the same AMP. In such case, Teradata may redistribute employee table on DepartmentNo column.
For the above Employee and Department tables, Teradata may duplicate the Department table on all AMPs, if the size of Department table is small.
Nested Join doesn’t use all AMPs. For the Nested Join to take place, one of the condition should be equality on the unique primary index of one table and then joining this column to any index on the other table.
In this scenario, the system will fetch the one row using Unique Primary index of one table and use that row hash to fetch the matching records from other table. Nested join is the most efficient of all Join methods.
Product Join compares each qualifying row from one table with each qualifying row from other table. Product join may take place due to some of the following factors −
Where condition is missing.
Join condition is not based on equality condition.
Table aliases is not correct.
Multiple join conditions.
Python - Diagonal element addition among lists - GeeksforGeeks

26 Mar, 2020
Sometimes, while working with Python lists, we can have a problem in which we need to perform addition of lists in diagonal manner that i.e. adding ith element of 1 list to i + 1 element of other list. This kind of problem can have application in day-day programming. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loopThis is brute force way in which this task can be performed. In this, we iterate one list and test add the i + 1th element of other list and construct the resultant list.
# Python3 code to demonstrate # Diagonal element addition among lists# using loop  # Initializing liststest_list1 = [1, 6, 8, 5, 3]test_list2 = [8, 10, 3, 4, 5]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Diagonal element addition among lists# using loopres = []for idx in range(0, len(test_list1) - 1):    res.append(test_list1[idx] + test_list2[idx + 1])  # printing result print ("List after diagonal addition : " + str(res))
The original list 1 is : [1, 6, 8, 5, 3]
The original list 2 is : [8, 10, 3, 4, 5]
List after diagonal addition : [11, 9, 12, 10]

 
Method #2 : Using zip() + list comprehensionThis is yet another way in which this task can be performed. In this, we group ith with i+1th element of other list using zip(). The task of performing addition is done in list comprehension.
# Python3 code to demonstrate # Diagonal element addition among lists# using zip() + list comprehension  # Initializing liststest_list1 = [1, 6, 8, 5, 3]test_list2 = [8, 10, 3, 4, 5]  # printing original listsprint("The original list 1 is : " + str(test_list1))print("The original list 2 is : " + str(test_list2))  # Diagonal element addition among lists# using zip() + list comprehensionres = [i + j for i, j in zip(test_list1, test_list2[1:])]  # printing result print ("List after diagonal addition : " + str(res))
The original list 1 is : [1, 6, 8, 5, 3]
The original list 2 is : [8, 10, 3, 4, 5]
List after diagonal addition : [11, 9, 12, 10]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
MySQL Tryit Editor v1.0

SELECT COALESCE(NULL, 1, 2, 'W3Schools.com');
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Combine Vectors, Matrix or Data Frames by Columns in R Language - cbind() Function - GeeksforGeeks

01 Jun, 2020
cbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by columns.
Syntax: cbind(x1, x2, ..., deparse.level = 1)
Parameters:x1, x2: vector, matrix, data framesdeparse.level: This value determines how the column names generated. The default value of deparse.level is 1.
Example 1:
# R program to illustrate# cbind function  # Initializing two vectorsx <- 2:7y <- c(2, 5)  # Calling cbind() functioncbind(x, y)
Output:
     x y
[1, ] 2 2
[2, ] 3 5
[3, ] 4 2
[4, ] 5 5
[5, ] 6 2
[6, ] 7 5

Example 2:
# R program to illustrate# cbind function  # Initializing a vectorx <- 1:5  # Calling cbind() functioncbind(x, 4)cbind(x, 5, deparse.level = 0)cbind(x, 6, deparse.level = 2)cbind(x, 4, deparse.level = 6)
Output:
     x  
[1, ] 1 4
[2, ] 2 4
[3, ] 3 4
[4, ] 4 4
[5, ] 5 4
     [, 1] [, 2]
[1, ]    1    5
[2, ]    2    5
[3, ]    3    5
[4, ]    4    5
[5, ]    5    5
     x 6
[1, ] 1 6
[2, ] 2 6
[3, ] 3 6
[4, ] 4 6
[5, ] 5 6
     [, 1] [, 2]
[1, ]    1    4
[2, ]    2    4
[3, ]    3    4
[4, ]    4    4
[5, ]    5    4

R DataFrame-Function
R Matrix-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Remove rows with NA in one column of R DataFrame
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Install C++ Compiler on Linux?

There are several alternatives for compiling C++ on Linux. Let's look at 2 of them −
Almost all Linux distros come with GCC installed. Check whether GCC is installed on your system by entering the following command from the command line −
$ g++ -v
If you have installed GCC, then it should print a message such as the following −
Using built-in specs.
Target: i386-redhat-linux
Configured with: ../configure --prefix=/usr .......
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-46)
If GCC is not installed, then you will have to install it yourself using the detailed instructions available at https://gcc.gnu.org/install/. 
Clang is a compiler developed by LLVM. You can install it using a freely available script on https://github.com/rsmmr/install-clang. You can find the docs for it there. If not, you can download the prebuilt binary from http://releases.llvm.org/download.html and install it by following the install instructions.
Java Program to check if a file or directory is readable

The method java.io.File.canRead() is used to check if a file or directory is readable in Java. This method returns true if the file specified by the abstract path name can be read by an application and false otherwise.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         System.out.println("The file can be read? " + file.canRead());
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The output of the above program is as follows −
The file can be read? true
Now let us understand the above program.
The method java.io.File.canRead() is used to check whether the file can be read and the boolean value that is returned by the method is printed. A code snippet that demonstrates this is given as follows −
try {
   File file = new File("demo1.txt");
   file.createNewFile();
   System.out.println("The file can be read? " + file.canRead());
} catch(Exception e) {
   e.printStackTrace();
}
What is the difference between "var" and "val" in Kotlin?

In Kotlin, we can declare a variable using two different keywords: one is var and the other one is val. In this article, we will take an example and demonstrate how these declarations are different from each other.
In the following example, we will see how we can declare two different variables using "val" and "var". We will also see that the variable declared using 'var' can be changed, while the variable declared using 'val' cannot be reassigned as it will throw an error at runtime with the error message "Val cannot be reassigned."
val sName = "tutorialspoint";
var varName = "hello World"

fun main() {
   println("Example of val--->"+sName);
   println("Example of Var--->"+varName);

   // Variable declared by var is mutable
   varName = "new value";
   println("New value of the variable declared using Var: " +varName);
}
It will generate the following output −
Example of val--->tutorialspoint
Example of Var--->hello World
New value of the variable declared using Var: new value
Now, let's try to change the value of the variable declared using val −
val sName = "tutorialspoint";
var varName = "hello World"

fun main() {
   println("Example of val--->"+sName);
   println("Example of Var--->"+varName);

   // Variable declared by val is not mutable
   sName = "new value";
   println("New value of the variable declared using Var: " +sName);
}
It will throw an error at runtime −
main.kt:9:5: error: val cannot be reassigned
sName = "new value";
^
How to perform shapiro test for all columns in an R data frame?

The shapiro test is used to test for the normality of variables and the null hypothesis for this test is the variable is normally distributed. If we have numerical columns in an R data frame then we might to check the normality of all the variables. This can be done with the help of apply function and shapiro.test as shown in the below example.
 Live Demo
Consider the below data frame −
set.seed(321)
x1<−rnorm(20,2,0.34)
x2<−rpois(20,5)
x3<−rpois(20,2)
x4<−rpois(20,5)
x5<−rpois(20,6)
x6<−runif(20,1,5)
x7<−rexp(20,0.62)
x8<−rpois(20,10)
df<−data.frame(x1,x2,x3,x4,x5,x6,x7,x8)
df
x1 x2 x3 x4 x5 x6 x7 x8
1 2.579667 7 0 2 4 4.712527 2.69354358 9
2 1.757907 4 0 3 3 1.519762 2.63275896 9
3 1.905485 5 2 5 4 3.087971 1.83827735 5
4 1.959319 7 0 10 14 3.564951 1.19092513 10
5 1.957853 7 3 5 5 4.576069 0.61126332 10
6 2.091182 4 0 4 10 3.316821 2.56506184 8
7 2.247126 3 4 5 7 1.636518 1.88751338 9
8 2.079266 8 4 7 7 3.018356 0.11237261 8
9 2.115299 3 2 7 4 4.516734 0.17862062 13
10 1.812349 3 0 6 5 3.009659 0.57255735 8
11 2.118218 5 2 6 4 1.025079 0.09536165 10
12 2.504761 4 1 3 4 1.936312 3.11482640 14
13 2.064031 1 0 5 7 2.388424 2.96859719 13
14 2.830708 2 4 9 6 3.779138 0.61244047 6
15 1.607831 6 5 7 7 2.740338 1.15703781 12
16 1.726412 6 3 5 7 4.690268 2.78394417 10
17 2.155064 3 2 8 11 4.043131 0.12627601 7
18 2.142913 3 4 8 4 1.481830 0.14825531 8
19 2.196379 4 2 3 6 1.490243 4.61761476 5
20 2.151761 6 1 5 2 1.914817 0.26060923 11
Applying shapiro test on all columns of df −
apply(df,2,shapiro.test)
$x1
Shapiro-Wilk normality test
data: newX[, i]
W = 0.94053, p-value = 0.2453
$x2
Shapiro-Wilk normality test
data: newX[, i]
W = 0.95223, p-value = 0.4022
$x3
Shapiro-Wilk normality test
data: newX[, i]
W = 0.88855, p-value = 0.02529
$x4
Shapiro-Wilk normality test
data: newX[, i]
W = 0.96244, p-value = 0.5938
$x5
Shapiro-Wilk normality test
data: newX[, i]
W = 0.87904, p-value = 0.017
$x6
Shapiro-Wilk normality test
data: newX[, i]
W = 0.93067, p-value = 0.1591
$x7
Shapiro-Wilk normality test
data: newX[, i]
W = 0.88531, p-value = 0.02208
$x8
Shapiro-Wilk normality test
data: newX[, i]
W = 0.96271, p-value = 0.5992
How to close all the opened files using Python?

There is no way in python natively to track all opened files. To do that you should either track all the files yourself or always use the with statement to open files which automatically closes the file as it goes out of scope or encounters an error.
with open('file.txt') as f:
    # do something with f here
You can also create a class to enclose all files and create a single close function to close all the files.
class OpenFiles():
    def __init__(self):
        self.files = []
    def open(self, file_name):
        f = open(file_name)
        self.files.append(f)
        return f
    def close(self):
        list(map(lambda f: f.close(), self.files))
files = OpenFiles()
# use open method
foo = files.open("text.txt", "r")
# close all files
files.close()
Tail Recursion in Scala

19 Jul, 2019
Recursion is a method which breaks the problem into smaller subproblems and calls itself for each of the problems. That is, it simply means function calling itself. The tail recursive functions better than non tail recursive functions because tail-recursion can be optimized by compiler. A recursive function is said to be tail recursive if the recursive call is the last thing done by the function. There is no need to keep record of the previous state.
For tail recursion function a package import scala.annotation.tailrec will be used in the program.
Syntax:
@tailrec
def FuntionName(Parameter1, Parameter2, ...): type = ...
Let us understand tail recursion by examples.
Example :
// Scala program of GCD using recursion import scala.annotation.tailrec  // Creating object object GFG {     // Function defined     def GCD(n: Int, m: Int): Int =    {        // tail recursion function defined         @tailrec def gcd(x:Int, y:Int): Int=        {             if (y == 0) x             else gcd(y, x % y)         }         gcd(n, m)    }           // Main method     def main(args:Array[String])     {         println(GCD(12, 18))     } } 
Output:
6
As we can see in above example @tailrec is used for gcd function that is tail recursion function. By using tail recursion no need to keep record of the previous state of gcd function.
Example :
// Scala program of factorial using tail recursion import scala.annotation.tailrec     // Creating object object GFG {     // Function defined     def factorial(n: Int): Int =    {         // Using tail recursion         @tailrec def factorialAcc(acc: Int, n: Int): Int =        {             if (n <= 1)                 acc             else                 factorialAcc(n * acc, n - 1)         }         factorialAcc(1, n)     }             // Main method     def main(args:Array[String])     {         println(factorial(5))     } } 
Output:
120
In the above code, we can use the @tailrec annotation to confirm that our algorithm is tail recursive.
If we use this annotation and our algorithm isn’t tail recursive, the compiler will complain. For instance, if we attempt to use this annotation on the above example of the factorial method, we will get the following compile-time error.
Example :
// Scala program of factorial with tail recursion import scala.annotation.tailrec     // Creating object object GFG {     // Function defined     @tailrec def factorial(n: Int): Int =    {         if (n == 1)             1        else             n * factorial(n - 1)     }             // Main method     def main(args:Array[String])     {         println(factorial(5))     } } 
Output:
Could not optimize @tailrec annotated method factorial: it contains a recursive call not in tail position.
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala List filter() method with example
Type Casting in Scala
Class and Object in Scala
Scala Map
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala Constructors
Scala | Arrays
How to Install Scala with VSCode?
Lodash _.reduce() Method

06 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers etc.The _.reduce() method reduces collection to value which is accumulated result of running each element in the collection through iteratee, where each successive invocation is supplied return value of the previous. The first element of the collection is used as the initial value, if accumulator is not given. There are many lodash methods are guarded to work as iteratees for methods like _.reduce, _.reduceRight, and _.transform.
Syntax:
_.reduce(collection, iteratee, accumulator)

Parameters: This method accepts three parameters as mentioned above and described below:
collection: This parameter holds the collection to iterate over.
iteratee: This parameter holds the function invoked per iteration.
accumulator: This parameter holds the initial value.
Return Value: This method returns the accumulated value.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
// Requiring the lodash library const _ = require("lodash");        // Original array var users = [ 1, 2, 3, 4 ];   // Use of _.reduce() method   let gfg = _.reduce(users, function(sum, n) {  return sum + n;}, 0);  // Printing the output console.log(gfg);
Output:
10

Example 2:
// Requiring the lodash library const _ = require("lodash");        // Original array var users = { 'p': 2, 'q': 3, 'r':2, 's': 2  }   // Use of _.reduce() method   let gfg = _.reduce(users, function(result, value, key) {  (result[value] || (result[value] = [])).push(key);  return result;}, {});  // Printing the output console.log(gfg);
Output:
{ '2': ['p', 'r', 's'], '3': ['q'] }

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HTML | Marquee hspace attribute - GeeksforGeeks

20 Jan, 2022
The Marquee hspace attribute in HTML is used to set the horizontal margin. A given value is used to set the space between the marquee element and other contents.
Note: This attribute is not supported by HTML5. Syntax:  
<marquee hspace="px/%" >
Attribute value:  
px: Specify horizontal space around marquee.
%: Specify horizontal space around marquee.
Example:  
html
<!DOCTYPE html><html> <head>    <title> HTML | Marquee hspace attribute</title>    <style>        .main {            text-align: center;        }                 .marq {            padding-top: 30px;            padding-bottom: 30px;        }    </style></head> <body>    <h1 style="color:green; text-align:center;">      GeeksforGeeks  </h1>    <div class="main">        <marquee class="marq"                 bgcolor="Green"                 direction="left"                 loop=""                 hspace="25%">            hspace 0        </marquee>        Other content        <marquee class="marq"                 bgcolor="Green"                 direction="left"                 loop=""                 hspace="45%">            hspace 50        </marquee>        Other content    </div></body> </html>
Output:  
Supported Browsers: The browsers supported by HTML Marquee hspace attribute are listed below:  
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
hritikbhatnagar2182
chhabradhanvi
ManasChhabra2
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
GATE | GATE-CS-2003 | Question 30 - GeeksforGeeks

14 Feb, 2018
Consider the following SQL query
select distinct al, a2,........., an
from r1, r2,........, rm
where P 
For an arbitrary predicate P, this query is equivalent to which of the following relational algebra expressions ?A: B: C: D: (A) A(B) B(C) C(D) DAnswer: (A)Explanation:Cross product (x) combines the tuples of one relation with all the tuples of the other relation. Thus, tuples of relation r1, r2 .... rn are combined.Select operator  is used to select resultant tuples.Projection operator  is used to select a subset of attributes from the resultant tuples by specifying the names of the attributes. So attributes a1, a2, an are projected from the resultant tuples.
 Thus, option (A) is correct. Please comment below if you find anything wrong in the above post.Quiz of this Question
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2012 | Question 65
How to convert Python DateTime string into integer milliseconds?

You can get the current time in milliseconds in Python using the time module. You can get the time in seconds using time.time function(as a floating point value). To convert it to milliseconds, you need to multiply it with 1000 and round it off.
import time
milliseconds = int(round(time.time() * 1000))
print(milliseconds)
This will give the output −
1514825676008
If you want to convert a datetime object to milliseconds timestamp, you can use the timestamp function then apply the same math as above to get the milliseconds time. 
import time
from datetime import datetime
dt = datetime(2018, 1, 1)
milliseconds = int(round(dt.timestamp() * 1000))
print(milliseconds)
This will give the output −
1514745000000
How to reverse a string using lambda expression in Java?

A String is an object that represents a sequence of characters and immutable in Java. We can reverse a string entered by the user using the charAt() method of String class to extract characters from the string and append them in reverse order to reverse the entered string.
In the below example, we need to reverse a string using lambda expression with the help of the Scanner class.
import java.util.Scanner;

interface StringFunc {
   String func(String n);
}
public class StringFuncLambdaTest {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      StringFunc reverse = (str) -> {   // lambda expression
         String result = "";
         for(int i = str.length()-1; i >= 0; i--)
            result += str.charAt(i);
         return result;
      };
      System.out.println("Lambda reversed is: " + reverse.func("Lambda Expression"));
     
      System.out.println("Enter a word to reverse a String:");
      String word = sc.nextLine();
      System.out.println(word +" in reversed form - " + reverse.func(word));
   }
}
Lambda reversed is: noisserpxE adbmaL
Enter a word to reverse a String:
TutorialsPoint
TutorialsPoint in reversed form - tnioPslairotuT
How can we specify default values in MySQL INSERT statement?

At the time of creation of a table, if any column is defined with default values then by using the keyword ‘DEFAULT’ in the INSERT statement, we can take default value for that column. For example, we have created a table ‘employee’ with a default value of column ‘DOJ’ as follows −
mysql> Create table employee(id int, name varchar(20), doj date DEFAULT '2005-01-01');
Query OK, 0 rows affected (0.09 sec)

mysql> Insert into employee(id, name, doj) values(1, ’Aarav’, DEFAULT);
Query OK, 1 row affected (0.03 sec)

mysql> select * from employee;
+------+------------+---------------+
| id   | name       | doj           |
+------+------------+---------------+
| 1    |Aarav       | 2005-01-01    |
+------+------------+---------------+
1 row in set (0.00 sec)
From the query above, it can be observed that while inserting the values we use DEFAULT keyword, MySQL insert the default value specified at the time of defining the column.
C++ program to calculate Profit Or Loss

Given with the cost price(CP) and the selling price(SP) and the task is to calculate the profit gained or loss incurred.
Cost price or CP is the price at which the product is purchased by the seller and the selling price or SP is the price at which the product is sold by the seller.
There is a formula to calculate profit gained or loss incurred
Profit = Selling price – Cost price
If Selling price is greater than cost price than there will be a profit
Loss = Cost price – Selling price
If cost price is greater than selling price than there will be a loss
Input-: CP = 600
   SP = 100
Output-: loss incurred = 500
Input-: CP = 100
   SP = 500
Output-: profit gained = 400
Approach used in the given program is as follows −
Take the input as cost price and selling price
Apply the formula given to calculate profit or loss
Display the result
Start
Step 1-> declare function to calculate Profit.
   int profit(int CP, int SP)
      set int profit = (SP - CP)
      return profit
step 2-> Declare function to calculate Loss
   int loss(int CP, int SP)
      set int loss = (CP - SP)
      return loss
step 3-> In main()
   set int CP = 600, SP = 100
      IF (SP == CP)
         Print "No profit nor Loss"
      End
      Else IF (SP > CP)
         call profit(CP, SP)
      End
      Else
         Call loss(CP , SP)
      End
Stop
 Live Demo
#include <iostream>
using namespace std;
// Function to calculate Profit.
int profit(int CP, int SP) {
   int profit = (SP - CP);
   return profit;
}
// Function to calculate Loss.
int loss(int CP, int SP) {
   int loss = (CP - SP);
   return loss;
}
int main() {
   int CP = 600, SP = 100;
   if (SP == CP)
      cout << "No profit nor Loss";
   else if (SP > CP)
      cout<<"profit gained = "<< profit(CP, SP);
   else
      cout<<"loss incurred = "<<loss(CP , SP);
   return 0;
}
IF WE RUN THE ABOVE CODE IT WILL GENERATE FOLLOWING OUTPUT
loss incurred = 500
How do I change focus to a new popup tab in Selenium?

We can change focus to a new popup tab with Selenium webdriver. The getWindowHandles and getWindowHandle methods are available to handle new popup tabs. The getWindowHandles method stores all the currently opened window handles in Set data structure.
The getWindowHandle method stores the window handle of the opened browser in focus. The iterator method is used to iterate over all the window handle ids. We have to add import java.util.Set to accommodate Set and import java.util.List and import java.util.Iterator statements to accommodate the iterator in our code.
Selenium driver object can access the elements of the parent window. In order to switch its focus from the parent to the new popup tab, we shall take the help of the switchTo().window method and pass the window handle id of the popup as an argument to the method.
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
public class SwitchToPopup {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.get("https://secure.indeed.com/account/login");
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.findElement(By.id("login-google-button")).click();
      // window handles
      Set wnd = driver.getWindowHandles();
      // window handles iterate
      Iterator i = wnd.iterator();
      String popwnd = i.next();
      String prntw = i.next();
      // switching pop up tab
      driver.switchTo().window(popwnd);
      System.out.println("Page title of popup: "+ driver.getTitle());
      // closes all windows
      driver.quit();
   }
}
Batch Script - SORT

This batch command takes the input from a source file and sorts its contents alphabetically, from A to Z or Z to A. It prints the output on the console.
Sort [filename]

Where filename is the file whose contents need to be sorted.
@echo off 
Sort C:\tp\lists.txt
 Print
 Add Notes
 Bookmark this page
C# OfType() Method

Filter a collection on the basis of each of its elements type.
Let’s say you have the following list with integer and string elements −
list.Add("Katie");
list.Add(100);
list.Add(200);
To filter collection and get only elements with string type.
var myStr = from a in list.OfType<string>() select a;
Work the same for integer type.
var myInt = from a in list.OfType<int>() select a;
The following is the complete code −
 Live Demo
using System;
using System.Linq;
using System.Collections;
public class Demo {
   public static void Main() {
      IList list = new ArrayList();
      list.Add("Katie");
      list.Add(100);
      list.Add(200);
      list.Add(300);
      list.Add(400);
      list.Add("Brad");
      list.Add(600);
      list.Add(700);

      var myStr = from a in list.OfType<string>() select a;
      var myInt = from a in list.OfType<int>() select a;
      Console.WriteLine("Strings...");
      foreach (var strVal in myStr) {
         Console.WriteLine(strVal);
      }
      Console.WriteLine("Integer...");
      foreach (var intVal in myInt) {
         Console.WriteLine(intVal);
      }
   }
}
Strings...
Katie
Brad
Integer...
100
200
300
400
600
700