code-rag-bench/online-tutorials huggingface dataset:
7 Segment Display  | Practice | GeeksforGeeks

Using seven segment display, you can write down any digit from 0 to 9 using at most seven segments. You will be given a positive number N and then a number of N digits. You have to rearrange the segments in this N digit number to get the smallest possible N digit number. This number can have leading zeros. You can not waste any segment or add any segment from your own. You have to use all of the segments of the given N digits. 
Input:
First line of input consist of a single integer T denoting the total number of test case. Then T test cases follow. Each test case consists of two lines. The first line consists of N. The second line consists of an N digit number. 
Output:
For each test case, print the smallest possible N digit number in a new line which can be made using all of the segments given.

Constraints:
1<=T<=400
1<=N<=10^4

Example:
Input:
2
6
234567
3 
011 
Output:
000011
011

Explanation: 
First Test Case
234567 has a total of 28 segments and we can rearrange them to form 000011 which has 28 segments too. 000011 is the smallest possible number which can be formed on rearrangement.
Second Test Case 
011 has a total of 10 segments and this is the smallest number with 10 segments.  
 
0
shunabhishek487 months ago
for 0123456789(49 segments) the output should be 0000000117(49 segments) but the code has correct output is given as  0000000111(48 segments). Can you please fix this.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

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

26 May, 2020
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for better understanding about the topic.
Example 1:
class GFG:    None      def value():    return 10  # Driver Codeg = GFG()  # Dynamic attribute of a# class objectg.d1 = value  # Dynamic attribute of a # functionvalue.d1 = "Geeks"  print(value.d1)print(g.d1() == value())
Output:
Geeks
True
Now, the above program seems to be confusing, but let’s try to understand it. Firstly let’s see the objects, g and value(functions are also considered as objects in Python) are the two objects. Here the dynamic attribute for both the objects is “d1”. This is defined at runtime and not at compile time like static attributes.
Note: The class “GFG” and all other objects or instances of this class do not know the attribute “d1”. It is only defined for the instance “g”.
Example 2:
class GFG:          employee = True  # Driver Codee1 = GFG()e2 = GFG()  e1.employee = Falsee2.name = "Nikhil"  print(e1.employee)print(e2.employee)print(e2.name)  # this will raise an error # as name is a dynamic attribute# created only for the e2 objectprint(e1.name)
Output:
False
True
Nikhil
Traceback (most recent call last):
  File "/home/fbcfcf668619b24bb8ace68e3c400bc6.py", line 19, in 
    print(e1.name)
AttributeError: 'GFG' object has no attribute 'name'
python-oop-concepts
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
How to convert a List to JSON array using the Jackson library in Java?

