code-rag-bench/online-tutorials huggingface dataset:
How to define a drop-down list in HTML5 ? - GeeksforGeeks

11 Jun, 2020
In this article, we define a Drop-Down List By using the <select> Element in the Document. This tag is used to create a drop-down list. The <select> tag contains <option> tag to display the available option of drop-down list.Note: The tag is used in a form to receive user response.Syntax:  
<select>
    <option>
    <option>
    ...
<select>


Examples:  
html
<!DOCTYPE html> <html>   <head>     <title>         HTML5: How to define a drop-down list?       </title> </head>   <body style="text-align:center;">     <h1>GeeksforGeeks</h1>           <h2>HTML5: How to define a drop-down list?</h2>             <p>Select one option from drop-down list:</p>             <select>         <option value="GFG">GFG</option>         <option value="OS">OS</option>         <option value="DBMS">DBMS</option>         <option value="Data Structure">             Data Structure         </option>     </select> </body>   </html>                     
Output :  
Supported Browsers are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML5
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
Angular File Upload
Form validation using jQuery
How to Dynamically Add/Remove Table Rows using jQuery ?
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript?
Overlap Elements with CSS

To overlap elements, use the CSS z-index property. You can try to run the following code to implement the z-index property and set image behind the text
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         img {
            position: absolute;
            left: 0px;
            top: 0px;
            z-index: -1;
         }
      </style>
   </head>
   <body>
      <img src = "https://www.tutorialspoint.com/assets/videotutorials/courses/swift_4_online_training/380_course_210_image.jpg" width="300" height="250">
      <p>This is demo text.</p>
   </body>
</html>
Creating views on Pandas DataFrame - GeeksforGeeks

23 Jan, 2019
Many times while doing data analysis we are dealing with a large data set, having a lot of attributes. All the attributes are not necessarily equally important. As a result, we want to work with only a set of columns in the dataframe. For that purpose, let’s see how we can create views on the Dataframe and select only those columns that we need and leave the rest.
For link to the CSV file used in the code, click here.
Solution #1: A set of columns in the DataFrame can be selected by dropping all those columns which are not needed.
# importing pandas as pdimport pandas as pd  # Reading the csv filedf = pd.read_csv("nba.csv")  # Print the dataframeprint(df)
Output :
Now we will select all columns except the first three columns.
# drop the first three columnsdf.drop(df.columns[[0, 1, 2]], axis = 1)
Output :
We can also use the names of the column to be dropped.
# drop the 'Name', 'Team' and 'Number' columnsdf.drop(['Name', 'Team', 'Number'], axis = 1)
Output :
 Solution #2 : We can individually select all those columns which we need and leave out the rest.
# importing pandas as pdimport pandas as pd  # Reading the csv filedf = pd.read_csv("nba.csv")  # select the first three columns# and store the result in a new dataframedf_copy = df.iloc[:, 0:3]  # Print the new DataFramedf_copy
Output :
We can also select the columns in a random manner by passing a list to the DataFrame.iloc attribute.
# select the first, third and sixth columns# and store the result in a new dataframe# The numbering of columns begins from 0df_copy = df.iloc[:, [0, 2, 5]]  # Print the new DataFramedf_copy
Output :
Alternatively, we can also name the columns that we want to select.
# Select the below listed columnsdf_copy = df[['Name', 'Number', 'College']]  # Print the new DataFramedf_copy
Output :
data-science
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Split the sentence into words in C++

Given is the task to split the sentence into words. In this, we will separate all the words present in sentence.
Input 
I am a good boy
Output 
I
am
a
good
boy
In the above example we will print the single word in single line.
#include<iostream.h>
#include<string.h>
#include<stdio.h>
Using namespace std;
void split( string st){
   String word = “ “;
   for ( char s : st){
      If (s== ‘ ‘){
         Cout<< z << endl;
         z = “ “;
      }
      else{
         z = z = s;
      }
   }
   Cout<< z <<endl;
}
Int main( ){
   String st = “ Blood from heaven is mortal”;
   Cout<< “Blood from heaven is mortal”;
   Split(st);
   return 0;
}
If we run the above code it will generate the following output
Blood from heaven is mortal
Blood
From
Heaven
is
mortal
#include
#include
#include
Using namespace std;
Void split( string st){
   String word = “ “;
   for ( char s : st){
      If (s== ‘ ‘){
         Cout<< z << endl;
         z = “ “;
      }
      else{
         z = z = s;
      }
   }
   Cout<< z <<
}
int main( ){
   String st = “ type a text message”;
   Cout<< “type a text message”;
   Split(st);
   return 0;
}
If we run the above code it will generate the following output
type a text message
type
a
text
message
How to get first day of the week using Python?

You can use the calender module to get the first day of the week using Python. The calender module has a special function, firstweekday(), that returns the current setting for the weekday to start each week.
import calendar
print(calendar.firstweekday())
calendar.setfirstweekday(2)
print(calendar.firstweekday())
This will give the output −
6
2
How to Convert Binary to Decimal?

