code-rag-bench/online-tutorials huggingface dataset:
Python Program to perform cross join in Pandas

10 Jul, 2020
In Pandas, there are parameters to perform left, right, inner or outer merge and join on two DataFrames or Series. However there’s no possibility as of now to perform a cross join to merge or join two methods using how="cross" parameter.
Cross Join :
Example 1:
The above example is proven as follows
# importing pandas moduleimport pandas as pd    # Define a dictionary with column Adata1 = {'A': [1, 2]}      # Define another dictionary with column Bdata2 = {'B': ['a', 'b', 'c']}     # Convert the dictionary into DataFrame  df = pd.DataFrame(data1, index =[0, 1])   # Convert the dictionary into DataFrame  df1 = pd.DataFrame(data2, index =[2, 3, 4])   # Now to perform cross join, we will create# a key column in both the DataFrames to # merge on that key.df['key'] = 1df1['key'] = 1  # to obtain the cross join we will merge # on the key and drop it.result = pd.merge(df, df1, on ='key').drop("key", 1)  result
DataFrame 1: DataFrame 2 : Output : 
Example 2:
Cross join on two DataFrames for user and product.
# importing pandas moduleimport pandas as pd    # Define a dictionary containing user IDdata1 = {'Name': ["Rebecca", "Maryam", "Anita"],        'UserID': [1, 2, 3]}      # Define a dictionary containing product ID data2 = {'ProductID': ['P1', 'P2', 'P3', 'P4']}    # Convert the dictionary into DataFrame  df = pd.DataFrame(data1, index =[0, 1, 2])   # Convert the dictionary into DataFrame  df1 = pd.DataFrame(data2, index =[2, 3, 6, 7])   # Now to perform cross join, we will create# a key column in both the DataFrames to # merge on that key.df['key'] = 1df1['key'] = 1  # to obtain the cross join we will merge on # the key and drop it.result = pd.merge(df, df1, on ='key').drop("key", 1)  result
DataFrame 1: DataFrame 2 : Output : 
Example 3:
# importing pandas moduleimport pandas as pd    # Define a dictionary with two columnsdata1 = {'col 1': [0, 1],        'col 2': [2, 3]}      # Define another dictionary data2 = {'col 3': [5, 6],        'col 4': [7, 8]}     # Convert the dictionary into DataFrame  df = pd.DataFrame(data1, index =[0, 1])   # Convert the dictionary into DataFrame  df1 = pd.DataFrame(data2, index =[2, 3])   # Now to perform cross join, we will create# a key column in both the DataFrames to# merge on that key.df['key'] = 1df1['key'] = 1  # to obtain the cross join we will merge on # the key and drop it.result = pd.merge(df, df1, on ='key').drop("key", 1)  result
DataFrame 1: DataFrame 2 : Output : 
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
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
How to Zip a directory in PHP?

We can use PHP ZipArchive class in order to zipping and unzipping the folder in PHP. As of PHP 5.3, this class is inbuilt. For using in windows users need to enable php_zip.dll inside of php.ini.
<?php
//Enter the name of directory
   $pathdir = "Directory Name/";
//Enter the name to creating zipped directory
   $zipcreated = "test.zip";
//Create new zip class
   $newzip = new ZipArchive;
   if($newzip -> open($zipcreated, ZipArchive::CREATE ) === TRUE) {
      $dir = opendir($pathdir);
      while($file = readdir($dir)) {
         if(is_file($pathdir.$file)) {
            $newzip -> addFile($pathdir.$file, $file);
         }
      }
      $newzip ->close();
   }
?>
Truncate a String using filter in Vue.js

15 Jul, 2021
In this article, we are going to learn how to truncate strings using filters in VueJS. Filters are a functionality provided by Vue components that let you apply formatting and transformations to any part of your template dynamic data. The filter property of the component is an object. A single filter is a function that accepts a value and returns another value. The returned value is the one that’s actually printed in the Vue.js template.
The string extraction can be performed by applying a filter on the required string. There can be two approaches for writing the logic of the filter function:
Approach 1: In this approach, we use the JavaScript built-in methods split, slice and, join. The split method is used to split each character and convert them into a set of a character array. The slice method extracts the required portion of the string and returns it. The join method is used to convert an array of characters to a normal string. We will use all three methods together to truncate the string. The substr method can also be used to return a truncated string.
Example:
index.html
<html><head>    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">    </script></head><body>    <div id='parent'>        <p>          <strong>Original String: </strong>            {{st1}}        </p>          <p>          <strong>Truncated String : </strong>            {{ st1 | truncate(13) }}        </p>      </div>    <script src='app.js'></script></body></html>
 
 
app.js
const parent = new Vue({    el: '#parent',    data: {        st1: 'GeekforGeeks is a computer science portal'    },      filters: {        truncate: function(data,num){            const reqdString =               data.split("").slice(0, num).join("");            return reqdString;        }    }})
 
 
Output:
 
 
Approach 2: This method does not use any built-in JavaScript methods. The truncation is done by looping through the characters of the string for the required number of times and keep the required number of characters by appending them to the final string that would be returned.
 
