code-rag-bench/online-tutorials huggingface dataset:
How to get website links using Invoke-WebRequest in PowerShell?

To get the links present on the website using PowerShell, we can first retrieve the data from the webpage using the Invoke-WebRequest cmdlet.
$req = Invoke-WebRequest -uri "https://theautomationcode.com"
$req
To retrieve only links we can use that property and there you will also find some sub-properties like InnerHTML, Innertext, href, etc as shown in the output.
$req = Invoke-WebRequest -uri "https://theautomationcode.com"
$req.Links
innerHTML : Scripts
innerText : Scripts
outerHTML : <A href="https://theautomationcode.com/scripts/">Scripts</A>
outerText : Scripts
tagName   : A
href      : https://theautomationcode.com/scripts/  
We need only links so we will use the href property.
$req.Links | Select -ExpandProperty href
https://theautomationcode.com/2020/11/
https://theautomationcode.com/author/chiragce17/
https://theautomationcode.com/category/powershell/
https://theautomationcode.com/category/troubleshooting/
Swap Column Values in SQL Server - GeeksforGeeks

05 Nov, 2020
Introduction (Swap Column Values in SQL Server) :If you are a developer and have learned the programming languages, you might think that you will need a third variable or another temporary storage location to swap the values. Here, as you are a SQL Server DBA, you can simply swap them using a single update statement.
Example and Application features :It happens that SQL user might enter incorrect values in the database columns, the next task is to swap those values.
Syntax :Syntax to write a query to swap column values in SQL server.
UPDATE [tablename]
SET [col1] = [col2],
   [col2] = [col1]
GO

Let us suppose we need to swap columns in any table in the SQL server.
Example –Let us suppose we have below the table “geek_demo”.
Select * from geek_demo ;

Output :
Now, to update the column or to swap the column used the following query given below.
UPDATE [geek_demo]
SET [FirstName] = [LastName], 
[LastName] = [FirstName]
GO

Now, let’s see the output.
Select * from geek_demo ;
Output :
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | GROUP BY
Difference between DELETE, DROP and TRUNCATE
SQL | Views
MySQL | Group_CONCAT() Function
How to Create a Table With Multiple Foreign Keys in SQL?
Difference between DELETE and TRUNCATE
C# program to determine if any two integers in array sum to given integer

The following is our array −
int[] arr = new int[] {
   7,
   4,
   6,
   2
};
Let’s say the given intger that should be equal to sum of two other integers is −
int res = 8;
To get the sum and find the equality.
for (int i = 0; i < arr.Length; i++) {
   for (int j = 0; j < arr.Length; j++) {
      if (i != j) {
         int sum = arr[i] + arr[j];
         if (sum == res) {
            Console.WriteLine(arr[i]);
         }
      }
   }
}
using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = new int[] {
            7,
            4,
            6,
            2
         };
         // given integer
         int res = 8;
         Console.WriteLine("Given Integer {0}: ", res);
         Console.WriteLine("Sum of:");
         for (int i = 0; i < arr.Length; i++) {
            for (int j = 0; j < arr.Length; j++) {
               if (i != j) {
                  int sum = arr[i] + arr[j];
                  if (sum == res) {
                     Console.WriteLine(arr[i]);
                  }
               }
            }
         }
      }
   }
}
Built-in objects in Python (builtins)

The builtins module is automatically loaded every time Python interpreter starts, either as a top level execution environment or as interactive session. The Object class, which happens to be the base class for all Python objects, is defined in this module. All built-in data type classes such as numbers, string, list etc are defined in this module. The BaseException class, as well as all built-in exceptions, are also defined in it. Further, all built-in functions are also defined in the built-ins module.
Since this module is imported in the current session automatically, normally it is not imported explicitly. All the built-in functions used in the executable code are by default considered to be from built-ins module. For example
>>> len('hello')
5
is implicitly equivalent to
>>> import builtins
>>> builtins.len('hello')
5
However, explicit import of this module is required when there is also a user defined function of the same name as built-in function. Python interpreter gives higher precedence to user defined function. Hence, if the code contains both user defined as well as built-in function of the same name, the latter must be prefixed with built-ins module.
def len(string):
print ('local len() function')
print ('calling len() function in builtins module')
import builtins
l = builtins.len(string)
print ('length:',l)
string = "Hello World"
len(string)
Output
local len() function
calling len() function in builtins module
length: 11
Most modules have the name __builtins__ made available as part of their globals. The value of __builtins__ is normally either this module or the value of this module’s __dict__attribute.
>>> import math
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'math': <module 'math' (built-in)>}
How can I loop over entries in JSON using Python?

You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −
{
   "id": "file",
   "value": "File",
   "popup": {
      "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
      ]
   }
}
You can load it in your python program and loop over its keys in the following way −
import json
f = open('data.json')
data = json.load(f)
f.close()

# Now you can use data as a normal dict:
for (k, v) in data.items():
   print("Key: " + k)
   print("Value: " + str(v))
This will give the output −
Key: id
Value: file
Key: value
Value: File
Key: popup
Value: {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}
Matplotlib - Simple Plot

