code-rag-bench/online-tutorials huggingface dataset:
Ext.js - Table Layout

As the name implies, this layout arranges the components in a container in the HTML table format.
Following is a simple syntax to use the Table layout.
layout: 'table' 

Following is a simple example showing the usage of Table layout.
<!DOCTYPE html>
<html>
   <head>
      <link href = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/classic/theme-classic/resources/theme-classic-all.css" 
         rel = "stylesheet" />
      <script type = "text/javascript" 
         src = "https://cdnjs.cloudflare.com/ajax/libs/extjs/6.0.0/ext-all.js"></script>
      
      <script type = "text/javascript">
         Ext.onReady(function() {
            Ext.create('Ext.container.Container', {
               renderTo : Ext.getBody(),
               layout : {
                  type :'table',
                  columns : 3,
                  tableAttrs: {
                     style: {
                        width: '100%'
                     }
                  }               
               },
               width:600,
               height:200,
               
               items : [{
                  title : 'Panel1',
                  html : 'This panel has colspan = 2',
                  colspan :2
               },{
                  title : 'Panel2',
                  html : 'This panel has rowspan = 2',
                  rowspan: 2
               },{
                  title : 'Panel3',
                  html : 'This  s panel 3'
               },{
                  title : 'Panel4',
                  html : 'This is panel 4'
               },{
                  title : 'Panel5',
                  html : 'This is panel 5'
               }]
            });
         });
      </script>
   </head>
   
   <body>
   </body>
</html>
The above program will produce the following result −
 Print
 Add Notes
 Bookmark this page
Find a document with ObjectID in MongoDB?

To find a document with Objectid in MongoDB, use the following syntax −
db.yourCollectionName.find({"_id":ObjectId("yourObjectIdValue")}).pretty();
To understand the above syntax, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Larry"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c90e4384afe5c1d2279d69b")
}
> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Mike","UserAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c90e4444afe5c1d2279d69c")
}