index.html
<html><head>    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js">    </script></head><body>    <div id='parent'>        <p>          <strong>Original String: </strong>            {{st1}}        </p>        <p><strong>Truncated String : </strong>            {{ st1 | truncate(18) }}        </p>    </div>    <script src='app.js'></script></body></html>
 
 
app.js
const parent = new Vue({    el: '#parent',    data: {        st1: 'GeekforGeeks is a computer science portal'    },      filters: {        truncate: function(data, num) {            reqdString = ''            for(let i=0; i<num; i++) {                reqdString += data[i]            }            return reqdString;        }    }})
 
 
Output:
 
 
anikakapoor
Vue.JS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Pandas Series.tolist()

01 Oct, 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 tolist() is used to convert a series to list. Initially the series is of type pandas.core.series.Series and applying tolist() method, it is converted to list data type.
Syntax: Series.tolist()
Return type: Converted series into List
To download the data set used in following example, click here.In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.
Example:In this example, the data type of Name column is stored in a variable. After that it is converted using tolist() method and again data type is stored and printed.
# importing pandas module import pandas as pd   # importing regex moduleimport re    # making data frame data = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")     # removing null values to avoid errors data.dropna(inplace = True)   # storing dtype before operationdtype_before = type(data["Salary"])  # converting to listsalary_list = data["Salary"].tolist()  # storing dtype after operationdtype_after = type(salary_list)  # printing dtypeprint("Data type before converting = {}\nData type after converting = {}".format(dtype_before, dtype_after))  # displaying listsalary_list
Output:As shown in the output image, the data type was converted from Series to List. The output of salary_list was in list format.
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Create a Pandas DataFrame from Lists
How to remove all white spaces from a string in PHP ?

27 May, 2020
Given a string element containing some spaces and the task is to remove all the spaces from the given string str in PHP. In order to do this task, we have the following methods in PHP:
Method 1: Using str_replace() Method: The str_replace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str.
Syntax:
str_replace($searchVal, $replaceVal, $subjectVal, $count)

Example :
PHP
<?php// PHP program to remove all white// spaces from a string   // Declare a string$str = "  Geeks for   Geeks  ";     // Using str_replace() function // to removes all whitespaces  $str = str_replace(' ', '', $str);  // Printing the resultecho $str; ?>
GeeksforGeeks
Method 2: Using str_ireplace() Method: The str_ireplace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str. The difference between str_replace and str_ireplace is that str_ireplace is a case-insensitive.
Syntax:
str_ireplace($searchVal, $replaceVal, $subjectVal, $count)

Example :
PHP
<?php// PHP program to remove all// white spaces from a string     $str = "  Geeks for   Geeks  ";     // Using str_ireplace() function // to remove all whitespaces  $str = str_ireplace (' ', '', $str);  // Printing the resultecho $str; ?>
GeeksforGeeks
Method 3: Using preg_replace() Method: The preg_replace() method is used to perform a regular expression for search and replace the content.
Syntax:
preg_replace( $pattern, $replacement, $subject, $limit, $count )

Example :
PHP
<?php// PHP program to remove all// white spaces from a string     $str = "  Geeks for   Geeks  ";     // Using preg_replace() function // to remove all whitespaces  $str = preg_replace('/\s+/', '', $str);  // Printing the resultecho $str; ?>
GeeksforGeeks
PHP-string
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java static method

The static keyword is used to create methods that will exist independently of any instances created for the class.
Static methods do not use any instance variables of any object of the class they are defined in. Static methods take all the data from parameters and compute something from those parameters, with no reference to variables.
 Class variables and methods can be accessed using the class name followed by a dot and the name of the variable or method.
The static modifier is used to create class methods and variables, as in the following example −
Live Demo
public class InstanceCounter {

   private static int numInstances = 0;