Binary is the simplest kind of number system that uses only two digits of 0 and 1 (i.e. value of base 2). Since digital electronics have only these two states (either 0 or 1), so binary number is most preferred in modern computer engineer, networking and communication specialists, and other professionals.
Whereas Decimal number is most familiar number system to the general public. It is base 10 which has only 10 symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9.
There are mainly two methods to convert a binary number into decimal number − using positional notation, and using doubling. These methods are explained are as following below.
Since number numbers are type of positional number system. That means weight of the positions from right to left are as 20, 21, 22, 23... and so on for the integer part and weight of the positions from left to right are as 2-1, 2-2, 2-3, 2-4... and so on for the fractional part.
Assume any unsigned binary number is bnb(n-1) ... b1b0.b-1b-2 ... b(m-1)bm. Then the decimal number is equal to the sum of binary digits (bn) times their power of 2 (2n), i.e., bnb(n-1) ... b1b0.b-1b-2 ... b(m-1)bm = bnx2n+b(n-1)x2(n-1)+ ... +b1x21+bx020+b-1x2-1+b-22-2+ ...
This is simple algorithm where you have to multiply positional value of binary with their digit and get the sum of these steps.
Example-1 − Convert binary number 11001010 into decimal number. Since there is no binary point here and no fractional part. So,
Binary to decimal is,
= (11001010)2
= 1x27+1x26+0x25+0x24+1x23+0x22+1x21+0x20
= 128+64+0+0+8+0+2+0
= (202)10
Example-2 − Convert binary number 1010.1011 into decimal number. Since there is a binary point here with fractional part. So,
Binary to decimal is,
= (1010.1011)2
= 1x23+0x22+1x21+0x20+1x2-1+0x2-2+1x2-3+1x2-4
= 8+0+2+0+0.5+0+0.125+0.0625
= (10.6875)10
This is simple method to convert a binary number into decimal number, you need to start from leftmost digit (or MSB) from the input. Take the most significant bit (MSB), right down, then multiply by 2 with it and add second leftmost bit, store it as current result, then again multiple by 2 with current result and add third leftmost bit, update this value as current result and follow this till addition of least significant bit (LSB or rightmost bit). Since you are doubling (multiplying by 2) each time, so this method is known as Doubling.
These are simple algorithm is explained below in steps −
Write down the binary number.
Write down the binary number.
Starting from the left, double your previous total and add the current digit.
Starting from the left, double your previous total and add the current digit.
Double your current total and add the next leftmost digit.
Double your current total and add the next leftmost digit.
Repeat the previous step.
Repeat the previous step.
For example, Convert binary number 11101110 into decimal number. According to above algorithm, Binary to decimal is,
= (11101110)2
= 1
= 12+1 =3
= 32+1=7
= 72+0=14
= 142+1=29
= 292+1=59
= 592+1=119
= 1192+0=238
= (238)10
These are above two simple methods to convert a binary number into decimal number.
MySQL strip time component from datetime?

You can strip time component from datetime with the help of DATE() function. The syntax is as follows −
SELECT DATE(yourColumnName) from yourTableName;
To understand the above concept, let us first create a table −
mysql> create table StripComponentDatetimeDemo
   -> (
   -> YourDateTime datetime
   -> );
Query OK, 0 rows affected (0.60 sec)
Let us now insert some records in the table. The query is as follows −
mysql> insert into StripComponentDatetimeDemo values(date_add(now(),interval 1 day));
Query OK, 1 row affected (0.13 sec)
Display records with the help of select statement. The query is as follows displaying datetime −
mysql> select *from StripComponentDatetimeDemo;
The following is the output −
+---------------------+
| YourDateTime        |
+---------------------+
| 2018-11-25 20:15:07 |
+---------------------+
1 row in set (0.00 sec)
The following is the query that strips time component −
mysql> SELECT DATE(YourDateTime) from StripComponentDatetimeDemo;
The following is the output −
+--------------------+
| DATE(YourDateTime) |
+--------------------+
| 2018-11-25         |
+--------------------+
1 row in set (0.00 sec)
Fetch a specific record using a single MySQL query with AND & OR operator

Let us first create a table −
mysql> create table DemoTable2015
   -> (
   -> StudentId int,
   -> StudentName varchar(20),
   -> StudentCountryName varchar(20)
   -> );
