code-rag-bench/online-tutorials huggingface dataset:
Calculate the difference between the maximum and the minimum values of a given NumPy array along the second axis - GeeksforGeeks

02 Sep, 2020
Let’s see how to calculate the difference between the maximum and the minimum values of a given NumPy array along the second axis. Here, the Second axis means row-wise.
So firstly for finding the row-wise maximum and minimum elements in a NumPy array we are using numpy.amax() and numpy.amin() functions of NumPy library respectively. then After that we simply perform subtraction on it.
numpy.amax(): This function returns maximum of an array or maximum along axis(if mentioned). 
Syntax: numpy.amax(arr, axis = None, out = None, keepdims = )
numpy.amin(): This function returns minimum of an array or minimum along axis(if mentioned). 
Syntax: numpy.amin(arr, axis = None, out = None, keepdims = )
Now, Let’s see an example:
Example 1:
Python3
# import libraryimport numpy as np  # create a numpy 2d-arrayx = np.array([[100, 20, 305],             [ 200, 40, 300]])  print("given array:\n", x)  # get maximum element row# wise from numpy arraymax1 = np.amax(x ,1)  # get minimum element row# wise from numpy arraymin1 = np.amin(x, 1)  # print the row-wise max # and min differenceprint("difference:\n", max1 - min1)
Output:
given array:
 [[100  20 305]
 [200  40 300]]
difference:
 [285 260]
Example 2:
Python3
# import libraryimport numpy as np  # listx = [12, 13, 14, 15, 16]y = [17, 18, 19, 20, 21]  # create a numpy 2d-arrayarray = np.array([x, y]).reshape((2, 5))  print("original array:\n", array)  # find max and min elements# row-wisemax1, min1 = np.amax(array, 1), np.amin(array,1)  # print the row-wise max # and min differenceprint("Difference:\n", max1 - min1)
Output:
original array:
 [[12 13 14 15 16]
 [17 18 19 20 21]]
Difference:
 [4 4]
Python numpy-Linear Algebra
Python numpy-program
Python-numpy
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()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
C# TimeSpan Min value

Timespan shows the length of time.
To get the minimum value of TimeSpan, use the following property.
TimeSpan.MinValue
 Live Demo
using System;
using System.Linq;
public class Demo {
   public static void Main() {
      Console.WriteLine(TimeSpan.MinValue);
   }
}
-10675199.02:48:05.4775808
Check if an Object is of Type Character in R Programming - is.character() Function - GeeksforGeeks

16 Jun, 2020
is.character() function in R Language is used to check if the object passed to it as argument is of character type.
Syntax: is.character(x)
Parameters:x: Object to be checked
Example 1:
# R program to check if # object is a character  # Creating a vectorx1 <- 4x2 <- c("a", "b", "c", "d")x3 <- c(1, 2, "a", 3, "b")  # Calling is.character() functionis.character(x1)is.character(x2)is.character(x3)
Output:
[1] FALSE
[1] TRUE
[1] TRUE

Example 2:
# R program to check if # object is a character  # Creating a matrixx1 <- matrix(letters[1:9], 3, 3)  # Calling is.character() functionis.character(x1)
Output:
[1] TRUE

R List-Function
R Matrix-Function
R Object-Function
R String-Functions
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
How to Delete a File or Folder using CMD? - GeeksforGeeks

10 Jul, 2020
In some cases, for whatever reason, Windows will make sure that the provided file is used by the system and prevent it from being deleted. This file situation is very frustrating, especially if you know the file is not in use.
If you are having trouble in deleting any file or folder directly by right-clicking, then you can delete it using cmd. The commands below delete the specific file or folder and place them in the recycle bin:
del
rmdir
Here we have created a sample File and a Folder to delete it using CMD:
del command is used to delete a file. Here, we will take our sample file “hello.txt” located at the desktop and try to delete it using the del command in CMD. Follow the steps given below to delete the file:
Step 1: Change the path of the directory in CMD and set it to the path of the file. Type the following command in cmd and press Enter:
cd desktop
Step 2: Delete the file “hello.txt” with following command:
 del hello.txt
rmdir command is used to delete the entire folder or directory. Here, we will take our sample folder named “Tasks” placed at desktop and try to delete it using rmdir command in CMD. Follow the steps given below to delete the folder:
Step 1: Change the path of the directory in CMD and set it to the path of the folder. Type the following command in cmd and press Enter:
cd desktop
Step 2: Delete the folder “Tasks” with following command:
rmdir tasks
GBlog
How To
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
DSA Sheet by Love Babbar
6 Best IDE's For Python in 2022
A Freshers Guide To Programming
ML | Underfitting and Overfitting
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to Install OpenCV for Python on Windows?
What is the difference between initialization and assignment of values in C#?