   protected static int getCount() {
      return numInstances;
   }

   private static void addInstance() {
      numInstances++;
   }

   InstanceCounter() {
      InstanceCounter.addInstance();
   }

   public static void main(String[] arguments) {
      System.out.println("Starting with " + InstanceCounter.getCount() + " instances");

      for (int i = 0; i < 500; ++i) {
         new InstanceCounter();
      }
      System.out.println("Created " + InstanceCounter.getCount() + " instances");
   }
}
Started with 0 instances
Created 500 instances
C++ 'a.out' not recognised as a command

Having entered following command from linux terminal −
$ g++ helloworld.cpp
The a.out file should be created in the current working directory if the compilation is successful. Check if a.out is created.
To execute enter following from command line −
$ ./a.out
In most cases, output of your source program is displayed. However, as in your case, error message indicating a.out is not executable is appearing. See the properties of a.out and make it executable (if not already) by following command −
$ chmod +x a.out
You may require sudo privilege for this. In all probability this should work. all the best
Convert PDF to Image in Python Using PyMuPDF | by Ednalyn C. De Dios | Towards Data Science

Recently, I was playing around with Amazon Textract when I ran into a little problem. Textract’s synchronous operation requires that the input document is in an image format. I had a bunch (hundreds) of PDFs to process; how was I supposed to convert each of them to PNGs without breaking a sweat?
PyMuPDF to the rescue!
Let’s fire up a terminal and type in the following:
pip install PyMuPDF
Then, let’s start a Jupyter Notebook and type in the following code:
Don’t forget to change the source path on line #8 (pdfs) and the destination path on line #15 (pngs).
And that’s it!
Thanks for stopping by and reading my post. I hope PyMuPDF can help you as much as it helped me! In my subsequent post, I will attempt to port this code over to AWS... maybe.
Stay tuned!
If you want to learn more about my journey from slacker to data scientist, check out the article below:
towardsdatascience.com
And if you’re thinking about switching gears and venture into data science, start thinking about rebranding now:
towardsdatascience.com
You can reach me on Twitter or LinkedIn.
How to get a particular date in Java 8?

The java.time package of Java provides API’s for dates, times, instances and durations. It provides various classes like Clock, LocalDate, LocalDateTime, LocalTime, MonthDay, Year, YearMonth, etc. Using classes of this package you can get details related to date and time in much simpler way compared to previous alternatives.
Java.time.LocalDate − This class represents a date object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current date from the system clock.
The of() method of java.time.LocalDate class accepts three integer parameters representing and year, a month of an year, day of a month and, returns the instance of the LocalDate object from the given details.
Following Java program reads year, month and day values from the user and creates a Date object of the given date using the classes and methods java.time package of Java8.
import java.time.LocalDate;
import java.util.Scanner;
public class LocalDateJava8 {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the year: ");
      int year = sc.nextInt();
      System.out.println("Enter the month: ");
      int month = sc.nextInt();
      System.out.println("Enter the day: ");
      int day = sc.nextInt();
      //Getting the current date value
      LocalDate givenDate = LocalDate.of(year, month, day);
      System.out.println("Date: "+givenDate);
   }
}
Enter the year:
2019
Enter the month:
07
Enter the day:
24
Date: 2019-07-24
How to catch TypeError Exception in Python?

