code-rag-bench/online-tutorials huggingface dataset:
Custom instance creator using Gson in Java?

While parsing JSON String to or from Java object, By default Gson try to create an instance of Java class by calling the default constructor. In the case of Java class doesn’t contain default constructor or we want to do some initial configuration while creating Java objects, we need to create and register our own instance creator.
We can create a custom instance creator in Gson using the InstanceCreator interface and need to implement the createInstance(Type type) method.
T createInstance(Type type)
import java.lang.reflect.Type;
import com.google.gson.*;
public class CustomInstanceCreatorTest {
   public static void main(String args[]) {
      GsonBuilder gsonBuilder = new GsonBuilder();
      gsonBuilder.registerTypeAdapter(Course.class, new CourseCreator());
      Gson gson = gsonBuilder.create();
      String jsonString = "{'course1':'Core Java', 'course2':'Advanced Java'}";
      Course course = gson.fromJson(jsonString, Course.class);
      System.out.println(course);
   }
}
// Course class
class Course {
   private String course1;
   private String course2;
   private String technology;
   public Course(String technology) {
      this.technology = technology;
   }
   public void setCourse1(String course1) {
      this.course1 = course1;
   }
   public void setCourse2(String course2) {
      this.course2 = course2;
   }
   public String getCourse1() {
      return course1;
   }
   public String getCourse2() {
      return course1;
   }
   public void setTechnology(String technology) {
      this.technology = technology;
   }
   public String getTechnology() {
      return technology;
   }
   public String toString() {
      return "Course[ " +
             "course1 = " + course1 +
             ", course2 = " + course2 +
             ", technology = " + technology +
             " ]";
   }
}
// CourseCreator class
class CourseCreator implements InstanceCreator {
   @Override
   public Course createInstance(Type type) {
      Course course = new Course("Java");
      return course;
   }
}
Course[ course1 = Core Java, course2 = Advanced Java, technology = Java ]
C# - continue Statement - GeeksforGeeks

14 Oct, 2020
In C#, the continue statement is used to skip over the execution part of the loop(do, while, for, or foreach) on a certain condition, after that, it transfers the control to the beginning of the loop. Basically, it skips its given statements and continues with the next iteration of the loop. Or in other words, the continue statement is used to transfer control to the next iteration of the enclosing statement(while, do, for, or foreach) in which it appears.
Syntax: 
continue;

Flow Chart:
Example 1:
C#
// C# program to illustrate the use// of continue statement in for loopusing System;  class GFG{    static public void Main (){          // Here, in this for loop start from 2 to 12,     // due to the continue statement, when x = 8    // it skip the further execution of the statements    // and transfer the controls back to the     // next iteration of the for loop    for(int x = 2; x <= 12; x++)    {        if (x == 8)        {            continue;        }        Console.WriteLine(x);    }}}
Output:
2
3
4
5
6
7
9
10
11
12

Example 2: 
C#
// C# program to illustrate the use// of continue statement in while loopusing System;  class GFG{    static public void Main (){    int x = 0;          // Here, using continue statement    // whenever the value of x<2, it    // skips the further execution of the    // statements and the control transfer    // to the next iteration of while loop    while (x < 8)    {        x++;          if (x < 2)            continue;          Console.WriteLine(x);    }}}
Output:
2
3
4
5
6
7
8

CSharp-ControlFlow
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C#
Swing Examples - Box Layout

The class BoxLayout arranges the components in stacked manner to put them on top on each other or in row. It provides flexibility over FlowLayout. Following example showcases the use of BoxLayout.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class SwingTester {
   public static void main(String[] args) {
      createWindow();
   }

   private static void createWindow() {    
      JFrame frame = new JFrame("Swing Tester");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setSize(560, 200);      
      frame.setLocationRelativeTo(null);  
      frame.setVisible(true);
   }

   private static void createUI(final JFrame frame){  
      JPanel panel = new JPanel();
      LayoutManager layout = new BoxLayout(panel, BoxLayout.PAGE_AXIS);  
      panel.setLayout(layout);       
      
      panel.add(new JButton("One"));
      panel.add(new JButton("Two")); 
      panel.add(new JButton("Three"));
      panel.add(new JButton("Four"));         
      frame.getContentPane().add(panel, BorderLayout.CENTER);    
   }
}
 Print
 Add Notes
 Bookmark this page
Infinity or Exception in Java when divide by 0? - GeeksforGeeks