The ObjectMapper class is the most important class in the Jackson API that provides readValue() and writeValue() methods to transform JSON to Java Object and Java Object to JSON. We can convert a List to JSON array using the writeValueAsString() method of ObjectMapper class and this method can be used to serialize any Java value as a String.
public String writeValueAsString(Object value) throws JsonProcessingException
import java.util.*;
import com.fasterxml.jackson.databind.*;
public class ListToJSONArrayTest {
   public static void main(String args[]) {
      List<String> list = new ArrayList<>();
      list.add("JAVA");
      list.add("PYTHON");
      list.add("SCALA");
      list.add(".NET");
      list.add("TESTING");
      ObjectMapper objectMapper = new ObjectMapper();
      try {
         String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
         System.out.println(json);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
[ "JAVA", "PYTHON", "SCALA", ".NET", "TESTING" ]
Getting Instagram profile details using Python - GeeksforGeeks

21 Jul, 2021
Instagram is a photo and video-sharing social networking service owned by Facebook. In this article, we will learn how can we get Instagram profile details using web scraping. Python provides powerful tools for web scraping, we will be using BeautifulSoup here.Modules required and Installation:Requests : Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs.  
pip install requests
Beautiful Soup: Beautiful Soup is a library that makes it easy to scrape information from web pages. It sits atop an HTML or XML parser, providing Pythonic idioms for iterating, searching, and modifying the parse tree.  
pip install beautifulsoup4
 Explanation – For a given user name data scraping will be done then parsing of data will be done so that output can be readable. The output will be description i.e followers count, following count, count of posts.Below is the implementation –  
Python3
# importing librariesfrom bs4 import BeautifulSoupimport requests # instagram URLURL = "https://www.instagram.com/{}/" # parse functiondef parse_data(s):         # creating a dictionary    data = {}         # splitting the content    # then taking the first part    s = s.split("-")[0]         # again splitting the content    s = s.split(" ")         # assigning the values    data['Followers'] = s[0]    data['Following'] = s[2]    data['Posts'] = s[4]         # returning the dictionary    return data # scrape functiondef scrape_data(username):         # getting the request from url    r = requests.get(URL.format(username))         # converting the text    s = BeautifulSoup(r.text, "html.parser")         # finding meta info    meta = s.find("meta", property ="og:description")         # calling parse method    return parse_data(meta.attrs['content']) # main functionif __name__=="__main__":         # user name    username = "geeks_for_geeks"         # calling scrape function    data = scrape_data(username)         # printing the info    print(data)
{'Followers': '120.2k', 'Following': '0', 'Posts': '702'}
 
anikakapoor
Python web-scraping-exercises
Python-BS3
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
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 String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Take screenshot of the options in dropdown in selenium c#.

We can take screenshots of the options in dropdown with Selenium Webdriver. A screenshot is generally captured for the failure test cases. This is achieved with the help of ITakesScreenshot interface.
We shall take the help of GetScreenshot method to grab the screenshot. Finally, the SaveAsFile method is used where we pass the parameters – the path of the file and format of the image.
((ITakesScreenshot)d).
GetScreenshot().SaveAsFile("Screenshot.png",ScreenshotImageFormat.Png);
For implementation we shall be using the NUnit framework.
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System;
namespace NUnitTestProject1{
   public class Tests{
      String u ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm";
      IWebDriver d;
      [SetUp]
      public void Setup(){
         //creating object of FirefoxDriver
         d = new FirefoxDriver();
      }
      [Test]
      public void Test1(){
         d.Navigate()
         .GoToUrl(u);
         d.Manage().Window.Maximize();
         //identify dropdown
         IWebElement l = d.FindElement(By.Name("continents"));
         //scroll to dropdown
         ((IJavaScriptExecutor)d)
         .ExecuteScript("arguments[0].scrollIntoView(true);", l);
         l.Click();
         //capture screenshot along file name
         ((ITakesScreenshot)d)
         .GetScreenshot().SaveAsFile("Screenshot.png", ScreenshotImageFormat.Png);
      }
      [TearDown]
      public void close_Browser(){
         d.Quit();
      }
   }
}
Right−click on the project in Solution Explorer. Then click on Open Folder in File Explorer.
Then move to folder bin−>Debug, the file named Screenshot.png should be available.
C# | Getting an enumerator that iterates through HashSet<T> - GeeksforGeeks

01 Feb, 2019
HashSet<T>.GetEnumerator Method is used to get an enumerator that iterates through a HashSet object.
Syntax:
public System.Collections.Generic.HashSet<T>.Enumerator GetEnumerator ();
Return Value: It returns a HashSet<T>.Enumerator object for the HashSet<T> object.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to get an enumerator that// iterates through the HashSet<T>using System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet<T> of strings        HashSet<string> mySet = new HashSet<string>();          // Inserting elements in HashSet        mySet.Add("DS");        mySet.Add("C++");        mySet.Add("Java");        mySet.Add("C#");          // To get an Enumerator        // for the HashSet<T>.        HashSet<string>.Enumerator em = mySet.GetEnumerator();        display(em);    }      // display method    static void display(IEnumerator<string> em)    {        while (em.MoveNext()) {            string val = em.Current;            Console.WriteLine(val);        }    }}
DS
C++
Java
C#

Example 2:
// C# code to get an enumerator that// iterates through the HashSet<T>using System;using System.Collections.Generic;  class GFG {      // Driver code    public static void Main()    {          // Creating a HashSet of integers        HashSet<int> mySet1 = new HashSet<int>();          // Inserting elements in HashSet        for (int i = 1; i <= 10; i++)            mySet1.Add(2 * i);          // To get an Enumerator        // for the HashSet<T>.        HashSet<int>.Enumerator em = mySet1.GetEnumerator();        display(em);    }      // display method    static void display(IEnumerator<int> em)    {        while (em.MoveNext()) {            int val = em.Current;            Console.WriteLine(val);        }    }}
2
4
6
8
10
12
14
16
18
20

Note:
The foreach statement of the C# language hides the complexity of the enumerators. Therefore, using foreach is recommended, instead of directly manipulating the enumerator.
Enumerators can be used to read the data in the collection, but they cannot be used to modify the underlying collection.
Current returns the same object until either MoveNext or Reset is called. MoveNext sets Current to the next element.
An enumerator remains valid as long as the collection remains unchanged. If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined.
This method is an O(1) operation.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.getenumerator?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.
Difference between Ref and Out keywords in C#
C# | Constructors
C# | Class and Object
Introduction to .NET Framework
C# | Delegates
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
Extension Method in C#
C# | Data Types
C# | Encapsulation
How to display a sequence of images using Matplotlib?

To display a sequence of images using Matplotlib, 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.
Make a list of images that have to be drawn.
Make a list of images that have to be drawn.
Turn off the axes.
Turn off the axes.
Iterate the images and redraw over the axes.
Iterate the images and redraw over the axes.
Take a pause after each draw.
Take a pause after each draw.
import matplotlib.pyplot as plt

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

images = ['opera.jpg', 'mountain.jpg', '9.jpg']
plt.axis('off')
img = None

for f in images:
   im = plt.imread(f)
   if img is None:
      img = plt.imshow(im)
      plt.pause(0.5)
   else:
      img.set_data(im)
   plt.pause(0.5)
   plt.draw()
When we execute the code, it will show the three images that we supplied, one by one.
PyQt5 QSpinBox - Setting Auto Fill Background property - GeeksforGeeks

17 May, 2020
In this article we will see how we can set the auto fill property of the spin box, this property will cause Qt to fill the background of the spin box before invoking the paint event. The color used is defined by the QPalette.Window color role from the spin box’s palette. By default this property is false.
This property should be handled with caution in conjunction with Qt Style Sheets. When a spin box has a style sheet with a valid background or a border-image, this property is automatically disabled.
In order to do this we use setAutoFillBackgroun method.
Syntax : spin_box.setAutoFillBackground(True)
Argument : It takes bool argument
Return : It returns None
Note :This property cannot be turned off (i.e., set to false) if a spin box’s parent has a static gradient for its background.
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom 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 spin box        self.spin = QSpinBox(self)          # setting geometry to spin box        self.spin.setGeometry(100, 100, 250, 40)          # setting prefix to spin        self.spin.setPrefix("Prefix ")          # setting suffix to spin        self.spin.setSuffix(" Suffix")          # allowing spin box to auto fill background        self.spin.setAutoFillBackground(True)          # filling background using palette of spin box        # and setting its color to the red        self.spin.setForegroundRole(QPalette.Base)        p = self.spin.palette()        p.setColor(self.spin.foregroundRole(), Qt.red)        self.spin.setPalette(p)    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python PyQt-SpinBox
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
DAX Statistical - RANKX function

Returns the ranking of a number in a list of numbers for each row in the table.
RANKX (<table>, <expression>, [<value>], [<order>], [<ties>])

table
Any DAX expression that returns a table of data over which the expression is evaluated.
expression
Any DAX expression that returns a single scalar value.
The expression is evaluated for each row of table, to generate all possible values for ranking.
value
Optional.
Any DAX expression that returns a single scalar value whose rank is to be found.
If omitted, the value of expression at the current row is used instead.
order
Optional.
A value that specifies how to rank value, low to high, or high to low.
ASC: Ranks in ascending order of columnName.
DESC: Ranks in descending order of columnName.
If omitted, default is DESC.
ties
Optional.
An enumeration that defines how to determine ranking when there are ties.
Skip: The next rank value, after a tie, is the rank value of the tie plus the count of tied values. For example, if five (5) values are tied with a rank of 8, then the next value will receive a rank of 13 (8 + 5).
This is the default value when ties parameter is omitted.
Dense: The next rank value, after a tie, is the next rank value. For example, if five (5) values are tied with a rank of 8, then the next value will receive a rank of 9.
If the parameter value is specified – returns the rank number of value among all possible values of expression evaluated for all rows of table.
If the parameter value is specified – returns the rank number of value among all possible values of expression evaluated for all rows of table.
If the parameter value is not specified - returns the rank number of the value of expression at the current row among all possible values of expression evaluated for all rows of table.
If the parameter value is not specified - returns the rank number of the value of expression at the current row among all possible values of expression evaluated for all rows of table.
If an expression or a value evaluates to BLANK, it is treated as a 0 (zero) for all expressions that result in a number, or as an empty text for all text expressions.
If a value is not among all possible values of expression, then RANKX temporarily adds value to the values from expression and re-evaluates RANKX to determine the proper rank of value.
= RANKX (Sales,Sales[Sales Amount],,DESC) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
Making an SAP ABAP program to wait

You can use WAIT to hold the program for few seconds. Here is the syntax
WAIT UP TO 36 SECONDS
However, you need to be careful about using it. WAIT does an implicit commit. So you need to be sure that the commit does not corrupt the database. It also releases the work process.
An alternative is to use below code −
CALL FUNCTION 'ENQUE_SLEEP'
      EXPORTING
         seconds = 36.
HashSet contains() Method in Java - GeeksforGeeks

26 Nov, 2018
The Java.util.HashSet.contains() method is used to check whether a specific element is present in the HashSet or not. So basically it is used to check if a Set contains any particular element.
Syntax:
Hash_Set.contains(Object element)
Parameters: The parameter element is of the type of HashSet. This is the element that needs to be tested if it is present in the set or not.
Return Value: The method returns true if the element is present in the set else return False.
Below program illustrate the Java.util.HashSet.contains() method:
// Java code to illustrate HashSet.contains() methodimport java.io.*;import java.util.HashSet;  public class HashSetDemo {    public static void main(String args[])    {        // Creating an empty HashSet        HashSet<String> set = new HashSet<String>();          // Using add() method to add elements into the Set        set.add("Welcome");        set.add("To");        set.add("Geeks");        set.add("4");        set.add("Geeks");          // Displaying the HashSet        System.out.println("HashSet: " + set);          // Check for "Geeks" in the set        System.out.println("Does the Set contains 'Geeks'? " + set.contains("Geeks"));          // Check for "4" in the set        System.out.println("Does the Set contains '4'? " + set.contains("4"));          // Check if the Set contains "No"        System.out.println("Does the Set contains 'No'? " + set.contains("No"));    }}
HashSet: [4, Geeks, Welcome, To]
Does the Set contains 'Geeks'? true
Does the Set contains '4'? true
Does the Set contains 'No'? false

Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
ArrayList in Java
Multidimensional Arrays in Java
Singleton Class in Java
Stack Class in Java
Multithreading in Java
LinkedList in Java
Overriding in Java
Collections in Java
Different ways of Reading a text file in Java
Java Program to Extract Content from a Java's .class File - GeeksforGeeks

02 Nov, 2020
In this article, we are going to extract the contents of the Java class file using the Apache Tika library. Apache Tika is used for document type detection and content extraction from various file formats. It uses various document parsers and document type detection techniques to detect and extract data. It provides a single generic API for parsing different file formats. All these parser libraries are encapsulated in a single interface called the Parser interface.
The following table shows a description of the important methods used in the solution : 
Method
Description
Example: Java code to extract the contents of Java class file format 
Java
// Java program to extract the// contents of Java class file// format  import java.io.File;import java.io.FileInputStream;import java.io.IOException;  // importing Apache Tika librariesimport org.apache.tika.exception.TikaException;import org.apache.tika.metadata.Metadata;import org.apache.tika.parser.AutoDetectParser;import org.apache.tika.parser.ParseContext;import org.apache.tika.parser.Parser;import org.apache.tika.sax.BodyContentHandler;  import org.xml.sax.SAXException;  public class ParserExtraction {      public static void main(final String[] args)        throws IOException, SAXException, TikaException    {        // create a File object        File f = new File("AddTwoNumbers.java");          // parse method parameters        Parser parser = new AutoDetectParser();          // instantiate BodyContentHandle        BodyContentHandler handler            = new BodyContentHandler();          // Creates the Metadata object        Metadata metadata = new Metadata();          FileInputStream inputstream            = new FileInputStream(f);          // creates a parse context object        ParseContext context = new ParseContext();          // parsing the file        parser.parse(inputstream, handler, metadata,                     context);                      // display the file content        System.out.println("File content : "                           + Handler.toString());    }}
AddTwoNumbers.java
Output:
File content :  public class AddTwoNumbers {

  public static void main(String[] args) {
       
     int num1 = 5, num2 = 15, sum;
     sum = num1 + num2;

     System.out.println("Sum of these numbers: "+sum);
  }
}

Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Generics in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to find number of ways we can decode a message in Python

Suppose we have mapping like 'a' = 1, 'b' = 2, ... 'z' = 26, and we have an encoded message message string, we have to count the number of ways it can be decoded.
So, if the input is like message = "222", then the output will be 3, as This can be decoded 3 ways: bbb, bv, and vb.
To solve this, we will follow these steps −
memo := a list of 0s of size same as message size + 1
memo := a list of 0s of size same as message size + 1
memo[0] := 1
memo[0] := 1
memo[1] := 1 when message[0] is not same as "0" otherwise 0
memo[1] := 1 when message[0] is not same as "0" otherwise 0
for i in range 2 to size of message, don1 := numeric value of message[from index i-1 to i]n2 := numeric value of message[from index i-2 to i]n1_valid:= true when n1 > 0n2_valid:= true when n2 > 9 and n2 < 27if n1_valid is true, thenmemo[i] := memo[i] + memo[i-1]if n2_valid is true, thenmemo[i] := memo[i] + memo[i-2]
for i in range 2 to size of message, do
n1 := numeric value of message[from index i-1 to i]
n1 := numeric value of message[from index i-1 to i]
n2 := numeric value of message[from index i-2 to i]
n2 := numeric value of message[from index i-2 to i]
n1_valid:= true when n1 > 0
n1_valid:= true when n1 > 0
n2_valid:= true when n2 > 9 and n2 < 27
n2_valid:= true when n2 > 9 and n2 < 27
if n1_valid is true, thenmemo[i] := memo[i] + memo[i-1]
if n1_valid is true, then
memo[i] := memo[i] + memo[i-1]
memo[i] := memo[i] + memo[i-1]
if n2_valid is true, thenmemo[i] := memo[i] + memo[i-2]
if n2_valid is true, then
memo[i] := memo[i] + memo[i-2]
memo[i] := memo[i] + memo[i-2]
return last element of memo
return last element of memo
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, message):
      memo = [0 for i in range(len(message)+1)]
      memo[0] = 1
      memo[1] = 1 if message[0]!="0" else 0

      for i in range(2,len(message)+1):
         n1 = int(message[i-1:i])
         n2 = int(message[i-2:i])

         n1_valid= n1>0
         n2_valid= n2>9 and n2<27

         if n1_valid:
            memo[i]+=memo[i-1]
         if n2_valid:
            memo[i]+=memo[i-2]
      return memo[-1]
ob = Solution()
message = "2223"
print(ob.solve(message))
"2223"
5
How to select sum or 0 if no records exist in MySQL?

You can use aggregate function sum() inside COALESCE(). The below syntax returns the sum of all if the record exists otherwise 0 is returned. The syntax is as follows.
select COALESCE(sum(yourColumnName2), 0) AS anyVariableName from yourTableName
where yourColumnName1 like '%yourValue%';
To understand the above syntax, let us create a table. The query to create a table is as follows.
mysql> create table SumDemo
-> (
-> Words varchar(100),
-> Counter int
-> );
Query OK, 0 rows affected (0.93 sec)
Insert some records in the table using insert command. The query is as follows.
mysql> insert into SumDemo values('Are You There',10);
Query OK, 1 row affected (0.16 sec)

mysql> insert into SumDemo values('Are You Not There',15);
Query OK, 1 row affected (0.13 sec)

mysql> insert into SumDemo values('Hello This is MySQL',12);
Query OK, 1 row affected (0.09 sec)

mysql> insert into SumDemo values('Hello This is not MySQL',14);
Query OK, 1 row affected (0.24 sec)
Display all records from the table using select statement. The query is as follows.
mysql> select *from SumDemo;
The following is the output.
+-------------------------+---------+
| Words                   | Counter |
+-------------------------+---------+
| Are You There           | 10      |
| Are You Not There       | 15      |
| Hello This is MySQL     | 12      |
| Hello This is not MySQL | 14      |
+-------------------------+---------+
4 rows in set (0.00 sec)
Here is the query that gives the total sum whenever record exist.
mysql> select COALESCE(sum(Counter), 0) AS SumOfAll from SumDemo where Words like '%hello%';
The following is the output.
+----------+
| SumOfAll |
+----------+
| 26       |
+----------+
1 row in set (0.00 sec)
If record does not exist then you will get 0. The query is as follows.
mysql> select COALESCE(sum(Counter), 0) AS SumOfAll from SumDemo where Words like '%End of MySQL%';
The following is the output.
+----------+
| SumOfAll |
+----------+
| 0       |
+----------+
1 row in set (0.00 sec)
Sum of first n natural numbers in C Program

The concept of finding the sum of sum of integers is found such that first, we will find the sum of numbers up to n and then add all the sums to get a value which will be the sum of sum which is our desired sum.
For this problem, we are given a number n up to which we have to find the sum of the sum. Let's take an example to find this sum.
n = 4
Now we will find the sum of numbers for every number from 1 to 4 :
Sum of numbers till 1 = 1
Sum of numbers till 2 = 1 + 2 = 3
Sum of numbers till 3 = 1 + 2 + 3 = 6
Sum of numbers till 4 = 1 + 2 + 3 + 4 = 10
Now we will find the sum of sum of numbers til n :
Sum = 1+3+6+10 = 20
For finding the sum of sum of n natural number, we have two methods :
Method 1 − Using the for loops (inefficient)
Method 2 − Using the mathematical formula (efficient)
In this method, we will use two for loops to find the sum of sum. The inner loop finds the sum of natural number and outer loop adds this sum to sum2 and increases the number by one.
#include <stdio.h>
int main() {
   int n = 4;
   int sum=0, s=0;
   for(int i = 1; i< n; i++){
      for(int j= 1; j<i;j++ ){
         s+= j;
      }
      sum += s;
   }
   printf("the sum of sum of natural number till %d is %d", n,sum);
   return 0;
}
The sum of sum of natural number till 4 is 5
We have a mathematical formula for finding the sum of sum of n natural numbers. The mathematical formula method is an efficient method.
The mathematical formula to find the sum of sum of n natural number :
sum = n*(n+1)*(n+2)/2
#include <stdio.h>
int main() {
   int n = 4;
   int sum = (n*(n+1)*(n+2))/2;
   printf("the sum of sum of natural number till %d is %d", n,sum);
   return 0;
}
the sum of sum of natural number till 4 is 60
Python | Pandas Series.multiply()

11 Feb, 2019
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.multiply() function perform the multiplication of series and other, element-wise. The operation is equivalent to series * other, but with support to substitute a fill_value for missing data in one of the inputs.
Syntax: Series.multiply(other, level=None, fill_value=None, axis=0)
Parameter :other : Series or scalar valuefill_value : Fill existing missing (NaN) valuelevel : Broadcast across a level,
Returns : result : Series
Example #1: Use Series.multiply() function to perform the multiplication of a scalar with the given series object.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([10, 25, 3, 11, 24, 6])  # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp']  # set the indexsr.index = index_  # Print the seriesprint(sr)
Output :
Now we will use Series.multiply() function to perform the multiplication of scalar with the series.
# multiply the given value with seriesresult = sr.multiply(other = 10)  # Print the resultprint(result)
Output :As we can see in the output, the Series.multiply() function has returned the result of multiplication of the given scalar with the series object. Example #2: Use Series.multiply() function to perform the multiplication of a scalar with the given series object. The given series object contains some missing values.
# importing pandas as pdimport pandas as pd  # Creating the Seriessr = pd.Series([19.5, 16.8, None, 22.78, None, 20.124, None, 18.1002, None])  # Print the seriesprint(sr)
Output :
Now we will use Series.multiply() function to perform the multiplication of scalar with the series.
# multiply the given value with series# fill 5 at the place of all the missing valuesresult = sr.multiply(other = 10, fill_value = 5)  # Print the resultprint(result)
Output :As we can see in the output, the Series.multiply() function has returned the result of multiplication of the given scalar with the series object.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
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
Create a Pandas DataFrame from Lists
GATE-CS-2017 (Set 1) - GeeksforGeeks

26 Oct, 2021
There are atleast Two Men and Two Women.
There are atleast 3 Right Handed People
No women are Right Handed - infers there are three right handed men
Every woman has a left-handed person to her immediate right - Means women circled in red needs to have a left handed person on her right and that too a man as on right side of ?? there is a right handed man.
So,  ?? - will be a left handed man

"The hold of the nationalist imagination on our colonial past is such that 
anything inadequately or improperly natinalist is just not history"

Case 1: If x > y :
(x + y) - |x - y| ] / 2
=  (x + y) - (x - y) ] / 2
= 2y / 2
= y (Minimum of x , y)
Case 2: If x < y :
(x + y) - |x - y| ] / 2
= (x + y) - (y - x) ] / 2
= 2x / 2
= x (Minimum of x , y)
P = 575
Q = 525
R = 475
S = 425
T = 500
R <500m425m<= S<=450m500m <=T<= 525m
R <500m
425m<= S<=450m
500m <=T<= 525m
So total combination of possibilities = 4 X 4 = 16
No.of ways  'Arun chooses red' + No.of ways Shwetha chooses white '=  2
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Git - Difference Between Git Fetch and Git Pull
ReactJS useNavigate() Hook
SDE SHEET - A Complete Guide for SDE Preparation
How to Install and Use NVM on Windows?
How to Set Upstream Branch on Git?
DSA Sheet by Love Babbar
Top 20 Puzzles Commonly Asked During SDE Interviews
TCS NQT Coding Sheet
Node.js path.dirname() Method