Query OK, 0 rows affected (1.20 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable2015 values(1,'Chris','US');
Query OK, 1 row affected (0.23 sec)

mysql> insert into DemoTable2015 values(2,'Bob','UK');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable2015 values(3,'David','AUS');
Query OK, 1 row affected (0.11 sec)

mysql> insert into DemoTable2015 values(4,'Robert','US');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable2015;
This will produce the following output −
+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 1         | Chris       | US                 |
| 2         | Bob         | UK                 |
| 3         | David       | AUS                |
| 4         | Robert      | US                 |
+-----------+-------------+--------------------+
4 rows in set (0.00 sec)
Here is the query to fetch a specific record with a single query −
mysql> select *from DemoTable2015
   -> where StudentName='David' OR StudentCountryName='UK' and StudentId=3;
This will produce the following output −
+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 3         | David       | AUS                |
+-----------+-------------+--------------------+
1 row in set (0.00 sec)
Pytest - Fixtures

Fixtures are functions, which will run before each test function to which it is applied. Fixtures are used to feed some data to the tests such as database connections, URLs to test and some sort of input data. Therefore, instead of running the same code for every test, we can attach fixture function to the tests and it will run and return the data to the test before executing each test.
A function is marked as a fixture by −
@pytest.fixture

A test function can use a fixture by mentioning the fixture name as an input parameter.
Create a file test_div_by_3_6.py and add the below code to it
import pytest

@pytest.fixture
def input_value():
   input = 39
   return input

def test_divisible_by_3(input_value):
   assert input_value % 3 == 0

def test_divisible_by_6(input_value):
   assert input_value % 6 == 0
Here, we have a fixture function named input_value, which supplies the input to the tests. To access the fixture function, the tests have to mention the fixture name as input parameter.
Pytest while the test is getting executed, will see the fixture name as input parameter. It then executes the fixture function and the returned value is stored to the input parameter, which can be used by the test.
Execute the test using the following command −
pytest -k divisible -v

The above command will generate the following result −
test_div_by_3_6.py::test_divisible_by_3 PASSED
test_div_by_3_6.py::test_divisible_by_6 FAILED
============================================== FAILURES
==============================================
________________________________________ test_divisible_by_6
_________________________________________
input_value = 39
   def test_divisible_by_6(input_value):
>  assert input_value % 6 == 0
E  assert (39 % 6) == 0
test_div_by_3_6.py:12: AssertionError
========================== 1 failed, 1 passed, 6 deselected in 0.07 seconds
==========================

However, the approach comes with its own limitation. A fixture function defined inside a test file has a scope within the test file only. We cannot use that fixture in another test file. To make a fixture available to multiple test files, we have to define the fixture function in a file called conftest.py. conftest.py is explained in the next chapter.

    21 Lectures 
     4 hours 

 Lucian Musat

    22 Lectures 
     1.5 hours 

 Fanuel Mapuwei

    44 Lectures 
     3.5 hours 

 Rohit Dharaviya
 Print
 Add Notes
 Bookmark this page
bool() in Python

The bool() in python returns a boolean value of the parameter supplied to it. The parameter can be any of the following and the results are as per the below conditions. Except the values mentioned here the remaining values return True.
False is returned when the parameter value passed is as below −
None
None
A False condition
A False condition
Zero of any numeric type
Zero of any numeric type
Empty sequence (), [] etc.
Empty sequence (), [] etc.
Empty mapping like {}
Empty mapping like {}
objects of Classes which has __bool__() or __len()__ method which returns 0 or False
objects of Classes which has __bool__() or __len()__ method which returns 0 or False
In the below program, we illustrate all such example scenarios.
print("None gives : ",bool(None))
print("True gives : ",bool(True))
print("Zero gives: ",bool(0))
# Expression evaluating to true
print("Expression evaluating to True: ",bool(0 == (18/3)))
# Expression evaluating to false
print("Expression evaluating to False: ",bool(0 == (18%3)))
s = ()
print("An mpty sequence: ",bool(s))
m = {}
print("An emty mapping: ",bool(m))
t = 'Tutoriaslpoint'
print("A non empty string: ",bool(t))
Running the above code gives us the following result −
None gives : False
True gives : True
Zero gives: False
Expression evaluating to True: False
Expression evaluating to False: True
An mpty sequence: False
An emty mapping: False
A non empty string: True
MathML - Matrices

<mtable> tag is used to draw matrices.
mtable is similar to table tag of HTML and this tag uses mtr, mtd elements which are similar to tr and td tags of HTML.
<mtable> <mtr> <mtd></mtd></mtr></mfrac>

Here is the description of all the attributes of this tag −
align − To specify the vertical alignment of the table . Valid values are: axis, baseline, bottom, center, top. Default is axis.
align − To specify the vertical alignment of the table . Valid values are: axis, baseline, bottom, center, top. Default is axis.
class, id, style − Used with stylesheets.
class, id, style − Used with stylesheets.
columnalign − To specify the horizontal alignment of the cells. Valid values are: left, center and right. Default is center.
columnalign − To specify the horizontal alignment of the cells. Valid values are: left, center and right. Default is center.
columnlines − To specify column borders. Valid values are: none, solid and dashed. Default is none.
columnlines − To specify column borders. Valid values are: none, solid and dashed. Default is none.
columnspacing − To specify the space between table columns.
columnspacing − To specify the space between table columns.
displaystyle − If true more vertical space is used for displayed equations , if false, a more compact layout is used to display formulas.
displaystyle − If true more vertical space is used for displayed equations , if false, a more compact layout is used to display formulas.
frame − To specify borders of the entire table. Valid values are: none, solid and dashed. Default is none.
frame − To specify borders of the entire table. Valid values are: none, solid and dashed. Default is none.
framespacing − To specify additional space added between the table and frame.
framespacing − To specify additional space added between the table and frame.
href − To specify a hyperlink to a specified uri.
href − To specify a hyperlink to a specified uri.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathbackground − To specify the background color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
mathcolor − To specify the text color. Valid formats are #rgb, #rrggbb and html color names.
rowalign − To specify vertical alignment of the cells. Valid values are axis, baseline, bottom, center and top. Default is baseline
rowalign − To specify vertical alignment of the cells. Valid values are axis, baseline, bottom, center and top. Default is baseline
rowlines − To specify row borders. Valid values are: none, solid and dashed. Default is none.
rowlines − To specify row borders. Valid values are: none, solid and dashed. Default is none.
width − To specify width of the entire table.
width − To specify width of the entire table.
Let's draw a 3 x 3 metric.
<math xmlns = "http://www.w3.org/1998/Math/MathML">
URL handling Python modules (urllib)

Python language is used extensively for web programming. When we browser website we use the web address which is also known as URL or uniform resource locator. Python has inbuilt materials which can handle the calls to the URL as well as pass the result that comes out of visiting the URL. In this article we will see a module named as urllib. We will also see the various functions present in this module which help in getting the result from the URL.
To install urllib in the python environment, we use the below command using pip.
pip install urllib
Running the above code gives us the following result −
The request.urlopen method is used to visit an URL and fetch its content to the python environment.
import urllib.request
address = urllib.request.urlopen('https://www.tutorialspoint.com/')
print(address.read())
Running the above code gives us the following result −
b'<!DOCTYPE html>\r\n<!--[if IE 8]><html class="ie ie8"> <![endif]-->\r\n<!--[if IE 9]><html class........
...............
...................
new Date());\r\ngtag(\'config\', \'UA-232293-6\');\r\n</script>\r\n</body>\r\n</html>\r\n' -->
We can parse the URL to check if it is a valid one or not. We can also Pass a query string to the search option. The response can be checked for its validity and we can print the entire response if it is a valid one.
import urllib.request
import urllib.parse
url='https://tutorialspoint.com'
values= {'q':'python'}
data = urllib.parse.urlencode(values)
data = data.encode('utf-8') # data should be bytes
print(data)
req = urllib.request.Request(url, data)
resp = urllib.request.urlopen(req)
print(resp)
respData = resp.read()
print(respData)
Running the above code gives us the following result −
b'q=python'
<http.client.HTTPResponse object at 0x00000195BF706850>
b'<!DOCTYPE html>\r\n<!--[if IE 8]><html class="ie ie8"> <![endif]............
.....................
\r\n</script>\r\n</body>\r\n</html<\r\n' -->
urlsplit can be used to takein an url, then split it into parts which can be used for further data manipulation. For example if we want to programmatically judge if a URL is SSL certified or not then we apply urlsplit and get the scheme value to decide. In the below example we check the different parts of the supplied URL.X
import urllib.parse
url='https://tutorialspoint.com/python'
value = urllib.parse.urlsplit(url)
print(value)
Running the above code gives us the following result −
SplitResult(scheme='https', netloc='tutorialspoint.com', path='/python', query='', fragment='')
Output of C++ Program | Set 20

04 May, 2017
Predict the output below program
#include<iostream>using namespace std;int main(){    int x = 1 , y = 1, z = 1;      cout << (++x || ++y && ++z ) << endl;        cout << x << " " << y << " " << z ;                return 0;}
Explanation:-It is based on fact that how LOGICAL – OR and LOGICAL-AND work. Note that Compiler reads OR and AND operators from left to right. Let us take the following cases into consideration:-
#include<iostream>using namespace std;int main(){    int x = 1 , y = 1;    cout << ( ++x  || ++y ) << endl;   // outputs 1;    cout << x << " " << y;             // x = 2 , y = 1;    return 0;}
Output:
1
2 1

Once compiler detects “true” on the LEFT of logical OR, IT IS NOT GOING TO EVALUATE THE RIGHT SIDE!, because even one is true, the whole “OR” expression becomes true!. SO compiler skips the RIGHT part and displays the result as 1 !So y is not incremented here , because compiler skipped reading it!
#include<iostream>using namespace std;int main(){    int x = 1 , y = 1;    cout << ( ++x && ++y ) << endl;     //outputs 1;    cout << x << " " << y;              // x = 2 , y = 2;    return 0;}
Output:
1
2 2

LOGICAL AND needs to evaluate both right and left part (Think about it !)So both left and right part is evaluated, thus incrementing both x and y here.
#include<iostream>using namespace std;int main(){    int x = 1 , y = 1, z = 1;    cout << ( ++x || ++y && ++z ) << endl;    //outputs 1;    cout << x << " " << y << " " << z ;       //x = 2 , y = 1 , z = 1;    return 0;}
Output:
1
2 1 1

Here compiler increments x first and then it detects a LOGICAL OR. We have a true quantity on left side . SO compiler won’t read the right part.Thus incrementing x and y,z remains same!
This article is contributed by Nishant .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.
CPP-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Output of C++ programs | Set 50
Runtime Errors
Output of C Programs | Set 2
Different ways to copy a string in C/C++
Output of C Programs | Set 3
Output of Python Program | Set 1
Output of Java Program | Set 2
Output of Java Program | Set 3
Output of C++ programs | Set 47 (Pointers)
Output of Java Programs | Set 12
Puzzle 3 | (Calculate total distance travelled by bee)

07 Sep, 2021
Puzzle: Two trains are on same track and they are coming toward each other. The speed of the first train is 50 km/h and the speed of the second train is 70 km/h. A bee starts flying between the trains when the distance between two trains is 100 km. The bee first flies from first train to second train. Once it reaches the second train, it immediately flies back to the first train ... and so on until trains collide. Calculate the total distance travelled by the bee. Speed of bee is 80 km/h. 
        
Answer: 66.67 km approx. 
Solution:  
 
Let the first train A move at u km/h.
 
Let the second train B move at v km/h.
 
Let the distance between two trains be d km
 
Let the speed of bee be b km/h
 
Therefore, the time taken by trains to collide = d/(u+v)
Now putting all the known values into the above equation, we get,  
u = 50 km/hr
v = 70 km/hr
d = 100 km
b = 80 km/hr

Therefore, the total distance travelled by bee 
= b*d/(u+v) 
= 80 * 100/(50+70) 
= 66.67 km (approx)
Another Solution:
Another easier approach to solve this can be by using the concept of relative velocity:
With respect to Train A, train B’s velocity is (70+50) = 120 km/hr. Thus, the time taken by Train B to collide with Train A will be
 (100 km) / (120 km/hr)  = 5/6 hr = 50 min
 Now, since the velocity of the bee is 80 km/hr, the distance travelled by the bee in this time interval will be
 80 km/hr * 5/6 hr = 66.67 km (approx)
 
Train & Bee Puzzle - YouTubeGeeksforGeeks School18.5K subscribersTrain & Bee PuzzleWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:20•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0q1U4kDtXWw" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
immanuelsavio
ManasChhabra2
Chinmoy Lenka
shubhangispc
kapoorsagar226
Yahoo
Puzzles
Yahoo
Puzzles
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript - Redirect a URL

To redirect a URL using JavaScript, the code is as follows −
 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;
   }