In this chapter, we will learn how to create a simple plot with Matplotlib.
We shall now display a simple line plot of angle in radians vs. its sine value in Matplotlib. To begin with, the Pyplot module from Matplotlib package is imported, with an alias plt as a matter of convention.
import matplotlib.pyplot as plt
Next we need an array of numbers to plot. Various array functions are defined in the NumPy library which is imported with the np alias.
import numpy as np
We now obtain the ndarray object of angles between 0 and 2π using the arange() function from the NumPy library.
x = np.arange(0, math.pi*2, 0.05)
The ndarray object serves as values on x axis of the graph. The corresponding sine values of angles in x to be displayed on y axis are obtained by the following statement −
y = np.sin(x)
The values from two arrays are plotted using the plot() function.
plt.plot(x,y)
You can set the plot title, and labels for x and y axes.
You can set the plot title, and labels for x and y axes.
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
The Plot viewer window is invoked by the show() function −
plt.show()
The complete program is as follows −
from matplotlib import pyplot as plt
import numpy as np
import math #needed for definition of pi
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
plt.plot(x,y)
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
plt.show()
When the above line of code is executed, the following graph is displayed −
Now, use the Jupyter notebook with Matplotlib.
Launch the Jupyter notebook from Anaconda navigator or command line as described earlier. In the input cell, enter import statements for Pyplot and NumPy −
from matplotlib import pyplot as plt
import numpy as np
To display plot outputs inside the notebook itself (and not in the separate viewer), enter the following magic statement −
%matplotlib inline
Obtain x as the ndarray object containing angles in radians between 0 to 2π, and y as sine value of each angle −
import math
x = np.arange(0, math.pi*2, 0.05)
y = np.sin(x)
Set labels for x and y axes as well as the plot title −
plt.xlabel("angle")
plt.ylabel("sine")
plt.title('sine wave')
Finally execute the plot() function to generate the sine wave display in the notebook (no need to run the show() function) −
plt.plot(x,y)
After the execution of the final line of code, the following output is displayed −

    63 Lectures 
     6 hours 

 Abhilash Nelson

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    9 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy

    32 Lectures 
     4 hours 

 Aipython

    10 Lectures 
     2.5 hours 

 Akbar Khan

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
How to implement merge sort in JavaScript?

Merge sort is an example of a divide-and-conquer type sorting-algorithm.The input of merge sort is an array of some elements, which are need to be arranged typically from least to the greatest. 
Merge sort divides the array in to two sub arrays and later divides each array in to another two arrays and so on until a bunch of single element arrays are left. For instance, in the following example the array [4,7,5,9,1,3,8,2] divides in to single array elements such as [4], [7], [5], [9], [1], [3], [8], [2].
It starts comparing arrays in such a manner that two arrays are compared and concatenated. In the following example, it compares two arrays at a time that is  [4], [7] are compared and concatenated then [5], [9] are compared and concatenated and so on such that arrays [4,7], [5,9], [1,3], [2,8] are formed.
It follows the same way that is two-two arrays are compared and concatenated to form two arrays. In the following example [4,7]  and [5,9] are compared and concatenated to get an array as [4,5,7,9] and same is the case with other two arrays to form an array as [1,2,3,8].
Same rule applicable here that is the remaining two arrays compares and concatenates to get a final array as [1,2,3,4,5,7,8,9].
Live Demo
<html>
<body>
<script>
   function mSort (array) {
      if (array.length === 1) {
      return array                            // return once we hit an array with a single item
   }
   const middle = Math.floor(array.length / 2) // get the middle item of the array rounded down
   const left = array.slice(0, middle)         // items on the left side
   const right = array.slice(middle)           // items on the right side
   document.write(middle);
   return merge(
      mSort(left),
      mSort(right)
   )
   }
   // compare the arrays item by item and return the concatenated result
   function merge (left, right) {
      let result = []
      let leftIndex = 0
      let rightIndex = 0
      while (leftIndex < left.length && rightIndex < right.length) {
         if (left[leftIndex] < right[rightIndex]) {
         result.push(left[leftIndex])
         leftIndex++
         document.write("</br>");        
         } else {
         result.push(right[rightIndex])
         rightIndex++      
      }
   }
   return result.concat(left.slice(leftIndex)).concat(right.slice(rightIndex))
   }
   const list = [4,7,5,9,1,3,8,2]
   document.write(mSort(list));
   </script>
   </body>
   </html>
1,2,3,4,5,7,8,9
Data profiling in Pandas using Python - GeeksforGeeks

04 May, 2020
Pandas is one of the most popular Python library mainly used for data manipulation and analysis. When we are working with large data, many times we need to perform Exploratory Data Analysis. We need to get the detailed description about different columns available and there relation, null check, data types, missing values, etc. So, Pandas profiling is the python module which does the EDA and gives detailed description just with a few lines of code.
Installation:
pip install pandas-profiling
Example:
#import the packagesimport pandas as pdimport pandas_profiling   # read the filedf = pd.read_csv('Geeks.csv')   # run the profile reportprofile = df.profile_report(title='Pandas Profiling Report')   # save the report as html fileprofile.to_file(output_file="pandas_profiling1.html")   # save the report as json fileprofile.to_file(output_file="pandas_profiling2.json")
Output:
HTML File:
JSON File:
python-modules
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
DAX Logical - SWITCH function