13 Oct, 2021
The path.dirname() method is used to get the directory name of the given path. It ignores the respective platform’s trailing directory separators.
Syntax:
path.dirname( path )
Parameters: This function accepts one parameter as mentioned above and described below:
path: It is the file path that would be used to extract the directory name. It throws a TypeError if this parameter is not a string value.
Return Value: It returns a string with the directory of the path.
Below programs illustrate the path.dirname() method in Node.js:
Example 1:
// Node.js program to demonstrate the    // path.dirname() method      // Import the path moduleconst path = require('path');   // Complete file pathpath1 = path.dirname("/users/admin/website/index.html");console.log(path1)   // Only file name// returns a period (.)path2 = path.dirname("readme.md");console.log(path2)   // Path with file not specifiedpath3 = path.dirname("website/post/comments")console.log(path3);
Output:
/users/admin/website
.
website/post
Example 2:
// Node.js program to demonstrate the    // path.dirname() method      // Import the path moduleconst path = require('path');   console.log("File name:", __filename);path1 = path.dirname(__filename);console.log(path1);   console.log("Directory name:", __dirname);path2 = path.dirname(__dirname);console.log(path2);
Output:
File name:  G:\tutorials\nodejs-path-dirname\index.js
G:\tutorials\nodejs-path-dirname
Directory name:  G:\tutorials\nodejs-path-dirname
G:\tutorials
Reference: https://nodejs.org/api/path.html#path_path_dirname_path
Node.js-path-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Post a picture automatically on Instagram using Python

