code-rag-bench/online-tutorials huggingface dataset:
CSS - Positioning

CSS helps you to position your HTML element. You can put any HTML element at whatever location you like. You can specify whether you want the element positioned relative to its natural position in the page or absolute based on its parent element.
Now, we will see all the CSS positioning related properties with examples −
Relative positioning changes the position of the HTML element relative to where it normally appears. So "left:20" adds 20 pixels to the element's LEFT position.
You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document.
Move Left - Use a negative value for left.
Move Right - Use a positive value for left.
Move Up - Use a negative value for top.
Move Down - Use a positive value for top.
NOTE − You can use bottom or right values as well in the same way as top and left.
Here is the example −
<html>
   <head>
   </head>

   <body>
      <div style = "position:relative; left:80px; top:2px; background-color:yellow;">
         This div has relative positioning.
      </div>
   </body>
</html>
It will produce the following result −
An element with position: absolute is positioned at the specified coordinates relative to your screen top-left corner.
You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document.
Move Left - Use a negative value for left.
Move Right - Use a positive value for left.
Move Up - Use a negative value for top.
Move Down - Use a positive value for top.
NOTE − You can use bottom or right values as well in the same way as top and left.
Here is an example −
<html>
   <head>
   </head>

   <body>
      <div style = "position:absolute; left:80px; top:20px; background-color:yellow;">
         This div has absolute positioning.
      </div>
   </body>
</html> 
Fixed positioning allows you to fix the position of an element to a particular spot on the page, regardless of scrolling. Specified coordinates will be relative to the browser window.
You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document.
Move Left - Use a negative value for left.
Move Right - Use a positive value for left.
Move Up - Use a negative value for top.
Move Down - Use a positive value for top.
NOTE − You can use bottom or right values as well in the same way as top and left.
Here is an example −
<html>
   <head>
   </head>

   <body>
      <div style = "position:fixed; left:80px; top:20px; background-color:yellow;">
         This div has fixed positioning.
      </div>
   </body>
</html>

    33 Lectures 
     2.5 hours 

 Anadi Sharma

    26 Lectures 
     2.5 hours 

 Frahaan Hussain

    44 Lectures 
     4.5 hours 

 DigiFisk (Programming Is Fun)

    21 Lectures 
     2.5 hours 

 DigiFisk (Programming Is Fun)

    51 Lectures 
     7.5 hours 

 DigiFisk (Programming Is Fun)

    52 Lectures 
     4 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Save a dictionary to a file

29 Dec, 2020
A dictionary in Python is a collection where every value is mapped to a key. They are unordered, mutable and there is no constraint on the data type of values and keys stored in the dictionary. This makes it tricky for dictionaries to be stored as files. Know more about dictionaries here.
Syntax:
dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}

There are two main approaches for saving dictionaries into files using Python.
1. Text Files
The most basic way to save dictionaries in Python would be to store them as strings in text files. This method would include the following steps:
Opening a file in write/append text mode
Converting the dictionary into a string
Entering the converted string into the file using write function
filehandler = open(filename, 'wt')
data = str(dictionary)
filehander.write(data)

Reading from the dictionary back from the stored text files is cumbersome and this method should only be used for smaller and non-critical programs.
2. Pickle Module (Recommended)
The pickle module in Python is mostly used in fields like Data Science where data persistence is critical. The pickle module stores the given data as a serialized byte sequence into files which can be easily retrieved at a later time. Pickle module supports various Python objects and dictionaries are one among them. This method would include the following steps:
Importing the pickle module
Opening the file in write/append binary mode
Entering the data into the file using pickle module’s dump method
filehandler = open(filename, 'wb')
pickle.dump(dictionary, filehandler)

Below is the implementation of the above methods.
Example 1: Writing to Text File
Python3
dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}  try:    geeky_file = open('geekyfile.txt', 'wt')    geeky_file.write(str(dictionary))    geeky_file.close()  except:    print("Unable to write to file")
Output:
Example 2: Appending to Text File
Python3
dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}  try:    geeky_file = open('geekyfile.txt', 'a')    geeky_file.write(str(dictionary))    geeky_file.close()  except:    print("Unable to append to file")
Output:
Example 3: Writing using Pickle Module
Python3
import pickle  dictionary = {'geek': 1, 'supergeek': True, 4: 'geeky'}  try:    geeky_file = open('geekyfile', 'wb')    pickle.dump(dictionary, geeky_file)    geeky_file.close()  except:    print("Something went wrong")
Note: As the pickle module stores data in binary form, the data in the file is unreadable by humans.
Python file-handling-programs
python-dict
python-file-handling
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Short Note on Size-Oriented Metrics