> db.findDocumentWithObjectIdDemo.insertOne({"UserName":"Carol","UserAge":26,"UserHobby":["Learning","Photography"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c90e4704afe5c1d2279d69d")
}
Display all documents from a collection with the help of find() method. The query is as follows −
> db.findDocumentWithObjectIdDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c90e4384afe5c1d2279d69b"), "UserName" : "Larry" }
{
   "_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
   "UserName" : "Mike",
   "UserAge" : 23
}
{
   "_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
   "UserName" : "Carol",
   "UserAge" : 26,
   "UserHobby" : [
      "Learning",
      "Photography"
   ]
}
Case 1 − Here is the query to find a document with ObjectId in MongoDB.
> db.findDocumentWithObjectIdDemo.find({"_id":ObjectId("5c90e4704afe5c1d2279d69d")}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c90e4704afe5c1d2279d69d"),
   "UserName" : "Carol",
   "UserAge" : 26,
   "UserHobby" : [
      "Learning",
      "Photography"
   ]
}
Case 2 − Here is the query to find another document with ObjectId in MongoDB.
The query is as follows −
> db.findDocumentWithObjectIdDemo.find({"_id": ObjectId("5c90e4444afe5c1d2279d69c")}).pretty();
The following is the output −
{
   "_id" : ObjectId("5c90e4444afe5c1d2279d69c"),
   "UserName" : "Mike",
   "UserAge" : 23
}
DecimalFormat("00E00") in Java

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers.
Let us set DecimalFormat("00E00") first.
Format f = new DecimalFormat("00E00");
Now, we will format a number and display the result in a string using the format() method −
String res = f.format(-5977.3427);
Since, we have used both Format and DecimalFormat class in Java, therefore importing the following packages in a must −
import java.text.DecimalFormat;
import java.text.Format;
The following the complete example −
 Live Demo
import java.text.DecimalFormat;
import java.text.Format;
public class Demo {
   public static void main(String[] argv) throws Exception {
      Format f = new DecimalFormat("00E00");
      String res = f.format(-5977.3427);
      System.out.println(res);
   }
}
-60E02
How can I get a random number in Kotlin?

Kotlin provides multiple ways to generate a random number. In this article, we will see different ways to generate a random number and access it throughout the program.
Random() is an abstract class which generates random numbers with the given conditions. It can be accessed after importing Kotlin.random.Random.
As per the Kotlin documentation, the companion object Random.Default is the default instance of Random class. In the following example, we will generate a list of random values with int (1-30) .
import kotlin.random.Random

fun main() {
   val myRandomValues = List(5) { Random.nextInt(0, 30) }

   // Prints a new sequence every time
   println(myRandomValues)

}
It generated the following random numbers. You may get a different set of numbers, as the output is random in nature.
[8, 21, 16, 29, 16]

Kotlin does provide a random() function to generate random numbers. It takes a series of numbers as an input and it returns a random Int as an output.
fun main() {
   // It generates a random number between 0 to 10
   println((0..10).random())
}
On execution, it produced the following output −
0

Kotlin does provide another method to generate random numbers between a sequence. We can use shuffled() to generate a random number in between 1 to 100.
fun main() {
   val random1 = (0..100).shuffled().last()
   println(random1)
}
On execution, it produced the following output. It could be different in your case, as the output is random in nature.
42
JSTL - Core <fmt:message> Tag

The <fmt:message> tag maps key to localized message and performs parametric replacement.
The <fmt:message> tag has the following attributes −
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/fmt" prefix = "fmt" %>

<html>
   <head>
      <title>JSTL fmt:message Tag</title>
   </head>

   <body>
      <fmt:setLocale value = "en"/>
      <fmt:setBundle basename = "com.tutorialspoint.Example" var = "lang"/>

      <fmt:message key = "count.one" bundle = "${lang}"/><br/>
      <fmt:message key = "count.two" bundle = "${lang}"/><br/>
      <fmt:message key = "count.three" bundle = "${lang}"/><br/>

   </body>
</html>
You will receive the following result −
One 
Two 
Three


    108 Lectures 
     11 hours 

 Chaand Sheikh

    517 Lectures 
     57 hours 

 Chaand Sheikh

    41 Lectures 
     4.5 hours 

 Karthikeya T

    42 Lectures 
     5.5 hours 

 TELCOMA Global

    15 Lectures 
     3 hours 

 TELCOMA Global

    44 Lectures 
     15 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to display full-screen mode on Tkinter?

Tkinter displays the application window by its default size. However, we can display a full-screen window by using attributes('fullscreen', True) method. The method is generally used for assigning a tkinter window with properties like transparentcolor, alpha, disabled, fullscreen, toolwindow, and topmost.
#Import the tkinter library
from tkinter import *

#Create an instance of tkinter frame
win = Tk()

#Set the geometry
win.geometry("650x250")

#Add a text label and add the font property to it
label= Label(win, text= "Hello World!", font=('Times New Roman bold',20))
label.pack(padx=10, pady=10)

#Create a fullscreen window
win.attributes('-fullscreen', True)

win.mainloop()
Running the above code will display a full-screen window that can be closed by pressing the Alt+ F4 key.
What can cause a Cannot find symbol error in java?

Whenever you need to use external classes/interfaces (either user defined or, built-in) in the current program you need to import those classes in your current program using the import keyword.
But, while importing any class −
If the path of the class/interface you are importing is not available to JVM.
If the path of the class/interface you are importing is not available to JVM.
If the absolute class name you have mentioned at the import statement is not accurate (including packages and class name).
If the absolute class name you have mentioned at the import statement is not accurate (including packages and class name).
If you have imported the class/interface used.
If you have imported the class/interface used.
You will get an exception saying “Cannot find symbol ......”
In the following example we are trying to read a string value representing the name of the user from key-board (System.in). For this we are using the scanner class of the Java.Util Package.
public class ReadingdData {
   public static void main(String args[]) {
      System.out.println("Enter your name: ");
      Scanner sc = new Scanner(System.in);
      String name = sc.next();
      System.out.println("Hello "+name);
   }
}
Since we are using a class named Scanner in our program and haven’t imported it in our program. On executing, this program generates the following compile time error −
ReadingdData.java:6: error: cannot find symbol
      Scanner sc = new Scanner(System.in);
      ^
   symbol: class Scanner
   location: class ReadingdData
ReadingdData.java:6: error: cannot find symbol
      Scanner sc = new Scanner(System.in);
      ^
   symbol: class Scanner
   location: class ReadingdData
2 errors
You need to set class path for the JAR file holding the required class interface.
You need to set class path for the JAR file holding the required class interface.
Import the required class from the package using the import keyword. While importing you need to specify the absolute name (including the packages and sub packages) of the required class.
Import the required class from the package using the import keyword. While importing you need to specify the absolute name (including the packages and sub packages) of the required class.
 Live Demo
import java.util.Scanner;
public class ReadingdData {
   public static void main(String args[]) {
      System.out.println("Enter your name: ");
      Scanner sc = new Scanner(System.in);
      String name = sc.next();
      System.out.println("Hello "+name);
   }
}
Enter your name:
krishna
Hello krishna
AWT AdjustmentEvent Class

The Class AdjustmentEvent represents adjustment event emitted by Adjustable objects.
Following is the declaration for java.awt.event.AdjustmentEvent class:
public class AdjustmentEvent
   extends AWTEvent
Following are the fields for java.awt.Component class:
static int ADJUSTMENT_FIRST  -- Marks the first integer id for the range of adjustment event ids.
static int ADJUSTMENT_FIRST  -- Marks the first integer id for the range of adjustment event ids.
static int ADJUSTMENT_LAST  -- Marks the last integer id for the range of adjustment event ids.
static int ADJUSTMENT_LAST  -- Marks the last integer id for the range of adjustment event ids.
static int ADJUSTMENT_VALUE_CHANGED  -- The adjustment value changed event.
static int ADJUSTMENT_VALUE_CHANGED  -- The adjustment value changed event.
static int BLOCK_DECREMENT  -- The block decrement adjustment type.
static int BLOCK_DECREMENT  -- The block decrement adjustment type.
static int BLOCK_INCREMENT  -- The block increment adjustment type.
static int BLOCK_INCREMENT  -- The block increment adjustment type.
static int TRACK  -- The absolute tracking adjustment type.
static int TRACK  -- The absolute tracking adjustment type.
static int UNIT_DECREMENT  -- The unit decrement adjustment type.
static int UNIT_DECREMENT  -- The unit decrement adjustment type.
static int UNIT_INCREMENT  -- The unit increment adjustment type.
static int UNIT_INCREMENT  -- The unit increment adjustment type.
AdjustmentEvent(Adjustable source, int id, int type, int value)  

Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.
AdjustmentEvent(Adjustable source, int id, int type, int value, boolean isAdjusting)  

Constructs an AdjustmentEvent object with the specified Adjustable source, event type, adjustment type, and value.
Adjustable getAdjustable()  
Returns the Adjustable object where this event originated.
int getAdjustmentType()  
Returns the type of adjustment which caused the value changed event.
int getValue()  
Returns the current value in the adjustment event.
boolean getValueIsAdjusting()  
Returns true if this is one of multiple adjustment events.
String	paramString()  
Returns a string representing the state of this Event.
This interface inherits methods from the following classes:
java.awt.AWTEvent
java.awt.AWTEvent
java.util.EventObject
java.util.EventObject
java.lang.Object
java.lang.Object

    13 Lectures 
     2 hours 

 EduOLC
 Print
 Add Notes
 Bookmark this page
Insert string at specified position in PHP - GeeksforGeeks

18 Oct, 2018
Given a sentence, a string and the position, the task is to insert the given string at the specified position. We will start counting the position form zero. See the examples below.
Input : sentence = ‘I am happy today.’string = ‘very’position = 4Output :I amvery happy today.Begin counting with 0. Start counting from the very first character till we reachthe given position in the given sentence.Spaces will also be counted and then insert the given string at the specified position.
Input : sentence = ‘I am happy today.’string = ‘ very’position = 4Output : I am very happy today.
The idea is to use substr_replace()
<?php$sentence = 'I am happy today.';$string = 'very ';$position = '5';  echo substr_replace( $sentence, $string, $position, 0 );?>
I am very happy today.

PHP-string
Picked
Technical Scripter 2018
PHP
Technical Scripter
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to check whether an array is empty using PHP?
How to receive JSON POST with PHP ?
Comparing two dates in PHP
PHP | Converting string to Date and DateTime
Download file from URL using PHP
How to fetch data from localserver database and display on HTML table using PHP ?
Split a comma delimited string into an array in PHP
How to run JavaScript from PHP?
Program to find Final Prices With a Special Discount in a Shop in Python

Suppose we have an array called prices where prices[i] represents price of the ith item in a shop. There is a special offer going on, if we buy the ith item, then we will get a discount equivalent to prices[j] where j is the minimum index such that j > i and price of jth item is less or same as price of ith item (i.e. prices[j] <= prices[i]), otherwise, we will not receive any discount at all. We have to find an array where the ith element is the final price that we will pay for the ith item of the shop considering the special discount.
So, if the input is like prices = [16,8,12,4,6], then the output will be [8, 4, 8, 4, 6], as price of item0 is 16, so we will get a discount equivalent to prices[1]=8, then, the final price will be 8 - 4 = 4. For item1 the price[1] is 8 we will receive a discount equivalent to prices[3]=2, so, the final price we will pay is 8 - 4 = 4. For item 2 with price[2] is 12 and we will get a discount value same as prices[3] = 4, therefore, the final price we will pay is 12 - 4 = 8. And for items 3 and 4 we will not receive any discount.
To solve this, we will follow these steps −
for i in range 0 to size of prices, dofor j in range i+1 to size of prices, doif prices[i] >= prices[j], thenprices[i] := prices[i] - prices[j]come out from the loopotherwise,j := j + 1
for i in range 0 to size of prices, do
for j in range i+1 to size of prices, doif prices[i] >= prices[j], thenprices[i] := prices[i] - prices[j]come out from the loopotherwise,j := j + 1
for j in range i+1 to size of prices, do
if prices[i] >= prices[j], thenprices[i] := prices[i] - prices[j]come out from the loop
if prices[i] >= prices[j], then
prices[i] := prices[i] - prices[j]
prices[i] := prices[i] - prices[j]
come out from the loop
come out from the loop
otherwise,j := j + 1
otherwise,
j := j + 1
j := j + 1
return prices
return prices
Let us see the following implementation to get better understanding −
 Live Demo
def solve(prices):
   for i in range(len(prices)):
      for j in range(i+1,len(prices)):
         if(prices[i]>=prices[j]):
            prices[i]-=prices[j]
            break
         else:
            j+=1
   return prices

prices = [16,8,12,4,6]
print(solve(prices))
[16,8,12,4,6]
[8, 4, 8, 4, 6]
Collectors toSet() method in Java 8

The toSet() method of the Collectors class in Java returns a Collector that accumulates the input elements into a new Set.
The syntax is as follows
static <T> Collector<T,?,Set<T>> toSet()
Here, the parameter,
T - Type of the input elements.
Set - A collection that contains no duplicate elements.
To work with Collectors class in Java, import the following package
import java.util.stream.Collectors;
The following is an example to implement toSet() method in Java
 Live Demo
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("This", "is", "it");
      Set<String> set = stream.collect(Collectors.toSet());
      System.out.println(set);
   }
}
[This, is, it]
nproc Command in Linux with Examples