29 May, 2021
Prerequisites: Python Programming LanguageInstagram is a photo and video-sharing social networking service owned by Facebook, Python provides powerful tools for interacting with Instagram. In this article, we will come to know how we can post a picture automatically on the Instagram account just by writing a few lines of Python code.Step 1: Install ‘instabot‘ package using the below command in the terminal.  
pip install instabot
Step 2: Import class ‘Bot‘ from ‘instabot‘ package.  
Python3
from instabot import Bot
Step 3: Create a variable let’s say ‘bot’ and store the class ‘Bot’ in it.  
Python3
bot = Bot()
Step 4: Login to your instagram account using the below command. Provide your Instagram ‘username’ and ‘password’.  
Python3
bot.login(username = "******",          password = "ppppppp")
Step 5: Upload your photo using the following command.  
Python3
bot.upload_photo("provide the path to the picture here",           caption = "provide the caption that you \           want to display on the post here")
Below is the full program to upload the photo on Instagram. The below program uploads a picture of “Technical Scripter 2019”. 
Python3
from instabot import Bot  bot = Bot() bot.login(username = "user_name",          password = "user_password") # Recommended to put the photo# you want to upload in the same# directory where this Python code# is located else you will have# to provide full path for the photobot.upload_photo("Technical-Scripter-2019.jpg",                 caption ="Technical Scripter Event 2019")
Below is the screen shot of the post at Instagram of the above photo.  
 