30 Jun, 2020
Size Oriented Metrics derived by normalizing quality and productivity Point Metrics measures by considering size of the software that has been produced. The organization builds a simple record of size measure for the software projects. It is built on past experiences of organizations. It is a direct measure of software.
This metrics is one of simplest and earliest metrics that is used for computer program to measure size. Size Oriented Metrics are also used for measuring and comparing productivity of programmers. It is a direct measure of a Software. The size measurement is based on lines of code computation. The lines of code are defined as one line of text in a source file.
While counting lines of code, simplest standard is:
Don’t count blank lines
Don’t count comments
Count everything else
The size-oriented measure is not a universally accepted method.
Simple set of size measure that can be developed is as given below:
Size = Kilo Lines of Code (KLOC) 
Effort = Person / month
Productivity = KLOC / person-month
Quality = Number of faults / KLOC
Cost = $ / KLOC
Documentation = Pages of documentation / KLOC 
Advantages :
Using these metrics, it is very simple to measure size.
Artifact of Software development which is easily counted.
LOC is used by many methods that are already existing as a key input.
A large body of literature and data based on LOC already exists.
Disadvantages :
This measure is dependent upon programming language.
This method is well designed upon programming language.
It does not accommodate non-procedural languages.
Sometimes, it is very difficult to estimate LOC in early stage of development.
Though it is simple to measure but it is very hard to understand it for users.
It cannot measure size of specification as it is defined on code.
Example –For a size oriented metrics, software organization maintains records in tabular form. The typical table entries are: Project Name, LOC, Efforts, Pages of documents, Errors, Defects, Total number of people working on it.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Average of two lists

19 Feb, 2020
The problem of finding a average values in a list is quite common. But sometimes this problem can be extended in two lists and hence becomes a modified problem. This article discusses shorthands by which this task can be performed easily. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using sum() + len() + “+” operatorThe average value can be determined by the conventional sum() and len function of python and the extension of one to two lists can be dealt using the “+” operator.
# Python3 code to demonstrate# Average of two lists# using sum() + len() + "+" operator  # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1]  # printing the original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # Average of two lists# using sum() + len() + "+" operatorres = sum(test_list1 + test_list2) / len(test_list1 + test_list2)  # printing resultprint ("The Average of both lists is : " + str(res))
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The Average of both lists is : 4.166666666666667

 
Method #2 : Using sum() + len() + chain()Another method to perform this particular task is by using the chain function which performs the task similar to the “+” operator but using an iterator, hence faster.
# Python3 code to demonstrate# Average of two lists# using sum() + len() + "+" operatorfrom itertools import chain  # initializing liststest_list1 = [1, 3, 4, 5, 2, 6]test_list2 = [3, 4, 8, 3, 10, 1]  # printing the original listsprint ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2))  # Average of two lists# using sum() + len() + "+" operatorres = sum(chain(test_list1, test_list2)) / len(list(chain(test_list1, test_list2)))  # printing resultprint ("The Average of both lists is : " + str(res))
The original list 1 is : [1, 3, 4, 5, 2, 6]
The original list 2 is : [3, 4, 8, 3, 10, 1]
The Average of both lists is : 4.166666666666667

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python OOPs Concepts
Python Classes and Objects
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
GATE | GATE CS 2018 | Question 14 - GeeksforGeeks

12 Aug, 2021
Consider the following C program:
#include <stdio.h>  int counter = 0;  int calc(int a, int b) {  int c;    counter++;  if (b == 3)    return (a * a * a);  else {    c = calc(a, b / 3);    return (c * c * c);  }}  int main() {  calc(4, 81);  printf("%d", counter);}
The output of this program is ________ .
Note – This was Numerical Type question.(A) 5(B) 4(C) 3(D) None of theseAnswer: (B)Explanation: 
YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersGATE PYQs 2017 and 2018 with Shubham Agrawal | GeeksforGeeks GATE CSEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0048:42 / 1:11:13•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=j9Vmf5yRw-I" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE CS 2018
GATE-GATE CS 2018
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2021 | Set 1 | Question 47
GATE | GATE CS 2011 | Question 7
How to create JLabel to hold multiline of text using HTML in Java?