30 Jun, 2020
nproc is a simple Unix command which is used to print the number of processing units available in the system or to the current process. This command could be used in system diagnostics and related purposes. It is part of GNU Core utils, so it comes pre-installed with all modern Linux operating systems.Syntax:
nproc [OPTION]...
1. Use nproc command
nproc
It prints the number of processing units available to the current process. It may be less than the number of online processors.
2. To print total installed processing units
nproc --all
We use the “–all” option when we want nproc to display the total installed processing units.
3. To exclude some processing units
nproc --ignore=4
We use “–ignore” option when we want nproc to exclude a set number of processing units.
4. To display the help section
nproc --help
This command will display the help section of the nproc command which will have all the information related to the nproc command.
5. To display version
nproc --version
This command will display the version of nproc command in Linux.
6. To display nproc manual
man nproc
This command will print the manual of the nproc command.
linux
linux-command
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
Introduction to Linux Operating System
chown command in Linux with Examples
How to Permanently Disable Swap in Linux?
SED command in Linux | Set 2
chmod command in Linux with examples
Basic Operators in Shell Scripting
Array Basics in Shell Scripting | Set 1
nohup Command in Linux with Examples
Equivalent of Java Static Methods in Kotlin

27 Dec, 2021
Prerequisite: static Keyword in Java
Static Keyword in Java is a non-access modifier. It is useful for representing meta-data (usually data related to a class). The static keyword serves for efficient memory management as in spite of recurring usages the Java Virtual Machine only once allocates memory for the variable, method, class or block declared as static. Static members are not related to instances being created but are owned by the class itself. In Kotlin however, we don’t have such keywords. So this functionality has to be achieved using some other ways. The most popular methods of implementing functionality similar to that of the static keyword are listed below:
Object expressions or Object declarations in Kotlin are used to create instances of an anonymous class. Using companion identifiers along with such object expressions or declarations facilitates members of the companion object to be called just by using the class name as the qualifier. When the matching class is loaded (resolved), a companion object is created that has the same semantics as a Java static initializer.
Kotlin
class GFG {      companion object{          fun getMetaData() : String {            return "Static Method of Class"        }      }}    fun main(args: Array<String>) {      // Calling method of companion object        println(GFG.getMetaData())}
Output:
Static Method of Class
In the case of Java, the method of companion object can be called but we need an additional ‘Companion’ field to be added before the function call after the class name. We can get rid of this too, by either giving our own name to the companion object or by using @JvmStatic annotation.
Adding @JvmStatic annotation simply before the members to be declared as the equivalent of static ones in Java works well in Kotlin to provide the same functionality.
Kotlin
object MyClass{   @JvmStatic   fun getMetaData(): String {      return "Static Method of the Class"   }}  fun main(args: Array<String>) {    println(GFG.getMetaData())}
Output:
Static Method of Class
An equivalent functionality as that of the static members and methods in Java can also be achieved by making that member, method, class, or block be a package-level member. This can be done by creating a .kt file and placing all such desired members into it without making any class inside. In this way, all these members will be compiled by the JVM as the static parts of the Kotlin class in which the package is being imported.
Kotlin File to achieve the functionality of static keyword:
Kotlin
package com.gfg.samplefun getMetaData() : String {    return "Static Method of Package"}
Main Kotlin File:
Kotlin
import com.gfg.sample  fun main(args: Array<String>) {    println(getMetaData())}
Output:
Static Method of Package
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
issuperset() in Python

05 Oct, 2021
Python set issuperset() method returns True if all elements of a set A occupies set B which is passed as an argument and returns false if all elements of B are not present in A. This means if A is a superset of B then it returns true; else False
A.issuperset(B)
checks whether A is a superset of B or not.
True if A is a superset of B; otherwise false.
Python
# Python program to demonstrate working of# issuperset(). A = {4, 1, 3, 5}B = {6, 0, 4, 1, 5, 0, 3, 5} print("A.issuperset(B) : ", A.issuperset(B)) # B is superset of Aprint("B.issuperset(A) : ", B.issuperset(A))
Output: 
A.issuperset(B) :  False
B.issuperset(A) :  True
Python
# Python program to demonstrate working# of issuperset(). A = {1, 2, 3}B = {1, 2, 3, 4, 5}C = {1, 2, 4, 5} print("A.issuperset(B) : ", A.issuperset(B))print("B.issuperset(A) : ", B.issuperset(A))print("A.issuperset(C) : ", A.issuperset(C))print("C.issuperset(B) : ", C.issuperset(B))
Output: 
A.issuperset(B) :  False
B.issuperset(A) :  True
A.issuperset(C) :  False
C.issuperset(B) :  False
kumar_satyam
python-set
Python
python-set
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to reverse a Numpy array?

This is a simple program wherein we have to reverse a numpy array. We will use numpy.flip() function for the same.
Step 1: Import numpy.
Step 2: Define a numpy array using numpy.array().
Step 3: Reverse the array using numpy.flip() function.
Step 4: Print the array.
import numpy as np

arr = np.array([10,20,30,40,50])
print("Original Array: \n", arr)

arr_reversed = np.flip(arr)
print("\nReversed Array: \n", arr_reversed)
Original Array:
[10 20 30 40 50]

Reversed Array:
[50 40 30 20 10]
How to compile unsafe code in C#?

For compiling unsafe code, you have to specify the /unsafe command-line switch with command-line compiler.
For example, to compile a program named one.cs containing unsafe code, from command line, give the command − 
csc /unsafe one.cs

Under Visual Studio IDE, enable use of unsafe code in the project properties. The following are the steps − 
Open Project properties by double clicking the properties node in the Solution Explorer.
Click on the “Build” tab.
Select the option "Allow unsafe code".
How to align the output using justificationsin C language?

By using justifications in printf statement we can arrange the data in any format.
Right Justification
To implement the right justification, insert a minus sign before the width value in the %s character.
printf("%-15s",text);
Let’s take an example to print data in row and column-wise with the help of justification.
 Live Demo
#include<stdio.h>
int main(){
   char a[20] = "Names", b[20]="amount to be paid";
   char a1[20] = "Bhanu", b1[20]="Hari",c1[20]="Lucky",d1[20]="Puppy";
   int a2=200,b2=400,c2=250,d2=460;
   printf("%-15s %-15s\n", a, b);
   printf("%-15s %-15d\n", a1,a2);
   printf("%-15s %-15d\n", b1,b2);
   printf("%-15s %-15d\n", c1, c2);
   printf("%-15s %-15d\n", d1, d2);
   return 0;
}
Names      amount to be paid
Bhanu      200
Hari       400
Lucky      250
Puppy      460
Consider the same example by changing the justification −
 Live Demo
#include<stdio.h>
int main(){
   char a[20] = "Names", b[20]="amount to be paid";
   char a1[20] = "Bhanu", b1[20]="Hari",c1[20]="Lucky",d1[20]="Puppy";
   int a2=200,b2=400,c2=250,d2=460;
   printf("%2s %2s\n", a, b);
   printf("%5s %5d\n", a1,a2);
   printf("%2s %2d\n", b1,b2);
   printf("%5s %5d\n", c1, c2);
   printf("%2s %2d\n", d1, d2);
   return 0;
}
Names      amount to be paid
Bhanu    200
Hari 400
Lucky    250
Puppy 460
Note: Alignment is note in proper if we not use correct justification
Python | Pandas dataframe.max()

19 Nov, 2018
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas dataframe.max() function returns the maximum of the values in the given object. If the input is a series, the method will return a scalar which will be the maximum of the values in the series. If the input is a dataframe, then the method will return a series with maximum of values over the specified axis in the dataframe. By default the axis is the index axis.
Syntax: DataFrame.max(axis=None, skipna=None, level=None, numeric_only=None, **kwargs)
Parameters :axis : {index (0), columns (1)}skipna : Exclude NA/null values when computing the resultlevel : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Seriesnumeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
Returns : max : Series or DataFrame (if level specified)
Example #1: Use max() function to find the maximum value over the index axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, 44, 1],                   "B":[5, 2, 54, 3, 2],                   "C":[20, 16, 7, 3, 8],                    "D":[14, 3, 17, 2, 6]})  # Print the dataframedf
Let’s use the dataframe.max() function to find the maximum value over the index axis
# Even if we do not specify axis = 0, # the method will return the max over# the index axis by defaultdf.max(axis = 0)
Output : Example #2: Use max() function on a dataframe which has Na values. Also find the maximum over the column axis.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.DataFrame({"A":[12, 4, 5, None, 1],                    "B":[7, 2, 54, 3, None],                   "C":[20, 16, 11, 3, 8],                   "D":[14, 3, None, 2, 6]})  # skip the Na values while finding the maximumdf.max(axis = 1, skipna = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program to find whether a no is power of two

19 Jul, 2021
Given a positive integer, write a function to find if it is a power of two or not.Examples :  
Input : n = 4
Output : Yes
22 = 4

Input : n = 7
Output : No

Input : n = 32
Output : Yes
25 = 32
1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2.  
C++
// C++ Program to find whether a// no is power of two#include <bits/stdc++.h>using namespace std; // Function to check if x is power of 2bool isPowerOfTwo(int n){    return (ceil(log2(n)) == floor(log2(n)));} // Driver programint main(){    isPowerOfTwo(31) ? cout << "Yes" << endl : cout << "No" << endl;    isPowerOfTwo(64) ? cout << "Yes" << endl : cout << "No" << endl;     return 0;} // This code is contributed by Surendra_Gangwar
No
Yes
 
Time Complexity: O(log2n)
Auxiliary Space: O(1)
2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2. Please see Count set bits in an integer for counting set bits.4. If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.For example for 4 ( 100) and 16(10000), we get following after subtracting 1 3 –> 011 15 –> 01111So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero. We can say n is a power of 2 or not based on value of n&(n-1). The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) (thanks to https://www.geeksforgeeks.org/program-to-find-whether-a-no-is-power-of-two/Mohammad for adding this case). Please refer complete article on Program to find whether a no is power of two for more details! 
souravmahato348
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Convert Float to digit list

29 Nov, 2019
Sometimes, while working with Python data, we can have a problem in which we need to convert a float number into a list of digits. This problem is common in day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + isdigit()The combination of above functions can be used to perform this task. In this, we first convert the float number to string and then iterate it converting each digit to integer and constructing the list using list comprehension.
# Python3 code to demonstrate working of# Convert Float to digit list# using  list comprehension + isdigit()  # initialize N N = 6.456  # printing N print("The floating number is : " + str(N))  # Convert Float to digit list# using  list comprehension + isdigit()res = [int(ele) for ele in str(N) if ele.isdigit()]      # printing resultprint("List of floating numbers is : " + str(res))
The floating number is : 6.456
List of floating numbers is : [6, 4, 5, 6]

 
Method #2 : Using map() + regex expression + findall()The combination of above functionalities can be used to perform this task. In this, we iterate through list using map() and extract and convert each element of float number using regex expression and findall().
# Python3 code to demonstrate working of# Convert Float to digit list# using map() + regex expression + findall()import re  # initialize N N = 6.456  # printing N print("The floating number is : " + str(N))  # Convert Float to digit list# using map() + regex expression + findall()res = list(map(int, re.findall('\d', str(N))))      # printing resultprint("List of floating numbers is : " + str(res))
The floating number is : 6.456
List of floating numbers is : [6, 4, 5, 6]

Python list-programs
Python
Python Programs
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()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
fromisoformat() Function Of Datetime.date Class In Python

23 Aug, 2021
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd.
Syntax: @classmethod fromisoformat(date_string)
Parameters: This function accepts a parameter which is illustrated below:
date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date object is going to be constructed.
Return values: This function returns a date object constructed from the specified ISO format date string.
Example 1: Getting a date object from a specified string that contains date in ISO format. i.e., yyyy-mm-dd
Python3
# Python3.7 code for Getting# a date object from a specified# string that contains date in# ISO format. i.e., yyyy-mm-dd  # Importing datetime moduleimport datetime  # Initializing a dateDate = "2012-10-12";  # Calling fromisoformat() function to# construct a datetime.date object New_date = datetime.date.fromisoformat(Date);  # Printing the new constructed date objectprint("The constructed date object is: %s"%New_date);
Output:
The constructed date object is: 2012-10-12
Example 2: Get the newly created date object for the specified date.
Python3
# Python3.7 code for Getting# a date object from a specified# string that contains date in# ISO format. i.e., yyyy-mm-dd  # Importing datetime modulefrom datetime import date  # Calling the fromisoformat() function# to Print the new created date object# for the specified date in# ISO format of 2020-10-09print(date.fromisoformat('2020-10-09'))
Output:
2020-10-09
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PHP | array_intersect() Function

08 Mar, 2018
This builtin function of PHP is used to compute the intersection of two or more arrays. The function is used to compare the values of two or more arrays and returns the matches. The function prints only those elements of the first array that are present in all other arrays.
Syntax:
array array_intersect($array1, $array2, $array3, $array4...)
Parameters: The array_intersect() function takes at least two arrays as arguments. It can take any number of arrays greater than or equal to two separated by commas (‘,’).
Return Type: The function returns another array containing the elements of the first array that are present in all other arrays passed as the parameter. If no element matches then, a NULL array is returned.
Note: The keys of elements are preserved. That is, the keys of elements in output array will be same as that of keys of those elements in the first array.
Examples:
Input : $array1 = array(5, 10, 15, 20, 25, 30)
        $array2 = array(20, 10, 15, 55, 110, 30)
        $array3 = array(10, 15, 30, 55, 100, 95)
Output :
        Array
        (
           [1] => 10
           [2] => 15
           [5] => 30
        )

Input : $array1 = array("ram", "laxman", "rishi", "ayush");
        $array2 = array("ayush", "gaurav", "rishi", "rohan");
        $array3 = array("rishi", "gaurav", "ayush", "ravi");
Output :
        Array
        (
           [2] => rishi
           [3] => ayush
        )

Below program illustrates the array_intersect() function in PHP:
<?php  // PHP function to illustrate the use of array_intersect()function Intersect($array1, $array2, $array3){    $result = array_intersect($array1, $array2, $array3);    return($result);}  $array1 = array(5, 10, 15, 20, 25, 30);$array2 = array(20, 10, 15, 55, 100, 110, 30);$array3 = array(10, 15, 30, 55, 100, 95);print_r(Intersect($array1, $array2, $array3));  ?>  
Output:
Array
(
    [1] => 10
    [2] => 15
    [5] => 30
)

Reference: http://php.net/manual/en/function.array-intersect.php
PHP-array
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to receive JSON POST with PHP ?
How to get parameters from a URL string in PHP?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Setup OpenCV With PyCharm Environment

01 Oct, 2020
If you love working on image processing and video analysis using python then you have come to the right place. Python is one of the key languages which is used to process videos and images.
32- or a 64-bit computer.
Windows, macOS or Linux.
Python 2.7, 3.4, 3.5 or 3.6.
PyCharm is a cross-platform IDE used in computer programming specifically for Python. The platform developed by JetBrains is mainly used in code analysis, graphical debugger etc... It supports web development with Django as well as Data Science with Anaconda.
OpenCV (Open Source Computer Vision) is a computer vision library that contains various functions to perform operations on pictures or videos. It was initially built by Intel but later managed by Willow Garag, presently it is managed by Itseez. It is a cross-platform library which available for programming languages apart from python.
1) Go to the terminal option at the bottom of the IDE window.
 