06 Feb, 2019
Consider the following code snippets:
public class Geeksforgeeks{    public static void main(String[] args)    {        double p = 1;        System.out.println(p/0);    }}
Output:
Infinity
public class Geeksforgeeks{    public static void main(String[] args)    {        int p = 1;        System.out.println(p/0);    }}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Geeksforgeeks.main(Geeksforgeeks.java:8)
Explanation: In the first piece of code, a double value is being divided by 0 while in the other case an integer value is being divide by 0. However the solution for both of them differs.
In case of double/float division, the output is Infinity, the basic reason behind that it implements the floating point arithmetic algorithm which specifies a special values like “Not a number” OR “infinity” for “divided by zero cases” as per IEEE 754 standards.
In case of integer division, it throws ArithmeticException.
This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Exception Handling
Java-Exceptions
Java
Java
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
Singleton Class in Java
Stack Class in Java
Set in Java
Multithreading in Java
LinkedList in Java
Collections in Java
Overriding in Java
Different ways of Reading a text file in Java
Python | Combine two lists by maintaining duplicates in first list - GeeksforGeeks

07 Mar, 2019
Given two lists, the task is to combine two lists and removing duplicates, without removing duplicates in original list.
Example:
Input : 
list_1 = [11, 22, 22, 15]
list_2 = [22, 15, 77, 9]

Output :
OutList = [11, 22, 22, 15, 77, 9]
Code #1: using extend
# Python code to combine two lists# and removing duplicates, without# removing duplicates in original list.  # Initialisation of first listlist1 = [111, 222, 222, 115]  # Initialisation of Second listlist2 = [222, 115, 77, 19]  output = list(list1)  # Using extend functionoutput.extend(y for y in list2 if y not in output)  # printing resultprint(output)
[111, 222, 222, 115, 77, 19]

 Code #2 : Using Set and IterationAppend those element in first list which are not in second list and then take union of first and second list.
# Python code to combine two lists # and removing duplicates, without # removing duplicates in original list.  # Initialisation of first listlist1 = [11, 22, 22, 15]  # Initialisation of Second listlist2 = [22, 15, 77, 9]  # creating setunique_list1 = set(list1)unique_list2 = set(list2)  # Difference in two setsdiff_element = unique_list2 - unique_list1  # union of difference + first listoutput = list1 + list(diff_element)  # printing outputprint(output) 
[11, 22, 22, 15, 9, 77]

Python list-programs
python-list
Python
Python Programs
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Small input group with Bootstrap

To set small input group with Bootstrap, use the .input-group-sm class.
You can try to run the following code to implement the .input-group-sm class &minsu;
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class = "container">
         <h1>Search</h1>
         <form>
            <div class = "input-group input-group-sm">
               <input type = "text" class = "form-control" placeholder = "Search here...">
                  <div class = "input-group-btn">
                     <button class = "btn btn-primary" type = "submit">
                     </button>
                  </div>
            </div>
         </form>
      </div>
   </body>
</html>
How to open a hyperlink in another window or tab in HTML ? - GeeksforGeeks

13 Jul, 2021
There are various methods of opening a hyperlink in another window or tab such as using javaScript, jQuery or HTML. For opening a hyperlink in another window or tab using HTML, use target attribute and provide it value _blank in the anchor tab.Syntax:  
<a target="target_name" rel="relation_name" href="link">Link Name</a>
Here, rel attribute is used to describe the relation between current document and linked document and target attribute is used to specify the target link.Example 1: This example opening a hyperlink in a new window or tab.  
html
<!DOCTYPE html><html> <head>    <title>        Open hyperlink in a        new window or tab    </title></head> <body>     <p>A computer science portal for geeks        <a target="_blank"            href="https://www.geeksforgeeks.org/">            GeeksforGeeks        </a>    </p> </body> </html>
Output:  
Explanation: Here, target=”_blank” is used to open hyperlink in a new window or tab.Example 2: Opening a hyperlink in a new window or tab using security measure.  
html
<!DOCTYPE html><html> <head>    <title>        Open hyperlink in a        new window or tab    </title></head> <body>     <p>A computer science portal for geeks        <a target="_blank" rel="noopener noreferrer"            href="https://www.geeksforgeeks.org/">            GeeksforGeeks        </a>    </p> </body> </html>
Output:  
Explanation: Here, rel=”noopener noreferrer” is used as a security measure.Example 3: Opening an image hyperlink in a new window or tab.  
html
<!DOCTYPE html><html> <head>    <title>        Open hyperlink in a        new window or tab    </title></head> <body>     <p>A computer science portal for geeks        <a target="_blank" rel="noopener noreferrer"                href="https://www.geeksforgeeks.org/">                             <img src=Geeksforgeeks_image.jpg" alt=""                    class="aligncenter" />        </a>    </p> </body> </html>
Output:  
 
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
varshagumber28
HTML-Misc
Picked
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
BigInteger valueOf() Method in Java - GeeksforGeeks