To hold multiline of text, set HTML under JLabel −
JLabel = new JLabel("<html><strong>" + "Line1<br>Line2</strong></html>",JLabel.LEFT);
The above will create multiline text in the JLabel −
Line1
Line2
The following is an example to create JLabel to hold multiline of text −
import java.awt.Font;
import javax.swing.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Label Example");
      JLabel label;
      label = new JLabel("" + "Line1
      Line2",JLabel.LEFT);
      label.setBounds(100, 100, 100, 30);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      frame.add(label);
      frame.setSize(500,300);
      frame.setLayout(null);
      frame.setVisible(true);
   }
}
Lodash _.eq() Method - GeeksforGeeks

09 Sep, 2020
The _.eq() method is used to find the two values are equivalent or not by performing the SameValueZero comparison. It returns true, if the values are equivalent. Otherwise, it returns false.
Syntax:
_.eq(value, other)

Parameters: This method accepts two parameters as mentioned above and described below:
value: This parameter holds the value to compare.
other: This parameter holds the other value to compare.
Return Value: This method returns true if the values are equivalent, else false.
Example 1:
Javascript
// Requiring the lodash library  const _ = require("lodash");         // Use of _.eq method console.log(_.eq("Geeks", "Geeks" )); console.log(_.eq("Geeks", Object("Geeks"))); console.log(_.eq(NaN, NaN)); 
Output:
true
false
true

Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");    // Given valuesvar object = { 'gfg': 2020 };var other = { 'gfg': 2020 };  // Use of _.eq method console.log(_.eq(object, object)); console.log(_.eq(object, other)); 
Output:
true
false

JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Hide or show elements in HTML using display property
Set the value of an input field in JavaScript
How to calculate the number of days between two dates in javascript?
Express.js express.Router() Function
Installation of Node.js on Linux
How to set input type date in dd-mm-yyyy format using HTML ?
Differences between Functional Components and Class Components in React
How to create footer to stay at the bottom of a Web page?
Program to find a sublist where first and last values are same in Python

Suppose we have a list of numbers called nums, we have to find the number of sublists where the first element and the last element are same.
So, if the input is like nums = [10, 15, 13, 10], then the output will be 5, as the sublists with same first and last element are: [10], [15], [13], [10], [10, 15, 13, 10].
To solve this, we will follow these steps −
num_sublists := size of nums
num_sublists := size of nums
d := an empty map
d := an empty map
for each n in nums, dod[n] := d[n] + 1
for each n in nums, do
d[n] := d[n] + 1
d[n] := d[n] + 1
for each number k and corresponding frequency v of elements in d, doif v is not same as 1, thennum_sublists := num_sublists +(quotient of (v-1) *(v) /2)
for each number k and corresponding frequency v of elements in d, do
if v is not same as 1, thennum_sublists := num_sublists +(quotient of (v-1) *(v) /2)
if v is not same as 1, then
num_sublists := num_sublists +(quotient of (v-1) *(v) /2)
num_sublists := num_sublists +(quotient of (v-1) *(v) /2)
return num_sublists
return num_sublists
Let us see the following implementation to get better understanding −
 Live Demo
from collections import defaultdict
class Solution:
   def solve(self, nums):
      num_sublists = len(nums)

      d = defaultdict(int)
      for n in nums:
         d[n] += 1
   
      for k,v in d.items():
         if v != 1:
            num_sublists += (v-1)*(v)//2
      return num_sublists
ob = Solution()
nums = [10, 15, 13, 10]
print(ob.solve(nums))
[10, 15, 13, 10]
5
Stack.ToString() Method in C# with examples

The Stack.ToString() method in C# is used to get the string representation of the Stack class object.
The syntax is as follows −
public string ToString ();
Let us now see an example −
 Live Demo
using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Stack stack = new Stack();
      stack.Push(150);
      stack.Push(300);
      stack.Push(500);
      stack.Push(750);
      stack.Push(1000);
      stack.Push(1250);
      stack.Push(1500);
      stack.Push(2000);
      stack.Push(2500);
      Console.WriteLine("Stack elements...");
      foreach(int val in stack) {
         Console.WriteLine(val.ToString());
      }
      Console.WriteLine("Count of elements = "+stack.Count);
      stack.Push(3000);
      stack.Push(3500);
      stack.Push(4000);
      Console.WriteLine("\nStack elements...updated");
      foreach(int val in stack) {
         Console.WriteLine(val.ToString());
      }
      Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
      Console.WriteLine("\nCopying the Stack to a new array...");
      Object[] objArr = stack.ToArray();
      foreach(Object ob in objArr) {
         Console.WriteLine(ob);
      }
      Console.WriteLine("\nCount of elements in array = "+objArr.Length);
   }
}
This will produce the following output −
Stack elements...
2500
2000
1500
1250
1000
750
500
300
150
Count of elements = 9