</style>
</head>
<body>
<h1>JavaScript Redirect a URL</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to redirect the url to www.google.com
</h3>
<script>
   document.querySelector('.Btn').addEventListener('click',()=>{
      window.location.href = 'https://www.google.com';
   })
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
Angular forms NgModel Directive - GeeksforGeeks

24 May, 2021
In this article, we are going to see what is NgModel in Angular 10 and how to use it. NgModel is used to create a top-level form group Instance, and it binds the form to the given form value.
Syntax:
<Input [(NgModel)= 'name']>
NgModule: Module used by NgModel is:
FormsModule
Selectors:
[ngModel]
Approach: 
Create the Angular app to be used
In app.component.ts make a variable that gives value to the input field.
In app.component.html make a form and use ngModel to get the value of the input.
Serve the angular app using ng serve to see the output.
Example 1:
app.component.ts
import { Component, Inject } from '@angular/core';  import { PLATFORM_ID } from '@angular/core';  import { isPlatformWorkerApp } from '@angular/common';    @Component({    selector: 'app-root',    templateUrl: './app.component.html',    styleUrls: [ './app.component.css' ]  })  export class AppComponent  {    gfg: string = '';    setValue() {    this.gfg = 'GeeksforGeeks';  }  }
app.component.html
<h1>GeeksforGeeks</h1>  <input [(ngModel)]="gfg" #ctrl="ngModel" required>    <p>Value: {{ gfg }}</p>      <button (click)="setValue()">Set value</button>
Output:
Reference: https://angular.io/api/forms/NgModel
Angular10
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Roadmap to Become a Web Developer in 2022
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Generate random numbers following a normal distribution in C/C++