TypeErrors are caused by combining the wrong type of objects, or calling a function with the wrong type of object.
import sys
try :
ny = 'Statue of Liberty'
my_list = [3, 4, 5, 8, 9]
print  my_list + ny
except TypeError as e:
print e
print sys.exc_type
can only concatenate list (not ""str") to list
<type 'exceptions.TypeError'>
Function to add up all the natural numbers from 1 to num in JavaScript

We are required to write a JavaScript function that takes in a number, say num.
Then our function should return the sum of all the natural numbers between 1 and num, including 1 and num.
For example, if num is −
const num = 5;
Then the output should be −
const output = 15;
because,
1+2+3+4+5 = 15
We will use the below formula to solve this problem −
Sum of all natural number upto n =
((n*(n+1))/2)
The code for this will be −
const num = 5;
const sumUpto = num => {
   const res = (num * (num + 1)) / 2;
   return res;
};
console.log(sumUpto(num));
console.log(sumUpto(7));
console.log(sumUpto(45));
console.log(sumUpto(2));
console.log(sumUpto(8));
console.log(sumUpto(99));
And the output in the console will be −
15
28
1035
3
36
4950
Can we change method signature in overriding in Java?

No, while overriding a method of the super class we need to make sure that both methods have same name, same parameters and, same return type else they both will be treated as different methods.
In short, if we change the signature, you cannot override the super class’s method if you try the method of the super class will be executed.
Reason − If you change the signature both are considered as different methods and, since the copy of super class method is available at sub class object, it will be executed.
 Live Demo
class Super {
   void sample(int a, int b) {
      System.out.println("Method of the Super class");
   }
}
public class MethodOverriding extends Super {
   void sample(int a, float b) {
      System.out.println("Method of the Sub class");
   }
   public static void main(String args[]) {
      MethodOverriding obj = new MethodOverriding();
      obj.sample(20, 20);
   }
}
Method of the Super class
How to enable or disable local user on Windows OS using PowerShell?

To disable the local user on the windows OS using PowerShell, we can use the Disable-Localuser command provided by the local user name. In the below example, we are going to disable the local user called TestUser.
Disable-LocalUser -Name TestUser
If we see the GUI, the user account is disabled.
To enable the above user, we can use the Enable-LocalUser command.
Enable-LocalUser -Name Testuser
To run the above command on the remote computer, we can use the Invoke-Command method. We need to make sure local user account exist on the remote computer.
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
   Enable-Localuser -Name TestUser
}
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
   Disable-Localuser -Name TestUser
}
If the PowerShell version 5.1 or higher doesn’t exist in your environment, you can use the command prompt to enable or disable the local user account with the Active switch.
net user username [/ACTIVE: {YES | NO}]
Disable local user example −
net user testuser /active:no
To disable the existing local user using the above command, we need to use Invoke-Command for remoting.
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
   Net user testuser /active:no
}
To enable the local user on the local system,
net user testuser /active:yes
On the remote system,
Invoke-Command -ComputerName Test1-Win2k12,Test1-Win2k16 -ScriptBlock{
   Net user testuser /active:yes
}
C library function - fputc()

The C library function int fputc(int char, FILE *stream) writes a character (an unsigned char) specified by the argument char to the specified stream and advances the position indicator for the stream.
Following is the declaration for fputc() function.
int fputc(int char, FILE *stream)
char − This is the character to be written. This is passed as its int promotion.
char − This is the character to be written. This is passed as its int promotion.
stream − This is the pointer to a FILE object that identifies the stream where the character is to be written.
stream − This is the pointer to a FILE object that identifies the stream where the character is to be written.
If there are no errors, the same character that has been written is returned. If an error occurs, EOF is returned and the error indicator is set.
The following example shows the usage of fputc() function.
#include <stdio.h>

int main () {
   FILE *fp;
   int ch;

   fp = fopen("file.txt", "w+");
   for( ch = 33 ; ch <= 100; ch++ ) {
      fputc(ch, fp);
   }
   fclose(fp);

   return(0);
}
Let us compile and run the above program that will create a file file.txt in the current directory, which will have following content −
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd

Now let's see the content of the above file using the following program −
#include <stdio.h>