Evaluates an expression against a list of values and returns one of multiple possible result expressions.
SWITCH (
   <expression>, <value>, <result>, [<value>, <result>] ..., [<else>]
) 

expression
Any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times for each row/context.
value
A constant value to be matched with the results of expression.
result
Any scalar expression to be evaluated, if the results of expression match the corresponding value.
else
Optional.
Any scalar expression to be evaluated, if the result of expression doesn't match any of the value arguments.
A scalar value coming from one of the result expressions, if there was a match with value, or from the else expression, if there was no match with any value.
All the result expressions and the else expression must be of the same data type.
= SWITCH (
   [Week Day], 1, "Sunday", 2, "Monday", 3, "Tuesday", 4, "Wednesday", 
      5, "Thursday", 6, "Friday", 7, "Saturday", "Unknown"
) 
This DAX formula returns a calculated column with the names of the Week Day values.

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Add zero columns to Pandas Dataframe - GeeksforGeeks

11 Dec, 2020
Prerequisites: Pandas
The task here is to generate a Python program using its Pandas module that can add a column with all entries as zero to an existing dataframe.
A Dataframe is a two-dimensional, size-mutable, potentially heterogeneous tabular data.It is used to represent data in tabular form like an Excel file format. Below is the syntax for creating a dataframe in pandas. It can be imagines as a dictionary like container for series object.
Syntax:
DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
Import required libraries
Create or import data
Add a new column with all zeroes.
Example 1:
Python3
# import pandas libraryimport pandas as pd  # creating dictionary of listsdict = {'name': ["sohom", "rakesh", "rajshekhar", "sumit"],        'department': ["ECE", "CSE", "EE", "MCA"],        'CGPA': [9.2, 8.7, 8.6, 7.7]}  # creating a dataframedf = pd.DataFrame(dict)  print("data frame before adding the column:")display(df)  # creating a new column# of zeroes to the# dataframedf['new'] = 0  # showing the dataframeprint("data frame after adding the column:")display(df)
Output:
Example 2:
Python3
# import pandas libraryimport pandas as pd  # create datadata = [["geeks", 1], ["for", 2], ["best", 3]]  # creating a dataframedf = pd.DataFrame(data, columns=['col1', 'col2'])  print("data frame before adding the column:")display(df)  # creating a new column with all zero entriesdf['col3'] = 0  # showing the dataframeprint("data frame after adding the column:")display(df)
Output:
Python pandas-dataFrame
Python-pandas
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
CSS | rotateY() Function - GeeksforGeeks

07 Aug, 2019
The rotateY() function is an inbuilt function which is used to rotate an element around the vertical axis.
Syntax:
rotateY( angle )
Parameters: This function accepts single parameter angle which represents the angle of rotations. The positive and negative angles rotate the elements in clockwise and counter-clockwise respectively.
Below examples illustrate the rotateY() function in CSS:Example 1:
<!DOCTYPE html> <html> <head>     <title>CSS rotateY() function</title>     <style>         body {            text-align:center;        }        h1 {            color:green;        }        .rotateY_image {            transform: rotateY(60deg);        }    </style> </head>   <body>     <h1>GeeksforGeeks</h1>    <h2>CSS rotateY() function</h2>          <img class="rotateY_image" src= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"        alt="GeeksforGeeks logo"> </body> </html>                                  
Output:
Example 2:
<!DOCTYPE html> <html> <head>     <title>CSS rotateY() function</title>     <style>         body {            text-align:center;        }        h1 {            color:green;        }        .GFG {            font-size:35px;            font-weight:bold;            color:green;            transform: rotateY(60deg);        }    </style> </head>   <body>     <h1>GeeksforGeeks</h1>    <h2>CSS rotateY() function</h2>          <div class="GFG">Welcome to GeeksforGeeks</div> </body> </html>
Output:
Supported Browsers: The browsers supported by rotateY() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Functions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a web page using HTML and CSS
Form validation using jQuery
How to style a checkbox using CSS?
Search Bar using HTML, CSS and JavaScript
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
10’s Complement of a decimal number?