Here we will see how to generate random numbers, which are following in a normal distribution. For the normal random, the formula is like below.
z = √−2 ln x1 cos (2πx2)
Here x1 and x2 are chosen randomly.
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iostream>
using namespace std;
double rand_gen() {
   // return a uniformly distributed random value
   return ( (double)(rand()) + 1. )/( (double)(RAND_MAX) + 1. );
}
double normalRandom() {
   // return a normally distributed random value
   double v1=rand_gen();
   double v2=rand_gen();
   return cos(2*3.14*v2)*sqrt(-2.*log(v1));
}
main() {
   double sigma = 82.0;
   double Mi = 40.0;
   for(int i=0;i<20;i++) {
      double x = normalRandom()*sigma+Mi;
      cout << " x = " << x << endl;
   }
}
x = 1.91628
x = 57.0448
x = 51.4348
x = 53.5612
x = -83.8511
x = -28.9197
x = -76.0576
x = 62.1435
x = 23.9
x = -87.0663
x = 50.6942
x = 94.1685
x = -88.1597
x = 168.502
x = 40.7563
x = 90.1091
x = 16.9218
x = -36.9178
x = 135.969
x = 56.8888
C# | Math.Asin() Method - GeeksforGeeks

31 Jan, 2019
Math.Asin() is an inbuilt Math class method which returns the angle whose sine value is given as a double value argument. If the argument is NaN, then the result will be NaN.
Syntax:
public static double Asin(double num)