29 Nov, 2019
The java.math.BigInteger.valueOf(long value) method returns a BigInteger whose value is equal to value of long passed as parameter. This method is static method so It is not necessary to create object of BigInteger class to use this method.we can call this function by BigInteger.valueOf(long value) code.
Syntax:
public static BigInteger valueOf(long val)
Parameter: This method accepts a single parameter value which is the value of the BigInteger to be created.
Return Value: This method returns the BigInteger whose value is equal to value of long passed as parameter.
Below programs illustrate valueOf(long value ) method of BigInteger class:
Example 1: To apply valueOf() without creating BigInteger Object.
// Java program to demonstrate valueOf() method of BigInteger  import java.math.BigInteger;  public class GFG {      public static void main(String[] args)    {          // Creating 2 BigInteger objects        BigInteger b1, b2;          // apply valueOf()        b1 = BigInteger.valueOf(456782765);        b2 = BigInteger.valueOf(12345543);          // print result        System.out.println("Value of BigInteger b1: " + b1);        System.out.println("Value of BigInteger b2: " + b2);    }}
Value of BigInteger b1: 456782765
Value of BigInteger b2: 12345543

Example 2: Apply valueOf() by creating BigInteger object.
// Java program to demonstrate valueOf() method of BigInteger  import java.math.BigInteger;  public class GFG {      public static void main(String[] args)    {          // Creating BigInteger objects        BigInteger b1, b2, b3;          // create bigInteger with some value        b1 = new BigInteger("532721");          // apply valueOf()        b2 = b1.valueOf(234567898);        b3 = b2.valueOf(98765432);          // print result        System.out.println("Value of BigInteger 1: " + b2);        System.out.println("Value of BigInteger 2: " + b3);    }}
Value of BigInteger 1: 234567898
Value of BigInteger 2: 98765432

Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#valueOf(long)
Akanksha_Rai
java-basics
Java-BigInteger
Java-Functions
java-math
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Python - Get summation of numbers in string list - GeeksforGeeks

26 Jun, 2020
Sometimes, while working with data, we can have a problem in which we receive series of lists with data in string format, which we wish to accumulate as list. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + int()This is the brute force method to perform this task. In this, we run a loop for entire list, convert each string to integer and perform summation listwise and store in a separate list.
# Python3 code to demonstrate working of# Summation of String Integer lists# using loop + int()  # initialize list test_list = [['1', '4'], ['5', '6'], ['7', '10']]  # printing original list print("The original list : " + str(test_list))  # Summation of String Integer lists# using loop + int()res = []for sub in test_list:    par_sum = 0    for ele in sub:        par_sum = par_sum + int(ele)    res.append(par_sum)  # printing resultprint("List after summation of nested string lists : " + str(res))
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after summation of nested string lists : [5, 11, 17]

 
Method #2 : Using sum() + int() + list comprehensionThis is the shorthand with the help of which this task can be performed. In this, we run a loop on lists using list comprehension and extract summation using sum().
# Python3 code to demonstrate working of# Summation of String Integer lists# using sum() + int() + list comprehension  # initialize list test_list = [['1', '4'], ['5', '6'], ['7', '10']]  # printing original list print("The original list : " + str(test_list))  # Summation of String Integer lists# using sum() + int() + list comprehensionres = [sum(int(ele) for ele in sub) for sub in test_list]  # printing resultprint("List after summation of nested string lists : " + str(res))
The original list : [['1', '4'], ['5', '6'], ['7', '10']]
List after summation of nested string lists : [5, 11, 17]

nidhi_biet
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
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 | Convert a list to dictionary
Output of C++ programs | Set 29 (Strings) - GeeksforGeeks

12 Dec, 2021
Prerequisite: Strings  
Question What is the Output? 
CPP
#include <iostream>#include <cstring>using namespace std; int main(){    char s1[] = "geeksforgeeksforgeeks";    char s2 = 'f';    char *ptr = strchr( s1, s2);    cout << ptr;    return 0;}
Output: 
forgeeksforgeeks
Description: strchr( str, c) returns a pointer to the first occurrence of character ‘c’ in str. Here s2 is ‘f’, strchr() returns the address where it occurs for the first time in s1.  
Question What is the Output? 
CPP
#include <iostream>#include <cstring>using namespace std; int main(){    char s1[] = "geeksforgeeksforgeeks";    char s2[] = "for";    char *ptr = strstr(s1, s2);    cout << ptr;    return 0;}
Output: 
forgeeksforgeeks
Description: strstr( str1, str2) returns a pointer to the first occurrence of string str2 in str1. Here s2 is “for”, strstr() returns the address where it occurs for the first time in s1. 
Question What is the Output? 
CPP
#include <iostream>using namespace std; int main(){    char str[] = "geeksforgeeks";    cout << 6[str];    return 0;}
Output: 
o
Description: For the compiler 6[str] is same as str[6]. so, it will search for the 6th element in the string “str” and print it which is ‘o’ in this case. 
Question What is the Output? 
CPP
#include <iostream>#include <cstring>using namespace std; int main (){  char string[50] = "geeks, for:geeks";  char *p;  p = strtok (string, ", :" ); //, and ; are delimiteres.  while (p != NULL)  {    cout << p << endl;    p = strtok (NULL, ", :");  }  return 0;}
Output: 
geeks
for
geeks
Description: strtok() is used to tokenize or phrase the string using delimiters. strtok() returns the string which is before the delimiter and writes NULL immediately after the token in string.  
Question What is the Output? 
CPP
#include <iostream>#include <cstring>using namespace std; int main (){  char string[50] = "geeksforgeeks";  memset (string, '*', 8);  cout << string;  return 0;}
Output: 
********geeks
Description: memset( string, c, n) sets first n characters of string to ‘c’. In this program first ‘8’ characters in the string will be set to ‘*’. We often see this kind of text on the checks, where we want to hide some data. For more details on memset Refer here 
This article is contributed by I.HARISH KUMAR. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nidhi_biet
saurabh1990aror
CPP-Output
cpp-string
C++
Program Output
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Bitwise Operators in C/C++
C++ Classes and Objects
Operator Overloading in C++
Templates in C++ with Examples
Arrow operator -> in C/C++ with Examples
Output of Java program | Set 18 (Overriding)
Output of Java Program | Set 11
delete keyword in C++
Output of Java Program | Set 1
map::clear() in C++ STL - GeeksforGeeks