2) The pip (package manager) can also be used to download and install OpenCV. To install OpenCV, just type the following command:
Python3
pip install opencv-python
3) Now simply import OpenCV in your python program in which you want to use image processing functions.
To check if OpenCV is correctly installed, just run the following program in PyCharm to perform a version check:
Python3
import cv2print("GeeksForGeeks")print("Your OpenCV version is: " + cv2.__version__)
GeeksForGeeks
Your OpenCV version is: 4.4.0

Python-OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Setting python3 as Default in Linux

23 Jul, 2020
Python 2 support ended on 1-January-2020, and many major projects already signed the Python 3 Statement that declares that they will remove Python 2 support. However many of us prefer to code on python interpreter for tiny code snippets, instead of making .py files. And when we fire command ‘python’ on the terminal, interpreter of python2 gets launched by default.  
Which leaves us with no choice other than, explicitly typing python3. However, we can set python3 as default by firing two commands on terminal
echo "alias python='python3'" >> .bashrc
source .bashrc

Now if we check in the terminal by just running the “python” command it would result in the following:
The interpreter of python 3 was launched, rather than an interpreter of python2. We basically wrote a permanent alias in .bashrc, which replaces command python as python3 and we reloaded the .bashrc file.
Linux-Unix
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Program to Toss a Coin