Parameter:
num: It is the number that represents a sine and type of this parameter is System.Double. It must be greater than or equal to -1, but less than or equal to 1.
Return Type: Returns an angle Θ, measured in radians and its type is System.Double. Here the angle is always measured in radians, such that -π/2 ≤ Θ ≤ π/2.
Note: If the value of the num is greater than 1 or less than -1 or equals to NaN, then this method always returns NaN as result. To convert the radians(return value) to degrees multiply it by 180 / Math.PI. A positive return value always represents a counter clock-wise angle from the x-axis and a negative return value always represents a clockwise angle.
Examples:
Input  : Math.Asin(2)
Output : NaN

Input  : Math.Asin(0.3584)
Output : 0.366553473829125
     
Input  : Math.Asin(0.0)
Output : 0

Input  : Math.Asin(-0.0)
Output : 0

Input  : Math.Asin(Double.PositiveInfinity)
Output : NaN

Input  : Math.Asin(Double.NegativeInfinity)
Output : NaN

Program: To illustrate the Math.Asin() method
// C# program to demonstrate working// of Math.Asin() methodusing System;  class Geeks {      // Main Method    public static void Main(String[] args)    {        double a = Math.PI;          // using Math.Asin() method        Console.WriteLine(Math.Asin(a));          // argument is greater than 1        Console.WriteLine(Math.Asin(2));                  Console.WriteLine(Math.Asin(0.3584));          double d = 0.0;        double e = -0.0;        double posi = Double.PositiveInfinity;        double nega = Double.NegativeInfinity;        double nan = Double.NaN;          // Input positive zero        // Output 0        double res = Math.Asin(d);          // converting to degree        // i.e. output is 0 degree        double rest = res * (180 / Math.PI);        Console.WriteLine(rest);          // Input negative zero        // Output 0        Console.WriteLine(Math.Asin(e));          // input PositiveInfinity        // Output NaN        Console.WriteLine(Math.Asin(posi));          // input NegativeInfinity        // Output NaN        Console.WriteLine(Math.Asin(nega));          // input NaN        // Output NaN        Console.WriteLine(Math.Asin(nan));    }}
NaN
NaN
0.366553473829125
0
0
NaN
NaN
NaN

Reference: https://msdn.microsoft.com/en-us/library/system.math.Asin
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Method Overriding
Difference between Ref and Out keywords in C#
C# | Constructors
C# | Class and Object
Introduction to .NET Framework
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
Extension Method in C#
How to set the value for the attribute layout_weight for button in Android dynamically from java code?

This example demonstrates how do I set the value for the attribute layout_weight for button in android dynamically from java code.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="horizontal"
   android:gravity="center"
   android:id="@+id/linearLayout"
   android:padding="4dp"
   tools:context=".MainActivity">
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
   LinearLayout linearLayout;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      linearLayout = findViewById(R.id.linearLayout);
      LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
      params1.weight = 0.3f;
      Button button1 = new Button(this);
      button1.setText("Button 1");
      button1.setLayoutParams(params1);
      linearLayout.addView(button1);
      LinearLayout.LayoutParams params2 = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
      params2.weight = 0.7f;
      Button button2 = new Button(this);
      button2.setText("Button 2");
      button2.setLayoutParams(params2);
      linearLayout.addView(button2);
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
</application>

</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run   icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Return values of printf() and scanf() in C

The printf() and scanf() functions are required for output and input respectively in C. Both of these functions are library functions and are defined in the stdio.h header file.
Details about the return values of the printf() and scanf() functions are given as follows −
The printf() function is used for printing the output. It returns the number of characters that are printed. If there is some error then it returns a negative value.
A program that demonstrates this is as follows −
 Live Demo
#include <stdio.h>

int main(){
   char str[] = "THE SKY IS BLUE";

   printf("\nThe value returned by printf() for the above string is : %d", printf("%s", str));

   return 0;
}
The output of the above program is as follows −
THE SKY IS BLUE
The value returned by printf() for the above string is : 15
Now let us understand the above program.
First, the string is initialized. Then the string is displayed using printf() as well as the value returned by printf(). The code snippet that shows this is as follows −
char str[] = "THE SKY IS BLUE";