9’s complement and 10’s complement are used to make the arithmetic operations in digital system easier. These are used to make computational operations easier using complement implementation and usually trade hardware usage to the program.
To obtain the 9’s complement of any number we have to subtract the number with (10n – 1) where n = number of digits in the number, or in a simpler manner we have to subtract each digit of the given decimal number from 9.
10’s complement, it is relatively easy to find out the 10’s complement after finding out the 9’s complement of that number. We have to add 1 with the 9’s complement of any number to obtain the desired 10’s complement of that number. Or if we want to find out the 10’s complement directly, we can do it by following the following formula, (10n – number), where n = number of digits in the number.
Let us take a decimal number 456, 9’s complement of this number will be
999
-456
_____
543
10’s complement of this no
543
(+)1
______
544
Input:456
Output:544
Mathematically,
10’s complement = 9’s complement + 1
10’s complement = 10i – num
Where, i = total number of digits in num.
#include <iostream>
#include<math.h>
using namespace std;
int main() {
   int i=0,temp,comp,n;
   n=456;
   temp = n;
   while(temp!=0) {
      i++;
      temp=temp/10;
   }
   comp = pow(10,i) - n;
   cout<<comp;
   return 0;
}
Taking input from console in Python

In this tutorial, we are going to learn how to take input from the console in Python.
The interactive shell in Python is treated as a console. We can take the user entered data the console using input() function.
# taking input from the user
a = input()
# printing the data
print("User data:-", a)
Tutorialspoint
User data:- Tutorialspoint
If you run the above code, then you will get the following result.
Tutorialspoint
User data:- Tutorialspoint
The data that is entered by the user will be in the string format. If you have any doubts in the
tutorial, mention them in the comment section.
fill in C++ STL - GeeksforGeeks

22 Sep, 2019
The ‘fill’ function assigns the value ‘val’ to all the elements in the range [begin, end), where ‘begin’ is the initial position and ‘end’ is the last position.
NOTE : Notice carefully that ‘begin’ is included in the range but ‘end’ is NOT included. Below is an example to demonstrate ‘fill’ :
// C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std;  int main(){    vector<int> vect(8);      // calling fill to initialize values in the    // range to 4    fill(vect.begin() + 2, vect.end() - 1, 4);      for (int i = 0; i < vect.size(); i++)        cout << vect[i] << " ";      return 0;}
0 0 4 4 4 4 4 0

We can also use fill to fill values in an array.
// C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std;  int main(){    int arr[10];      // calling fill to initialize values in the    // range to 4    fill(arr, arr + 10, 4);      for (int i = 0; i < 10; i++)        cout << arr[i] << " ";      return 0;}
4 4 4 4 4 4 4 4 4 4

Filling list in C++.
// C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std;  int main(){    list<int> ml = { 10, 20, 30 };      fill(ml.begin(), ml.end(), 4);      for (int x : ml)        cout << x << " ";      return 0;}
4 4 4

cpp-list
cpp-vector
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
C++ Classes and Objects
Operator Overloading in C++
Constructors in C++
Virtual Function in C++
Socket Programming in C/C++
Templates in C++ with Examples
Copy Constructor in C++
Object Oriented Programming in C++
rand() and srand() in C/C++
C++ program to find the Sum of each Row and each Column of a Matrix

In this tutorial, we will be discussing a program to find the sum of each row and each column for a given matrix.
For this, we will be given with a say A*B matrix. Our task is to traverse through all the elements of the matrix and find the sum of each row and each column of the matrix.
#include <iostream>
using namespace std;
#define m 7
#define n 6
//calculating sum of each row
void calc_rsum(int arr[m][n]){
   int i,j,sum = 0;
   for (i = 0; i < 4; ++i) {
      for (j = 0; j < 4; ++j) {
         sum = sum + arr[i][j];
      }
      cout << "Sum of the row "<< i << ": " << sum << endl;
      sum = 0;
   }
}
//calculating sum of each column
void calc_csum(int arr[m][n]) {
   int i,j,sum = 0;
   for (i = 0; i < 4; ++i) {
      for (j = 0; j < 4; ++j) {
         sum = sum + arr[j][i];
      }
      cout << "Sum of the column "<< i << ": " << sum <<endl;
      sum = 0;
   }
}
int main() {
   int i,j;
   int arr[m][n];
   int x = 1;
   for (i = 0; i < m; i++)
   for (j = 0; j < n; j++)
   arr[i][j] = x++;
   calc_rsum(arr);
   calc_csum(arr);
   return 0;
}
Sum of the row 0: 10
Sum of the row 1: 34
Sum of the row 2: 58
Sum of the row 3: 82
Sum of the column 0: 40
Sum of the column 1: 44
Sum of the column 2: 48
Sum of the column 3: 52
PyQt5 QPushButton - GeeksforGeeks

17 Sep, 2019
QPushButton is a simple button in PyQt, when clicked by a user some associated action gets performed. For adding this button into the application, QPushButton class is used.
Example:
A window having a Push Button, when clicked a message will appear “You clicked Push Button”.
Below is the code:
from PyQt5 import QtCore, QtGui, QtWidgetsimport sys  class Ui_MainWindow(object):      def setupUi(self, MainWindow):        MainWindow.resize(506, 312)        self.centralwidget = QtWidgets.QWidget(MainWindow)                  # adding pushbutton        self.pushButton = QtWidgets.QPushButton(self.centralwidget)        self.pushButton.setGeometry(QtCore.QRect(200, 150, 93, 28))          # adding signal and slot         self.pushButton.clicked.connect(self.changelabeltext)            self.label = QtWidgets.QLabel(self.centralwidget)        self.label.setGeometry(QtCore.QRect(140, 90, 221, 20))                # keeping the text of label empty before button get clicked        self.label.setText("")                      MainWindow.setCentralWidget(self.centralwidget)        self.retranslateUi(MainWindow)        QtCore.QMetaObject.connectSlotsByName(MainWindow)      def retranslateUi(self, MainWindow):        _translate = QtCore.QCoreApplication.translate        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))        self.pushButton.setText(_translate("MainWindow", "Push Button"))              def changelabeltext(self):          # changing the text of label after button get clicked        self.label.setText("You clicked PushButton")              # Hiding pushbutton from the main window        # after button get clicked.         self.pushButton.hide()     if __name__ == "__main__":     app = QtWidgets.QApplication(sys.argv)         MainWindow = QtWidgets.QMainWindow()     ui = Ui_MainWindow()     ui.setupUi(MainWindow)     MainWindow.show()       sys.exit(app.exec_()) 
Output:
Main Window having push button.
After clicking the button message appeared “You clicked Push Button.
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Convert integer to string in Python
Check if element exists in list in Python
Graph Plotting in Python | Set 1
Java float Keyword

❮ Java Keywords

float myNum = 5.75f;
System.out.println(myNum);


Try it Yourself »

The float keyword is a data type that can store fractional numbers from 3.4e−038 to 3.4e+038.
Note that you should end the value with an "f":
Read more about data types in our Java Data Types Tutorial.

❮ Java Keywords

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.
Egg Dropping Puzzle

This is a famous puzzle problem. Suppose there is a building with n floors, if we have m eggs, then how can we find the minimum number of drops needed to find a floor from which it is safe to drop an egg without breaking it.
There some important points to remember −
When an egg does not break from a given floor, then it will not break for any lower floor also.
If an egg breaks from a given floor, then it will break for all upper floors.
When an egg breaks, it must be discarded, otherwise, we can use it again.
Input:
The number of eggs and the maximum floor. Say the number of eggs are 4 and the maximum floor is 10.
Output:
Enter number of eggs: 4
Enter max Floor: 10
Minimum number of trials: 4
eggTrialCount(eggs, floors)
Input: Number of eggs, maximum floor.
Output − Get a minimum number of trials.
Begin
   define matrix of size [eggs+1, floors+1]
   for i:= 1 to eggs, do
      minTrial[i, 1] := 1
      minTrial[i, 0] := 0
   done

   for j := 1 to floors, do
      minTrial[1, j] := j
   done

   for i := 2 to eggs, do
      for j := 2 to floors, do
         minTrial[i, j] := ∞
         for k := 1 to j, do
            res := 1 + max of minTrial[i-1, k-1] and minTrial[i, j-k]
            if res < minTrial[i, j], then
               minTrial[i,j] := res
         done
      done
   done

   return minTrial[eggs, floors]
End
#include<iostream>
using namespace std;

int max(int a, int b) {
   return (a > b)? a: b;
}

int eggTrialCount(int eggs, int floors) {    //minimum trials for worst case
   int minTrial[eggs+1][floors+1];    //to store minimum trials for ith egg and jth floor
   int res;

   for (int i = 1; i <= eggs; i++) {    //one trial to check from first floor, and no trial for 0th floor
      minTrial[i][1] = 1;
      minTrial[i][0] = 0;
   }

   for (int j = 1; j <= floors; j++)    //when egg is 1, we need 1 trials for each floor
      minTrial[1][j] = j;

   for (int i = 2; i <= eggs; i++) {    //for 2 or more than 2 eggs
      for (int j = 2; j <= floors; j++) {    //for second or more than second floor
         minTrial[i][j] = INT_MAX;
         for (int k = 1; k <= j; k++) {
            res = 1 + max(minTrial[i-1][k-1], minTrial[i][j-k]);
            if (res < minTrial[i][j])
               minTrial[i][j] = res;
         }
      }
   }

   return minTrial[eggs][floors];    //number of trials for asked egg and floor
}

int main () {
   int egg, maxFloor;
   cout << "Enter number of eggs: "; cin >> egg;
   cout << "Enter max Floor: "; cin >> maxFloor;
   cout << "Minimum number of trials: " << eggTrialCount(egg, maxFloor);
}
Enter number of eggs: 4
Enter max Floor: 10
Minimum number of trials: 4
How to convert PHP array to JavaScript array?

You can use PHP array in JavaScript. It works for the single as well as the multidimensional array. Use the json_encode() method to achieve this.
Let’s say Our PHP array is −
$myArr = array('Amit', 'amit@example.com');
Converting PHP array into JavaScript.
<script>
var arr = <?php echo json_encode($myArr); ?>;
</script>
Now, let’s finally learn how to access it to output the email −
document.write(arr[1]);
Operations on an Array in Data Structures

Here we will see some basic operations of array data structure. These operations are −
Traverse
Insertion
Deletion
Search
Update
The traverse is scanning all elements of an array. The insert operation is adding some elements at given position in an array, delete is deleting element from an array and update the respective positions of other elements after deleting. The searching is to find some element that is present in an array, and update is updating the value of element at given position. Let us see one C++ example code to get better idea.
 Live Demo