Stack elements...updated
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150
Count of elements (updated) = 12

Copying the Stack to a new array...
4000
3500
3000
2500
2000
1500
1250
1000
750
500
300
150

Count of elements in array = 12
Let us now see another example −
 Live Demo
using System;
using System.Collections;
public class Demo {
   public static void Main() {
      Stack stack = new Stack();
      stack.Push("Inspiron");
      stack.Push("Alienware");
      stack.Push("Projectors");
      stack.Push("Monitors");
      stack.Push("XPS");
      stack.Push("Laptop");
      stack.Push("Notebook");
      Console.WriteLine("Stack elements...");
      foreach(string val in stack) {
         Console.WriteLine(val.ToString());
      }
      Console.WriteLine("Count of elements = "+stack.Count);
      Console.WriteLine("Element at the top = "+ stack.Peek());
      stack.Push("Ultrabook");
      stack.Push("Cameras");
      stack.Push("Keyboards");
      Console.WriteLine("\nStack elements...updated");
      foreach(string val in stack) {
         Console.WriteLine(val.ToString());
      }
      Console.WriteLine("Element at the top = "+ stack.Peek());      
      Console.WriteLine("\nCount of elements (updated) = "+stack.Count);
      stack.Clear();
      Console.Write("Count of elements (updated) = "+stack.Count);
   }
}
This will produce the following output −
Stack elements...
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Count of elements = 7
Element at the top = Notebook
Stack elements...updated
Keyboards
Cameras
Ultrabook
Notebook
Laptop
XPS
Monitors
Projectors
Alienware
Inspiron
Element at the top = Keyboards
Count of elements (updated) = 10
Count of elements (updated) = 0
Java Program to Compare two Double Arrays - GeeksforGeeks

28 Dec, 2020
Java double array is used to store double data type values only. The default value of the elements in a double array is 0.
We can compare two double arrays by two ways:
By naive approach of traversing through the whole array and comparing each element.By Arrays.equals() method.
By naive approach of traversing through the whole array and comparing each element.
By Arrays.equals() method.
Method 1: Naive Approach
By Comparing one element at a time by traversing through both the arrays using for loop.
Java
// Java program to compare two double arrays  import java.util.*;import java.lang.*;import java.io.*;  class GFG {      public static void main(String[] args) throws java.lang.Exception    {            // Two double arrays array1 and array2        double[] array1 = { 1.5, 2.5, 3.5, 4.5 };        double[] array2 = { 1.5, 2.5, 3.5 };          // when the length of two arrays are not         // same, then both the arrays cannot be equal        // so no need of comparing each element        if (array1.length != array2.length)              System.out.println("Arrays are not Equal");                else {            for (int i = 0; i < array1.length; i++)            {                   // comparing each and every element                if (array1[i] != array2[i])                {                    System.out.println("Arrays are not Equal");                    System.exit(0);                }            }                        System.out.println("Arrays are Equal");        }    }}
Arrays are not Equal
Time Complexity: O(n)
Method 2: Using Arrays.equals() method
Syntax :
public static boolean equals(int[] a, int[] a2)
Parameters : 
a1 – one array to be tested for equality
a2 – the other array to be tested for equality
Returns : true if the two arrays are equal
Java
// Java program to compare two double arrays  import java.util.*;import java.lang.*;import java.io.*;  class GFG {    public static void main(String[] args) throws java.lang.Exception    {        double[] array1 = { 1.5, 2.5, 3.5, 4.5 };        double[] array2 = { 1.5, 2.5, 3.5, 4.5 };           // Arrays.equals() compares the equality        // of two arrays        if (Arrays.equals(array1, array2))            System.out.println("Arrays are Equal");        else            System.out.println("Arrays are Not Equal");    }}
Arrays are Equal
Time Complexity: O(1)
Java-Arrays
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java
How to avoid duplicate columns after join in PySpark ? - GeeksforGeeks