printf("\nThe value returned by printf() for the above string is : %d", printf("%s", str));
The scanf() function is used for obtaining the input from the user. It returns the number of input values that are scanned. If there is some input failure or error then it returns EOF (end-of-file).
A program that demonstrates this is as follows −
 Live Demo
#include
int main(){
   int x, y, z;

   printf("The value returned by the scanf() function is : %d",
   scanf("%d%d%d", &x, &y, &z));

   printf("\nx = %d", x);
   printf("\ny = %d", y);
   printf("\nz = %d", z);

   return 0;
}
The output of the above program is as follows −
7 5 4
The value returned by the scanf() function is : 3
x = 7
y = 5
z = 2
Now let us understand the above program.
There are 3 int variables i.e. x, y and z. Their values are entered by the user using the scanf() function and the return value of scanf() is printed. The code snippet that shows this is as follows −
int x, y, z;

printf("The value returned by the scanf() function is : %d",
scanf("%d%d%d", &x, &y, &z));
Then the values of x, y and z that were obtained from the user are printed. The code snippet that shows this is as follows −
printf("\nx = %d", x);
printf("\ny = %d", y);
printf("\nz = %d", z);
The Object Class in C#

The Object class is the base class of all the classes in C#. It has the following methods on C#.
Let us see an example how to create an object of a class in C#.
 Live Demo
using System;
namespace MyApplication {
   class Demo {
      protected string name = "Website";
      protected void Display(string str) {
         Console.WriteLine("Tabs: " + str);
      }  
   }

   class Test : Demo {
      static void Main(string[] args) {
         Test t = new Test();
         Console.WriteLine("Details: " + t.name);
         t.Display("Product");
         t.Display("Services");
         t.Display("Tools");
         t.Display("Plugins");
      }
   }
}
Details: Website
Tabs: Product
Tabs: Services
Tabs: Tools
Tabs: Plugins
Program to make the XOR of all segments equal to zero in Python

Suppose we have an array called nums and another value k. The XOR of a segment [left, right] (left <= right) is the XOR of all elements whose indices are in between left and right (inclusive).
We have to find the minimum number of elements to change in the array such that the XOR of all segments of size k is same as zero.
So, if the input is like nums = [3,4,5,2,1,7,3,4,7], k = 3, then the output will be 3 because we can modify elements at indices 2, 3, 4 to make the array [3,4,7,3,4,7,3,4,7].
To solve this, we will follow these steps −
LIMIT := 1024
LIMIT := 1024
temp := make an array whose size is LIMIT x k, and fill with 0
temp := make an array whose size is LIMIT x k, and fill with 0
for each index i and value x in nums, dotemp[i mod k, x] := temp[i mod k, x] + 1
for each index i and value x in nums, do
temp[i mod k, x] := temp[i mod k, x] + 1
temp[i mod k, x] := temp[i mod k, x] + 1
dp := an array of size LIMIT and fill with -2000
dp := an array of size LIMIT and fill with -2000
dp[0] := 0
dp[0] := 0
for each row in temp, domaxprev := maximum of dpnew_dp := an array of size LIMIT and fill with maxprevfor each index i and value cnt row, doif cnt > 0, thenfor each index j and value prev in dp, donew_dp[i XOR j] := maximum of new_dp[i XOR j] and prev+cntdp := new_dp
for each row in temp, do
maxprev := maximum of dp
maxprev := maximum of dp
new_dp := an array of size LIMIT and fill with maxprev
new_dp := an array of size LIMIT and fill with maxprev
for each index i and value cnt row, doif cnt > 0, thenfor each index j and value prev in dp, donew_dp[i XOR j] := maximum of new_dp[i XOR j] and prev+cnt
for each index i and value cnt row, do
if cnt > 0, thenfor each index j and value prev in dp, donew_dp[i XOR j] := maximum of new_dp[i XOR j] and prev+cnt
if cnt > 0, then
for each index j and value prev in dp, donew_dp[i XOR j] := maximum of new_dp[i XOR j] and prev+cnt
for each index j and value prev in dp, do
new_dp[i XOR j] := maximum of new_dp[i XOR j] and prev+cnt
new_dp[i XOR j] := maximum of new_dp[i XOR j] and prev+cnt
dp := new_dp
dp := new_dp
return size of nums - new_dp[0]
return size of nums - new_dp[0]
Let us see the following implementation to get better understanding
def solve(nums, k):
   LIMIT = 2**10
   temp = [[0 for _ in range(LIMIT)] for _ in range(k)]
   for i,x in enumerate(nums):
      temp[i%k][x] += 1

   dp = [-2000 for _ in range(LIMIT)]
   dp[0] = 0
   for row in temp:
      maxprev = max(dp)
      new_dp = [maxprev for _ in range(LIMIT)]
      for i,cnt in enumerate(row):
         if cnt > 0:
            for j,prev in enumerate(dp):
               new_dp[i^j] = max(new_dp[i^j], prev+cnt)
         dp = new_dp
   return len(nums) - new_dp[0]