#include<iostream>
#include<vector>
using namespace std;
main(){
   vector<int> arr;
   //insert elements
   arr.push_back(10);
   arr.push_back(20);
   arr.push_back(30);
   arr.push_back(40);
   arr.push_back(50);
   arr.push_back(60);
   for(int i = 0; i<arr.size(); i++){ //traverse
      cout << arr[i] << " ";
   }
   cout << endl;  
   //delete elements
   arr.erase(arr.begin() + 2);
   arr.erase(arr.begin() + 3);
   for(int i = 0; i<arr.size(); i++){ //traverse
      cout << arr[i] << " ";
   }
   cout << endl;
   arr[0] = 100; //update
   for(int i = 0; i<arr.size(); i++){ //traverse
      cout << arr[i] << " ";
   }
   cout << endl;
}
10 20 30 40 50 60
10 20 40 60
100 20 40 60
JavaScript for Loop

Loops can execute a block of code a number of times.
Loops are handy, if you want to run the same code over and over again, each 
time with a different value.
Often this is the case when working with arrays:
JavaScript supports different kinds of loops:
for - loops through a block of code a number of times
for/in - loops through the properties of an object
for/of - loops through the values of an 
  iterable object 
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true
The for loop has the following syntax:
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
From the example above, you can read:
Statement 1 sets a variable before the loop starts (let i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 
5).
Statement 3 increases a value (i++) each time the code block in the loop has 
been executed.
Normally you will use statement 1 to initialize the variable used in the loop (let i = 0).
This is not always the case, JavaScript doesn't care. Statement 1 is 
optional.
You can initiate many values in statement 1 (separated by comma):
And you can omit statement 1 (like when your values are set 
before the loop starts):
Often statement 2 is used to evaluate the condition of the initial variable.
This is not always the case, JavaScript doesn't care. Statement 2 is 
also optional.
If statement 2 returns true, the loop will start over again, if it returns false, the 
loop will end.
If you omit statement 2, you must provide a break inside the 
loop. Otherwise the loop will never end. This will crash your browser.
Read about breaks in a later chapter of this tutorial.
Often statement 3 increments the value of the initial variable.
This is not always the case, JavaScript doesn't care, and statement 3 is 
optional.
Statement 3 can do anything like negative increment (i--), positive 
increment (i = i + 15), or anything else.
Statement 3 can also be omitted (like when you increment your values inside the loop): 
Using var in a loop:
Using let in a loop:
In the first example, using var, the variable declared in 
the loop redeclares the variable outside the loop. 
In the second example, using let, the variable declared in 
the loop does not redeclare the variable outside the loop. 
When let is used to declare the i variable in a loop, the i 
variable will only be visible within the loop. 
The for/in loop and the for/of loop are explained in the next chapter.
The while loop and the do/while are explained in the next chapters.
Create a loop that runs from 0 to 9.
let i;
 ( = ;  < ; ) {
  console.log(i);
}

Start the Exercise
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.
Default value of primitive data types in Java

Primitive datatypes are predefined by the language and named by a keyword in Java. Here is an example to display the default value of primitive data types.
 Live Demo
public class Demo {
   static boolean val1;
   static double val2;
   static float val3;
   static int val4;
   static long val5;
   static String val6;
   public static void main(String[] args) {
      System.out.println("Default values.....");
      System.out.println("Val1 = " + val1);
      System.out.println("Val2 = " + val2);
      System.out.println("Val3 = " + val3);
      System.out.println("Val4 = " + val4);
      System.out.println("Val5 = " + val5);
      System.out.println("Val6 = " + val6);
   }
}
Default values.....
Val1 = false
Val2 = 0.0
Val3 = 0.0
Val4 = 0
Val5 = 0
Val6 = null
Above, firstly we have declared variables of specific type. Remember, to get the default values, you do not need to assign values to the variable.
static boolean val1;
static double val2;
static float val3;
static int val4;
static long val5;
static String val6;
Now to display the default values, you need to just print the variables.
System.out.println("Val1 = " + val1);
System.out.println("Val2 = " + val2);
System.out.println("Val3 = " + val3);
System.out.println("Val4 = " + val4);
System.out.println("Val5 = " + val5);
System.out.println("Val6 = " + val6);
How to normalize a histogram in Python?

To normalize a histogram in Python, we can use hist() method. In normalized bar, the area underneath the plot should be 1.
Make a list of numbers.
Make a list of numbers.
Plot a histogram with density=True.
Plot a histogram with density=True.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

k = [5, 5, 5, 5]
x, bins, p = plt.hist(k, density=True)

plt.show()
Tensorflow - linspace() in Python - GeeksforGeeks