sooda367
Python-projects
python-utility
Technical Scripter 2019
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Reading Text File into Java HashMap

28 Dec, 2020
We will look into the Method that allows us to read the HashMap Text from the file or how we can De-serialised the File
De-Serialization: Here we are reproducing the HashMap object and it’s content from a serialized file.
Approach:
Firstly the method/Function HashMapFromTextFile will have the Method bufferedReader which read the Line of the text File and insert into the map and then return the Map
bf = new BufferedWriter( new FileWriter(file_name) );
Firstly we call the BufferedReader to read each line.
At each Line, We have the Key-Value Pair. So, Now split it by “:” and same time put the key and Value to the map
and return the Map
Java
// Java program to reading// text file to HashMap  import java.io.*;import java.util.*;  class GFG {    final static String filePath        = "F:/Serialisation/write.txt";    public static void main(String[] args)    {          // read text file to HashMap        Map<String, String> mapFromFile            = HashMapFromTextFile();          // iterate over HashMap entries        for (Map.Entry<String, String> entry :             mapFromFile.entrySet()) {            System.out.println(entry.getKey() + " : "                               + entry.getValue());        }    }      public static Map<String, String> HashMapFromTextFile()    {          Map<String, String> map            = new HashMap<String, String>();        BufferedReader br = null;          try {              // create file object            File file = new File(filePath);              // create BufferedReader object from the File            br = new BufferedReader(new FileReader(file));              String line = null;              // read file line by line            while ((line = br.readLine()) != null) {                  // split the line by :                String[] parts = line.split(":");                  // first part is name, second is number                String name = parts[0].trim();                String number = parts[1].trim();                  // put name, number in HashMap if they are                // not empty                if (!name.equals("") && !number.equals(""))                    map.put(name, number);            }        }        catch (Exception e) {            e.printStackTrace();        }        finally {              // Always close the BufferedReader            if (br != null) {                try {                    br.close();                }                catch (Exception e) {                };            }        }          return map;    }}
Java-Files
Java-HashMap
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
How to create 3-Tuple or Triple Tuple in C#?