20 Jan, 2018
Map is dictionary like data structure. It is an associative array of (key, value) pair, where only single value is associated with each unique key.
map::clear()clear() function is used to remove all the elements from the map container and thus leaving it’s size 0.
Syntax:
map1.clear()
where map1 is the name of the map.

Parameters:
No parameters are passed.

Return Value: None
Examples:
Input : map1 = { 
                {1, "India"},
                {2, "Nepal"},
                {3, "Sri Lanka"},
                {4, "Myanmar"}
               }
        map1.clear();
Output: map1 = {}

Input : map2 = {}
        map2.clear();
Output: map2 = {}

// CPP program to illustrate// Implementation of clear() function#include <bits/stdc++.h>using namespace std;  int main(){    // Take any two maps    map<int, string> map1, map2;          // Inserting values    map1[1] = "India";    map1[2] = "Nepal";    map1[3] = "Sri Lanka";    map1[4] = "Myanmar";          // Print the size of map    cout<< "Map size before running function: \n";    cout << "map1 size = " << map1.size() << endl;    cout << "map2 size = " << map2.size() << endl;;          // Deleting the map elements    map1.clear();    map2.clear();          // Print the size of map    cout<< "Map size after running function: \n";    cout << "map1 size = " << map1.size() << endl;    cout << "map2 size = " << map2.size();    return 0;}
Output:
Map size before running function: 
map1 size = 4
map2 size = 0
Map size after running function: 
map1 size = 0
map2 size = 0

Time complexity: Linear i.e. O(n)
cpp-map
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Inline Functions in C++
Array of Strings in C++ (5 Different Ways to Create)
Queue in C++ Standard Template Library (STL)
Convert string to char array in C++
Tryit Editor v3.7

Tryit: Height and width properties
How to get the home directory in Python?

To get the homedir in python, you can use os.path.expanduser('~') from the os module. This also works if its a part of a longer path like ~/Documents/my_folder/. If there is no ~ in the path, the function will return the path unchanged. You can use it like −
import os
print(os.path.expanduser('~'))
You can also query the environment variables for the HOME variable −
import os
print(os.environ['HOME'])
ML | Raw and Central Moments - GeeksforGeeks

26 Jul, 2019
Moments are a set of statistical parameters which are used to describe different characteristics and feature of a frequency distribution i.e. central tendency, dispersion, symmetry, and peakedness (hump) of the frequency curve.
For Ungrouped data i.e. discrete data, observations on a variable X are obtained as , For Grouped data i.e. continuous data, observations on a variable X are obtained and tabulated in K class intervals in a frequency table. The mid points of the inervals are denoted by  which occur with frequencies  respectively and .
Moments about an arbitrary point AThe  moment of a variable X about any arbitrary point A on the observations  is defined as:
For ungrouped data 
For grouped data 
where
 Moment about any arbitrary point in Python –
Consider the given data points. Following are the time (in hours) spent by 20 different persons at GeeksforGeeks portal every week.
15, 25, 18, 36, 40, 28, 30, 32, 23, 22, 21, 27, 31, 20, 14, 10, 33, 11, 7, 13
# data pointstime = [15, 25, 18, 36, 40, 28, 30, 32, 23, 22,         21, 27, 31, 20, 14, 10, 33, 11, 7, 13]  # Arbitrary point A = 22  # Moment for r = 1moment = (sum([(item-A) for item in time]))/len(time)
The  moment around origin A = 0 known as raw moment and is defined as:
For ungrouped data, For grouped data, 
where, 
Notes:
-> We can find first raw moment () just by replacing r with 1 and second raw moment () just by replacing r with 2 and so on.-> When r = 0 the moment  for both grouped and ungrouped data.
 Raw moment in Python –