Let’s say we have a coin and 10 chances. Here, we will first initialize the values for head, tail and chances −
int heads = 0;
int tails = 0;
int chances = 10;
Now, we will get the head and tail values using the Random object −
for (int i = 1; i<= chances; i++) {
   if (t.chanceFunc().equals("tails")) {
      tails++;
   } else {
      heads++;
   }
}
Above, the function chanceFunc() is having Random class with the nextInt() method to get the next random value. The condition is checked and the heads and tails values are returned −
public String chanceFunc() {
   Random r = new Random();
   int chance = r.nextInt(2);
   if (chance == 1) {
      return"tails";
   } else {
      return"heads";
   }
}
 Live Demo
import java.util.Random;
class Toss {
   public String chanceFunc() {
      Random r = new Random();
      int chance = r.nextInt(2);
      if (chance == 1) {
         return"tails";
      } else {
         return"heads";
      }
   }
}
public class Demo {
   public static void main(String[] args) {
      Toss t = new Toss();
      int heads = 0;
      int tails = 0;
      int chances = 10;
      for (int i = 1; i<= chances; i++) {
         if (t.chanceFunc().equals("tails")) {
            tails++;
         } else {
            heads++;
         }
      }
      System.out.println("Chances = " + chances);
      System.out.println("Heads: " + heads);
      System.out.println("Tails: " + tails);
   }
}
Chances = 10
Heads: 3
Tails: 7
Let us run the program again −
Chances = 10
Heads: 4
Tails: 6
Lower case to upper case | Practice | GeeksforGeeks