Let us understand the difference between initialization and assignment of values.
Declaring an array.
int []  n  // declaring

Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array. Array is a reference type, so you need to use the new keyword to create an instance of the array.
int n= new int[10]; // initialization

Let’s assign value. You can assign values to individual array elements, by using the index number −
n[0] = 100;
n[1] = 200
With C#, you can declare, initialize and assign values to an array in a single line −
int n= new int[10] {100, 200, 300, 400, 500};

When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0.
Changing data type from date to date/time in MySQL?

To change data type from date to date/time, use alter command.
alter table yourTableName change yourColumnName yourColumnName datetime;
Let us first create a table −
mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   LoginDate date
   );
Query OK, 0 rows affected (1.26 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(LoginDate) values('2019-01-21');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable(LoginDate) values('2018-05-01');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable(LoginDate) values('2017-12-31');
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
+----+------------+
| Id | LoginDate  |
+----+------------+
| 1  | 2019-01-21 |
| 2  | 2018-05-01 |
| 3  | 2017-12-31 |
+----+------------+
3 rows in set (0.66 sec)
Following is the query to change data type from date to date/time in MySQL −
mysql> alter table DemoTable change LoginDate LoginDate datetime;
Query OK, 3 rows affected (1.63 sec)
Records : 3 Duplicates : 0 Warnings : 0
Let us check the table description using desc command −
mysql> desc DemoTable;
+-----------+----------+------+-----+---------+----------------+
| Field     | Type     | Null | Key | Default | Extra          |
+-----------+----------+------+-----+---------+----------------+
| Id        | int(11)  | NO   | PRI | NULL    | auto_increment |
| LoginDate | datetime | YES  |     | NULL    |                |
+-----------+----------+------+-----+---------+----------------+
2 rows in set (0.19 sec)
HTML | <body> link Attribute - GeeksforGeeks

25 Mar, 2022
The HTML <body> link Attribute is used to specify the default color for a unvisited link in a document. 
Note : The HTML <body> link attribute is not supported by HTML5. Instead of using this attribute we can use CSS | :link Selector 
Syntax:
<body link="color_name|hex_number|rgb_number"> 
Attribute Values: 
color_name: It is used to specifies the name of the color of the unvisited link.
hex_number: It is used to specifies the color of the unvisited link in terms of hex code.
rgb_number: It is used to specifies the color of the unvisited link in terms of RGB value.
Example: 
html
<!DOCTYPE html><html> <head>    <title>        HTML body link Attribute    </title></head> <body link = "red">    <center>        <h1 style="color:green;">            GeeksforGeeks        </h1>                 <h2>HTML <body> link Attribute</h2>                 <a href="#">            A computer science            portal for geeks        </a>    </center></body> </html>       
Output:
  
Supported Browsers: The browser supported by HTML <body> link attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
ManasChhabra2
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
HTML Cheat Sheet - A Basic Guide to HTML
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
Types of CSS (Cascading Style Sheet)
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
Google Charts - Bar chart with data labels

Following is an example of a bar chart with data labels. We've already seen the configuration used to draw this chart in Google Charts Configuration Syntax chapter. So, let's see the complete example.
We've used role as annotation configuration to show data labels in bar chart.
var data = google.visualization.arrayToDataTable([
   ['Year', 'Asia', { role: 'annotation'} ,'Europe', { role: 'annotation'}],
   ['2012',  900,'900',      390, '390']
]);
googlecharts_bar_labels.htm
<html>
   <head>
      <title>Google Charts Tutorial</title>
      <script type = "text/javascript" src = "https://www.gstatic.com/charts/loader.js">
      </script>
      <script type = "text/javascript">
         google.charts.load('current', {packages: ['corechart']});     
      </script>
   </head>
   
   <body>
      <div id = "container" style = "width: 550px; height: 400px; margin: 0 auto">
      </div>
      <script language = "JavaScript">
         function drawChart() {
            // Define the chart to be drawn.
            var data = google.visualization.arrayToDataTable([
               ['Year', 'Asia', { role: 'annotation'} ,'Europe', { role: 'annotation'}],
               ['2012',  900,'900',      390, '390'],
               ['2013',  1000,'1000',      400,'400'],
               ['2014',  1170,'1170',      440,'440'],
               ['2015',  1250,'1250',       480,'480'],
               ['2016',  1530,'1530',      540,'540']
            ]);

            var options = {title: 'Population (in millions)', isStacked:'percent'};  

            // Instantiate and draw the chart.
            var chart = new google.visualization.BarChart(document.getElementById('container'));
            chart.draw(data, options);
         }
         google.charts.setOnLoadCallback(drawChart);
      </script>
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
How to set dialog to show with full screen in Android using Kotlin?

This example demonstrates how to set dialog to show with full screen in Android using Kotlin.
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"?>
<RelativeLayout 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"
   tools:context=".MainActivity">
<Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="40dp"
   android:onClick="clickHere"
   android:text="Click here" />
<TextView
   android:textSize="24sp"
   android:textStyle="bold|italic"
   android:textColor="@android:color/holo_purple"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:text="Hello World" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.app.Dialog
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
   }
   fun clickHere(view: View) {
      val dialog = Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen)
      dialog.setContentView(R.layout.activity_main)
      dialog.show()
   }
}
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="com.example.q11">
   <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 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