# data pointstime = [15, 25, 18, 36, 40, 28, 30, 32, 23,       22, 21, 27, 31, 20, 14, 10, 33, 11, 7, 13]    # Moment for r = 1moment = sum(time)/len(time)
The moments of a variable X about the arithmetic mean () are known as central moments and defined as:
For ungrouped data,
For grouped data,
where  and 
Notes:
-> We can find first raw moment () just by replacing r with 1 and second raw moment () just by replacing r with 2 and so on.-> When r = 0 the moment , and when r = 1 the moment  for both grouped and ungrouped data.
# data pointstime = [15, 25, 18, 36, 40, 28, 30, 32, 23, 22,       21, 27, 31, 20, 14, 10, 33, 11, 7, 13]  # Mean A = sum(time)/len(time)  # Moment for r = 1moment = (sum([(item-A) for item in time]))/len(time)
 Relationship between Raw and Central moments –
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Decision Tree
ML | Linear Regression
ML | Underfitting and Overfitting
Python | Decision tree implementation
Decision Tree Introduction with example
Adding new column to existing DataFrame in Pandas
Read JSON file using Python
Python map() function
Python Dictionary
Taking input in Python
Explain difference between == and is operator in Python.

== operator compares the operands by checking the equality of values of objects.
is operator compares the operands by checking the objects to be the same or not.
Following is the program in Python to showcase the difference.
 Live Demo
list1 = [1]
list2 = [1]
list3 = list1

print(id(list1))
print(id(list2))

if (list1 == list2):
   print("True")
else:
   print("False")

if (list1 is list2):
   print("True")
else:
   print("False")

if (list1 is list3):
   print("True")
else:
   print("False")
140380664377096
140380664376904
True
False
True
How to access elements from an array in C#?

First, define and initalize an array −
int[] p = new int[3] {99, 92, 95};
Now, display the array elements −
for (j = 0; j < 3; j++ ) {
   Console.WriteLine("Price of Product[{0}] = {1}", j, p[j]);
}
To acess any element, just include the index of the element you want like this −
p[2];
The above is to acess the 3rd element.
Now let us see the complete code −
using System;

namespace Program {
   class Demo {
      static void Main(string[] args) {
         int[] p = new int[3] {99, 92, 95};
         int j;

         for (j = 0; j < 3; j++ ) {
            Console.WriteLine("Price of Product[{0}] = {1}", j, p[j]);
         }

         // access
         int e = p[2];
         Console.WriteLine("Product 3rd price: "+e);

         Console.ReadKey();
      }
   }
}
Array.LastIndexOf() Method in C#

The Array.LastIndexOf() method in C# is used to search for the specified object and returns the index of the last occurrence within the entire one-dimensional Array.
public static int LastIndexOf (Array arr, object val);
Above, arr is the one-dimensional Array to search, whereas val is the object to locate in arr.
 Live Demo
using System;
public class Demo {
   public static void Main() {
      string[] strArr = {"John", "Tim", "Fedric", "Gary", "Harry", "Damien", "David", "Harry"};
      Array.Sort(strArr);
      Console.WriteLine("Array elements...");
      foreach(string s in strArr) {
         Console.WriteLine(s);
      }
      Console.Write("Element Gary is at index = " + Array.BinarySearch(strArr, "Gary"));
      Console.Write("\nElement Tom is at index = " + Array.BinarySearch(strArr, "Tom"));
      Console.Write("\nLast index of element Harry = " + Array.LastIndexOf(strArr, "Harry"));
   }
}
Array elements...
Damien
David
Fedric
Gary
Harry
Harry
John
Tim
Element Gary is at index = 3
Element Tom is at index = -9
Last index of element Harry = 5
 Live Demo
using System;
public class Demo {
   public static void Main() {
      int[] intArr = {5, 10, 15, 20, 15, 25, 30};
      Array.Sort(intArr);
      Console.WriteLine("Array elements...");
      foreach(int i in intArr) {
         Console.WriteLine(i);
      }
      Console.Write("Element 25 is at index = " + Array.BinarySearch(intArr, 20));
      Console.Write("\nLast index of element 15 = " + Array.LastIndexOf(intArr, 15));
      Console.Write("\nLast index of element 50 = " + Array.LastIndexOf(intArr, 50));
   }
}
Array elements...
5
10
15
15
20
25
30
Element 25 is at index = 4
Last index of element 15 = 3
Last index of element 50 = -1
Print the pattern | Practice | GeeksforGeeks

Write a program that receives a number n as input and prints it in the following format as shown below.
Like for n = 2 the pattern will be:
1*2*5*6
--3*4
Example 1:
Input: n = 3
Output: 
1*2*3*10*11*12
--4*5*8*9
----6*7
Explaination: If the pattern shown in question 
is followed, this will be the output.
Your Task:
You do not need to read input or print anything. Your task is to complete the function pattern() which takes n as input parameter and returns a list of string where each string denotes a new line of the pattern.
Expected Time Complexity: O(n2)
Expected Auxiliary Space: O(n2)
Constraints:
1 ≤ n ≤ 70  
0
Annanya Mathur1 year ago
Annanya Mathur
https://ide.geeksforgeeks.o...
0
Annanya Mathur1 year ago
Annanya Mathur
vector<string> pattern(int n){
   int a=1;        int p=0;        int b=n*n+1;        vector<string>v;        for(int i=n-1;i>=0;i--)        { string r="";            for(int j=n-1;j>i;j--)           r+="--";           for(int k=0;k<=i;k++)           {               r+=to_string(a);               r+="*";               a++;           }           for(int j=0;j<=i;j++)           {               r+=to_string(b);               if(j<i) r+="*" ;="" b++;="" }="" b="b-(i)*2-1;" v.push_back(r);="" }="" return="" v;="" }="">
0
Qulzhe song
This comment was deleted.
0
ultrainstinct2 years ago
ultrainstinct
Python solution:
https://ide.geeksforgeeks.o...
0
Abhishek Kumar Gupta2 years ago
Abhishek Kumar Gupta
https://ide.geeksforgeeks.o...Raw looping logicIs it fine, or we can tune it further?Time:0.14
0
Mrigank Singh3 years ago
Mrigank Singh
Solution:https://practice.geeksforge...
0
Subhajit3 years ago
Subhajit
Here is the most optimal solution
https://ide.geeksforgeeks.o...
0
vishwasjha174 years ago
vishwasjha17
need help visit this# i codehttps://ide.geeksforgeeks.o...
0
vishwasjha17
This comment was deleted.
0
Llc5 years ago
Llc
It seems that some test cases inputs are not as specified in statement (missing testcases number)
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.
ISRO | ISRO CS 2016 | Question 49 - GeeksforGeeks

27 Mar, 2018
Consider the join of a relation R , with a relation S . If R has m number of tuples and S has n number of tuples then the maximum and minimum sizes of the join respectively are:(A) m + n & 0(B) mn & 0(C) m + n & | m – n |(D) mn & m + nAnswer: (B)Explanation: Consider the folloewing examples:
Case 1: Maximum tuples- When the common attribute contain identical values
Relation R               Relation S              R ⋈ S
a       b                a       d            a     b    d
1       2                1       10           1     2    10   
1       3                1       11           1     2    11
1       4                                     1     3    10
                                              1     3    11
                                              1     4    10
                                              1     4    11
Case 2 : Minimum Tuples- When Both the relations have a common attribute but no tuple in both relations match.
Relation R               Relation S              R ⋈ S
a       b                a       d            a     b    d
1       2                2       10             No tuple  
1       3                3       11           
1       4  
So, option (B) is correct.Quiz of this QuestionPlease comment below if you find anything wrong in the above post
ISRO
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ISRO | ISRO CS 2009 | Question 30
ISRO | ISRO CS 2015 | Question 51
ISRO | ISRO CS 2013 | Question 8
ISRO | ISRO CS 2013 | Question 7
ISRO | ISRO CS 2013 | Question 22
ISRO | ISRO CS 2014 | Question 31
ISRO | ISRO CS 2013 | Question 31
ISRO | ISRO CS 2017 - May | Question 21
ISRO | ISRO CS 2017 | Question 42
ISRO | ISRO CS 2017 | Question 57
Algorithms | Recursion | Question 2 - GeeksforGeeks

28 Jun, 2021
Consider the following recursive function fun(x, y). What is the value of fun(4, 3)
int fun(int x, int y) {  if (x == 0)    return y;  return fun(x - 1,  x + y);} 
(A) 13(B) 12(C) 9(D) 10Answer: (A)Explanation: The function fun() calculates and returns ((1 + 2 ... + x-1 + x) +y) which is x(x+1)/2 + y.Quiz of this Question
Algorithms-Recursion
Algorithms Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithms | Dynamic Programming | Question 2
Algorithms | Dynamic Programming | Question 3
Algorithms | Sorting | Question 1
Algorithms | Analysis of Algorithms | Question 17
Algorithms | Greedy Algorithms | Question 1
Algorithms Quiz | Dynamic Programming | Question 8
Algorithms | Analysis of Algorithms | Question 8
Algorithms | Divide and Conquer | Question 6
Algorithms | Graph Traversals | Question 12
Algorithms | Sorting | Question 23
Function call by reference in Objective-C

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.
To pass the value by reference, argument pointers are passed to the functions just like any other value. So accordingly, you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.
/* function definition to swap the values */
- (void)swap:(int *)num1 andNum2:(int *)num2 {
   int temp;

   temp = *num1;  /* save the value of num1 */
   *num1 = *num2; /* put num2 into num1 */
   *num2 = temp;  /* put temp into num2 */
  
   return;
}
To check more details about Objective-C - Pointers, you can check Objective-C - Pointers chapter.
For now, let us call the function swap() by passing values by reference as in the following example −
#import <Foundation/Foundation.h>

@interface SampleClass:NSObject
/* method declaration */
- (void)swap:(int *)num1 andNum2:(int *)num2;
@end

@implementation SampleClass

- (void)swap:(int *)num1 andNum2:(int *)num2 {
   int temp;

   temp = *num1;     /* save the value of num1 */
   *num1 = *num2;    /* put num2 into num1 */
   *num2 = temp;     /* put temp into num2 */
  
   return;
   
}

@end

int main () {
   
   /* local variable definition */
   int a = 100;
   int b = 200;
   
   SampleClass *sampleClass = [[SampleClass alloc]init];

   NSLog(@"Before swap, value of a : %d\n", a );
   NSLog(@"Before swap, value of b : %d\n", b );
 
   /* calling a function to swap the values */
   [sampleClass swap:&a andNum2:&b];
 
   NSLog(@"After swap, value of a : %d\n", a );
   NSLog(@"After swap, value of b : %d\n", b );
 
   return 0;
}
Let us compile and execute it, it will produce the following result −
2013-09-09 12:27:17.716 demo[6721] Before swap, value of a : 100
2013-09-09 12:27:17.716 demo[6721] Before swap, value of b : 200
2013-09-09 12:27:17.716 demo[6721] After swap, value of a : 200
2013-09-09 12:27:17.716 demo[6721] After swap, value of b : 100

Which shows that the change has reflected outside of the function as well unlike call by value where changes does not reflect outside of the function.

    18 Lectures 
     1 hours 

 PARTHA MAJUMDAR

    6 Lectures 
     25 mins

 Ken Burke
 Print
 Add Notes
 Bookmark this page
How to check if a python module exists without importing it?

To check if you can import something in Python 2, you can use imp module with try...except. For example,
import imp
try:
    imp.find_module('eggs')
    found = True
except ImportError:
    found = False
print found
This will give you the output:
False
You can also use iter_modules from the pkgutil module to iterate over all modules to find if specified module exists. For example,
from pkgutil import iter_modules
def module_exists(module_name):
    return module_name in (name for loader, name, ispkg in iter_modules())
print module_exists('scrapy')
This will give the output:
True
This is because this module is installed on my PC.
Or if you just want to check it in the shell, you could use,
python -c "help('modules');" | grep yourmodule
How to select a random element from a C# list?

Firstly, set a list in C#.
var list = new List<string>{ "one","two","three","four"};
Now get the count of the elements and display randomly.
int index = random.Next(list.Count);
Console.WriteLine(list[index]);
To select a random element from a list in C#, try to run the following code −
 Live Demo
using System;
using System.Collections.Generic;
namespace Demo {
   class Program {
      static void Main(string[] args) {
         var random = new Random();
         var list = new List<string>{ "one","two","three","four"};
         int index = random.Next(list.Count);
         Console.WriteLine(list[index]);
      }
   }
}
three
Style select options with CSS

To style the options in <select>, you can try to run the following code,
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         select {
            width: 100%;
            padding: 10px 15px;
            border: 1px dashed blue;
            border-radius: 4px;
            background-color: orange;
         }
      </style>
   </head>
   <body>
      <p>Learn,</p>
      <form>
         <select id = "country" name = "country">
            <option value = "java">Java</option>
            <option value = "ruby">Ruby</option>
            <option value = "oracle">Oracle</option>
            <option value = "tableau">Tableau</option>
         </select>
      </form>
   </body>
</html>
Tryit Editor v3.7

Tryit: HTML header element
\mathord - Tex Command

\mathord - forces the argument to be treated in the 'ordinary' class.
{ \mathord #1}
\mathord command is used to force the argument to be treated in the 'ordinary' class.

a+b+c

a+b+c


a\mathord{+}b\mathord{+}c

a+b+c


1,234,567

1,234,567


1\mathord{,}234{,}567

1,234,567



a+b+c

a+b+c


a+b+c
a\mathord{+}b\mathord{+}c

a+b+c


a\mathord{+}b\mathord{+}c
1,234,567

1,234,567


1,234,567
1\mathord{,}234{,}567

1,234,567


1\mathord{,}234{,}567

    14 Lectures 
     52 mins

 Ashraf Said

    11 Lectures 
     1 hours 

 Ashraf Said

    9 Lectures 
     1 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    29 Lectures 
     2.5 hours 

 Mohammad Nauman

    14 Lectures 
     1 hours 

 Daniel Stern

    15 Lectures 
     47 mins

 Nishant Kumar
 Print
 Add Notes
 Bookmark this page
Java for Keyword

❮ Java Keywords

Print the numbers 0 to 4:
for (int i = 0; i < 5; i++) {
  System.out.println(i);
}


Try it Yourself »

The for loop loops through a block of code a number of times.
From the example above:
Statement 1 sets a variable before the loop starts (int i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 
5). If the condition is true, the loop will start over again, if it is false, 
the loop will end.
Statement 3 increases a value (i++) each time the code block in the loop has 
been executed.
There is also a "for-each" loop, which is used exclusively to loop through elements in an array:
The following example outputs all elements in the cars 
array, using a "for-each" loop:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}