29 Nov, 2019
In C#, a 3-tuple is a tuple that contains three elements and it is also known as triple. You can create a 3-tuple using two different ways:
Using Tuple<T1,T2,T3>(T1, T2, T3) Constructor
Using the Create method
You can create 3-tuple using Tuple<T1, T2,T3>(T1, T2, T3) constructor. It initializes a new instance of the Tuple<T1, T2, T3> class. But when you create a tuple using this constructor then you have to specify the type of the element stored in the tuple.
Syntax:
public Tuple (T1 item1, T2 item2, T3 item3);
Parameters:
item1: It is the value of the first tuple component.
item2: It is the value of the second tuple component.
item3: It is the value of the third tuple component.
Example:
// C# program to create 3-tuple// using the tuple constructorusing System;  public class GFG {      // Main method    static public void Main()    {          // Creating tuple with three elements        // Using Tuple<T1, T2, T3>(T1, T2, T3) constructor        Tuple<string, int, char> My_Tuple = new Tuple<string, int, char>("GeeksforGeeks", 10, 'C#');          Console.WriteLine("Element 1: " + My_Tuple.Item1);        Console.WriteLine("Element 2: " + My_Tuple.Item2);        Console.WriteLine("Element 3: " + My_Tuple.Item3);    }}
Element 1: GeeksforGeeks
Element 2: 10
Element 3: C#