Click here to download the project code.
Comments in Lua Programming

Comments are a set of commands that are ignored by the compiler. They are used in a scenario where you want to attach a note to your code or a section of code so that when you visit it later, you can recall it easily. The comment statements are usually ignored during the execution of the program.
There are two types of comments in Lua −
Single-line comments
Single-line comments
Multi-line comments
Multi-line comments
Multi-line comments are also known as block comments in Lua.
A single-line comment in Lua starts with a double hyphen (--) and runs until the end of the line.
-- this is a comment
Let’s consider an example where we write multiple single-line comments and then deliberately write invalid codes inside them and see what happens.
Consider the example shown below −
-- z = 10
print(z)

x = 11
-- print(x)

-- ans
Notice that on the last line, we are declaring a global variable without an assignment which is illegal according to Lua, but since we are doing it inside a comment, it will be ignored by Lua.
nil

Multi-Line comments, also known as block comments in Lua, make use of a special syntax.
--[[
this
is
a
comment
--]]
Let’s create an example where we write two block comments, one of them is a valid
comment and the other one is not a valid block comment.
Consider the example shown below −
--[[
print(110)
--]]

---[[
print("str")
--]]
In the above example, the second section of code looks like a valid block level comment, but if we look closely, then we will notice that it isn’t.
str
How to select element using XPATH syntax on Selenium for Python?

We can select elements using xpath with Selenium webdriver. Xpath is one of the most important locators. There are two types of xpath. They are known as absolute [starting from parent node in DOM] and relative xpath [starting from anywhere in DOM].
The xpath syntax is − //tagname[@attribute='value'] or //*[@attribute='value'].
Let us consider the html code of an element that we shall identify with the help of xpath−
The xpath expression is //input[@name='firstname'] or //*[@name='firstname'].
from selenium import webdriver
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm")
// identify element with xpath
l = driver.find_element_by_xpath("//input[@name='firstname']")
l.send_keys("Python")
driver.quit()
Sum of Series | Practice | GeeksforGeeks

Write a program to find the sum of the given series 1+2+3+ . . . . . .(N terms) 
Example 1:
Input:
N = 1
Output: 1
Explanation: For n = 1, sum will be 1.

Example 2:
Input:
N = 5
Output: 15
Explanation: For n = 5, sum will be 1
+ 2 + 3 + 4 + 5 = 15.

Your Task:
Complete the function seriesSum() which takes single integer n, as input parameters and returns an integer denoting the answer. You don't to print answer or take inputs.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 105
 
-1
mdiftekhar7024 days ago
100100/100100 
 
class Solution {   // function to return sum of  1, 2, ... n   long seriesSum(long n) {       // code here          if(n<=0)      {          return 0;      }      long sum =n*(n+1)/2;       return  sum;   }}
0
harshscode2 weeks ago
   long long s= (((long long)n)*((long long)(n+1)))/2;    return s;
-1
rsbly7300952 weeks ago
class Solution {
    