19 Dec, 2021
In this article, we will discuss how to avoid duplicate columns in DataFrame after join in PySpark using Python.
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of employee datadata = [["1", "sravan", "company 1"],        ["2", "ojaswi", "company 1"],        ["3", "rohith", "company 2"],        ["4", "sridevi", "company 1"],        ["5", "bobby", "company 1"]]  # specify column namescolumns = ['ID', 'NAME', 'Company']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)  dataframe.show()
Output:
Python3
# list  of employee datadata1 = [["1", "45000", "IT"],         ["2", "145000", "Manager"],         ["6", "45000", "HR"],         ["5", "34000", "Sales"]]  # specify column namescolumns = ['ID', 'salary', 'department']  # creating a dataframe from the lists of datadataframe1 = spark.createDataFrame(data1, columns)  dataframe1.show()
Output:
We can join the dataframes using joins like inner join and after this join, we can use the drop method to remove one duplicate column.
Syntax: dataframe.join(dataframe1,dataframe.column_name == dataframe1.column_name,”inner”).drop(dataframe.column_name)
where,
dataframe is the first dataframe
dataframe1 is the second dataframe
inner specifies inner join
drop() will delete the common column and delete first dataframe column
Python3
# inner join on two dataframes# and remove duplicate columndataframe.join(dataframe1,               dataframe.ID == dataframe1.ID,               "inner").drop(dataframe.ID).show()
Output:
Here we are simply using join to join two dataframes and then drop duplicate columns.
Syntax: dataframe.join(dataframe1, [‘column_name’]).show()
where,
dataframe is the first dataframe
dataframe1 is the second dataframe
column_name is the common column exists in two dataframes
Python3
# join on two dataframes# and remove duplicate columndataframe.join(dataframe1, ['ID']).show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python | Pandas Series.to_clipboard() - GeeksforGeeks