Try it Yourself »

Read more about for loops in our Java For Loop Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
Tweedie Loss Function. A loss function for data with massive... | by Wenbo Shi | Towards Data Science

Nowadays, it is not uncommon to observe data with right-skewed distribution and long tail, e.g., data from e-commerce website, Ads click & purchase, insurance claim, etc.
Under this circumstance, prediction models may not be well trained if loss functions for other distributions (e.g., MSE for Gaussian distributions) are used. In this article, we introduce a method using Tweedie-based loss function for models trained on this type of right-skewed data with long tail.
Tweedie distribution is a special case of exponential dispersion models (EDM) with a power parameter p, which characterizes the power relation between distribution mean and variance as follow
where μ and φ are mean and dispersion parameter, respectively.
Power parameter p determines the sub-class of distributions within the family. For instance, p=1 links to Poisson distribution, p=3 links to inverse Gaussian distribution, and the focus of this article, p∈ (1, 2) links to compound Poisson-gamma distribution.
Given that it is a compound distribution, a random variable X ~ Tw(p, μ, φ) can be characterized as
The probability density function (pdf) of x is
where α(x, φ, p) is a normalizing constant that ensures this is a valid pdf.
To convert Tweedie distribution to a loss function, we need to maximize the likelihood of sample data through model training. A common way to do this is through the negative log-likelihood
If we use distribution mean μ as an estimator (i.e., prediction), then the loss function becomes
Given a pre-defined power parameter p (a hyper-parameter), Tweedie loss function can be used in various gradient-based models, such as gradient-boosting tree, neural network, etc. An example of implementation is given below.
import tensorflow as tfdef tweedie_loss_func(p):    def tweedie_loglikelihood(y, y_hat):        loss = - y * tf.pow(y_hat, 1 - p) / (1 - p) + \               tf.pow(y_hat, 2 - p) / (2 - p)        return tf.reduce_mean(loss)return tweedie_loglikelihood
He Zhou, Yi Yang, Wei Qian. “Tweedie Gradient Boosting for Extremely Unbalanced Zero-inflated Data.” 2019.
Aritra Halder, Shariq Mohammed, Kun Chen, Dipak Dey. “Spatial risk estimation in Tweedie compound Poisson double generalized linear models.” 2020.
MySQL Tryit Editor v1.0

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
​
        
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, and Opera.
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
Python Bokeh - Plotting Squares on a Graph - GeeksforGeeks

10 Jul, 2020
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity.
Bokeh can be used to plot squares on a graph. Plotting squares on a graph can be done using the square() method of the plotting module.
Syntax : square(parameters)
Parameters :
x : x-coordinates of the center of the square
y : y-coordinates of the center of the square
Returns : an object of class GlyphRenderer
Example 1 : In this example we will be using the default values for plotting the graph.
# importing the modulesfrom bokeh.plotting import figure, output_file, show        # file to save the modeloutput_file("gfg.html")        # instantiating the figure objectgraph = figure(title = "Bokeh Square Graph")      # the points to be plottedx = 0y = 0     # plotting the graphgraph.square(x, y)      # displaying the modelshow(graph)
Output :
Example 2 : In this example we will be plotting the multiple squares with various other parameters
# importing the modules from bokeh.plotting import figure, output_file, show   # file to save the model output_file("gfg.html")        # instantiating the figure object graph = figure(title = "Bokeh Square Graph",               match_aspect = True)   # name of the x-axis graph.xaxis.axis_label = "x-axis"       # name of the y-axis graph.yaxis.axis_label = "y-axis"  # points to be plottedx = [3, 3, 5]y = [3, 3, 3]size = [130, 100, 60]  # color value of the squarecolor = ["yellow", "red", "purple"]  # fill alpha value of the squarefill_alpha = [0.9, 0.7, 0.5]  # plotting the graph graph.square(x, y,             size = size,             color = color,             fill_alpha = fill_alpha)        # displaying the model show(graph)
Output :
Data Visualization
Python Bokeh-plotting-figure-class
Python-Bokeh
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()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
Change the font size of a button with CSS

To change the font size of a button, use the font-size property.
You can try to run the following code to change the font size
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         .button {
            background-color: yellow;
            color: black;
            text-align: center;
            font-size: 15px;
         }
      </style>
   </head>
   <body>
      <h2>Result</h2>
      <p>Click below for result:</p>
      <button class = "button">Result</button>
   </body>
</html>