    seriesSum(n) {
        // let sum = 0;
        
        // for(let i = 1; i <= n; i++) {
        //     sum =sum + i;
        // }
        // return sum;
        return (n*(n+1))/2;
    }
}
0
19wh1a12112 weeks ago
//java
long seriesSum(long n) {       // code here       long  sum=n*(n+1)/2;       return sum;
0
rsbly7300952 weeks ago
class Solution {      seriesSum(n) {       // let sum = 0;              // for(let i = 1; i <= n; i++) {       //     sum =sum + i;       // }       // return sum;       return (n*(n+1))/2;   }}
0
sangrambachu2 weeks ago
Formula = n*(n+1)/2
 
class Solution {
    seriesSum(n) {
        // code here
        return n*(n+1)/2;
    }
}
0
mayank180919993 weeks ago
	//100100/100100 passed successfull
	long long seriesSum(int n) {
	    // code here
	    const int m=1e15+10;
	    return ((n%m)*1LL*((n%m)+1)/2);
	}
0
mayank18091999
This comment was deleted.
0
convertedengineer3 weeks ago
//C++

long long sum=(((long long)n)*((long long)(n+1)))/2;
        return sum;
0
kmabhi1113 weeks ago
//Java Solution
// User function Template for Java
class Solution {   // function to return sum of  1, 2, ... n   long seriesSum(int n) {       // long a =  ((1+(long)n)/2)*(long)n;       return (long)n*((long)n+1)/2 ;   }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
PostgreSQL - SERIAL - GeeksforGeeks

22 Feb, 2021
PostgreSQL has a special kind of database object generator called SERIAL. It is used to generate a sequence of integers which are often used as the Primary key of a table. 
Syntax: variable_name SERIAL
When creating a table, this sequence of integers can be created as follows: 
CREATE TABLE table_name(
    id SERIAL
);
By assigning the SERIAL to the id column, PostgreSQL carries out the following: 
The initial step generates sequences of integers, where the next default value depends upon the value for the column.
As SERIAL always generates a sequence of integers, it is important to set that no null value is added as an ID to any column. This is done by adding the NOT NULL constraint.
Finally, it is needed to set t5he owner of the sequence for the ID column. These IDs are automatically deleted if the column or table is dropped. 
PostgreSQL supports 3 serial pseudo-types namely SMALLSERIAL, SERIAL, and BIGSERIAL which has the following characteristics: 
Example 1: First, we will create a animals table with the id column as the SERIAL column as below: 
CREATE TABLE animals(
   id SERIAL PRIMARY KEY,
   name VARCHAR NOT NULL
);
Now while inserting the values to the table one can use anyone of the below commands: 
INSERT INTO animals(name) 
VALUES('Dog');
or, 
INSERT INTO animals(id, name) 
VALUES(DEFAULT, 'Dog');
So let’s add some rows to our animal table using the command below: 
INSERT INTO animals(name) 
VALUES
      ('Dog'),
      ('Cat'),
      ('Cow'),
      ('Tiger'),
      ('Snake'),
      ('Bull');
Now check if ids are auto-assigned to each row by using the below command: 
SELECT * FROM animals;
Output:
Example 2: First, we will create a fruits table with the id column as the SERIAL column as below: 
CREATE TABLE fruits(
   id SERIAL PRIMARY KEY,
   name VARCHAR NOT NULL
);
Now while inserting the values to the table one can use anyone of the below commands: 
INSERT INTO fruits(name) 
VALUES('Apple');
or, 
INSERT INTO fruits(id, name) 
VALUES(DEFAULT, 'Apple');
So let’s add some rows to our fruits table using the command below: 
INSERT INTO fruits(name) 
VALUES
      ('Apple'),
      ('Banana'),
      ('Cherry'),
      ('Mango'),
      ('Grapes'),
      ('Orange');
Now check if ids are auto-assigned to each row by using the below command: 
SELECT * FROM fruits;
Output: 
RajuKumar19
postgreSQL-dataTypes
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
PostgreSQL - GROUP BY clause
PostgreSQL - LEFT JOIN
PostgreSQL - Rename Table
PostgreSQL - Select Into
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Record type variable
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - Boolean Data Type
PostgreSQL - Cursor
How to generate multiple reports in HTML using PowerShell?

To generate or append multiple outputs in the HTML file using PowerShell, we need to use the - Fragment parameter in the ConvertTo-HTML command.
For example, let say we need to generate the computer utilization report which includes the top 5 consuming processes, stopped services, and the disk utilization report. A single report can be generated by sending the output to the ConvertTo-HTML pipeline command.
$Heading = "<h1><center>System Utilization Report</h1></center>"

$procs = Get-Process | Sort-Object -Property CPU -Descending| Select -
First 5 | `
   ConvertTo-Html -Property ProcessName, ID, CPU -Fragment -
PreContent "<h3>High Utilization Processes</h3>"

$services = Get-Service | where{$_.StartType -eq "Disabled"} | `
   ConvertTo-Html -Property Name, Status, StartType -Fragment -
PreContent "<h3>Disabled Services</h3>"

$disks = Get-WmiObject win32_logicaldisk | `
   Select DeviceID, @{N='FreeSpace(GB)';E={[math]::Round(($_.FreeSpace/1GB),2)}}
, `
   @{N='TotalSpace(GB)';E={[math]::Round(($_.Size/1GB),2)}} | `
   ConvertTo-Html -Fragment -PreContent "<h3>Disk Information</h3>"
ConvertTo-Html -Body "$Heading $procs $services $disks" | OutFile C:\Temp\SystemUtilizationReport.html

ii C:\Temp\SystemUtilizationReport.html
To add the CSS style to the Report,
$Heading = "<h1><center>System Utilization Report</h1></center>"

$procs = Get-Process | Sort-Object -Property CPU -Descending| Select -
First 5 | `
   ConvertTo-Html -Property ProcessName, ID, CPU -Fragment -
PreContent "<h3>High Utilization Processes</h3>"

$services = Get-Service | where{$_.StartType -eq "Disabled"} | `
   ConvertTo-Html -Property Name, Status, StartType -Fragment -
PreContent "<h3>Disabled Services</h3>"

$disks = Get-WmiObject win32_logicaldisk | `
   Select DeviceID, @{N='FreeSpace(GB)';E={[math]::Round(($_.FreeSpace/1GB),2)}}
, `
   @{N='TotalSpace(GB)';E={[math]::Round(($_.Size/1GB),2)}} | `
   ConvertTo-Html -Fragment -PreContent "<h3>Disk Information</h3>"

ConvertTo-Html -Body "$Heading $procs $services $disks" -Head $cssstyle | OutFile C:\Temp\SystemUtilizationReport.html

ii C:\Temp\SystemUtilizationReport.html
Python Program to Convert Gray Code to Binary

When it is required to convert gray code to binary code, a method is defined, that checks to see if the number is 0 or not.
Below is the demonstration of the same −
 Live Demo
def flip_num(my_nu):
   return '1' if(my_nu == '0') else '0';

def gray_to_binary(gray):
   binary_code = ""
   binary_code += gray[0]
   for i in range(1, len(gray)):

      if (gray[i] == '0'):
         binary_code += binary_code[i - 1]
      else:
         binary_code += flip_num(binary_code[i - 1])

   return binary_code
gray_code = "01101001"
print("The gray code is :")
print(gray_code)
print("Binary code of", gray_code, "is", gray_to_binary(gray_code))
The gray code is :
01101001
Binary code of 01101001 is 01001110
A method named ‘flip_num’ is defined that checks to see if the number is 0.
A method named ‘flip_num’ is defined that checks to see if the number is 0.
If it is 0, it returns 1, else it returns 0.
If it is 0, it returns 1, else it returns 0.
Another method named ‘gray_to_binary’ is defined that takes a gray code as a parameter.
Another method named ‘gray_to_binary’ is defined that takes a gray code as a parameter.
It iterates over the numbers in gray code, and stores the value in binary number’s index.
It iterates over the numbers in gray code, and stores the value in binary number’s index.
If the number is not 0, then the ‘flip_num’ method is called, and the number is changed to 1.
If the number is not 0, then the ‘flip_num’ method is called, and the number is changed to 1.
A binary number is defined, and the method is called by passing this value.
A binary number is defined, and the method is called by passing this value.
The output is displayed on the console.
The output is displayed on the console.
bg command in Linux with Examples - GeeksforGeeks

15 May, 2019
bg command in linux is used to place foreground jobs in background.
Syntax:
bg [job_spec ...]
job_spec may be:
%n : Refer to job number n.%str : Refer to a job which was started by a command beginning with str.%?str : Refer to a job which was started by a command containing str.%% or %+ : Refer to the current job. fg and bg will operate on this job if no job_spec is given.%- : Refer to the previous job.
Options for bg command:
bg [JOB_SPEC] : This command is used to put the mentioned job in background. In the below screenshot, we do following :We use jobs command to list all jobsWe create a process using sleep command, we get its ID as 1.We put it in background by providing its ID to bg.‘sleep 500’ is used to create dummy foreground job.
We use jobs command to list all jobsWe create a process using sleep command, we get its ID as 1.We put it in background by providing its ID to bg.
We use jobs command to list all jobs
We create a process using sleep command, we get its ID as 1.
We put it in background by providing its ID to bg.
‘sleep 500’ is used to create dummy foreground job.
bg –help : This command displays help information.
linux-command
Linux-system-commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
tar command in Linux with examples
curl command in Linux with Examples
UDP Server-Client implementation in C
diff command in Linux with examples
Conditional Statements | Shell Script
Cat command in Linux with examples
'crontab' in Linux with Examples
touch command in Linux with Examples
echo command in Linux with Examples
Tail command in Linux with examples
Tryit Editor v3.7

Tryit: Border color with HSL values
How to count a depth level of nested JavaScript objects?

We have an array of objects, which further have nested objects like this −
const arr = [{
   id: 0, children: []
}, {
      id: 1, children: [{
      id: 2, children: []
}, {
      id: 3, children: [{
         id: 4, children: []
      }]
   }]
}];
Our job is to write a recursive function, say assignDepth() that takes in this array and assigns
depth property to each nested object. Like the object with id 0 will have depth 0, id 1 will have
depth 1 as well, and since id 2 and id 3 are nested inside id 1 they will have depth 1 and id 4
which is further nested inside id 3 will have depth 2.
Therefore, let’s write the code for this function. It’s a simple recursive function which iterates
over sub objects repeatedly until it reaches the end of the array −
const arr = [{
   id: 0, children: []
}, {
      id: 1, children: [{
      id: 2, children: []
}, {
      id: 3, children: [{
         id: 4, children: []
      }]
   }]
}];
const assignDepth = (arr, depth = 0, index = 0) => {
   if(index < arr.length){
      arr[index].depth = depth;
      if(arr[index].children.length){
         return assignDepth(arr[index].children, depth+1, 0);
      };
      return assignDepth(arr, depth, index+1);
   };
   return;
};
assignDepth(arr);
console.log(JSON.stringify(arr, undefined, 4));
The output in the console will be −
[
   {
      "id": 0,
      "children": [],
      "depth": 0
   },
   {
      "id": 1,
      "children": [
         {
            "id": 2,
            "children": [],
            "depth": 1
         },
         {
            "id": 3,
            "children": [
               {
                  "id": 4,
                  "children": [],
                  "depth": 2
               }
            ],
            "depth": 1
         }
      ],
      "depth": 0
   }
]
Make JavaScript take HTML input from user, parse and display?

The HTML input value is a string. To convert the string to integer, use parseInt().
Following is the code −
 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>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <input type="text" id="txtInput" placeholder="Enter a number">
   <button type="button" onclick="result();">GetANumber</button>
</body>
<script>
   function result() {
      var numberValue = document.getElementById("txtInput").value;
      if (!isNaN(numberValue))
         console.log("The value=" + parseInt(numberValue));
      else
         console.log("Please enter the integer value..");
   }
</script>
</html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VS Code editor.
This will produce the following output on console −
Now, enter a value into the text box.
Now press the button, you will get the following output.
This will produce the following output −
The output in console −
How to validate an email address in C#?

There are several ways to validate an email address in C#.
System.Net.Mail −The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery.
System.Text.RegularExpressions − Represents an immutable regular expression.
Use the below expression
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([azA-Z]{2,4}|[0-9]{1,3})(\]?)$"
We can use the MailAddress class of the System.Net.Mail namespace to validate an email address
 Live Demo
using System;
using System.Net.Mail;
namespace DemoApplication{
   class Program{
      public static void Main(){
         try{
            string email = "hello@xyzcom";
            Console.WriteLine($"The email is {email}");
            var mail = new MailAddress(email);
            bool isValidEmail = mail.Host.Contains(".");
            if(!isValidEmail){
               Console.WriteLine($"The email is invalid");
            } else {
               Console.WriteLine($"The email is valid");
            }
            Console.ReadLine();
         }
         catch(Exception){
            Console.WriteLine($"The email is invalid");
            Console.ReadLine();
         }
      }
   }
}
The output of the above code is
The email is hello@xyzcom
The email is invalid
Example using Regex −
We can also use regular expression to validate an email address.
using System;
using System.Text.RegularExpressions;
namespace DemoApplication{
   public class Program{
      public static void Main(){
         string email = "hello@xyz.com";
         Regex regex = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-
         9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
         RegexOptions.CultureInvariant | RegexOptions.Singleline);
         Console.WriteLine($"The email is {email}");
         bool isValidEmail = regex.IsMatch(email);
         if (!isValidEmail){
            Console.WriteLine($"The email is invalid");
         } else {
            Console.WriteLine($"The email is valid");
         }
         Console.ReadLine();
      }
   }
}
The output of the above code is
The email is hello@xyz.com
The email is valid
How to remove NaN values from a given NumPy array?

29 Aug, 2020
In this article, we are going to learn how to remove Nan values from a given array. man values are those values that do not have a specific value associated with it or they are different from the type of values that are to be used in the declared array.
There are basically two approaches that work in the same way, just a slight difference in syntax. Either we could use a function specified in NumPy or we could use an operator, the basic working will be the same.
Method #1 : Using numpy.logical_not() and numpy.nan() functions
The numpy.isnan() will give true indexes for all the indexes where the value is nan and when combined with numpy.logical_not() function the boolean values will be reversed. So, in the end, we get indexes for all the elements which are not nan. From the indexes, we can filter out the values that are not nan and save it in another array.
Python3
import numpy    # create a 1D arraya = numpy.array([5, 2, 8, 9, 3, numpy.nan,                 2, 6, 1, numpy.nan])  # remove nan values using numpy.isnan()# and numpy.logical_notb = a[numpy.logical_not(numpy.isnan(a))]  # print the resultsprint("original 1D array                    ->", a)print("1D array after removing nan values   ->", b)print()  # create a 2D arrayc = numpy.array([[6, 2, numpy.nan], [2, 6, 1],                 [numpy.nan, 1, numpy.nan]])  # remove nan values using numpy.isnan()# and numpy.logical_notd = c[numpy.logical_not(numpy.isnan(c))]  # print the resultsprint("Original 2D array   ->")print(c)print("2D array converted to 1D after removing nan values   ", d)
Output:
Note: No matter what Dimension of the array is, it will be flattened into a 1D array
Method #2 : Combining the ~ operator instead of numpy.logical_not() with numpy.isnan() function. This will work the same way as the above, it will convert any dimension array into 1D array.
In the below code only the 2D array is shown for example.
Python3
import numpy    # create a 2D arrayc = numpy.array([[12, 5, numpy.nan, 7],                  [2, 61, 1, numpy.nan],                 [numpy.nan, 1,                  numpy.nan, 5]])  # remove nan values using numpy.isnan() # and numpy.logical_notd = c[~(numpy.isnan(c))]  # print the resultsprint("Original 2D array   ")print(c)print()  print("2D array converted to 1D after removing nan values   ")print(d)
Output:
Python numpy-arrayManipulation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Steiner Tree Problem

02 Jun, 2022
What is Steiner Tree? Given a graph and a subset of vertices in the graph, a Steiner tree spans through the given subset. The Steiner Tree may contain some vertices which are not in the given subset but are used to connect the vertices of the subset. The given set of vertices is called Terminal Vertices and other vertices that are used to construct the Steiner tree are called Steiner vertices. The Steiner Tree Problem is to find the minimum cost of Steiner Tree. See below for an example.  Spanning Tree vs Steiner Tree Minimum Spanning Tree is a minimum weight tree that spans through all vertices. If the given subset (or terminal) vertices are equal to the set of all vertices in the Steiner Tree problem, then the problem becomes the Minimum Spanning Tree problem. And if the given subset contains only two vertices, then it shortest path problem between two vertices. Finding out Minimum Spanning Tree is polynomial-time solvable, but the Minimum Steiner Tree problem is NP-Hard and the related decision problem is NP-Complete. Applications of Steiner Tree Any situation where the task is to minimize the cost of connection among some important locations like VLSI Design, Computer Networks, etc. Shortest Path-based Approximate Algorithm Since the Steiner Tree problem is NP-Hard, there are no polynomial-time solutions that always give optimal cost. Therefore, there are approximate algorithms to solve the same. Below is one simple approximate algorithm.
1) Start with a subtree T consisting of 
   one given terminal vertex
2) While T does not span all terminals
   a) Select a terminal x not in T that is closest 
      to a vertex in T.
   b) Add to T the shortest path that connects x with T