You can also create 3-tuple with the help of Create method. When you use this method then there is no need to specify the type of the elements stored in the tuple.
Syntax:
public static Tuple<T1,T2,T3> Create<T1, T2, T3> (T1 item1, T2 item2, T3 item3);
Type Parameters:
T1: It is the type of the first tuple component.
T2: It is the type of the second tuple component.
T3: It is the type of the third tuple component.
Parameters:
item1: It is the value of the first tuple component.
item2: It is the value of the second tuple component.
item3: It is the value of the third tuple component.
Return Type: This method returns 3-tuple whose value is item1, item2, and item3.
Example:
// C# program to create 3-tuple// using create methodusing System;  public class GFG {      // Main method    static public void Main()    {          // Creating tuple with three         // elements using Create method        var My_Tuple = Tuple.Create("Geeks", 20, 'f');          Console.WriteLine("Element 1: " + My_Tuple.Item1);        Console.WriteLine("Element 2: " + My_Tuple.Item2);        Console.WriteLine("Element 3: " + My_Tuple.Item3);    }}
Element 1: Geeks
Element 2: 20
Element 3: f

References:
https://docs.microsoft.com/en-us/dotnet/api/system.tuple-3.-ctor?view=netframework-4.8
https://docs.microsoft.com/en-us/dotnet/api/system.tuple.create?view=netframework-4.8#System_Tuple_Create__3___0___1___2_
CSharp-Tuple
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | Constructors
C# | Class and Object
Extension Method in C#
C# | Replace() Method
ReactJS | Refs