20 Apr, 2022
TensorFlow is an open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. While working with TensorFlow many times we need to generate evenly-spaced values in an interval.
tensorflow.linspace(): This method takes starting tensor, ending tensor, number of values and axis and returns a Tensor with specified number of evenly spaced values.
Example 1: 
python3
# importing the libraryimport tensorflow as tf # Initializing Inputstart = tf.constant(1, dtype = tf.float64)end = tf.constant(5, dtype = tf.float64)num = 5 # Printing the Inputprint("start: ", start)print("end: ", end)print("num: ", num) # Getting evenly spaced valuesres = tf.linspace(start, end, num) # Printing the resulting tensorprint("Result: ", res)
Output:
start:  tf.Tensor(1.0, shape=(), dtype=float64)
end:  tf.Tensor(5.0, shape=(), dtype=float64)
num:  5
Result:  tf.Tensor([1. 2. 3. 4. 5.], shape=(5, ), dtype=float64)
Example 2: This example uses 2-D tensors and on providing different axis value different Tensors will be generated. This type of evenly-spaced value generation is currently allowed in nightly version. 
python3
# importing the libraryimport tensorflow as tf # Initializing Inputstart = tf.constant((1, 15), dtype = tf.float64)end = tf.constant((10, 35), dtype = tf.float64)num = 5 # Printing the Inputprint("start: ", start)print("end: ", end)print("num: ", num) # Getting evenly spaced valuesres = tf.linspace(start, end, num, axis = 0) # Printing the resulting tensorprint("Result 1: ", res) # Getting evenly spaced valuesres = tf.linspace(start, end, num, axis = 1) # Printing the resulting tensorprint("Result 2: ", res)
Output:
start:  tf.Tensor([ 1. 15.], shape=(2, ), dtype=float64)
end:  tf.Tensor([10. 35.], shape=(2, ), dtype=float64)
num:  5
Result 1:  tf.Tensor(
[[ 1.   15.  ]
 [ 3.25 20.  ]
 [ 5.5  25.  ]
 [ 7.75 30.  ]
 [10.   35.  ]], shape=(5, 2), dtype=float64)

Result 2:  tf.Tensor(
[[ 1.    3.25  5.5   7.75 10.  ]
 [15.   20.   25.   30.   35.  ]], shape=(2, 5), dtype=float64)
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
Difference between Streams and Collections in Java 8

Java Collections framework is used for storing and manipulating group of data. It is an in-memory data structure and every element in the collection should be computed before it can be added in the collections.
Stream API is only used for processing group of data. It does not modify the actual collection, they only provide the result as per the pipelined methods.
public class CollectiosExample {
   public static void main(String[] args) {

      List<String> laptopList = new ArrayList<>();
      laptopList.add("HCL");
      laptopList.add("Apple");
      laptopList.add("Dell");
      Comparator<String> com = (String o1, String o2)->o1.compareTo(o2);

      Collections.sort(laptopList,com);

      for (String name : laptopList) {
         System.out.println(name);
      }
   }
}
public class StreamsExample {
   public static void main(String[] args) {

      List<String> laptopList = new ArrayList<>();
      laptopList.add("HCL");
      laptopList.add("Apple");
      laptopList.add("Dell");
      laptopList.stream().sorted().forEach(System.out::println);
   }
}
agetty - Unix, Linux Command

agetty has several non-standard features that are useful
for hard-wired and for dial-in lines:


Under System V, a "-" port argument should be preceded
by a "--".


Baud rates should be specified in descending order, so that the
null character (Ctrl-@) can also be used for baud rate switching.


Since the -m feature may fail on heavily-loaded systems,
you still should enable BREAK processing by enumerating all
expected baud rates on the command line.


For a hard-wired line or a console tty:
   /sbin/agetty 9600 ttyS1


For a directly connected terminal without proper carriage detect wiring:
(try this if your terminal just sleeps instead of giving you a password:
prompt.)
   /sbin/agetty -L 9600 ttyS1 vt100


For a old style dial-in line with a 9600/2400/1200 baud modem:
   /sbin/agetty -mt60 ttyS1 9600,2400,1200


For a Hayes modem with a fixed 115200 bps interface to the machine:
(the example init string turns off modem echo and result codes, makes
modem/computer DCD track modem/modem DCD, makes a DTR drop cause a
dis-connection and turn on auto-answer after 1 ring.)
   /sbin/agetty -w -I ’ATE0Q1&D2&C1S0=1\015’ 115200 ttyS1








   This is \n.\o (\s \m \r) \t


   This is thingol.orcan.dk (Linux i386 1.1.9) 18:29:30





/var/run/utmp, the system status file.
/etc/issue, printed before the login prompt.
/dev/console, problem reports (if syslog(3) is not used).
/etc/inittab, init(8) configuration file.


The text in the /etc/issue file (or other) and the login prompt
are always output with 7-bit characters and space parity.


The baud-rate detection feature (the -m option) requires that
the modem emits its status message after raising the DCD line.

W.Z. Venema <wietse@wzv.win.tue.nl>
Eindhoven University of Technology
Department of Mathematics and Computer Science
Den Dolech 2, P.O. Box 513, 5600 MB Eindhoven, The Netherlands