Given a string str containing only lowercase letters, generate a string with the same letters, but in uppercase.
Example 1:
Input:
str = "geeks"
Output: GEEKS
Example 2:
Input:
str = "geeksforgeeks"
Output: GEEKSFORGEEKS
Your Task:
You don't need to read input or print anything. Your task is to complete the function to_upper() which takes the string str as an argument and returns the resultant string.
Expected Time Complexity: O(length of the string).
Expected Auxiliary Space: O(1).
Constraints:
1 ≤ length of the string ≤ 50
0
visionsameer394 days ago
IN PYTHON
class Solution:   def to_upper(self, str):       return str.upper()
+1
mayank180919991 week ago
string to_upper(string str){
    //code
    for(int i=0;i<str.length();i++){
        if(islower(str[i])){
            str[i]=str[i]-32;
        }
    }
 return str;
}
0
avicode4243 weeks ago
class Solution {    String to_upper(String str)    {        // code here       String str1 = str.toUpperCase();       return str1;   }}
0
priyaranjandash1 month ago
class Solution {    String to_upper(String str)    {        return str.toUpperCase();   }} 
0
shivanshixa312 months ago
string to_upper(string str){
    //code
    for(int i=0;i<str.length();i++){
        str[i] -= 32;
    }
    return str;
}
0
vikkrammor2 months ago
String to_upper(String str)    {        return str.toUpperCase();   }
0
jaatgfg112 months ago
string to_upper(string str){   int n=str.length();   for(int i=0;i<n;i++){       str[i]=str[i]-32;   }   return str;   }
 
 
0
abythankachan3143 months ago
Python code
Time taken : 0.0
def to_upper(self,str):
     return str.upper()
0
mris127893 months ago
IN C++ LANGUAGE :
for(int i=0;str[i]!='\0';i++)           str[i]-=32;   return str;
0
shaktig1011013 months ago
package string;public class Greek {String to_Upper(String str){String st=str;         System.out.println(st.toUpperCase());return st;}public static void main(String[] args) {Greek obj=new Greek();obj.to_Upper("geeks");obj.to_Upper("geeksforgeeks");}} 
 
 
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.
Plotting grids across the subplots in Python Matplotlib

To plot grids across the subplots in Python Matplotlib, we can create multiple subplots and set the spine visibility false out of multiple axes.
Set the figure size and adjust the padding between and around the subplots.
Create a figure and a set of subplots using subplots() method.
Add a subplot to the current figure and set its spine visibility as false.
Turn off the a☓3 labels.
Share the X-axis accordingly.
Configure the grid lines for a☓1, a☓2 and a☓3.
To display the figure, use show() method.
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax3 = fig.add_subplot(111, zorder=-1)

for _, spine in ax3.spines.items():
   spine.set_visible(False)

ax3.tick_params(labelleft=False, labelbottom=False, left=False, right=False)
ax3.get_shared_x_axes().join(ax3, ax1)
ax3.grid(axis="x")

ax1.grid()
ax2.grid()

plt.show()
How to Fix: TypeError: cannot perform reduce with flexible type - GeeksforGeeks

28 Nov, 2021
In this article we will discuss TypeError: cannot perform reduce with flexible type and how can we fix it. This error may occur when we find the mean for a two-dimensional NumPy array which consists of data of multiple types.
Dataset in use:
Student ID
Student Name
Branch
Marks
101
Harry
CSE
87
102
Ron
ECE
88
103
Alexa
CSE
72
When we create this table using NumPy then this 2D Array consists of data with multiple types. In this, we had String and Integer datatypes. To find the mean value for any of the numeric columns like Marks, it throws TypeError, because it doesn’t know how to take mean when not all the values are numbers (i.e. Student Name, Branch consists data of type string).
Example: Error producing code
Python3
# import necessary packagesimport numpy as np  # create a 2D Arraystudents = np.array([['Student ID', 'Student Name', 'Branch', 'Marks'],                     [101, 'Hary', 'CSE', 87],                     [102, 'Ron', 'ECE', 88],                     [103, 'Alexa', 'CSE', 72]])  # mean of marks(3rd column)print(students[:, 3].mean())
Output:
To overcome this problem create a 2D array using Pandas DataFrame instead of NumPy. Since DataFrame has an index value for each row and name for each column, it helps the interpreter to distinguish between columns of different types.
This single alternative fixes the issue efficiently.
Example: Fixed code
Python3
# import necessary packagesimport pandas as pd  # create dataframestudents = pd.DataFrame({'student_ID': [101, 102, 103],                         'student_Name': ['Hary', 'Ron', 'Alexa'],                         'Branch': ['CSE', 'ECE', 'CSE'],                         'Marks': [87, 88, 72]})# Tableprint(students)  # mean values for all numeric columnsprint(students.mean())
Output:
Students Table and Mean Values Results
In the above example, dataframe mean value is generated for all columns with numeric type if the column name is not specified- student_ID and Marks columns are of type float. So it calculates the mean for those 2 columns and the rest of the columns are of type string. So it won’t calculate the mean value.
Picked
Python How-to-fix
Python-numpy
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 drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python