code-rag-bench/online-tutorials huggingface dataset:
Python | Sort a list of percentage - GeeksforGeeks

11 May, 2020
Given a list of percentage, write a Python program to sort the given list in ascending order.
Let’s see different ways to do the task.
Code #1: Chops ‘%’ in string and convert it into float.
# Python code to sort list of percentage   # List initializationInput =['2.5 %', '6.4 %', '91.6 %', '11.5 %']  # removing % and converting to float# then apply sort functionInput.sort(key = lambda x: float(x[:-1]))  # printing outputprint(Input)
['2.5 %', '6.4 %', '11.5 %', '91.6 %']

 Code #2:
# Python code to sort list of percentage   # List initializationInput =['2.5 %', '6.4 %', '91.6 %', '11.5 %']  # Temporary list initializationtemp = []  # removing % signfor key in Input:    temp.append((key[:-1]))  # sorting list of floattemp = sorted(temp, key = float)  # Output list initializationoutput = []  # Adding percentage signfor key in temp:    output.append(key + '%')  # printing outputprint(output)
['2.5 %', '6.4 %', '11.5 %', '91.6 %']

Python list-programs
Python-sort
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 Convert Python Dictionary To JSON?
Check if element exists in list in Python
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?
Find the size of a Set in Python - GeeksforGeeks

17 May, 2020
A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set. The size of a set means the amount of memory (in bytes) occupied by a set object. In this article, we will learn various ways to get the size of a python set.
1.Using getsizeof() function:
The getsizeof() function belongs to the python’s sys module. It has been implemented in the below example.
Example 1:
import sys  # sample SetsSet1 = {"A", 1, "B", 2, "C", 3}Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"}Set3 = {(1, "Lion"), ( 2, "Tiger"), (3, "Fox")}  # print the sizes of sample Setsprint("Size of Set1: " + str(sys.getsizeof(Set1)) + "bytes")print("Size of Set2: " + str(sys.getsizeof(Set2)) + "bytes")print("Size of Set3: " + str(sys.getsizeof(Set3)) + "bytes")
Output:
Size of Set1: 736bytes
Size of Set2: 736bytes
Size of Set3: 224bytes
Note:The sys.getsizeof() function includes the marginal space usage, which includes the garbage collection overhead for the object. Meaning it returns the total space occupied by the object in addition to the garbage collection overhead for the spaces being used.
1.Using inbuilt __sizeof__() method:
Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.Example 2:
import sys  # sample SetsSet1 = {"A", 1, "B", 2, "C", 3}Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"}Set3 = {(1, "Lion"), ( 2, "Tiger"), (3, "Fox")}  # print the sizes of sample Setsprint("Size of Set1: " + str(Set1.__sizeof__()) + "bytes")print("Size of Set2: " + str(Set2.__sizeof__()) + "bytes")print("Size of Set3: " + str(Set3.__sizeof__()) + "bytes")
Output:
Size of Set1: 712bytes
Size of Set2: 712bytes
Size of Set3: 200bytes
Python set-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python program to check whether a number is Prime or not
Tryit Editor v3.7

CSS Grid Intro
Tryit: Using display: grid
Can we overload or override a static method in Java?


If a class has multiple functions by the same name but different parameters, it is known as Method Overloading. If a subclass provides a specific implementation of a method that is already provided by its parent class, it is known as Method Overriding. Method overloading increases the readability of the program. Method overriding provides the specific implementation of the method that is already provided by its superclass parameter must be different in case of overloading, the parameter must be same in case of overriding.
Now considering the case of static methods, then static methods have following rules in terms of overloading and overriding.
Can be overloaded by another static method.
Can be overloaded by another static method.
Can not be overridden by another static method in sub-class. The reason behind this is that sub-class only hides the static method but not overrides it.
Can not be overridden by another static method in sub-class. The reason behind this is that sub-class only hides the static method but not overrides it.
Following example demonstrates the same.
Live Demo
class SuperClass {
   public static void display() {
      System.out.println("SuperClass.display()");
   }

   //Method overloading of static method
   public static void display(int a) {
      System.out.println("SuperClass.display(int): " + a);
   }
}

class SubClass extends SuperClass {
   //Not method overriding but hiding
   public static void display() {
      System.out.println("SubClass.display()");
   }
}

public class Tester {
   public static void main(String[] args) {
      SuperClass object = new SubClass();

      //SuperClass display method is called
      //although object is of SubClass.
      object.display();        
      object.display(1);    
   }
}
SuperClass.display()
SuperClass.display(int): 1
The static method is resolved at compile time cannot be overridden by a subclass. An instance method is resolved at runtime can be overridden.
The static method is resolved at compile time cannot be overridden by a subclass. An instance method is resolved at runtime can be overridden.
A static method can be overloaded.
A static method can be overloaded.
Boolean.Parse() Method in C#

The Boolean.Parse() method in C# is used to convert the specified string representation of a logical value to its Boolean equivalent.
Following is the syntax −
public static bool Parse (string val);
Above, the parameter value is a string containing the value to convert.
Let us now see an example to implement the Boolean.Parse() method −
using System;
public class Demo {
   public static void Main(){
      bool b;
      b = bool.Parse("FALSE");
      Console.WriteLine("After parsing = "+b);
   }
}
This will produce the following output −
After parsing = False
Let us see another example −
using System;
public class Demo {
   public static void Main(){
      bool b;
      b = bool.Parse(bool.TrueString);
      Console.WriteLine("After parsing = "+b);
   }
}
This will produce the following output −
After parsing = True
LPAD, LOWER and LTRIM Function in MariaDB - GeeksforGeeks

09 Oct, 2020
1. LPAD Function :In MariaDB, the LPAD Function is used for the string that is left-padded with a specified string to a given length. In this function, it will take the first parameter a string, the second parameter length and the third parameter will be pad string.it will return left-padded with a specified string to a given length.
If the string length is greater than the given length then it will remove characters from the string to shorten it to length characters.otherwise it will padding the string from left.
Syntax :
LPAD( string, length, pad_string )

Example-1 :
SELECT LPAD('geeksforgeeks', 15, 'A');

Output :
AAgeeksforgeeks

Example-2 :
SELECT LPAD('Computer', 4, 'x');

Output :
Comp
Example-3 :
SELECT LPAD('DSA', 4, 'gfg');

Output :
gDSA
2. LOWER Function :In MariaDB, the LOWER Function is used for the converts all characters in the specified string to lowercase. In this first parameter will be the string. And it will return the lowercase of that string. If the characters of the string are not letters then those will not be affected. It works similarly to LCASE function.
Syntax :
LOWER( string )

Example-1 :
SELECT LOWER('GFG');
Output :
gfg
Example-2 :
SELECT LOWER('GeeksForGeeks');
Output :
geeksforgeeks
Example-3 :
SELECT LOWER('DSA@SELF!');
Output :
dsa@self!
3. LTRIM Function :In MariaDB, The LTRIM Function is used to removes all space characters from the left-hand side of a string. In this function, a string will be passed as a parameter and it will return the zero space at the starting of the string. If the string also contains the space in the right end then this function does not any effects on that.
Syntax :
LTRIM( string )
Example-1 :
SELECT LTRIM('   geeksforgeeks');
Output :
'geeksforgeeks'
Example-2 :
ELECT LTRIM('   gfg  ');
Output :
'gfg  '
Example-3 :
SELECT LTRIM('This is best portal  ');
Output :
'This is best portal  '
DBMS-SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | DROP, TRUNCATE
Composite Key in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL indexes
SQL | Date functions
What is Temporary Table in SQL?
Window functions in SQL
SQL | ALTER (ADD, DROP, MODIFY)
Java Program to illustrate Total Marks and Percentage Calculation

09 Nov, 2020
Java Program to illustrate Total marks and Percentage Calculation can be done using storing marks of all subjects in an array and taking the summation of marks of all subjects and taking the average of all marks respectively.
Example
Input: N = 5, marks[] = {70, 60, 90, 40, 80}
Output: Total Marks = 340
        Total Percentage = 68%
        
Input: N = 5, marks[] = {60, 70, 80, 90, 100}
Output: Total Marks = 400
        Total Percentage = 80%
Approach : 
Enter the number of subjects N and marks of those subjects into a 1-D array, say, marks[].
Create a variable total_marks which stores the total of all the marks.
To print the percentage of that student, divide total_marks with N.
Below are the examples of the above approach.
Java
// Java Program to illustrate Total// marks and Percentage Calculationimport java.io.*;class GFG {    public static void main(String[] args)    {        int N = 5, total_marks = 0;        float percentage;          // create 1-D array to store marks        int marks[] = { 89, 75, 82, 60, 95 };          // calculate total marks        for (int i = 0; i < N; i++) {            total_marks += marks[i];        }        System.out.println("Total Marks : " + total_marks);          // calculate percentage        percentage = (total_marks / (float)N);        System.out.println(            "Total Percentage : " + percentage + "%");    }}
Total Marks : 401
Total Percentage : 80.2%

Time Complexity: O(N)
Space Complexity: O(1)
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Java Examples - Align Text

How to align the text in a word document using Java.
Following is the program to align the text in a word document using Java.
import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

public class AlignTextInWord {
   public static void main(String[] args)throws Exception {

      //Blank Document
      XWPFDocument document = new XWPFDocument();

      //Write the Document in file system
      FileOutputStream out = new FileOutputStream(new File
         ("C:/poiword/alignparagraph.docx"));

      //create paragraph
      XWPFParagraph paragraph = document.createParagraph();

      //Set alignment paragraph to RIGHT
      paragraph.setAlignment(ParagraphAlignment.RIGHT);
      
      XWPFRun run = paragraph.createRun();
      run.setText("At tutorialspoint.com, we strive hard to " +
         "provide quality tutorials for self-learning " +
         "purpose in the domains of Academics, Information " +
         "Technology, Management and Computer Programming " +
         "Languages.");

      //Create Another paragraph
      paragraph = document.createParagraph();

      //Set alignment paragraph to CENTER
      paragraph.setAlignment(ParagraphAlignment.CENTER);
      
      run = paragraph.createRun();
      run.setText("The endeavour started by Mohtashim, an AMU " +
         "alumni, who is the founder and the managing director " +
         "of Tutorials Point (I) Pvt. Ltd. He came up with the " +
         "website tutorialspoint.com in year 2006 with the help" +
         "of handpicked freelancers, with an array of tutorials" +
         " for computer programming languages. ");

      document.write(out);
      out.close();
      
      System.out.println("alignparagraph.docx written successfully");
   }
}
 Print
 Add Notes
 Bookmark this page
What is a constructor method in JavaScript?

The constructor method in JavaScript is used to create and initialize object created within a class. If a constructor method is not added, then a default constructor should be used.
Note − Only one occurrence of a constructor method is allowed in a class. More than one throws an error.
You can try to run the following code to learn how to implement a constructor method
Live Demo
<html>
   <body>
      <script>
         class Department {
            constructor() {
               this.name = "Department";
            }
         }
         class Employee extends Department {
            constructor() {
               super();
            }
         }
         class Company {}
         Object.setPrototypeOf(Employee.prototype, Company.prototype);
         document.write("<br>"+Object.getPrototypeOf(Employee.prototype) === Department.prototype);
         let myInstance = new Employee();
         document.write("<br>"+myInstance.name);
      </script>
   </body>
</html>
How  to Check Leap Year using Python?

Leap year comes after every four years. For normal year, if it is divisible by four, it is called leap year, whereas for century year, it should be divisible by 400. The following Python program shows whether the year is leap or not
yr=int(input('enter year'))
if yr%100==0: #century year
if yr%400==0:
   print ('{} is leap year'.format(yr))
else:
   print ('{} is not leap year'.format(yr))
else:
   if yr%4==0:
      print ('{} is leap year'.format(yr))
else:
   print ('{} is not leap year'.format(yr))
enter year2012
2012 is leap year

enter year2018
2018 is not leap year

2000 is leap year

enter year1900
1900 is not leap year
Python 3 - time sleep() Method

The method sleep() suspends execution for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time.
The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine.
Following is the syntax for sleep() method −
time.sleep(t)

t − This is the number of seconds execution to be suspended.
This method does not return any value.
The following example shows the usage of sleep() method.
#!/usr/bin/python3
import time

print ("Start : %s" % time.ctime())
time.sleep( 5 )
print ("End : %s" % time.ctime())
When we run the above program, it produces the following result −
Start : Mon Feb 15 12:08:42 2016
End : Mon Feb 15 12:08:47 2016


    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
C# | Check if a HashSet contains the specified element - GeeksforGeeks

01 Feb, 2019
A HashSet is an unordered collection of the unique elements. It is found in System.Collections.Generic namespace. It is used in a situation where we want to prevent duplicates from being inserted in the collection. As far as performance is concerned, it is better in comparison to the list. HashSet.Contains(T) Method is used to check whether a HashSet object contains the specified element.
Syntax:
mySet.Contains(T item);

Here, mySet is the name of the HashSet and item is the required element to locate in the HashSet object.
Return Type: This method returns true if the HashSet object contains the specified element; otherwise, false.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to check if a HashSet// contains the specified elementusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet of strings        HashSet<string> mySet = new HashSet<string>();          // Inserting elements in HashSet        mySet.Add("DS");        mySet.Add("C++");        mySet.Add("Java");        mySet.Add("JavaScript");          // Check if a HashSet contains        // the specified element        if (mySet.Contains("Java"))            Console.WriteLine("Required Element is present");        else            Console.WriteLine("Required Element is not present");    }}
Required Element is present