08 Jan, 2021
Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all. They also provide us with good functionality as we can use callbacks with them. 
Example:  
Javascript
// without refsclass App extends React.Component {  constructor(){   super();   this.state = { sayings: ""};   }  update(e){   this.setState({ sayings: e.target.value});  }  render(){   return (    <div>     Mukul Says <input type="text" onChange = {this.update.bind(this)}/>    <br/>    <em>{this.state.sayings}</em>   </div>  ); }}ReactDOM.render(< App />, document.getElementById('root'));
Output: 
In the above example, we are making use of the target value of event e, for getting the value of what Mukul is saying. The above output can also be achieved by using the refs. 
Example:  
Javascript
// using refsclass App extends React.Component { constructor(){  super();  this.state = { sayings: ""}; } update(e){  this.setState({ sayings: this.refs.anything.value}); } render(){  return (   <div>    Mukul Says <input type="text" ref="anything"      onChange = {this.update.bind(this)}/>   <br/>   <em>{this.state.sayings}</em>  </div>  ); }} ReactDOM.render(< App />, document.getElementById('root'));
Output:  
In the above we make use of refs provided by React, they can also be used to add callback functions inside them which is helpful in many cases. 
Example:  
Javascript
// callback used inside refclass App extends React.Component {  constructor(){   super();   this.state = { sayings: ""};  }  update(e){   this.setState({ sayings: this.a.value});  }  render(){   return (    <div>     Mukul Says <input type="text"     ref={(call_back) => {this.a = call_back}} onChange =     {this.update.bind(this)}/>   <br/>   <em>{this.state.sayings}</em>   </div>  ); }}ReactDOM.render(< App />, document.getElementById('root'));
Output: 
When to use refs  
Helpful when using third party libraries.
Helpful in animations.
When not to use refs 
Should not be used with functional components because they don’t have instances.
Not to be used on things that can be done declaratively.
 
ManasChhabra2
shubhamyadav4
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?