The above algorithm is (2-2/n) approximate, i.e., it guarantees that the solution produced by this algorithm is not more than this ratio of optimized solution for a given graph with n vertices. There are better algorithms also that provide a better ratio. Refer to the below reference for more details. References: www.cs.uu.nl/docs/vakken/an/teoud/an-steiner.ppt This article is contributed by Shivam Gupta. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above
raj2002
MST
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dijkstra's shortest path algorithm | Greedy Algo-7
Find if there is a path between two vertices in a directed graph
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Detect Cycle in a Directed Graph
Introduction to Data Structures
Find if there is a path between two vertices in an undirected graph
Bellman–Ford Algorithm | DP-23
What is Data Structure: Types, Classifications and Applications
Minimum number of swaps required to sort an array
m Coloring Problem | Backtracking-5
Python | Get key from value in Dictionary

08 Dec, 2020
Let’s see how to get the key by value in Python Dictionary. 
Method 1: Using list.index()
The index() method returns index of corresponding value in a list. Below is an implementation how to use index() method to fetch Dictionary key using value.  
Python3
# creating a new dictionarymy_dict ={"java":100, "python":112, "c":11} # list out keys and values separatelykey_list = list(my_dict.keys())val_list = list(my_dict.values()) # print key with val 100position = val_list.index(100)print(key_list[position]) # print key with val 112position = val_list.index(112)print(key_list[position]) # one-linerprint(list(my_dict.keys())[list(my_dict.values()).index(112)])
java
python
python
 
Explanation: The approach used here is to find two separate lists of keys and values. Then fetch the key using the position of the value in the val_list. As key at any position N in key_list will have corresponding value at position N in val_list.   
Method #2: Using dict.item() We can also fetch key from a value by matching all the values and then print the corresponding key to given value.  
Python3
# function to return key for any valuedef get_key(val):    for key, value in my_dict.items():         if val == value:             return key     return "key doesn't exist" # Driver Code my_dict ={"java":100, "python":112, "c":11} print(get_key(100))print(get_key(11))
java
c
 
unknow0060
Python dictionary-programs
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Difference between SHA1 and SHA2

22 May, 2020
1. SHA1 (Secure Hash Algorithm 1) :SHA1 is a cryptographic hash function which is designed by United States National Security Agency. It takes an input and produces a 160 bits hash value. Further the output produced by this function is converted into a 40 digits long hexadecimal number. It is a U.S. Federal Information Processing Standard. It was first published in 1995. It is successor to SH0 published in 1993.Example:
Data : Geeksforgeeks
SHA1 : bc7623b7a94ed3d8feaffaf7580df3eca4f5f5ca 
2. SHA2 (Secure Hash Algorithm 2) :SHA1 is also a cryptographic hash function which is designed by United States National Security Agency. It is constructed using the Merkle-Damgard structure from a one-way compression function. The compression function used is constructed using the Davies-Meyer structure from a classified block cipher. It was first published in 2001. It is successor to SH1.Example:
Data : Geeksforgeeks
SHA2(256) : 86d755349c6b9f95f365c6ffe7734f25bf2b00cabe8c6bc5f2b8b746c1aac332 
Difference between SHA1 and SHA2 :
cryptography
Computer Networks
Difference Between
GATE CS
cryptography
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Wireless Application Protocol
GSM in Wireless Communication
Secure Socket Layer (SSL)
Mobile Internet Protocol (or Mobile IP)
Advanced Encryption Standard (AES)
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Matplotlib.ticker.FixedLocator Class in Python