int main () {
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1) {
      c = fgetc(fp);
      if( feof(fp) ) {
         break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}
Let us compile and run above program to produce the following result −
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcd


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to Justify Text in TextView on Android?

This example demonstrates how to Justify Text in TextView on Android.
Step 1  − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2  − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">
   <TextView
      android:id="@+id/tvJustified"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="20sp"
      android:padding="20sp"
      android:justificationMode="inter_word"
      android:text="The text in this TextView is justified.
      This feature is introduced in Android version >= 8.0.
      The text in this TextView is justified.
      This feature is introduced in Android version >= 8.0.
      The text in this TextView is justified.
      This feature is introduced in Android version >= 8.0." />
   <TextView
      android:id="@+id/tvNotJustified"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="20sp"
      android:padding="20sp"
      android:text="The text in this TextView is not justified.
      No justification. The text in this TextView is not justified.
      No justification. The text in this
      TextView is not justified. No justification. " />
</LinearLayout>
Step 3  − Add the following code to src/MainActivity.java
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 3  − Add the following code to Manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code.
How to add a number and a string in JavaScript?

In javascript , we can add a number and a number but if we try to add a number and a string then, as addition is not possible, 'concatenation' takes place.
In the following example, variables a,b,c and d are taken. For variable 'a', two numbers(5, 5) are added therefore it returned a  number(10). But in case of variable 'b' a string and a number ('5', 5) are added therefore, since a string is involved, we get the result as '55', which is a string. since strings are involved, Variables 'c' and 'd' also return a string as shown in the output.   
Live Demo
<html>
<body>
<script type="text/javascript">
   var a = 5 + 5;
   var b = "5" + 5;
   var c = 5 + 5 + "5" + 5
   var d = "Hello" + 5;
   document.write(a + "<br>" + b + "<br>" + c + "</br>" + d);
   document.write("</br>");
   document.write(typeof(a));
   document.write("</br>");
   document.write(typeof(b));
   document.write("</br>");
   document.write(typeof(c));
   document.write("</br>");
   document.write(typeof(d));
</script>
</body>
</html>
10
55
1055
Hello5
number
string
string
string
sciPy stats.gmean() function | Python

19 Aug, 2021
scipy.stats.gmean(array, axis=0, dtype=None) calculates the geometric mean of the array elements along the specified axis of the array (list in python). It’s formula –  
 
Parameters : array: Input array or object having the elements to calculate the geometric mean. axis: Axis along which the mean is to be computed. By default axis = 0 dtype: It sets the type of returned element.Returns : Geometric mean of the array elements based on the set parameters.
Code #1:  
Python3
# Geometric Mean from scipy.stats.mstats import gmeanarr1 = gmean([1, 3, 27])  print("Geometric Mean is :", arr1)
Geometric Mean is : 4.32674871092
 
  Code #2: With multi-dimensional data  
Python3
# Geometric Mean from scipy.stats.mstats import gmeanarr1 = [[1, 3, 27],        [3, 4, 6],        [7, 6, 3],        [3, 6, 8]]  print("Geometric Mean is :", gmean(arr1)) # using axis = 0print("\nGeometric Mean is with default axis = 0 : \n",      gmean(arr1, axis = 0)) # using axis = 1print("\nGeometric Mean is with default axis = 1 : \n",      gmean(arr1, axis = 1)) 
Geometric Mean is : [ 2.81731325  4.55901411  7.89644408]

Geometric Mean is with default axis = 0 : 
 [ 2.81731325  4.55901411  7.89644408]

Geometric Mean is with default axis = 1 : 
 [ 4.32674871  4.16016765  5.01329793  5.24148279]
 
anikaseth98
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Test Internet Speed using Python

19 Feb, 2020
Prerequisites: Python Programming Language
Python is a high-level widely used general-purpose language. Python can be used for many tasks such as web development, machine learning, Gui applications. It can also be used for testing Internet speed. Python provides various libraries for doing the same. One such library is speedtest-cli. This library is a command-line interface for testing internet bandwidth using speedtest.net
This module does not come built-in with Python. To install it type the below command in the terminal.
pip install speedtest-cli

After installing the above package one can check if the package is installed correctly or not by doing the version check. The version of the package can be checked using the following command
speedtest-cli --version

Speedtest-cli is a module that is used in the command-line interface for testing internet bandwidth using speedtest.net. To get the speed in the megabits type the below command in the terminal.
speedtest-cli

The above command gives the speed test result is in Megabits. To get the result in Bytes we can use the following command.
speedtest-cli --bytes

The pictorial version of your speed test result can also be retrieved using this module. To do the same type the below command in the terminal.
speedtest-cli --share

It returns a link on which we can visit on our browser and see the graphical representation of various kinds of our internet speed.
To print a simpler version of the speed test result containing only Ping, Download & Upload results instead of detailed output.
speedtest-cli --simple

Using Python script to check the internet speed
# Python program to test# internet speed  import speedtest      st = speedtest.Speedtest()  option = int(input('''What speed do you want to test:    1) Download Speed    2) Upload Speed    3) Ping   Your Choice: '''))    if option == 1:        print(st.download())    elif option == 2:       print(st.upload())    elif option == 3:        servernames =[]        st.get_servers(servernames)        print(st.results.ping)    else:      print("Please enter the correct choice !") 
Output:
To get the list of all the available options, type the below command in the terminal.
speedtest-cli -h
speedtest-cli -h
speedtest-cli --help
speedtest-cli --help
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Introduction To PYTHON
Python PySpark – DataFrame filter on multiple columns

14 Sep, 2021
In this article, we are going to filter the dataframe on multiple columns by using filter() and where() function in Pyspark in Python.
Creating Dataframe for demonestration:
Python3
# importing moduleimport pyspark  # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession  # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate()  # list  of employee datadata = [[1, "sravan", "company 1"],        [2, "ojaswi", "company 1"],         [3, "rohith", "company 2"],        [4, "sridevi", "company 1"],        [1, "sravan", "company 1"],        [4, "sridevi", "company 1"]]  # specify column namescolumns = ['ID', 'NAME', 'Company']  # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns)  # display dataframedataframe.show()
Output:
filter() is used to return the dataframe based on the given condition by removing the rows in the dataframe or by extracting the particular rows or columns from the dataframe. We are going to filter the dataframe on multiple columns. It can take a condition and returns the dataframe.
Syntax:
filter(dataframe.column condition)
Example 1: Conditional operator includes boolean or logical or relational operators.
Python3
# select dataframe where ID less than 3dataframe.filter(dataframe.ID < 3).show()
Output:
Example 2: Python program to filter data based on two columns. In this example, we created a pyspark dataframe and select dataframe where ID less than 3 or name is Sridevi
Python3
# select dataframe where ID less than# 3 or name is sridevidataframe.filter((dataframe.ID < 3) |                  (dataframe.NAME == 'sridevi')).show()
Output:
Example 3: Multiple columns filtering
Python3
# select dataframe where ID less than# 3 or name is sridevi and comapny 1dataframe.filter((dataframe.ID < 3) | (    (dataframe.NAME == 'sridevi') &   (dataframe.Company == 'company 1'))).show()
Output:
Where: where is similar to filter() function that is used to return the dataframe based on the given condition by removing the rows in the dataframe or by extracting the particular rows or columns from the dataframe. It can take a condition and returns the dataframe.
where(dataframe.column condition)
Example 1: Python program to filter on multiple columns
Python3
# select dataframe where ID less than# 3 or name is sridevi and comapny 1dataframe.where((dataframe.ID < 3) | (    (dataframe.NAME == 'sridevi') &  (dataframe.Company == 'company 1'))).show()
Output:
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
How to fetch elements with iterator in Java?

Let us first create a List and add elements −
List<String>list = Arrays.asList(new String[] { "P", "Q", "R", "S", "T", "U", "V", "W" });
Now, use Iterator to fetch each element −
Iterator<String>i = list.iterator();
Display the elements −
while (i.hasNext()) {
   System.out.println(i.next());
}
 Live Demo
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Demo {
   public static void main(String[] a) {
      List<String>list = Arrays.asList(new String[] { "P", "Q", "R", "S", "T", "U", "V", "W" });
      Iterator<String>i = list.iterator();
      System.out.println("Displaying elements...");
      while (i.hasNext()) {
         System.out.println(i.next());
      }
   }
}
Displaying elements...
P
Q
R
S
T
U
V
W
numpy.var() in Python

03 Dec, 2018
numpy.var(arr, axis = None) : Compute the variance of the given data (array elements) along the specified axis(if any).
Example :
x = 1 1 1 1 1Standard Deviation = 0 . Variance = 0
y = 9, 2, 5, 4, 12, 7, 8, 11, 9, 3, 7, 4, 12, 5, 4, 10, 9, 6, 9, 4
Step 1 : Mean of distribution 4 = 7Step 2 : Summation of (x – x.mean())**2 = 178Step 3 : Finding Mean = 178 /20 = 8.9This Result is Variance.
Parameters :
arr : [array_like] input array.axis : [int or tuples of int] axis along which we want to calculate the variance. Otherwise, it will consider arr to be flattened (works on all the axis). axis = 0 means variance along the column and axis = 1 means variance along the row.out : [ndarray, optional] Different array in which we want to place the result. The array must have the same dimensions as expected output.dtype : [data-type, optional] Type we desire while computing variance.
Results : Variance of the array (a scalar value if axis is none) or array with variance values along specified axis.
Code #1:
# Python Program illustrating # numpy.var() method import numpy as np       # 1D array arr = [20, 2, 7, 1, 34]   print("arr : ", arr) print("var of arr : ", np.var(arr))   print("\nvar of arr : ", np.var(arr, dtype = np.float32)) print("\nvar of arr : ", np.var(arr, dtype = np.float64)) 
Output :
arr :  [20, 2, 7, 1, 34]
var of arr :  158.16

var of arr :  158.16

var of arr :  158.16
 Code #2:
# Python Program illustrating # numpy.var() method import numpy as np       # 2D array arr = [[2, 2, 2, 2, 2],     [15, 6, 27, 8, 2],     [23, 2, 54, 1, 2, ],     [11, 44, 34, 7, 2]]         # var of the flattened array print("\nvar of arr, axis = None : ", np.var(arr))       # var along the axis = 0 print("\nvar of arr, axis = 0 : ", np.var(arr, axis = 0))   # var along the axis = 1 print("\nvar of arr, axis = 1 : ", np.var(arr, axis = 1)) 
Output :
var of arr, axis = None :  236.14000000000004

var of arr, axis = 0 :  [ 57.1875 312.75   345.6875   9.25     0.    ]

var of arr, axis = 1 :  [  0.    77.04 421.84 269.04]
Python numpy-Statistics Functions
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JavaScript Array includes() Method

08 Jul, 2020
Below is the example of the Array includes() method.
Example:<script>    var name = [ 'gfg', 'cse', 'geeks', 'portal' ];      a = name.includes('gfg')      // Printing result of includes()    document.write(a);</script>
<script>    var name = [ 'gfg', 'cse', 'geeks', 'portal' ];      a = name.includes('gfg')      // Printing result of includes()    document.write(a);</script>
Output:true
true
The array.includes() method is used to know either a particular element is present in the array or not and accordingly, it returns true or false i.e, if the element is present, then it returns true otherwise false.
Syntax:
array.includes(searchElement, start)
Parameter: This method accepts two parameters as mentioned above and described below:
searchElement: This parameter holds the element which will be searched.
start: This parameter is optional and it holds the starting point of the array, where to begin the search the default value is 0.
Return Value: It returns a Boolean value i.e, either True or False.
Below examples illustrate the Array includes() method in JavaScript:
Example 1: In this example the method will searched for the element 2 in that array.Input : [1, 2, 3, 4, 5].includes(2);
Output: true
Input : [1, 2, 3, 4, 5].includes(2);
Output: true
Example 2: In this example the method will searched for the element 9 in that array.Input : [1, 2, 3, 4, 5].includes(9);
Output: false
Input : [1, 2, 3, 4, 5].includes(9);
Output: false
Code for the above method is provided below:
Program 1:
<script>      // Taking input as an array A    // having some elements.    var A = [ 1, 2, 3, 4, 5 ];      // includes() method is called to    // test whether the searching element    // is present in given array or not.    a = A.includes(2)      // Printing result of includes().    document.write(a);</script>
Output:
true
Program 2:
<script>    // Taking input as an array A    // having some elements.    var name = [ 'gfg', 'cse', 'geeks', 'portal' ];      // includes() method is called to    // test whether the searching element    // is present in given array or not.    a = name.includes('cat')      // Printing result of includes()    document.write(a);</script>
Output:
false
Supported Browsers: The browsers supported by JavaScript Array includes() method are listed below:
Google Chrome 47.0
Microsoft Edge 14.0
Mozilla Firefox 43.0
Safari 9.0
Opera 34.0
nidhi_biet
Akanksha_Rai
javascript-array
JavaScript-Methods
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
How do you run JavaScript script through the Terminal?
JavaScript | console.log() with Examples
Matplotlib.axes.Axes.arrow() in Python

13 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute.
The Axes.arrow() function in axes module of matplotlib library is also used to add an arrow to the axes. This function is used to draws an arrow from (x, y) to (x+dx, y+dy)
Syntax:
Axes.arrow(self, x, y, dx, dy, **kwargs)

Parameters: This method accept the following parameters that are described below:
x, y: These parameter are the x and y coordinates of the arrow base.
dx, dy: These parameter are the length of the arrow along x and y direction.
Returns: This method returns the arrow which is a created FancyArrow object.
Below examples illustrate the matplotlib.axes.Axes.arrow() function in matplotlib.axes:
Example-1:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt  ax = plt.axes()ax.arrow(0, 0, 0.6, 0.7, head_width = 0.05,          head_length = 0.1)  ax.set_title('matplotlib.axes.Axes.arrow() Example',              fontsize = 14, fontweight ='bold')  plt.show()
Output:
Example-2:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt  ax = plt.axes()ax.arrow(6, 7, -2.5, -2.5, head_width = 0.5,         head_length = 0.5, fc ='g', ec ='g')ax.set_title('matplotlib.axes.Axes.arrow() Example',              fontsize = 14, fontweight ='bold')   ax.set(xlim =(1, 10), ylim =(1, 10))ax.set_xlabel("X-Axis")ax.set_ylabel("Y-Axis")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Groovy - Environment

There are a variety of ways to get the Groovy environment setup.
Binary download and installation − Go to the link  www.groovy-lang.org/download.html to get the Windows Installer section. Click on this option to start the download of the Groovy installer.
Once you launch the installer, follow the steps given below to complete the installation.
Step 1 − Select the language installer.
Step 2 − Click the Next button in the next screen.
Step 3 − Click the ‘I Agree’ button.
Step 4 − Accept the default components and click the Next button.
Step 5 − Choose the appropriate destination folder and then click the Next button.
Step 6 − Click the Install button to start the installation.
Step 7 − Once the installation is complete, click the Next button to start the configuration.
Step 8 − Choose the default options and click the Next button.
Step 9 − Accept the default file associations and click the Next button.
Step 10 − Click the Finish button to complete the installation.
Once the above steps are followed, you can then start the groovy shell which is part of the Groovy installation that helps in testing our different aspects of the Groovy language without the need of having a full-fledged integrated development environment for Groovy. This can be done by running the command groovysh from the command prompt.
If you want to include the groovy binaries as part of you maven or gradle build, you can add the following lines
matplotlib.pyplot.nipy_spectral() in Python

22 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The nipy_spectral() function in pyplot module of matplotlib library is used to set the colormap to “nipy_spectral”.
Syntax:
matplotlib.pyplot.nipy_spectral()

Parameters: This method does not accepts any parameters.
Return value: This method does not returns any value.
Below examples illustrate the matplotlib.pyplot.nipy_spectral() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport matplotlib.tri as triimport numpy as np          ang = 40rad = 10radm = 0.35radii = np.linspace(radm, 0.95, rad)         angles = np.linspace(0, 4 * np.pi, ang)angles = np.repeat(angles[..., np.newaxis], rad, axis = 1)angles[:, 1::2] += np.pi / ang         x = (radii * np.cos(angles)).flatten()y = (radii * np.sin(angles)).flatten()z = (np.sin(4 * radii) * np.cos(4 * angles)).flatten()         triang = tri.Triangulation(x, y)triang.set_mask(np.hypot(x[triang.triangles].mean(axis = 1),                         y[triang.triangles].mean(axis = 1))                < radm)         tpc = plt.tripcolor(triang, z, shading ='flat')plt.nipy_spectral()plt.title('matplotlib.pyplot.nipy_spectral() function Example', fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm            dx, dy = 0.015, 0.05x = np.arange(-3.0, 3.0, dx)y = np.arange(-3.0, 3.0, dy)X, Y = np.meshgrid(x, y)         extent = np.min(x), np.max(x), np.min(y), np.max(y)                  Z1 = np.add.outer(range(6), range(6)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest',                 extent = extent, alpha = 1)         def geeks(x, y):    return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2))         Z2 = geeks(X, Y)         plt.imshow(Z2, alpha = 0.7, interpolation ='bilinear',                 extent = extent)plt.nipy_spectral()plt.title('matplotlib.pyplot.nipy_spectral() function Example', fontweight ="bold")plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
Program to find Simple Interest and Compound Interest in PL/SQL

02 Jul, 2018
Prerequisite – PL/SQL introduction
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given principal(p), rate(r), time(t), the task is to calculate the simple interest and compound interest.
Examples:
Input: p = 1500
       r = 5
       t = 3
Output: SI = 225, CI = 1736.44 

Input: p = 2700
       r = 7
       t = 8
Output: SI = 1512, CI = 4639.1

Formula for Simple Interest:Formula for Compound Interest:Where:P: Principal (original amount)R: Rate of Interest (in %)T: Time period
Below is the required implementation:-
  DECLARE    --declaration of principal variable    p  NUMBER(9, 2);    ----declaration of rate variable    r  NUMBER(9, 2);    --declaration of time period variable    t  NUMBER(9, 2);    --declaration of simple interest variable    si NUMBER(9, 2);    ci NUMBER(9, 2);BEGIN    --Code Block Start     --assigning principal values    p := 33000;      --assigning rate  values    r := 7;      --assigning time period values    t := 6;      --To calculate SI by simple     --mathematical formula    si := ( p * r * t ) / 100;      ci := p * Power (1 + ( r / 100 ),t);      --Print Result of SI.........    dbms_output.Put_line('Simple Interest = '                         ||si);      dbms_output.Put_line('Compound interest = '                         || ci);END;--End program   
Output
Simple Interest = 13860
Compound interest = 49524.1

SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows