code-rag-bench/online-tutorials huggingface dataset:
How to find the sum of column values of an R data frame?

An R data frame contain columns that might represent a similar type of variables; therefore, we might want to find the sum of the values for each of the columns and make a comparison based on the sum. This can be done with the help of sum function but first we need to extract the columns to find the sum.
Consider the below data frame −
> set.seed(1)
> x1<-rnorm(20)
> x2<-rnorm(20,0.5)
> x3<-rnorm(20,1)
> x4<-rnorm(20,1.5)
> x5<-rnorm(20,2)
> x6<-rnorm(20,2.5)
> x7<-rnorm(20,3)
> df<-data.frame(x1,x2,x3,x4,x5,x6,x7)
> df
x1 x2 x3 x4 x5 x6 x7
1 -0.62645381 1.41897737 0.83547640 3.9016178 1.4313313 1.879633 2.494043
2 0.18364332 1.28213630 0.74663832 1.4607600 1.8648214 2.542116 4.343039
3 -0.83562861 0.57456498 1.69696338 2.1897394 3.1780870 1.589078 2.785421
4 1.59528080 -1.48935170 1.55666320 1.5280022 0.4764332 2.658029 2.820443
5 0.32950777 1.11982575 0.31124431 0.7567268 2.5939462 1.845415 2.899809
6 -0.82046838 0.44387126 0.29250484 1.6887923 2.3329504 4.267287 3.712666
7 0.48742905 0.34420449 1.36458196 -0.3049586 3.0630998 3.216707 2.926436
8 0.73832471 -0.97075238 1.76853292 2.9655549 1.6958161 3.410174 2.962366
9 0.57578135 0.02184994 0.88765379 1.6532533 2.3700188 2.884185 2.318340
10 -0.30538839 0.91794156 1.88110773 3.6726117 2.2670988 4.182176 2.675730
11 1.51178117 1.85867955 1.39810588 1.9755095 1.4574800 1.864264 3.060160
12 0.38984324 0.39721227 0.38797361 0.7900536 3.2078678 2.038355 2.411106
13 -0.62124058 0.88767161 1.34111969 2.1107264 3.1604026 3.932282 3.531496
14 -2.21469989 0.44619496 -0.12936310 0.5659024 2.7002136 1.849304 1.481606
15 1.12493092 -0.87705956 2.43302370 0.2463666 3.5868335 2.292619 3.306558
16 -0.04493361 0.08500544 2.98039990 1.7914462 2.5584864 2.107192 1.463550
17 -0.01619026 0.10571005 0.63277852 1.0567081 0.7234078 2.180007 2.699024
18 0.94383621 0.44068660 -0.04413463 1.5011054 1.4267346 2.220887 2.471720
19 0.82122120 1.60002537 1.56971963 1.5743413 0.7753874 2.994188 2.347905
20 0.59390132 1.26317575 0.86494540 0.9104791 1.5265994 2.322670 2.943103
Finding the sum of all columns one by one −
> sum(df$x1)
[1] 3.810478
> sum(df$x2)
[1] 9.87057
> sum(df$x3)
[1] 22.77594
> sum(df$x4)
[1] 32.03474
> sum(df$x5)
[1] 42.39702
> sum(df$x6)
[1] 52.27657
> sum(df$x7)
[1] 55.65452
Let’s have a look at one more example −
> y1<-1:10
> y2<-11:20
> y3<-rep(c(1,2,3,4,5),times=2)
> df_y<-data.frame(y1,y2,y3)
> df_y
  y1 y2 y3
 1 1 11 1
 2 2 12 2
 3 3 13 3
 4 4 14 4
 5 5 15 5
 6 6 16 1
 7 7 17 2
 8 8 18 3
 9 9 19 4
10 10 20 5
> sum(df_y$y1)
[1] 55
> sum(df_y$y2)
[1] 155
> sum(df_y$y3)
[1] 30
HTML5 Canvas - Drawing Rectangles

There are three methods that draw rectangles on the canvas −
fillRect(x,y,width,height)
This method draws a filled rectangle.
strokeRect(x,y,width,height)
This method draws a rectangular outline.
clearRect(x,y,width,height)
This method clears the specified area and makes it fully transparent
Here x and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle and width and height are width and height of the rectangle.
Following is a simple example which makes use of above mentioned methods to draw a nice rectangle.
<!DOCTYPE HTML>

<html>
   <head>
   
      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      
      <script type = "text/javascript">
         function drawShape() {
            
            // Get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');

            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext) {
               
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');

               // Draw shapes
               ctx.fillRect(25,25,100,100);
               ctx.clearRect(45,45,60,60);
               ctx.strokeRect(50,50,50,50);
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
   
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
	
</html>
The above code would draw the following rectangle −

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
How to change number formatting from scientific to numbers of axes labels in a scatterplot using ggplot2 package in R?

When we create a scatterplot or any other plot and the values are presented in scientific form in the original data then the axes values of the plot are also plotted in scientific form. This makes the plot ambiguous, therefore, reading the plot or interpreting it becomes difficult. Hence, we need to convert the scientific form of the axes labels to numbers and it can be done by using scale_x_continuous(labels =comma) and scale_y_continuous(labels=comma) for both the axes.
Consider the below data frame −
set.seed(101)
x <-rpois(10,2)*100000
y <-rpois(10,5)*100000
df <-data.frame(x,y)
library(ggplot2)
Creating the scatterplot −
ggplot(df,aes(x,y))+geom_point()
Creating the scatterplot with numbers on axes −
ggplot(df,aes(x,y))+geom_point()+scale_x_continuous(labels = comma)+scale_y_continuous(labels=comma)
There is No Argmax Function for Python List | by Eden Au | Towards Data Science

Dear Python programmers,
Given a Python list l = [50, 99, 67, 99, 48], how do you find the argmax of the list? Turns out there is no built-in argmax function for Python list! You can’t just do argmax(l) or max(l).index. The first thing I can think of is to convert the list to a numpy array, or pandas DataFrame, or even Tensorflow tensor if you believe it is okay to overkill:
import numpy as npl_np = np.asarray(l)print(l_np.argmax())import pandas as pdl_pd = pd.DataFrame({'l': l})print(l_pd.idxmax())import tensorflow as tfl_tf = tf.constant(l)with tf.Session() as sess:    print(sess.run(tf.argmax(l_tf)))
They all return 1, as they should be. If multiple items are maximal, the function returns the first one encountered. But it feels like cheating transforming an object to another data type, and it also requires more execution time. Here are several ways to fix it:
Construct a for-loop and check every single element manually, and it works perfectly well. However, it is composed of multiple lines of codes that are not very readable. It also requires slightly more computation time compared to the alternatives discussed below.
index, max_val = -1, -1for i in range(len(l)):    if l[i] > max_val:        index, max_val = i, l[i]print(index)
We can leverage the built-in counter of enumerate function in Python. Note that max((x,i) for i,x in enumerate(l))[1] returns the index of last maximal item, but it can be fixed by
-max((x,-i) for i,x in enumerate(l))[1]
But this is by no means readable. We can also mimic the enumerate function by using zip and make it more readable:
max(zip(l, range(len(l))))[1]
This is perhaps the most readable hack. It turns out that we can still use the default maxfunction. But instead of passing the list as an argument, we pass the list of indexes as the argument, and also a function as ‘key’. That function maps indexes to their corresponding elements in the list.
f = lambda i: l[i]max(range(len(l)), key=f)
There you go, three ways to perform argmax on Python list.
Thank you for reading! If you are interested in Python, check out the following articles:
towardsdatascience.com
towardsdatascience.com
Originally published on my blog edenau.github.io.
Write a C program to reverse array

An array is a group of related items that store with a common name.
The syntax is as follows for declaring an array −
datatype array_name [size];
An array can also be initialized at the time of declaration −
int a[5] = { 10,20,30,40,50};
We can reverse array by using swapping technique.
For example, if 'P' is an array of integers with four elements −
P[0] = 1, P[1] = 2, P[2] = 3 and P[3]=4
Then, after reversing −
P[0] = 4, P[1] = 3, P[2] = 2 and P[3]=1
Following is the C program to reverse an array −
#include <stdio.h>
int main(){
   int num, i, j, array1[50], array2[50];
   printf("Enter no of elements in array\n");
   scanf("%d", &num);
   printf("Enter array elements\n");
   for (i = 0; i < num ; i++)
      scanf("%d", &array1[i]);
   // Copying elements into array
   for (i = num - 1, j = 0; i >= 0; i--,j++)
      array2[j] = array1[i];
   // Copying reversed array into the original
   for (i = 0; i < num; i++)
      array1[i] = array2[i];
   printf("The reversed array:\n");
   for (i = 0; i< num; i++)
      printf("%d\n", array1[i]);
   return 0;
}
Upon execution, you will receive the following output −
Enter no of elements in array
4
Enter array elements
20
50
60
70
The reversed array:
70
60
50
20
PyQt5 – How to create and get the name of Push Button ?

09 Feb, 2022
In this article we will see how to create and get the name of Push Button. When we design a GUI (Graphical User Interface) application we create lots of push button. In order to classify them we set names to them for examples names like “settings button”, “displaying button” etc.In order to create a name we use setAccessibleName method and to get the name we use accessibleName.Note : If name is not created and we try to get the name it will return blank string. 
Syntax :  
button.setAccessibleName(name)
button.accessibleName()
Argument : setAccessibleName takes string as argument. accessibleName takes no argument.Return : setAccessibleName returns None. accessibleName returns string.
Code :  
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):    def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 600, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for widgets    def UiComponents(self):         # creating a push button        button = QPushButton("CLICK", self)         # setting geometry of button        button.setGeometry(200, 150, 100, 40)         # setting name        button.setAccessibleName("push button")         # adding action to a button        button.clicked.connect(self.clickme)         # accessing the name of button        name = button.accessibleName()         # creating a label to display a name        label = QLabel(self)        label.setText(name)        label.move(200, 200)     # action method    def clickme(self):          # printing pressed        print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :  
 
kalrap615
varshagumber28
Python-gui
Python-PyQt
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
WeekFields weekOfYear() method in Java with Examples

29 Jan, 2020
The weekOfYear() method of WeekFields class is used to return a field to access the week of year based on this WeekFields.Example:
if the 1st day of the year is a Monday, week one starts on the 1st and there is no week zero
if the 2nd day of the year is a Monday, week one starts on the 2nd and the 1st is in week zero
if the 4th day of the year is a Monday, week one starts on the 4th and the 1st to 3rd is in week zero
if the 5th day of the year is a Monday, week two starts on the 5th and the 1st to 4th is in week one
This field can be used with any calendar system.
Syntax:
public TemporalField weekOfYear()

Parameters: This method accepts nothing.
Return value: This method returns a field providing access to the week-of-year, not null.
Below programs illustrate the WeekFields.weekOfYear() method:Program 1:
// Java program to demonstrate// WeekFields.weekOfYear() method  import java.time.DayOfWeek;import java.time.LocalDate;import java.time.temporal.TemporalField;import java.time.temporal.WeekFields;  public class GFG {    public static void main(String[] args)    {          // create WeekFields        WeekFields weekFields            = WeekFields.of(DayOfWeek.MONDAY, 1);          // apply weekOfYear()        TemporalField weekOfYear            = weekFields.weekOfYear();          // create a LocalDate        LocalDate day            = LocalDate.of(2021, 12, 21);          // get week of year for localdate        int wow = day.get(weekOfYear);          // print results        System.out.println("Week of year for "                           + day + " :" + wow);    }}
Week of year for 2021-12-21 :52

Program 2:
// Java program to demonstrate// WeekFields.weekOfYear() method  import java.time.DayOfWeek;import java.time.LocalDate;import java.time.temporal.TemporalField;import java.time.temporal.WeekFields;  public class GFG {    public static void main(String[] args)    {          // create WeekFields        WeekFields weekFields            = WeekFields.of(DayOfWeek.SUNDAY, 1);          // apply weekOfYear()        TemporalField weekOfYear            = weekFields.weekOfYear();          // create a LocalDate        LocalDate day = LocalDate.of(2014, 10, 12);          // get week of year for localdate        int wow = day.get(weekOfYear);          // print results        System.out.println("Week of year for "                           + day + " :" + wow);    }}
Week of year for 2014-10-12 :42

References: https://docs.oracle.com/javase/10/docs/api/java/time/temporal/WeekFields.html#weekOfYear()
Java-Functions
Java-WeekFields
java.time.temporal package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Set in Java
Singleton Class in Java
Stack Class in Java
How to copy a file in Node.js?

04 Feb, 2021
Node.js is an open source and cross-platform runtime environment for executing JavaScript code outside a browser. There are various platforms such as Windows, Linux, Mac OS  where Node.js runs. 
There are various methods used in Node.js such as readFile() and writeFile() method. The readFile() and writeFile() method is used to copy the content of the file to another file.
readFile(file[,option],callback )
file: Source filename path.option: It has to encode i.e. utf8.callback: The callback gets two arguments.
file: Source filename path.
option: It has to encode i.e. utf8.
callback: The callback gets two arguments.
writeFile(filename, data,encoding, callback)
filename: Filepath of the file to read.data: It is the data that we want to write.encoding: It is the encoding of the data.callback: It will show the error or null.
filename: Filepath of the file to read.
data: It is the data that we want to write.
encoding: It is the encoding of the data.
callback: It will show the error or null.
Javascript
var fs=require('fs'); // Import the filesystem module  console.log('File Reading from file.txt ..........');  // ReadFile method is used to read the content from file.txtfs.readFile('file.txt','utf8',readingFile);  function readingFile(error,data){    if(error){        console.log(error);    } else    {        console.log(data); // Printing the file.txt file's content                   // Creating new file - paste.txt with file.txt's content        fs.writeFile('paste.txt',data,'utf8',writeFile);    } }  function writeFile(error){    if(error){        console.log(error)    } else {        console.log('Content has been pasted to paste.txt file');    }}
Output
NodeJS-Questions
Picked
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tcl - Bitwise Operators

The Bitwise operators supported by Tcl language are listed in the following table. Assume variable A holds 60 and variable B holds 13, then −
Try the following example to understand all the bitwise operators available in Tcl language −
#!/usr/bin/tclsh

set a 60  ;# 60 = 0011 1100   
set b 13  ;# 13 = 0000 1101 

set c [expr $a & $b] ;# 12 = 0000 1100 
puts "Line 1 - Value of c is $c\n"

set c [expr $a | $b;] ;# 61 = 0011 1101 
puts "Line 2 - Value of c is $c\n"

set c [expr $a ^ $b;] ;# 49 = 0011 0001 
puts "Line 3 - Value of c is $c\n"

set c [expr $a << 2] ;# 240 = 1111 0000 
puts "Line 4 - Value of c is $c\n"

set c [expr $a >> 2] ;# 15 = 0000 1111 
puts "Line 5 - Value of c is $c\n"
When you compile and execute the above program, it produces the following result −
Line 1 - Value of c is 12

Line 2 - Value of c is 61

Line 3 - Value of c is 49

Line 4 - Value of c is 240

Line 5 - Value of c is 15
Calculate the Median Absolute Deviation in R Programming – mad() Function

24 Jun, 2020
mad() function in R Language is used to compute the median absolute deviation i.e. the (lo-/hi-)median of the absolute deviations from the median.
Syntax: mad(x)
Parameters:x: Vector
Example 1:
# R Program to calculate # Median Absolute Deviation  # Creating a vectorx <- c(1:9)  # Calling mad() Functionmad(x)
Output:
[1] 2.9652

Example 2:
# R Program to calculate # Median Absolute Deviation  # Creating a vectorx <- c(1, 4, 2, 3, 7, 3, 8, 9, 2)  # Calling mad() Functionmad(x)
Output:
[1] 1.4826

R Math-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
R - if statement
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
Fortran - Vector and Matrix Multiplication Functions

The following table describes the vector and matrix multiplication functions:
Example
The following example demonstrates dot product:
program arrayDotProduct

   real, dimension(5) :: a, b
   integer:: i, asize, bsize
   
   asize = size(a)
   bsize = size(b)
   
   do i = 1, asize
      a(i) = i
   end do
   
   do i = 1, bsize
      b(i) = i*2
   end do
   
   do i = 1, asize
      Print *, a(i)
   end do
   
   do i = 1, bsize
      Print *, b(i)
   end do
   
   Print*, 'Vector Multiplication: Dot Product:'
   Print*, dot_product(a, b)
   
end program arrayDotProduct
When the above code is compiled and executed, it produces the following result:
1.00000000    
2.00000000    
3.00000000    
4.00000000    
5.00000000    
2.00000000    
4.00000000    
6.00000000    
8.00000000    
10.0000000    
Vector Multiplication: Dot Product:
110.000000   

Example
The following example demonstrates matrix multiplication:
program matMulProduct

   integer, dimension(3,3) :: a, b, c
   integer :: i, j
    
   do i = 1, 3
      do j = 1, 3
         a(i, j) = i+j
      end do
   end do
   
   print *, 'Matrix Multiplication: A Matrix'
   
   do i = 1, 3
      do j = 1, 3
         print*, a(i, j)
      end do
   end do
   
   do i = 1, 3
      do j = 1, 3
         b(i, j) = i*j
      end do
   end do
   
   Print*, 'Matrix Multiplication: B Matrix'
   
   do i = 1, 3
      do j = 1, 3
         print*, b(i, j)
      end do
   end do
   
   c = matmul(a, b)
   Print*, 'Matrix Multiplication: Result Matrix'
   
   do i = 1, 3
      do j = 1, 3
         print*, c(i, j)
      end do
   end do
   
end program matMulProduct
When the above code is compiled and executed, it produces the following result:
Matrix Multiplication: A Matrix
2
3
4
3
4
5
4
5
6
 Matrix Multiplication: B Matrix
1
2
3
2
4
6
3
6
9
Matrix Multiplication: Result Matrix
Python any() function

13 Sep, 2021
Python any() function returns True if any of the elements of a given iterable( List, Dictionary, Tuple, set, etc) are True else it returns False. 
Syntax: any(iterable)
Parameters: Iterable: It is an iterable object such as a dictionary, tuple, list, set, etc.                 
Returns: Python any() function returns true if any of the items is True.
Python3
# All elements of list are truel = [ 4, 5, 1]print(any( l )) # All elements of list are falsel = [ 0, 0, False]print(any( l )) # Some elements of list are# true while others are falsel = [ 1, 0, 6, 7, False]print(any( l )) # Empty Listl = []print(any( l ))
Output:
True
False
True
False
Python3
# All elements of tuple are truet = (2, 4, 6)print(any(t)) # All elements of tuple are falset = (0, False, False)print(any(t)) # Some elements of tuple are true while# others are falset = (5, 0, 3, 1, False)print(any(t)) # Empty tuplet = ()print(any(t))
Output:
True
False
True
False
Python3
# All elements of set are trues = { 1, 1, 3}print(any( s )) # All elements of set are falses = { 0, 0, False}print(any( s )) # Some elements of set are true while others are falses = { 1, 2, 0, 8, False}print(any( s )) #Empty sets = {}print(any( s ))
Output:
True
False
True
False
Note: In the case of a dictionary if all the keys of the dictionary are false or the dictionary is empty the any() returns False. If at least one key is True any() returns True.
Python3
# All elements of dictionary are trued = {1: "Hello", 2: "Hi"}print(any(d)) # All elements of dictionary are falsed = {0: "Hello", False: "Hi"}print(any(d)) # Some elements of dictionary# are true while others are falsed = {0: "Salut", 1: "Hello", 2: "Hi"}print(any(d)) # Empty dictionaryd = {}print(any(d))
Output:
True
False
True
False
Python3
# Non-Empty Strings = "Hi There!"print(any(s)) # Non-Empty Strings = "000"print(any(s)) # Empty strings = ""print(any(s))
Output:
True
True
False
It checks for any element satisfying a condition and returns a True in case it finds any one element.
Python3
# Python3 code to demonstrate working of# Check if any element in list satisfies a condition# Using any() # initializing listtest_list = [4, 5, 8, 9, 10, 17] # printing listprint("The original list : " + str(test_list)) # Check if any element in list satisfies a condition# Using any()res = any(ele > 10 for ele in test_list) # Printing resultprint("Does any element satisfy specified condition ? : " + str(res))
Output:
The original list : [4, 5, 8, 9, 10, 17]
Does any element satisfy specified condition ? : True
Python3
def any(list_x):    for item in list_x:        if item:            return True    return False x = [4, 5, 8, 9, 10, 17]print(any(x))
Output:
True
kumar_satyam
Python-Built-in-functions
Python
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
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Python - Find all combinations of overlapping substrings of a string - GeeksforGeeks

29 Jun, 2021
Given a string, the task is to write a Python program to find all combinations of overlapping substrings of a string and store it in a list. The list of lists will be ordered and grouped by length of substrings.
Input : test_str = ‘Geeks4G’
Output : [[”, ”, ”, ”, ”, ”, ”, ”], [‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘4’, ‘G’], [‘Ge’, ‘ee’, ‘ek’, ‘ks’, ‘s4’, ‘4G’], [‘Gee’, ‘eek’, ‘eks’, ‘ks4’, ‘s4G’], [‘Geek’, ‘eeks’, ‘eks4’, ‘ks4G’], [‘Geeks’, ‘eeks4’, ‘eks4G’], [‘Geeks4’, ‘eeks4G’], [‘Geeks4G’]]
Explanation : All lengths overlapping substrings extracted.
Input : test_str = ‘Geeks’
Output : [[”, ”, ”, ”, ”, ”], [‘G’, ‘e’, ‘e’, ‘k’, ‘s’], [‘Ge’, ‘ee’, ‘ek’, ‘ks’], [‘Gee’, ‘eek’, ‘eks’], [‘Geek’, ‘eeks’], [‘Geeks’]]
Explanation : All lengths overlapping substrings extracted.
Method : Using list comprehension, slicing and loop
In this, we perform task of getting each slice using slicing, all the strings of particular size is created using list comprehension. Manipulation of all sizes is done using loop. Later all are printed as a list of lists.
Example:
Python3
# Python3 code to demonstrate working of# Overlapping substrings of all lengths# Using list comprehension + slicing + loop  # initializing stringtest_str = 'Geeks4G'  # printing original stringprint("The original string is : " + str(test_str))  # manipulating overlap size using loopres = []for idx in range(len(test_str) + 1):      # getting overlap strings    res.append([test_str[j: j + idx] for j in range(len(test_str) - idx + 1)])  # printing resultprint("All overlapping Strings : " + str(res))
Output:
The original string is : Geeks4G
All overlapping Strings : [[”, ”, ”, ”, ”, ”, ”, ”], [‘G’, ‘e’, ‘e’, ‘k’, ‘s’, ‘4’, ‘G’], [‘Ge’, ‘ee’, ‘ek’, ‘ks’, ‘s4’, ‘4G’], [‘Gee’, ‘eek’, ‘eks’, ‘ks4’, ‘s4G’], [‘Geek’, ‘eeks’, ‘eks4’, ‘ks4G’], [‘Geeks’, ‘eeks4’, ‘eks4G’], [‘Geeks4’, ‘eeks4G’], [‘Geeks4G’]]
Python string-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?
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?
File System Consistency Checker (FSCK) - GeeksforGeeks

11 Jul, 2019
File system inconsistency is a major issue in operating systems. FSCK is one of the standard solutions adopted.
File System Consistency Checker (FSCK):FSCK is one approach still used by older Linux-based systems to find and repair inconsistencies. It is not a complete solution and may still have inodes pointing to garbage data. The major focus is to make the metadata internally consistent.
The following are the checks that FSCK performs to achieve consistency:
Superblock Checks:FSCK performs a sanity check to see if the file size is greater than the number of blocks allocated. In this case, it tries to find the suspect superblock and use an alternate copy instead.
Free Block Checks:FSCK also scans inodes to ensure that blocks in inodes are marked allocated.
Inode State Checks:FSCK checks inodes for corruption. Corrupted inodes are simply cleared.
Inode Link Checks:FSCK counts the number of links to an inode, and modifies the inode count. If an allocated inode has no directory or file referring to it, FSCK moves it to the lost and found directory.
Duplicate Pointers:FSCK checks duplicate pointers. For example, if two inodes have pointers to the same data block, one of the inode can be deleted.
Bad Blocks:A bad pointer is simply one that points to a memory address which is out of range. In this case, FSCK deletes the pointer.
Directory Checks:FSCK makes sure the directory format is correct, e.g. they should start with “.” and “..”.
Advantages of FSCK:
It requires little overhead space.
Disadvantages of FSCK:
Scanning the disk, again and again, is slow and infeasible for large disk sizes.
It requires a heavy understanding and prior knowledge of the file system. As file systems continue to evolve, it is difficult to keep track of each and every nuance.
fsck Command in Linux:The fsck command in Linux allows us to manually check for file system inconsistencies. Below is the sample usage of the command.
sudo fsck /dev/sda2
The above command simply checks the file system mounted onto the /dev/sda2 partition. If the file system may have some inconsistencies, fsck prompts us with possible actions.
fsck.fat 4.1 (2017-01-24) 
0x41: Dirty bit is set. Fs was not properly unmounted and some data may be corrupt: Remove dirty bit, and No action.
linux-command
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Memory Management in Operating System
File Allocation Methods
Segmentation in Operating System
Difference between Internal and External fragmentation
Mutex lock for Linux Thread Synchronization
States of a Process in Operating Systems
Program for Least Recently Used (LRU) Page Replacement algorithm
Introduction of Process Management
Logical and Physical Address in Operating System
Structures of Directory in Operating System
Flask â Routing

Modern web frameworks use the routing technique to help a user remember application URLs. It is useful to access the desired page directly without having to navigate from the home page.
The route() decorator in Flask is used to bind URL to a function. For example −
@app.route(‘/hello’)
def hello_world():
   return ‘hello world’
Here, URL ‘/hello’ rule is bound to the hello_world() function. As a result, if a user visits http://localhost:5000/hello URL, the output of the hello_world() function will be rendered in the browser.
The add_url_rule() function of an application object is also available to bind a URL with a function as in the above example, route() is used.
A decorator’s purpose is also served by the following representation −
def hello_world():
   return ‘hello world’
app.add_url_rule(‘/’, ‘hello’, hello_world)

    22 Lectures 
     6 hours 

 Malhar Lathkar

    21 Lectures 
     1.5 hours 

 Jack Chan

    16 Lectures 
     4 hours 

 Malhar Lathkar

    54 Lectures 
     6 hours 

 Srikanth Guskra

    88 Lectures 
     3.5 hours 

 Jorge Escobar

    80 Lectures 
     12 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Java Program to list Weekday names

To list weekday names, use the getWeekdays () from the DateFormatSymbols class in Java.
DateFormatSymbols is a class for encapsulating localizable date-time formatting data.
Get weekday month names in an array −
String[] days = new DateFormatSymbols().getWeekdays ();
Display the weekdays −
for (int i = 0; i < days.length; i++) {
   String weekday = days[i];
   System.out.println(weekday);
}
The following is an example −
 Live Demo
import java.text.DateFormatSymbols;
public class Demo {
   public static void main(String[] args) {
      String[] days = new DateFormatSymbols().getWeekdays();
      for (int i = 0; i < days.length; i++) {
         String weekday = days[i];
         System.out.println(weekday);
      }
   }
}
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Python 3 - Number ceil() Method

The ceil() method returns the ceiling value of x i.e. the smallest integer not less than x.
Following is the syntax for the ceil() method −
import math

math.ceil( x )

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using the math static object.
x − This is a numeric expression.
This method returns the smallest integer not less than x.
The following example shows the usage of the ceil() method.
#!/usr/bin/python3
import math   # This will import math module

print ("math.ceil(-45.17) : ", math.ceil(-45.17))
print ("math.ceil(100.12) : ", math.ceil(100.12))
print ("math.ceil(100.72) : ", math.ceil(100.72))
print ("math.ceil(math.pi) : ", math.ceil(math.pi))
When we run the above program, it produces the following result −
math.ceil(-45.17) :  -45
math.ceil(100.12) :  101
math.ceil(100.72) :  101
math.ceil(math.pi) :  4


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Formatting strings and numbers in python | by Lars Nielsen | Towards Data Science

Most of the time, a sample print() statement might lead to messy code. And sometimes you do not need a logger to handle the job. Python offers different output options to deal with your string outputs. Here are a few
print(“Some text %s some text %s some text “ %(str1,str2))
str1 and str2 takes the place of %s and %s in that order
You can even do mathematical operations in string outputs .
We can write the same code using the f-string method .
It overcomes the limitation that %s has — you cannot specify an order (‘easily’) . So when you are using {variable_name} you embed these in the desired parts of your statement and naturally overcome the ‘order-problem’
You can use the :>, :< or :^ option in the f-format to left align, right align or center align the text that you want to format.
After formatting the alignment of output text ...
4. Using the format keyword
We can use the fortmat() string function in python to output the desired text in the order we want.
Now extending the formatting using f keyword ( look at the piece above ) , lets try to use that in numbers, particularly involving decimals ( float )
eg: if i want to restrict the value of pi ( to the 2nd or 3rd decimal )
Normally, we would get this as a result
Now by formatting the number, we can restrict the number of decimals to 2 digits ....
or to 3 digits ...
To take it a little further, if you want to display the numbers in a particular format in your dataframe, when using pandas you can use the pd.options.display to show the way you want it. Here is an example of how numbers are displayed , before and after you enable the options.display settings.
Lets take an example —
We are reading a file test.csv and displaying the contents. We see that the length column has 6 decimal places displayed.
If we are interested in only displaying 2 decimal places, we can change it using the pd.options.display attribute. Below is the output of the dataframe after the formatting is applied.
Note : Here on , for all the pandas displays ( even for other data-frames), only 2 decimal points will be displayed. If you want to set it back to 4 or 5 decimal points , you will have to set the format back to which ever format you want. Till then it will continue to display only 2 decimal points.
Numpy has settings to change the decimal point precision to a desired one.
np.set_printoptions(precision=2)  
Lets see the output as an extension to the previous example from pandas .
GATE | GATE-CS-2015 (Set 2) | Question 13 - GeeksforGeeks

11 Oct, 2021
Consider the following two statements.
S1: If a candidate is known to be corrupt, then he will not be elected.
S2: If a candidate is kind, he will be elected.
Which one of the following statements follows from S1 and S2 as per sound inference rules of logic?(A) If a person is known to be corrupt, he is kind(B) If a person is not known to be corrupt, he is not kind(C) If a person is kind, he is not known to be corrupt(D) If a person is not kind, he is not known to be corruptAnswer: (C)Explanation:
S1: If a candidate is known to be corrupt, then 
    he will not be elected.
S2: If a candidate is kind, he will be elected.

If p → q, then ¬q → ¬p
So from S1, elected → not corrupt
and S2 is,   kind → elected

Therefore, kind → not corrupt


YouTubeGeeksforGeeks GATE Computer Science16.2K subscribersInference Rules with Sakshi Singhal  | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0039:49 / 47:50•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=5lwkWaymx7Q" 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-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE CS 2019 | Question 27
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2006 | Question 49
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2017 (Set 2) | Question 42
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2000 | Question 43
GATE | GATE CS 2021 | Set 1 | Question 47
How to Find Linux Server Geographic Location in Terminal?

For purpose of security, cyber-crime investigation, government compliance or just for curiosity we might ned to track the geographical location of a Linux server in the internet or at least the location of the server which diverts the internet traffic to the server we are interested in. It involves getting the I.P address of the server and using some third party services offered in the web, to map that I.P address to get the location. In this article we will see the steps to achieve that.
Step 1 − Install curl jq
The curl package will make the http requests to the server and jq will be required to process the JSON data we receive from APIs for mapping the IP addresses to geographical locations. The below steps shows how to install these tools.
sudo apt-get install curl jq
Running the above code gives us the following result −
$ sudo apt-get install curl jq
Reading package lists... Done
Building dependency tree
Reading state information... Done
curl is already the newest version (7.47.0-1ubuntu2.14).
The following NEW packages will be installed:
jq libonig2
...
..
Setting up libonig2:amd64 (5.9.6-1ubuntu0.1) ...
Setting up jq (1.5+dfsg-1ubuntu0.1) ...
Processing triggers for libc-bin (2.23-0ubuntu11) .
Step 2 − Find the Server’s I.P address
You can use nslookup to find the server’s I.P address if you know the domain name being served from the server. In the below example we see how to get the IP address of a domain name by using nslookup command. Let's consider oracle.com as our example.
Use the following curl command to get the server I.P address. Ipinfo.io is a web service that gives the I.P details.
$ nslookup www.oracle.com
Running the above code gives us the following result −
Server:127.0.1.1
Address:127.0.1.1#53
Non-authoritative answer:
www.oracle.comcanonical name = ds-www.oracle.com.edgekey.net.
ds-www.oracle.com.edgekey.netcanonical name = e870.dscx.akamaiedge.net.
Name:e870.dscx.akamaiedge.net
Address: 104.80.62.56
Step 3 − Find Information about the I.P address
Next we use IP info.in to get the details related to this IP address. That details comes back in form of JSON listing the the hostname,the city, the state, the country etc.
$ curl https://ipinfo.io/104.80.62.56
Running the above code gives us the following result:
{
   "ip": "104.80.62.56",
   "hostname": "a104-80-62-56.deploy.static.akamaitechnologies.com",
   "city": "New York City",
   "region": "New York",
   "country": "US",
   "loc": "40.7143,-74.0060",
   "org": "AS20940 Akamai International B.V.",
   "postal": "10004",
   "timezone": "America/New_York",
   "readme": "https://ipinfo.io/missingauth"
}
Now when we need additional details like latitude and longitude we can use another geolocation service provider called ipvigilante.com. Then we use the jq tool to get the formatted response from the JSON structure returned by the the API call.
$curl -s https://ipvigilante.com/104.80.62.56 | jq '.data.latitude, .data.longitude, .data.city_name, .data.country_name'
Running the above code gives us the following result −
"42.36260"
"-71.08430"
"Cambridge"
"United States"
Python - Filter Sorted Rows - GeeksforGeeks

16 Nov, 2020
Given a Matrix, extract rows that are sorted, either by ascending or descending.
Input : test_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]] Output : [[3, 6, 8, 10], [8, 5, 3, 2]] Explanation : Both lists are ordered, 1st ascending, second descending.
Input : test_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 7, 2], [1, 4, 5, 3]] Output : [[3, 6, 8, 10]] Explanation : List ordered in ascending order.  
Method #1 : Using list comprehension + sorted() + reverse
In this, we check for each row, perform sort by sorted(), and reverse sorted by passing reverse as key. 
Python3
# Python3 code to demonstrate working of# Filter Sorted Rows# Using list comprehension + sorted() + reverse  # initializing listtest_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]  # printing original listprint("The original list is : " + str(test_list))  # filtering using sorted() and reverse as keyres = [sub for sub in test_list if sub == list(    sorted(sub)) or sub == list(sorted(sub, reverse=True))]  # printing resultprint("Extracted rows : " + str(res))
Output:
The original list is : [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]Extracted rows : [[3, 6, 8, 10], [8, 5, 3, 2]]
Method #2 : Using filter() + lambda + sorted() + reverse
In this, we perform task of filtering using lambda and sorted() and reverse can be used to check for equality with ordered list.
Python3
# Python3 code to demonstrate working of# Filter Sorted Rows# Using filter() + lambda + sorted() + reverse  # initializing listtest_list = [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]  # printing original listprint("The original list is : " + str(test_list))  # filtering using sorted() and reverse as keyres = list(filter(lambda sub: sub == list(sorted(sub)) or sub ==                  list(sorted(sub, reverse=True)), test_list))  # printing resultprint("Extracted rows : " + str(res))
Output:
The original list is : [[3, 6, 8, 10], [1, 8, 2, 4, 3], [8, 5, 3, 2], [1, 4, 5, 3]]Extracted rows : [[3, 6, 8, 10], [8, 5, 3, 2]]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
C++ Vector Library - vector() Function

The C++ fill constructor std::vector::vector() constructs a container of size n and assigns value val(if provided) to each element of the container.
Following is the declaration for fill constructor std::vector::vector() form std::vector header.
explicit vector (size_type n, const value_type& val = value_type(), 
   const allocator_type& alloc = allocator_type());

vector (size_type n, const value_type& val,
   const allocator_type& alloc = allocator_type());
      explicit vector (size_type n);

n − Size of container.
n − Size of container.
val − Value to be assigned to each element of container.
val − Value to be assigned to each element of container.
Constructor never returns value.
This member function never throws exception.
Linear i.e. O(n)
The following example shows the usage of fill constructor std::vector::vector().
#include <iostream>
#include <vector>

using namespace std;

int main(void) {
   vector<int> v(5, 200);

   for (int i = 0; i < v.size(); ++i)
      cout << v[i] << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
200
200
200
200
200

 Print
 Add Notes
 Bookmark this page
Using G++ to compile multiple .cpp and .h files

To compile multiple files like file_name.h, or file_name.cpp at once, we can use the files like a list one after another. The syntax will be like this −
g++ abc.h xyz.cpp
To run the program, we can use this −
./a.out
float area(float r){
   return (3.1415*r*r); //area of a circle
}
float area(float l, float w){
   return (l * w); //area of a rectangle
}
#include <iostream>
#include "area.h"
using namespace std;
main(){
   cout << "Area of circle with radius 2.5 is: " << area(2.5) << endl;
   cout << "Area of rectangle with length and width are 5 and 7 is: " << area(5, 7) << endl;
}
$ g++ area.h find_area.cpp
$ ./a.out
Area of circle with radius 2.5 is: 19.6344
Area of rectangle with length and width are 5 and 7 is: 35
$
Transactional memory

Transactional memory originated in database theory, provides an alternative strategy for process synchronization.
A memory transaction is atomic is a sequence of memory read–write operations. The memory transaction is committed, if all operations in a transaction are completed. Otherwise, the operations must be aborted and rolled back. The ease of transactional memory can be obtained through features added to a programming language. Consider an example. Suppose we have a function update() that modifies shared data. Traditionally, this function would be written using mutex locks (or semaphores) such as the following −
void update (){
   acquire(); /* modify shared data */
   release();
}
However, using synchronization mechanisms such as mutex locks and semaphores involves many potential problems, including deadlock. Additionally, as the number of threads increases, traditional locking scales less well, because the level of contention among threads for lock ownership becomes very high. As an alternative to traditional locking methods, new features that take advantage of transactional memory can be added to a programming language. In our example, suppose we add the construct atomic{S}, which ensures that the operations in S execute as a transaction. This allows us to rewrite the update() function as follows &minus;
void update (){
   atomic {
      /* modify shared data */
   }
}
The advantage of using such a mechanism rather than locks is that the transactional memory system—not the developer-is responsible guaranteeing atomicity. Additionally, because no locks are involved, deadlock is not possible. Furthermore, a transactional memory system can identify which statements in atomic blocks can be executed concurrently, such as concurrent read access to a shared variable. It is, of course, possible for a programmer to identify these situations and use reader-writer locks, but the task becomes increasingly difficult as the number of threads within an application grows. Transactional memory can be implemented in either software or hardware. Software transactional memory(STM), which implements transactional memory exclusively in software—no special hardware is needed. It works by inserting instrumentation code inside transaction blocks. The code is inserted by a compiler and manages each transaction by examining where statements may run concurrently and where specific low-level locking is required. Hardware transactional memory (HTM) uses hardware cache hierarchies and cache coherency protocols to manage and resolve conflicts involving shared data residing in separate processors’ caches. It requires no special code instrumentation and thus has less overhead than STM. However, HTM does require that existing cache hierarchies and cache coherency protocols be modified to support transactional memory. Transactional memory has existed for several years without widespread implementation. However, the growth of multicore systems and the associated emphasis on concurrent and parallel programming have prompted a significant amount of research in this area on the part of both academics and commercial software and hardware vendors.