Peter Orbaek <poe@daimi.aau.dk>
Linux port and more options. Still maintains the code.

Eric Rasmussen <ear@usfirst.org>
Added -f option to display custom login messages on different terminals.



Peter Orbaek <poe@daimi.aau.dk>
Linux port and more options. Still maintains the code.


Eric Rasmussen <ear@usfirst.org>
Added -f option to display custom login messages on different terminals.



Sat Nov 25 22:51:05 MET 1989

96/07/20


Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
C Program for Find sum of odd factors of a number?

In this section, we will see how we can get the sum of all odd prime factors of a number in an efficient way. There is a number say n = 1092, we have to get all factor of this. The prime factors of 1092 are 2, 2, 3, 7, 13. The sum of all odd factors is 3+7+13 = 23. To solve this problem, we have to follow this rule −
When the number is divisible by 2, ignore that factor, and divide the number by 2
repeatedly.
When the number is divisible by 2, ignore that factor, and divide the number by 2
repeatedly.
Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then add the factor with the sum, and change the number by divide it with the current number then continue.
Now the number must be odd. Now starting from 3 to square root of the number, if the number is divisible by current value, then add the factor with the sum, and change the number by divide it with the current number then continue.
Finally, the remaining number will also be added if the remaining number is odd
Finally, the remaining number will also be added if the remaining number is odd
Let us see the algorithm to get a better idea.
begin
   sum := 0
   while n is divisible by 2, do
      n := n / 2
   done
   for i := 3 to √n, increase i by 2, do
      while n is divisible by i, do
         sum := sum + i
         n := n / i
      done
   done
   if n > 2, then
      if n is odd, then
         sum := sum + n
      end if
   end if
end
#include<stdio.h>
#include<math.h>
int sumOddFactors(int n) {
   int i, sum = 0;
   while(n % 2 == 0) {
      n = n/2; //reduce n by dividing this by 2
   }
   //as the number is not divisible by 2 anymore, all factors are odd
   for(i = 3; i <= sqrt(n); i=i+2){ //i will increase by 2, to get
      only odd numbers
      while(n % i == 0) {
         sum += i;
         n = n/i;
      }
   }
   if(n > 2) {
      if(n%2 == 1)
         sum += n;
   }
   return sum;
}
main() {
   int n;
   printf("Enter a number: ");
   scanf("%d", &n);
   printf("Sum of all odd prime factors: %d", sumOddFactors(n));
}
Enter a number: 1092
Sum of all odd prime factors: 23
Slope of the line parallel to the line with the given slope

08 Jun, 2022
Given an integer m which is the slope of a line, the task is to find the slope of the line which is parallel to the given line.Examples:  
Input: m = 2 Output: 2Input: m = -3 Output: -3  
 
Approach:  
Let P and Q be two parallel lines with equations y = m1x + b1, and y = m2x + b2 respectively.Here m1 and m2 are the slopes of the lines respectively. Now as the lines are parallel, they don’t have any intersecting point, and hence there will be no system of solutions for the lines. So, let us try to solve the equations, 
For y, m1x + b1 = m2x + b2 m1x – m2x = b2 – b1 x(m1 – m2) = b2 – b1 The only way there can be no solution for x is for m1 – m2 to be equal to zero. m1 – m2 = 0 This gives us m1 = m2 and the slopes are equal.  
Below is the implementation of the above approach:  
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the slope// of the line which is parallel to// the line with the given slopedouble getSlope(double m){    return m;} // Driver codeint main(){    double m = 2;    cout << getSlope(m);     return 0;}
// Java implementation of the approachclass GfG{     // Function to return the slope// of the line which is parallel to// the line with the given slopestatic double getSlope(double m){    return m;} // Driver codepublic static void main(String[] args){    double m = 2;    System.out.println(getSlope(m));}} // This code is contributed by Code_Mech.
# Python3 implementation of the approach # Function to return the slope# of the line which is parallel to# the line with the given slopedef getSlope(m):     return m; # Driver codem = 2;print(getSlope(m)); # This code is contributed# by Akanksha Rai
// C# implementation of the approachclass GFG{     // Function to return the slope// of the line which is parallel to// the line with the given slopestatic double getSlope(double m){    return m;} // Driver codestatic void Main(){    double m = 2;    System.Console.Write(getSlope(m));}} // This code is contributed by mits
<?php// PHP implementation of the approach // Function to return the slope// of the line which is parallel to// the line with the given slopefunction getSlope($m){    return $m;} // Driver code$m = 2;echo getSlope($m); // This code is contributed by Ryuga?>
<script> // javascript implementation of the approach     // Function to return the slope// of the line which is parallel to// the line with the given slopefunction getSlope(m){    return m;} var m = 2;document.write(getSlope(m)); // This code contributed by Princi Singh </script>
2
 
Time Complexity: O(1)Auxiliary Space: O(1)
ankthon
Code_Mech
Mithun Kumar
Akanksha_Rai
princi singh
rishavmahato348
Geometric-Lines
school-programming
Geometric
Mathematical
Mathematical
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.