05 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.to_clipboard() function copy object to the system clipboard. It write a text representation of object to the system clipboard. This can be pasted into Excel as well.
Syntax: Series.to_clipboard(excel=True, sep=None, **kwargs)
Parameter :excel : bool, default Truesep : str, default ‘\t’**kwargs : These parameters will be passed to DataFrame.to_csv.
Returns : None
Example #1: Use Series.to_clipboard() function to copy the given Series object to the systems clipboard.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow'])  # Create the Datetime Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                      periods = 6, tz = 'Europe/Berlin')   # set the indexsr.index = didx  # Print the seriesprint(sr)
Output :
Now we will use Series.to_clipboard() function to copy the given series object to the systems clipboard.
# copy to clipboardsr.to_clipboard()
Output :
After executing the last line of code we simply pasted what was copied to the system’s clipboard in Notepad++. This is what it looks like.
Example #2: Use Series.to_clipboard() function to copy the given Series object to the systems clipboard.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None])  # Print the seriesprint(sr)
Output :
Now we will use Series.to_clipboard() function to copy the given series object to the systems clipboard.
# copy to clipboardsr.to_clipboard()
Output :
After executing the last line of code we simply pasted what was copied to the system’s clipboard in Notepad++. This is what it looks like. Notice how missing values has been represented as blanks.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
matplotlib.axes.Axes.vlines() in Python - GeeksforGeeks

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.vlines() function in axes module of matplotlib library is used to Plot vertical lines at each x from ymin to ymax.
Syntax: Axes.vlines(self, x, ymin, ymax, colors=’k’, linestyles=’solid’, label=”, *, data=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
x: This parameter is the sequence of x-indexes where to plot the lines.
ymin, ymax: These parameter contains an array.And they represents the beginning and end of each line.
colors: This parameter is an optional parameter. And it is the color of the lines with default value k.
linetsyle: This parameter is also an optional parameter. And it is used to represent the linestyle{‘solid’, ‘dashed’, ‘dashdot’, ‘dotted’}.
label: This parameter is also an optional parameter.It is the label of the plot.
Returns: This returns the LineCollection.
Below examples illustrate the matplotlib.axes.Axes.vlines() function in matplotlib.axes:
Example #1:
# Implementation of matplotlib function       import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt  fig, ax = plt.subplots()ax.vlines([1, 2, 3, 4], 0, 1,           color ="green",          transform = ax.get_xaxis_transform())  ax.set_title('matplotlib.axes.Axes.vlines Example')  plt.show()
Output:
Example #2:
# Implementation of matplotlib function       import numpy as npfrom matplotlib import patchesimport matplotlib.pyplot as plt   t = np.arange(0.0, 5.0, 0.1)s = np.exp(-t) + np.cos(3 * np.pi * t) + np.sin(np.pi * t)nse = np.random.normal(0.0, 0.8, t.shape) * s  fig, ax = plt.subplots()  ax.vlines(t, [0], s)ax.vlines([1, 2], 0, 1, color ="lightgreen",           transform = ax.get_xaxis_transform())  ax.set_xlabel('time (s)')ax.set_title('matplotlib.axes.Axes.vlines Example')  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
numpy.log2() in Python - GeeksforGeeks

29 Nov, 2018
numpy.log2(arr, out = None, *, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None, ufunc ‘log1p’) :This mathematical function helps user to calculate Base-2 logarithm of x where x belongs to all the input array elements.
Parameters :
array    : [array_like]Input array or object.
out      : [ndarray, optional]Output array with same dimensions as Input array, 
           placed with result.
**kwargs : Allows you to pass keyword variable length of argument to a function. 
           It is used when we want to handle named argument in a function.
where    : [array_like, optional]True value means to calculate the universal 
           functions(ufunc) at that position, False value means to leave the 
           value in the output alone.

Return :
An array with Base-2 logarithmic value of x; 
where x belongs to all elements of input array. 

Code 1 : Working
# Python program explaining# log2() functionimport numpy as np  in_array = [1, 3, 5, 2**8]print ("Input array : ", in_array)  out_array = np.log2(in_array)print ("Output array : ", out_array)    print("\nnp.log2(4**4) : ", np.log2(4**4))print("np.log2(2**8) : ", np.log2(2**8))
Output :
Input array :  [1, 3, 5, 256]
Output array :  [ 0.          1.5849625   2.32192809  8.        ]

np.log2(4**4) :  8.0
np.log2(2**8) :  8.0

 Code 2 : Graphical representation
# Python program showing# Graphical representation of # log2() functionimport numpy as npimport matplotlib.pyplot as plt  in_array = [1, 1.2, 1.4, 1.6, 1.8, 2]out_array = np.log2(in_array)  print ("out_array : ", out_array)  plt.plot(in_array, in_array, color = 'blue', marker = "*")  # red for numpy.log2()plt.plot(out_array, in_array, color = 'red', marker = "o")plt.title("numpy.log2()")plt.xlabel("out_array")plt.ylabel("in_array")plt.show()  
Output :
out_array :  [ 0.          0.26303441  0.48542683  0.67807191  0.84799691  1.        ]
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.exp.html.
Python numpy-Logic Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python - Cumulative product of dictionary value lists - GeeksforGeeks

25 Aug, 2021
Sometimes, while working with Python dictionaries, we can have it’s values as lists. In this can we can have a problem that we just require the product of elements in those list as a whole. This can be a problem in Data Science in which we need to get total records in observations. Let’s discuss certain ways in which this task can be performedMethod #1 : Using loop + list comprehension This task can be performed using explicit product function which can be used to get the product and internal list comprehension can provide a mechanism to iterate this logic to all the keys of dictionary. 
Python3
# Python3 code to demonstrate working of# Cumulative product of dictionary value lists# using loop + list comprehension def prod(val) :        res = 1            for ele in val:                res *= ele            return res # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Cumulative product of dictionary value lists# using loop + list comprehensionres = sum(prod(sub) for sub in test_dict.values()) # printing resultprint("Product of dictionary list values are : " + str(res))
The original dictionary is : {'best': [19, 31, 22], 'gfg': [5, 6, 7], 'is': [10, 11]}
Product of dictionary list values are : 13278
 
 Method #2 : Using loop + map() This task can also be performed using map function in place of list comprehension to extend the logic of finding the product, rest all the functionality remaining same as the above method. 
Python3
# Python3 code to demonstrate working of# Cumulative product of dictionary value lists# using loop + map() def prod(val) :        res = 1            for ele in val:                res *= ele            return res # initialize dictionarytest_dict = {'gfg' : [5, 6, 7], 'is' : [10, 11], 'best' : [19, 31, 22]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Cumulative product of dictionary value lists# using loop + map()res = sum(map(prod, test_dict.values())) # printing resultprint("Product of dictionary list values are : " + str(res))
The original dictionary is : {'best': [19, 31, 22], 'gfg': [5, 6, 7], 'is': [10, 11]}
Product of dictionary list values are : 13278
 
gabaa406
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Tensorflow tf.add() Function - GeeksforGeeks

04 Mar, 2021
The tf.add() function returns the addition of two tf.Tensor objects element wise. The tf.Tensor object represents the multidimensional array of numbers.
Syntax:
tf.add( a, b )
Parameters: 
a: It contains the first tf.Tensor object that is to be added. The value of this parameter can be tf.TensorTypedArray|Array.
b: It contains the second tf.Tensor object that is to be added into the first tf.Tensor object. The value of this parameter can be (tf.Tensor|TypedArray|Array). The type of this parameter is same as type of a.
Return Value: This function returns the tf.Tensor object.
Example 1:
Javascript
// Importing the tensorflow.js library import * as tf from "@tensorflow/tfjs"  // Declare the Tensor arrayconst arr1 = tf.tensor1d([10, 20, 30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]);  // Use add() function to add// two Tensor objectsarr1.add(arr2).print();
Output:
Tensor
    [15, 30, 45, 60, 75]
Example 2:
Javascript
// Importing the tensorflow.js library import * as tf from "@tensorflow/tfjs"  // Declare the Tensor arrayconst arr1 = tf.tensor1d([30, 40, 50]);const arr2 = tf.tensor1d([5, 10, 15, 20, 25]);  // Use add() function to add// two Tensor objectsarr1.add(arr2).print();
Output:
An error occured on line: 7
Operands could not be broadcast together with shapes 3 and 5.
Example 3:
Javascript
// Importing the tensorflow.js library import * as tf from "@tensorflow/tfjs"  // Declare the Tensor arrayconst arr = tf.tensor1d([5, 10, 15, 20, 25]);  // Declare a numberconst num = tf.scalar(30);  // Use add() function to add// Tensor object and a numberarr.add(num).print();
Output:
Tensor
    [35, 40, 45, 50, 55]
Reference: https://js.tensorflow.org/api/latest/#add
Tensorflow
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
Python - Interconvert Tuple to Byte Integer - GeeksforGeeks

03 Jul, 2020
Sometimes, while working with Python data, we can have a problem in which we need to perform conversion of tuple values, into combined byte and then to integer and vice-versa. This kind of problem can have application in data domains. Let’s discuss certain ways in which this task can be performed.
Input : test_tuple = (1, 2, 3, 4, 5)Output : 4328719365
Input : test_int = 4328719365Output : (1, 2, 3, 4, 5)
Method #1 : Tuple -> Byte Integer : Using int.from_bytes()The combination of above functions can be used to solve this problem. In this, we perform the task of conversion using internal function from_bytes() and obtain the desired integer value.
# Python3 code to demonstrate working of # Interconvert Tuple to Byte Integer# Tuple -> Byte Integer : Using int.from_bytes()  # initializing tuplestest_tuple = (6, 8, 3, 2)  # printing original tupleprint("The original tuple : " + str(test_tuple))  # Interconvert Tuple to Byte Integer# Tuple -> Byte Integer : Using int.from_bytes()res = int.from_bytes(test_tuple, byteorder ='big')  # printing result print("Tuple after conversion : " + str(res))
The original tuple : (6, 8, 3, 2)
Tuple after conversion : 101188354

 
Method #2 : Byte Integer -> Tuple : Using tuple.to_bytes()The combination of above functions can be used to solve this problem. In this, we perform the task of conversion using internal method to_bytes() to obtain desired result.
# Python3 code to demonstrate working of # Interconvert Tuple to Byte Integer# Using Byte Integer -> Tuple : Using tuple.to_bytes()  # initializing integertest_int = 101188354  # printing original integerprint("The original integer : " + str(test_int))  # Interconvert Tuple to Byte Integer# Using Byte Integer -> Tuple : Using tuple.to_bytes()res = tuple(test_int.to_bytes(4, byteorder ='big'))  # printing result print("Integer after conversion : " + str(res))
The original integer : 101188354
Integer after conversion : (6, 8, 3, 2)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
DXC Technology Interview Experience - GeeksforGeeks

27 Jul, 2021
DXC Technology Campus Drive was held in the month of July 21 (For the batch of 2022 i.e final year students) for the full-time employees as Associate Professional-Software Engineering.
All rounds were held online.
ROUND 1: This was an Aptitude based exam with the following sections- Logical Reasoning, Quantitative Aptitude, Verbal Ability, Essay Writing, Computer Programming, and Coding Section(Automata Fix) and its platform was Amcat.
Apart from Automata Fix and Essay Writing all other sections were objective type(MCQs) and each section had limited time. Sample papers and preparatory material for this test are available online.
Automata Fix consists of 7 questions. These questions are debugging and coding-based questions. These questions were very basic.
It was an elimination round and only the students who cleared the test were invited for Technical+HR Round.
Candidates were asked to submit their resumes in DXC Format with this test.
ROUND 2: This was a mix of Technical and HR interviews. 
The interviewer asked me few general questions like “Tell me about yourself”, “Short term and long term goal”, “Are you willing to relocate”, “Do you have any gap in education or not”. 
After that, My interview is solely based on my projects. He asked me few questions related to my projects. 
At last, he asked me “Do you have any questions for me”. I asked him one question and after answering it my interview got over.
Some candidates were also asked to write the code in the editor. The interview was held on the Amcat SmartMeet platform.
The result was declared when all interviews were done and I got selected for the role of Associate Professional.
Verdict: Selected
DXC Technology
Marketing
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
EPAM Interview Experience (Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience for SDE-1 (On-Campus)
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
Lagrange Multipliers - GeeksforGeeks

01 Oct, 2019
One of the major problems that engineers face is the problem of optimization of a certain function. Mathematics provides us with a beautiful way to solve such problems. This method is known as the Method of Lagrange Multipliers.
So how and when to apply? There are certain conditions.Suppose you have the following problem:Find the coordinates of the point on the plane 2x + 3y – 5z = 1 which is at the least distance from the origin.
So the function you want to optimize is,
√(x2 + y2 + z2),
Let this be f(x, y, z) 
But we have a constraint;the point should lie on the given plane.Hence this ‘constraint function’ is generally denoted by g(x, y, z).But before applying Lagrange Multiplier method we should make sure that g(x, y, z) = c where ‘c’ is a constant. In this situation,
g(x, y, z) = 2x + 3y - 5z
It is indeed equal to a constant that is ‘1’. Hence we can apply the method.
Now the procedure is to solve this equation:
∇f(x, y, z) = λ∇g(x, y, z)
where λ is a real number.
This gives us 3 equations and the fourth equation is of course our constraint function g(x, y, z).Solve for x, y, z and λ.
An example will make it clear.
Example:Find the maximum and minimum values of f(x, y, z) = 3x2 + y subject to the constraint,
4x - 3y = 9 
and x2 + z2 = 9
.
This example has been deliberately taken to teach you what to do in case of more than one constraint functions. In such cases assume as many arbitrary constants as the number of constraint functions and write the equation in the form:
∇f(x, y, z) = c1∇g(x, y, z) + c2∇h(x, y, z) + c3∇p(x, y, z) ... ...
where ci for i=1, 2, 3... are just real numbers and g, h, p are constraint functions.
Now if you get more than one triplet, figure out which one represents a maximum and which one represents the minimum by satisfying it in the function to be optimized and compare the values.In this question the answer would be:
Maximum for (-2/√13, 3/√13, -2 - 7/√13) and 
Minimum for (2/√13, -3/√13, -2 + 7/√13)
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Difference between Propositional Logic and Predicate Logic
Logic Notations in LaTeX
Univariate, Bivariate and Multivariate data and its analysis
Z-test
Proof that vertex cover is NP complete
Brackets in Latex
Betweenness Centrality (Centrality Measure)
Introduction of Statistics and its Types
Mathematics | Introduction of Set theory
Python - Validate String date format - GeeksforGeeks

11 Aug, 2021
Given a date format and a string date, the task is to write a python program to check if the date is valid and matches the format.
Examples:
Input : test_str = ’04-01-1997′, format = “%d-%m-%Y”
Output : True
Explanation : Formats match with date.
Input : test_str = ’04-14-1997′, format = “%d-%m-%Y”
Output : False
Explanation : Month cannot be 14.
In this, the function, strptime usually used for conversion of string date to datetime object, is used as when it doesn’t match the format or date, raises the ValueError, and hence can be used to compute for validity.
Python3
# Python3 code to demonstrate working of# Validate String date format# Using strptime()from datetime import datetime # initializing stringtest_str = '04-01-1997' # printing original stringprint("The original string is : " + str(test_str)) # initializing formatformat = "%d-%m-%Y" # checking if format matches the dateres = True # using try-except to check for truth valuetry:    res = bool(datetime.strptime(test_str, format))except ValueError:    res = False # printing resultprint("Does date match format? : " + str(res))
Output:
The original string is : 04-01-1997
Does date match format? : True
In this, we check for validated format using different inbuilt function, dateutil.parser. This doesn’t need the format to detect for a date.
Python3
# Python3 code to demonstrate working of# Validate String date format# Using dateutil.parser.parsefrom dateutil import parser # initializing stringtest_str = '04-01-1997' # printing original stringprint("The original string is : " + str(test_str)) # initializing formatformat = "%d-%m-%Y" # checking if format matches the dateres = True # using try-except to check for truth valuetry:    res = bool(parser.parse(test_str))except ValueError:    res = False # printing resultprint("Does date match format? : " + str(res))
Output:
The original string is : 04-01-1997
Does date match format? : True
kk773572498
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?