21 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.ticker.FixedLocator class is a subclass of matplotlib.ticker.Locator class and is used to fix tick locations. If the value of nbins is not equal to None, then the array of all possible positions would be sub-sampled to keep the total number of ticks smaller than or equal to nbins + 1. The sub-sampling is done as to include the absolute value that is smallest. for instance, if zero is included inside the array of possibly values, then it guarantees a chosen tick.
Syntax: class matplotlib.ticker.FixedLocator(locs, nbins=None)
Parameters:
locs: It represents the location of the ticks.
nbins: It represents the number of bins that the data is to be divided into.
Methods of the class:
set_params(self, nbins=None): It is used to set the parameters within the locator.
tick_value(self, vmin, vmax): It returns the location of ticks between vmax and vmin.
Example 1:
import numpy as npimport matplotlib.pyplot as pltimport matplotlib     np.arange(0, 15, 5)plt.figure(figsize = [6,4])   x = np.array([1, 2, 3, 4, 5,              6, 7, 8, 9, 10,              11, 12, 13, 14, 15])  y = np.array([15, 16, 17, 18,               19, 20, 40, 50,               60, 70, 80, 90,               100, 110, 120])  ax = sns.pointplot(x, y,                   color = 'k',                   markers = ["."],                    scale = 2)  ax.xaxis.set_major_locator(matplotlib.ticker.FixedLocator([1,5,8]))  plt.show()
Output:
Example 2:
import matplotlib.pyplot as pltimport numpy as npimport matplotlib.ticker    t = np.arange(0.0, 100.0, 0.1)s = np.sin(0.1 * np.pi * t)*np.exp(-t * 0.01)  fig, ax = plt.subplots()plt.plot(t, s)  ax1 = ax.twiny()ax1.plot(t, s)  ax1.xaxis.set_ticks_position('bottom')  majors = np.linspace(0, 100, 6)minors = np.linspace(0, 100, 11)thirds = np.linspace(0, 100, 101)  ax.xaxis.set_major_locator(matplotlib.ticker.FixedLocator(majors))ax.xaxis.set_minor_locator(matplotlib.ticker.FixedLocator(minors))ax1.xaxis.set_major_locator(matplotlib.ticker.FixedLocator([]))ax1.xaxis.set_minor_locator(matplotlib.ticker.FixedLocator(thirds))  ax1.tick_params(which ='minor', length = 2)ax.tick_params(which ='minor', length = 4)ax.tick_params(which ='major', length = 6)  ax.grid(which ='both', axis ='x', linestyle ='--')  plt.axhline(color ='green')  plt.show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Convert string to integer in Python
How to set input type date in dd-mm-yyyy format using HTML ?
Python infinity
Factory method design pattern in Java
Matplotlib.pyplot.title() in Python