Example 2:
// C# code to check if a HashSet// contains the specified elementusing System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet of integers        HashSet<int> mySet = new HashSet<int>();          // Inserting elements in HashSet        for (int i = 0; i < 5; i++) {            mySet.Add(i * 2);        }          // Check if a HashSet contains        // the specified element        if (mySet.Contains(5))            Console.WriteLine("Required Element is present");        else            Console.WriteLine("Required Element is not present");    }}
Required Element is not present

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.contains?view=netframework-4.7.2
CSharp-Generic-HashSet
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Delegates
Destructors in C#
C# | Constructors
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
Introduction to .NET Framework
C# | Abstract Classes
C# | Class and Object
C# | Data Types
C# | Encapsulation
Explain the Random accessing files in C language

Random accessing of files in C language can be done with the help of the following functions −
ftell ( )
rewind ( )
fseek ( )
It returns the current position of the file ptr.
The syntax is as follows −
int n = ftell (file pointer)
For example,
FILE *fp;
int n;
_____
_____
_____
n = ftell (fp);
Note − ftell ( ) is used for counting the number of characters which are entered into a file.
It makes file ptr move to beginning of the file.
The syntax is as follows −
rewind (file pointer);
For example,
FILE *fp;
   -----
   -----
   rewind (fp);
   n = ftell (fp);
   printf ("%d”, n);
Output
The output is as follows −
0 (always).
It is to make the file pntr point to a particular location in a file.
The syntax is as follows −
fseek(file pointer, offset, position);
The no of positions to be moved while reading or writing.
If can be either negative (or) positive.Positive - forward direction.Negative – backward direction.
Positive - forward direction.
Negative – backward direction.
It can have three values, which are as follows −
0 – Beginning of the file.
1 – Current position.
2 – End of the file.
fseek (fp,0,2) - fp moved 0 bytes forward from the end of the file.
fseek (fp,0,2) - fp moved 0 bytes forward from the end of the file.
fseek (fp, 0, 0) – fp moved 0 bytes forward from beginning of the file
fseek (fp, 0, 0) – fp moved 0 bytes forward from beginning of the file
fseek (fp, m, 0) – fp moved m bytes forward from the beginning of the file.
fseek (fp, m, 0) – fp moved m bytes forward from the beginning of the file.
fseek (fp, -m, 2) – fp moved m bytes backward from the end of the file.
fseek (fp, -m, 2) – fp moved m bytes backward from the end of the file.
The errors related to fseek () function are as follows −
fseek (fp, -m, 0);
fseek(fp, +m, 2);
Python | Pandas Series.index - GeeksforGeeks

28 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
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.index attribute is used to get or set the index labels of the given Series object.
Syntax:Series.index
Parameter : None
Returns : index
Example #1: Use Series.index attribute to set the index label for the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon'])  # Print the seriesprint(sr)
Output :
Now we will use Series.index attribute to set the index label for the given object.
# Creating the row axis labelssr.index = ['City 1', 'City 2', 'City 3', 'City 4'] 
Output :
As we can see in the output, the Series.index attribute has successfully set the index labels for the given Series object.
Example #2 : Use Series.index attribute to get the index labels of the given Series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series(['1/1/2018', '2/1/2018', '3/1/2018', '4/1/2018'])  # Creating the row axis labelssr.index = ['Day 1', 'Day 2', 'Day 3', 'Day 4']  # Print the seriesprint(sr)
Output :
Now we will use Series.index attribute to get the index label for the given object.
# print the index labelsprint(sr.index)
Output :
As we can see in the output, the Series.index attribute has successfully returned the index labels for the given Series object.
data-science
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Instruction type RAR in 8085 Microprocessor

In 8085 Instruction set, RAR stands for “Rotate Accumulator Right involving Cy flag in rotation”. It rotates the Accumulator contents to the right by 1-bit position. From the following Fig. we are getting the operation details.
From the Fig. we can see that, during right rotate the least significant bit is coming out and will be copied on the Cy flag bit and the previous Cy flag bit will be moved to the most significant bit position of the Accumulator. It is 1-Byte instruction. And it is 9-bit rotation of Accumulator and Cy contents. Only Cy flag is affected by this instruction execution.
This instruction can be used in multiple case studies.
After rotate as the least significant bit of the Accumulator is getting copied to Accumulator, so we can check its value and can infer whether Accumulator was holding even or odd values.
After rotate as the least significant bit of the Accumulator is getting copied to Accumulator, so we can check its value and can infer whether Accumulator was holding even or odd values.
It can be used to perform division by 2. We know that Accumulator’s content will have n-bits right shift if we divide the Accumulator by 2n.
It can be used to perform division by 2. We know that Accumulator’s content will have n-bits right shift if we divide the Accumulator by 2n.
To insert a new bit value at the most significant bit position, putting this bit value in the Cy flag and then executing this instruction.
To insert a new bit value at the most significant bit position, putting this bit value in the Cy flag and then executing this instruction.
With the help of following examples, we can understand the operation better.
(A)
(Cy)
8AH --->    1000 1010
0100 0101 ---> 45H (Last bit 0 is copied to Cy bit)
                                 (And initial Cy=0 bit at the MS place)

Note that Accumulator value is halved.
(A)
(Cy)
8AH --->    1000 1011
 1100 0101 --->C5H (Last bit 1 is copied to Cy bit)
                                 (And initial Cy=1 bit at the MS place)

Note that Accumulator value is not halved in this case because Cy=1 before rotation.
The timing diagram against this instruction RAR execution is as follows −
Summary − So this instruction RAR requires 1-Byte, 1-Machine Cycle (Opcode Fetch) and 4 T-States for execution as shown in the timing diagram.
Program to find maximum sum of non-adjacent nodes of a tree in Python

Suppose we have a binary tree, we have to find the maximum sum of the values that can be obtained given no two values can be adjacent parent to child.
So, if the input is like
then the output will be 17 as 10, 4, 3 are not adjacent to each other.
To solve this, we will follow these steps −
Define a function f() . This will take node
if node is null, thenreturn (0, 0)
return (0, 0)
(a, b) := f(left of node)
(c, d) := f(right of node)
return a pair (maximum of value of node + b + d and a + c, a + c)
from the main method call f(root) and return the first value of it
Let us see the following implementation to get better understanding −
 Live Demo
class TreeNode:
def __init__(self, data, left = None, right = None):
   self.val = data
   self.left = left
   self.right = right
def f(node):
   if not node:
      return 0, 0
   a, b = f(node.left)
   c, d = f(node.right)
   return max(node.val + b + d, a + c), a + c
class Solution:
   def solve(self, root):
      return f(root)[0]
ob = Solution()
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(10) root.left.left = TreeNode(4) root.left.right = TreeNode(3) print(ob.solve(root))
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(10)
root.left.left = TreeNode(4)
root.left.right = TreeNode(3)
17
Static functions in C

A static function in C is a function that has a scope that is limited to its object file. This means that the static function is only visible in its object file. A function can be declared as static function by placing the static keyword before the function name.
An example that demonstrates this is given as follows −
There are two files first_file.c and second_file.c. The contents of these files are given as follows −
Contents of first_file.c
static void staticFunc(void)
{
   printf("Inside the static function staticFunc() ");
}
Contents of second_file.c
int main()
{
   staticFunc();
   return 0;
}
Now, if the above code is compiled then an error is obtained i.e “undefined reference to staticFunc()”. This happens as the function staticFunc() is a static function and it is only visible in its object file.
A program that demonstrates static functions in C is given as follows −
#include <stdio.h>

static void staticFunc(void){
   printf("Inside the static function staticFunc() ");
}

int main()
{
   staticFunc();
   return 0;
}
The output of the above program is as follows −
Inside the static function staticFunc()
In the above program, the function staticFunc() is a static function that prints ”Inside the static function staticFunc()”. The main() function calls staticFunc(). This program works correctly as the static function is called only from its own object file.
Batch Script - Nested If Statements

Sometimes, there is a requirement to have multiple ‘if’ statement embedded inside each other. Following is the general form of this statement.
if(condition1) if (condition2) do_something

So only if condition1 and condition2 are met, will the code in the do_something block be executed.
Following is an example of how the nested if statements can be used.
@echo off
SET /A a = 5
SET /A b = 10
if %a%==5 if %b%==10 echo "The value of the variables are correct"
The above command produces the following output.
"The value of the variables are correct"

Yet another special case is "if errorlevel", which is used to test the exit codes of the last command that was run. Various commands issue integer exit codes to denote the status of the command. Generally, commands pass 0 if the command was completed successfully and 1 if the command failed.
Following is the general syntax of this statement.
if errorlevel n somecommand

where "n" is one of the integer exit codes.
Generally, the execution of a batch file proceeds line-by-line with the command(s) on each line being run in turn. However, it is often desirable to execute a particular section of a batch file while skipping over other parts. The capability to hop to a particular section is provided by the appropriately named "goto" command (written as one word). The target section is labeled with a line at the beginning that has a name with a leading colon. Thus the script looks like −
... 
goto :label 
...some commands 
:label 
...some other commands

Execution will skip over "some commands" and start with "some other commands". The label can be a line anywhere in the script, including before the "goto" command. "Goto" commands often occur in "if" statements. For example, you might have a command of the type −
if (condition) goto :label

Following is an example of how the goto statement can be used.
@echo off 
SET /A a = 5 

if %a%==5 goto :labela 
if %a%==10 goto :labelb

:labela 
echo "The value of a is 5" 

exit /b 0

:labelb 
echo "The value of a is 10"
The key thing to note about the above program is −
The code statements for the label should be on the next line after the declaration of the label.
The code statements for the label should be on the next line after the declaration of the label.
You can define multiple goto statements and their corresponding labels in a batch file.
You can define multiple goto statements and their corresponding labels in a batch file.
The label declarations can be anywhere in the file.
The label declarations can be anywhere in the file.
The above command produces the following output.
"The value of a is 5" 

 Print
 Add Notes
 Bookmark this page
SVG - Patterns

SVG uses <pattern> element to define patterns. Patterns are defined using <pattern> element and are used to fill graphics elements in tiled fashion.
Following is the syntax declaration of <pattern> element. We've shown main attributes only.
<pattern
   patternUnits="units to define x,y, width and height attributes."
   patternContentUnits ="units to define co-ordinate system of contents of pattern"
   patternTransform = "definition of an additional transformation from the pattern coordinate system onto the target coordinate system"
   
   x="x-axis co-ordinate" 
   y="y-axis co-ordinate"     
   
   width="length"
   height="length"
   
   preserveAspectRatio="to preserve width/height ratio of original content"
   xlink:href="reference to another pattern" >
</pattern>
<html>
   <title>SVG Pattern</title>
   <body>
      <h1>Sample SVG Pattern</h1>
      
      <svg width="800" height="800">
         
         <defs>
            <pattern id="pattern1" patternUnits="userSpaceOnUse"
               x="0" y="0" width="100" height="100"
               viewBox="0 0 4 4" >
               <path d="M 0 0 L 3 0 L 1.5 3 z" fill="blue" stroke="green" />
            </pattern> 
         </defs>
         
         <g>
            <text x="30" y="50" >Using Pattern (Triangles): </text>
            <rect x="100" y="100" width="300" height="300" stroke="green" 
            stroke-width="3" fill="url(#pattern1)" />
         </g> 
         
      </svg>
   
   </body>
</html>
One <pattern> element defined as pattern1.
One <pattern> element defined as pattern1.
In pattern, a viewbox is defined and a path which is to be used as pattern is defined.
In pattern, a viewbox is defined and a path which is to be used as pattern is defined.
in rect element, in fill attribute, url of the pattern is specified to fill the rectangle with pattern created earlier.
in rect element, in fill attribute, url of the pattern is specified to fill the rectangle with pattern created earlier.
Open textSVG.htm in Chrome web browser. You can use Chrome/Firefox/Opera to view SVG image directly without any plugin. Internet Explorer 9  and higher also supports SVG image rendering.

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Classification of Number System - GeeksforGeeks

28 Jan, 2020
A number is a way to represent arithmetic value, count or measure of a particular quantity. A number system can be considered as a mathematical notation of numbers using a set of digits or symbols. In simpler words the number system is a method of representing numbers. Every number system is identified with the help of its base or radix.
Base or Radix of a Number System:The base or radix of a number system can be referred as the total number of different symbols which can be used in a particular number system. Radix means “root” in Latin.
Base equals to 4 implies there are 4 different symbols in that number system. Similarly, base equals to “x” implies there are “x” different symbols in that number system.
Classification of Number System:The number system can be classified in to two types namely:
Positional and Non-Positional number system 
1. Positional (or Weighted) Number System:A positional number system is also known as weighted number system. As the name implies there will be a weight associated with each digit.
According to its position of occurrence in the number, each digit is weighted. Towards the left the weights increases by a constant factor equivalent to the base or radix. With the help of the radix point (‘.’), the positions corresponding to integral weights (1) are differentiated from the positions corresponding to fractional weights (<1).
Any integer value that is greater than or equal to two can be used as the base or radix. The digit position ‘n’ has weight . Largest value of digit position is always 1 less than the base value. The value of a number is weighted sum of its digits.
For example:
1358 = 1 x  + 3 x  + 5 x  + 8 x  
13.58 = 1 x  + 3 x  + 5 x  + 8 x  
Few examples of positional number system are decimal number system, Binary number system, octal number system, hexadecimal number system, BCD, etc.
2. Non-Positional (or Non-weighted) Number System:Non-positional number system is also known as non-weighted number system. Digit value is independent of its position. Non-positional number system is used for shift position encodes and error detecting purpose.
Few examples of non-weighted number system are gray code, roman code, excess-3 code, etc.
Digital Electronics & Logic Design
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Shift Registers in Digital Logic
4-bit binary Adder-Subtractor
BCD to 7 Segment Decoder
Full Subtractor in Digital Logic
Carry Look-Ahead Adder
Layers of OSI Model
ACID Properties in DBMS
Types of Operating Systems
TCP/IP Model
Page Replacement Algorithms in Operating Systems
Get number of records in MongoDB?

To get number of records, use count() in MongoDB. Let us create a collection with documents −
> db.demo697.insertOne({Name:"Chris",Age:21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d7d1551299a9f98c9395")
}
> db.demo697.insertOne({Name:"Bob",Age:23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d7d8551299a9f98c9396")
}
> db.demo697.insertOne({Name:"David",Age:24});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ea6d7dd551299a9f98c9397")
}
Display all documents from a collection with the help of find() method −
> db.demo697.find();
This will produce the following output −
{ "_id" : ObjectId("5ea6d7d1551299a9f98c9395"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5ea6d7d8551299a9f98c9396"), "Name" : "Bob", "Age" : 23 }
{ "_id" : ObjectId("5ea6d7dd551299a9f98c9397"), "Name" : "David", "Age" : 24 }
Following is the query to get number of records −
> var numberOfRecords= db.demo697.count();
> print("Number of records=",numberOfRecords);
This will produce the following output −
Number of records= 3
Drawing circles on an image with Matplotlib and NumPy

To draw a circle on an image with matplotlib and numpy, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Read an image from a file into an array.
Read an image from a file into an array.
Create x and y data points using numpy.
Create x and y data points using numpy.
Create a figure and a set of subplots using subplots() method.
Create a figure and a set of subplots using subplots() method.
Display data as an image, i.e., on a 2D regular raster using imshow() method.
Display data as an image, i.e., on a 2D regular raster using imshow() method.
Turn off the axes.
Turn off the axes.
Add patches on the current axes.
Add patches on the current axes.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Circle

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

img = plt.imread('bird.jpg')

x = np.random.rand(5) * img.shape[1]
y = np.random.rand(5) * img.shape[0]

fig, ax = plt.subplots(1)
ax.imshow(img)
ax.axis('off')

for xx, yy in zip(x, y):
   circ = Circle((xx, yy), 50, color='red')
   ax.add_patch(circ)

plt.show()
How to fix getImageData() error ‘The canvas has been tainted by cross-origin data’ in HTML?

The crossOrigin attribute allows images that are loaded from external origins to be used in canvas like the one they were being loaded from the current origin.
Using images without CORS approval tains the canvas. Once a canvas has been tainted, you can no longer pull data back out of the canvas. By loading the canvas from cross origin domain, you are tainting the canvas.
You can prevent this by setting −
img.crossOrigin = "Anonymous";
This works if the remote server sets the header aptly −
Access-Control-Allow-Origin "*"
Pandas – Convert the first and last character of each word to upper case in a series

10 Jul, 2020
In python, if we wish to convert only the first character of every word to uppercase, we can use the capitalize() method. Or we can take just the first character of the string and change it to uppercase using the upper() method. So, to convert the first and last character of each word to upper case in a series we will be using a similar approach. First of all, let’s create a series in Pandas.  
Example : Let’s create a Pandas Series
# importing pandas as pd import pandas as pd  # Create the seriesseries = pd.Series(['geeks', 'for', 'geeks',                    'pandas', 'series'])  # Print the seriesprint("Series:")series
Output :
Once we have created a series using Pandas, we will apply a lambda() function to the entire series using the map() function. The lambda function will take the first character using slicing, capitalize it and add the rest of the string as it is until the last character. The last character is again capitalized and added to the resultant series.
Example :
# Apply the lambda function to# capitalize first and last # character to each wordnewSeries = series.map(lambda x: x[0].upper() + x[1:-1] + x[-1].upper())  # Print the resulting seriesprint("\nResulting Series :")newSeries
Output :
pandas-series-program
Python pandas-series
Python-pandas
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQt5 – How to get Label coordinates ?

26 Mar, 2020
The main window in PyQt5 is like graph it has x-axis and y-axis, all the widgets are positioned according to their x, y co-ordinates. When we create label is formed at the top left corner, the op left co-ordinates are (0, 0), we can move the label using move() method.In this article, we will see how to get the co-ordinates of label. In order to do so we will use x() method for x co-ordinate and y() method for y co-ordinate.
Syntax :
x_position = label.x()
y_position =label.y()

Argument : Both method takes no argument.
Return : Both returns integer.
Code :
# importing the required libraries  from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):        def __init__(self):        super().__init__()            # set the title        self.setWindowTitle("Python")          # setting  the geometry of window        self.setGeometry(60, 60, 600, 400)            # creating a label widget        self.label_1 = QLabel(self)          # moving position        self.label_1.move(100, 100)          # setting up the border        self.label_1.setStyleSheet("border :3px solid blue;")          # getting x and y co-ordinates        x = str(self.label_1.x())        y = str(self.label_1.y())          # setting label text        self.label_1.setText(x+", "+ y)          # creating a label widget        self.label_2 = QLabel(self)          # moving position        self.label_2.move(160, 170)          # setting up the border        self.label_2.setStyleSheet("border :3px solid yellow;")          # getting x and y co-ordinates        x = str(self.label_2.x())        y = str(self.label_2.y())          # setting label text        self.label_2.setText(x + ", " + y)          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()# start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
Why to check both isset() and !empty() function in PHP ?

12 Aug, 2021
isset() Function 
The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.
Syntax: 
bool isset( $var, mixed )
Parameters: This function accepts more than one parameters. The first parameter of this function is $var. This parameter is used to store the value of variable.
Example:  
PHP
<?php // PHP program to illustrate// isset() function$num = '0'; if( isset( $num ) ) {    print_r(" $num is set with isset function <br>");} // Declare an empty array$array = array();   // Use isset functionecho isset($array['geeks']) ?'array is set.' :  'array is not set.';?>
0 is set with isset function 
array is not set.
 
empty() Function 
The empty() function is a language construct to determine whether the given variable is empty or NULL. The !empty() function is the negation or complement of empty() function. The empty() function is considerably equal to !isset() function and !empty() function is equal to isset() function.
Example:  
PHP
<?php // PHP program to illustrate// empty() function $temp = 0; // It returns true because// $temp is emptyif (empty($temp)) {    echo $temp . ' is considered empty';} echo "\n"; // It returns true since $new exist$new = 1;if (!empty($new)) {    echo $new . ' is considered set';}?>
0 is considered empty
1 is considered set
 
Reason to check both function: The isset() and !empty() functions are similar and both will return the same results. But the only difference is !empty() function will not generate any warning or e-notice when the variable does not exists. It is enough to use either of the function. By incorporating both functions in a program causes time lapse and unnecessary memory usage.
Example:  
PHP
<?php // PHP function to demonstrate isset()// and !empty() function // initialize a variable$num = '0'; // Check isset() functionif( isset ( $num ) ) {    print_r( $num . " is set with isset function");} // Display new lineecho "\n"; // Initialize a variable$num = 1; // Check the !empty() functionif( !empty ( $num ) ) {    print_r($num . " is set with !empty function");}
0 is set with isset function
1 is set with !empty function
 
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
gabaa406
Picked
Technical Scripter 2018
PHP
PHP Programs
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ List Library - unique() Function

The C++ function std::list::unique() Removes all consecutive duplicate elements from the list. It uses binary predicate for comparison.
Following is the declaration for std::list::unique() function form std::list header.
template <class BinaryPredicate>
void unique (BinaryPredicate binary_pred);

binary_pred − binary predicate which returns ​true if the elements should be treated as equal. It has following prototype.
bool pred(const Type1 &arg1, const Type2 &arg2);

None
This member function never throws exception.
Linear i.e. O(n)
The following example shows the usage of std::list::unique() function.
#include <iostream>
#include <list>

using namespace std;

/* Ignore sign of the value */
bool pred(int a, int b) {
   return (abs(a) == abs(b));
}

int main(void) {
   list <int> l = {1, -1, -1, -1, 2, 2, -2, -2, 3, -4, 4, -5, -5, 5};

   cout << "List elements before unique operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   /* Ignore sign of the value */
   l.unique(pred);

   cout << "List elements after unique operation" << endl;

   for (auto it = l.begin(); it != l.end(); ++it)
      cout << *it << endl;

   return 0;
}
Let us compile and run the above program, this will produce the following result −
List elements before unique operation
1
-1
-1
-1
2
2
-2
-2
3
-4
4
-5
-5
5
List elements after unique operation
1
2
3
-4
-5

 Print
 Add Notes
 Bookmark this page
MySQL update column to NULL for blank values

For this, you can use IF() along with UPDATE command. Let us first create a table −
mysql> create table DemoTable1601
   -> (
   -> FirstName varchar(20) ,
   -> LastName varchar(20)
   -> );
Query OK, 0 rows affected (0.53 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1601 values('John','Doe');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1601 values('Adam','');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1601 values('David','Miller');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1601 values('Chris','');
Query OK, 1 row affected (0.11 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1601;
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| John      |      Doe |
| Adam      |          |
| David     |   Miller |
| Chris     |          |
+-----------+----------+
4 rows in set (0.00 sec)
Following is the query to update column to null or its value −
mysql> update DemoTable1601 set LastName=if(LastName='',NULL,LastName);
Query OK, 2 rows affected (0.22 sec)
Rows matched: 4  Changed: 2 Warnings: 0
Let us check the table records once again −
mysql> select * from DemoTable1601;
This will produce the following output −
+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| John      |      Doe |
| Adam      |     NULL |
| David     |   Miller |
| Chris     |     NULL |
+-----------+----------+
4 rows in set (0.00 sec)