nums = [3,4,5,2,1,7,3,4,7]
k = 3
print(solve(nums, k))
[3,4,5,2,1,7,3,4,7], 3
-9
C program to remove the brackets from a given input.

Let’s create a simplified expression by removing brackets from the expressions.
Input: A string expression with bracket is as follows:
(x+y)+(z+q)
The output is as follows:
x+y+z+q
The input is as follows:
(x-y+z)-p+q
The output is as follows:
x-y+z-p+q
Refer an algorithm to remove the brackets from a given input.
Step 1: Declare and read the input at runtime.
Step 2: Traverse the string.
Step 3: Copy each element of the input string into new string.
Step 4: If anyone parenthesis is encountered as an element, replace it with empty space.
Following is the C program to remove the brackets from a given input −
#include<stdio.h>
int main(){
   int i=0,c=0,j=0;
   char a[100],b[100];
   printf("\nEnter the string :");
   scanf("%s",a);
   while(a[i]!='\0'){
      if((a[i]=='(') && (a[i-1]=='-')){
         (c=0)?j=i:j=c;
         while(a[i]!=')'){
            if(a[i+1]=='+')
               b[j++]='-';
            else if(a[i+1]=='-')
               b[j++]='+';
            else if(a[i+1]!=')')
               b[j++]=a[i+1];
               i++;
         }
         c=j+1;
      }
      else if(a[i]=='(' && a[i-1]=='+'){
         (c==0)?j=i:j=c;
         while(a[i]!=')'){
            b[j++]=a[i+1];
            i++;
         }
         j–;
         c=j+1;
      }
      else if(a[i]==')'){
         i++;
         continue;
      } else {
         b[j++]=a[i];
      }
      i++;
   }
   b[j]='\0';
   printf("%s",b);
   return 0;
}
When the above program is executed, it produces the following output −
Enter the string:(x+y)-z
x+y-z
Kotlin Arrays

Arrays are used to store multiple values in a single variable, instead of 
creating separate variables for each 
value.
To create an array, use the arrayOf() function, and place the 
values in a comma-separated list inside it:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")

You can access an array element by referring to the index number, 
inside square brackets.
In this example, we access the value of the first element in cars:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars[0])
// Outputs Volvo 
Note: Just like with Strings, Array indexes start with 0: [0] is the first element. [1] is the second 
element, etc.
To change the value of a specific element, refer to the index number:
cars[0] = "Opel"

 
To find out how many elements an array have, use the size property:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
println(cars.size)
// Outputs 4 
You can use the in operator to check if an element exists in 
an array:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
  println("It exists!")
} else {
  println("It does not exist.")
}
Often when you work with arrays, you need to loop through all of the 
elements.
You can loop through the array elements with the for 
loop, which you will learn even more about in the next chapter.
The following example outputs all elements in the cars 
array:
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars) {
  println(x)
}
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
C program to find the unique elements in an array.

Find the non-repeating element in an array by using the two loops. One is for the current element and the other is to check, if an element is already present in an array or not.
Consider an example given below −
15, 15, 16, 15, 13, 15
Here, the non-repeated elements in an array are 16 and 13.
Refer an algorithm given below for finding the unique or the non-repeated elements in an array.
Step 1 − Declare an array and input the array elements at run time.
Step 2 − Start traversing the array and check, if the current element is already present in an array or not.
Step 3 − If it is already present in an array then, move to the next element in an array and continue.
Step 4 − If not, output the element as the non-repeating element.
Following is the C program for finding the unique or the non-repeated elements in an array −
 Live Demo
#include <stdio.h>
#include <stdlib.h>
int uniqueEle(int array[], int n){
   int i,j;
   int count = 1;
   for(i = 0; i < n; i++){
      for(j = 0; j < n; j++){
         if(array[i] == array[j] && i != j)
         break;
      }
      if(j == n ){
         printf("\nunique elements in an array is [%d] : %d \n",count,array[i]);
         ++count;
      }
   }
   return -1;
}
int main(){
   int n,i;
   printf("\nEnter no: of elements : ");
   scanf("%d",&n);
   int array[n];
   printf("\nenter the array elements : ");
   for(i = 0; i < n; i++){
      scanf("%d",&array[i]);
   }
   uniqueEle(array, n);
   return 0;
}
When the above program is executed, it produces the following output −
Run 1:
Enter no: of elements: 5
enter the array elements :
11
11
15
16
13
unique elements in an array is [1] : 15
unique elements in an array is [2] : 16
unique elements in an array is [3] : 13
Run 2:
Enter no: of elements: 4
enter the array elements : 11
12
11
11
unique elements in an array is [1] : 12