code-rag-bench/online-tutorials huggingface dataset:
Python | Convert numeric String to integers in mixed List

25 Aug, 2021
Sometimes, while working with data, we can have a problem in which we receive mixed data and need to convert the integer elements in form of strings to integers. This kind of operation might be required in data preprocessing step. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + isdigit() This is one way in which this task can be performed. In this, we check for each element of string whether it is a number using isdigit, and then converted to int if it is one. The iteration is using list comprehension.
Python3
# Python3 code to demonstrate working of# Convert String numbers to integers in mixed List# using list comprehension + isdigit() # initialize listtest_list = ["gfg", "1", "is", "6", "best"] # printing original listprint("The original list : " + str(test_list)) # Convert String numbers to integers in mixed List# using list comprehension + isdigit()res = [int(ele) if ele.isdigit() else ele for ele in test_list] # printing resultprint("List after converting string numbers to integers : " + str(res))
The original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
 
Method #2 : Using map() + lambda + isdigit() This task can also be performed using above functions. In this, we perform the task of iteration using map() and lambda function. 
Python3
# Python3 code to demonstrate working of# Convert String numbers to integers in mixed List# using map() + lambda + isdigit() # initialize listtest_list = ["gfg", "1", "is", "6", "best"] # printing original listprint("The original list : " + str(test_list)) # Convert String numbers to integers in mixed List# using map() + lambda + isdigit()res = list(map(lambda ele : int(ele) if ele.isdigit()          else ele, test_list)) # printing resultprint("List after converting string numbers to integers : " + str(res))
The original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
 
sweetyty
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()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Python – Cost computation using Frequency and Price dictionary

01 Aug, 2020
Given price and frequency dictionary, compute total cost of products, i.e by summing the product of price and frequency of each item.
Input : test_dict = {“Apple” : 2, “Mango” : 2, “Grapes” : 2}, {“Apple” : 2, “Mango” : 2, “Grapes” : 2}Output : 12Explanation : (2*2) + (2*2) + (2*2) = 12.
Input : test_dict = {“Apple” : 3, “Mango” : 2, “Grapes” : 3}, {“Apple” : 2, “Mango” : 2, “Grapes” : 2}Output : 16Explanation : The summation of product leads to 16 as above.
Method #1 : Using loop
This is brute way in which this task can be performed. In this, we iterate through all the keys and multiply the frequency of each element by its cost and keep performing intermediate summation.
Python3
# Python3 code to demonstrate working of # Cost computation using Frequency and Price dictionary# Using loop  # initializing dictionarytest_dict = {"Apple" : 5, "Mango" : 8, "Grapes" : 10}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing Frequency dict cost_dict = {"Apple" : 3, "Mango" : 4, "Grapes" : 6}  res = 0for key in test_dict:          # computing summation of product    res = res + (test_dict[key] * cost_dict[key])      # printing result print("The extracted summation : " + str(res)) 
The original dictionary is : {'Apple': 5, 'Mango': 8, 'Grapes': 10}
The extracted summation : 107

Method #2 : Using sum() + list comprehension
The combination of these functionalities provide a shorthand to solve this problem. In this, we perform summation using sum() and list comprehension is used to compile result and iterate.
Python3
# Python3 code to demonstrate working of # Cost computation using Frequency and Price dictionary# Using sum() + list comprehension  # initializing dictionarytest_dict = {"Apple" : 5, "Mango" : 8, "Grapes" : 10}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # initializing Frequency dict cost_dict = {"Apple" : 3, "Mango" : 4, "Grapes" : 6}  # using list comprehension and sum() to provide one-linerres = sum([cost_dict[key] * test_dict[key] for key in test_dict])      # printing result print("The extracted summation : " + str(res)) 
The original dictionary is : {'Apple': 5, 'Mango': 8, 'Grapes': 10}
The extracted summation : 107

Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Saving a machine learning Model

10 Jun, 2022
In machine learning, while working with scikit learn library, we need to save the trained models in a file and restore them in order to reuse them to compare the model with other models, and to test the model on new data. The saving of data is called Serialization, while restoring the data is called Deserialization.
Also, we deal with different types and sizes of data. Some datasets are easily trained i.e- they take less time to train but the datasets whose size is large (more than 1GB) can take a very large time to train on a local machine even with GPU. When we need the same trained data in some different project or later sometime, to avoid the wastage of the training time, store the trained model so that it can be used anytime in the future. 
There are two ways we can save a model in scikit learn:
The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. 
Pickle model provides the following functions –
pickle.dump to serialize an object hierarchy, you simply use dump(). 
pickle.load to deserialize a data stream, you call the loads() function.
Example: Let’s apply K Nearest Neighbor on the iris dataset and then save the model. 
Python3
from sklearn.neighbors import KNeighborsClassifier as KNNimport numpy as np # Load datasetfrom sklearn.datasets import load_irisiris = load_iris() X = iris.datay = iris.target # Split dataset into train and testX_train, X_test, y_train, y_test = \    train_test_split(X, y, test_size=0.3,                     random_state=2018) # import KNeighborsClassifier modelknn = KNN(n_neighbors=3) # train modelknn.fit(X_train, y_train)
Output:
Save a model to string using pickle:
Python3
import pickle # Save the trained model as a pickle string.saved_model = pickle.dumps(knn) # Load the pickled modelknn_from_pickle = pickle.loads(saved_model) # Use the loaded pickled model to make predictionsknn_from_pickle.predict(X_test)
Output: 
Joblib is the replacement of pickle as it is more efficient on objects that carry large numpy arrays. These functions also accept file-like object instead of filenames. 
joblib.dump to serialize an object hierarchy 
joblib.load to deserialize a data stream
from joblib import parallel, delayed
Save to pickled file using joblib 
Python3
from joblib import Parallel, delayedimport joblib  # Save the model as a pickle in a filejoblib.dump(knn, 'filename.pkl') # Load the model from the fileknn_from_joblib = joblib.load('filename.pkl') # Use the loaded model to make predictionsknn_from_joblib.predict(X_test)
Output: 
 
as5853535
skal034
usmanfarid165
Advanced Computer Subject
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Docker - COPY Instruction
How to Run a Python Script using Docker?
ML | Underfitting and Overfitting
ML | Linear Regression
Agents in Artificial Intelligence
Search Algorithms in AI
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
How to get and store device ID in Android using Kotlin?

This example demonstrates how to get and store device ID in Android using Kotlin.
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"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerHorizontal="true"
   android:layout_marginTop="50dp"
   android:text="Tutorials Point"
   android:textAlignment="center"
   android:textColor="@android:color/holo_green_dark"
   android:textSize="32sp"
   android:textStyle="bold" />
<TextView
   android:id="@+id/textView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:textColor="@android:color/holo_purple"
   android:textSize="24sp"
   android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.provider.Settings
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      val textView: TextView = findViewById(R.id.textView)
      val id: String = Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
      textView.text = "Device ID: $id"
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
   <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 the 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.
Python PIL | Image.crop() method

17 Jun, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL.Image.crop() method is used to crop a rectangular portion of any image. 
Syntax: PIL.Image.crop(box = None)Parameters: box – a 4-tuple defining the left, upper, right, and lower pixel coordinate.Return type: Image (Returns a rectangular region as (left, upper, right, lower)-tuple).Return: An Image object.  
Code #1:  
Python3
# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"C:\Users\Admin\Pictures\geeks.png") # Size of the image in pixels (size of original image)# (This is not mandatory)width, height = im.size # Setting the points for cropped imageleft = 5top = height / 4right = 164bottom = 3 * height / 4 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom)) # Shows the image in image viewerim1.show()
Original Image  
Output:  
  Code #2:  
Python3
# Importing Image class from PIL modulefrom PIL import Image # Opens a image in RGB modeim = Image.open(r"C:\Users\Admin\Pictures\network.png") # Setting the points for cropped imageleft = 155top = 65right = 360bottom = 270 # Cropped image of above dimension# (It will not change original image)im1 = im.crop((left, top, right, bottom)) # Shows the image in image viewerim1.show()
Original Image:  
Output:  
 
simranarora5sos
Image-Processing
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
STL Priority Queue for Structure or Class in C++

STL Priority Queue is the implementation of maxheap.
This is a C++ program of STL priority queue for structure.
Begin
   Define a structure of type student.
   Initialize variables in student structure.
   Define another structure of type comparemarks
   Overload the variables of student structure in comapremarks
   structure.
   Use priority queue with structure.
   Insert some elements in priority queue using student structure.
   While the queue is not empty do
      Print the elements.
End.
 Live Demo
#include <iostream>
#include <queue>
using namespace std;
#define ROW 6
#define COL 3
struct student { //defining the student structure
   int roll,marks;
   student(int roll, int marks)
      : roll(roll), marks(marks)
   {
   }
};
struct comparemarks{ // defining the comparemarks structure
   bool operator()(student const& s1, student const& s2)
   //overloading the operators of the student structure
   {
      return s1.marks < s2.marks;
   }
};
int main()
{
   priority_queue<student, vector<student>, comparemarks> M;
   // using the priority queue. We have to use this type of syntax to use the priority queue.
   int a[ROW][COL] = {{15, 50}, {16, 60},
   {18,70}, {14, 80}, {12, 90}, {20, 100}};
   for (int i = 0; i < ROW; ++i) {
      M.push(student(a[i][0], a[i][1])); //inserting variables in the queue
   }
   cout<<"priority queue for structure ::"<<endl;
   while (!M.empty()) {
      student s = M.top();
      M.pop();
      cout << s.roll << " " << s.marks << "\n"; //printing the values
   }
   return 0;
}
priority queue for structure ::
20 100
12 90
14 80
18 70
16 60
15 50
C# program to Display Hostname and IP address

To find the hostname, use the Dns.GetHostName() method in C# −
String hostName = string.Empty;
hostName = Dns.GetHostName();
Console.WriteLine("Hostname: "+hostName);
Now, use the IPHostEntry.AddressList Property to get IP Address −
IPHostEntry myIP = Dns.GetHostEntry(hostName);
IPAddress[] address = myIP.AddressList;
Try the following code to display hostname and IP address −
using System;
using System.Net;
class Program {
   static void Main() {
      String hostName = string.Empty;
      hostName = Dns.GetHostName();
      Console.WriteLine("Hostname: "+hostName);
      IPHostEntry myIP = Dns.GetHostEntry(hostName);
      IPAddress[] address = myIP.AddressList;
      for (int i = 0; i < address.Length; i++) {
         Console.WriteLine("IP Address {1} : ",address[i].ToString());
      }
      Console.ReadLine();
   }
}
How to add multiple objects to a single array list in Javascript?

There are many ways to add multiple objects to a single array list in
Javascript. Let us look at some of them −
To add multiple objects at the end of an array, you can repeatedly call push on it. For example,
let arr = [];
arr.push(1);
arr.push(2);
console.log(arr);
This will give the output −
[1, 2]
To add multiple objects at the start of an array, you can repeatedly call unshift on it. For example,
let arr = [];
arr.unshift(1);
arr.unshift(2);
console.log(arr);
This will give the output −
[2, 1]
The spread operator can help you copy over one array into another. For example,
let arr1 = [1, 2, 3];
let arr2 = ['hello', ...arr1, 'world];
console.log(arr2);
This will give the output −
['hello', 1, 2, 3, 'world]
Program to check if the String is Null in Java

22 Jan, 2020
Given a string str, the task is to check if this string is null or not, in Java.
Examples:
Input: str = null 
Output: True

Input: str = "GFG"
Output: False

Approach:
Get the String to be checked in str
We can simply compare the string with Null using == relational operator.Syntax:if(str == null)

if(str == null)

Print true if the above condition is true. Else print false.
Below is the implementation of the above approach:
// Java Program to check if// the String is Null in Java  class GFG {      // Function to check if the String is Null    public static boolean isStringNull(String str)    {          // Compare the string with null        // using == relational operator        // and return the result        if (str == null)            return true;        else            return false;    }      // Driver code    public static void main(String[] args)    {        String str1 = "GeeksforGeeks";        String str2 = null;          System.out.println("Is string [" + str1                           + "] null? "                           + isStringNull(str1));        System.out.println("Is string [" + str2                           + "] null? "                           + isStringNull(str2));    }}
Is string [GeeksforGeeks] null? false
Is string [null] null? true

Java-String-Programs
Java
Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
Write a program to reverse an array or string
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not
Perl | hex Function

07 May, 2019
The hex function in Perl converts the given hexadecimal number ( of base 16 ) into its equivalent decimal number ( of base 10 ).
Syntax: hex number
Parameters:number: hexadecimal number to be converted
Returns: equivalent decimal number of the given hexadecimal number.
Example 1:
#!/usr/bin/perl  # Initialising some hexadecimal values for# the parameter of the hex function$A = "A";$B = "B";$C = "1A";$D = "2C";  # Calling the hex function$E = hex $A;$F = hex $B;$G = hex $C;$H = hex $D;  # Getting the equivalent decimal number# of the given hexadecimal numberprint "$E\n";print "$F\n";print "$G\n";print "$H\n";
Output:
10
11
26
44

Example 2:
#!/usr/bin/perl  # Initialising some hexadecimal values and# Calling the hex function$A = hex D;$B = hex af;$C = hex AF;$D = hex BF;  # Getting the equivalent decimal number# of the given hexadecimal numberprint "$A\n";print "$B\n";print "$C\n";print "$D\n";
Output :
13
175
175
191
Perl-function
Perl-Math-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | Arrays (push, pop, shift, unshift)
Perl | Arrays
Perl | Polymorphism in OOPs
Perl Tutorial - Learn Perl With Examples
Perl | Boolean Values
Perl | length() Function
Perl | Subroutines or Functions
Introduction to Perl
Perl | Basic Syntax of a Perl Program
Hello World Program in Perl
D3.js scaleOrdinal() Function

18 Sep, 2020
The d3.scaleOrdinal() function is used to create and return the ordinal scale which has the specified range and domain. If the domain and range are not given then both are set to empty array. These types of scales have a discrete domain and range.
Syntax:
d3.scaleOrdinal([[domain, ]range]);

Parameters:  This function takes two parameters as given above and described below:
domain: It defines the minimum and maximum value for the scale.
range:  Every value in domain maps with value in the range.
Return Values: This function does not return anything.
Example 1:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" path1tent=        "width=device-width,         initial-scale=1.0" />    <script src=        "https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>          // Creating the Ordinal scale.        var ordinal = d3.scaleThreshold()              // Setting domain for the scale            .domain([1, 2, 3, 4])            .range([10, 20, 30, 40]);                  console.log("The value of ordinal(1) is: ",                ordinal(1));        console.log("The value of ordinal(2) is: ",                ordinal(2));        console.log("The value of ordinal(3) is: ",                ordinal(3));    </script></body>  </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8" />    <meta name="viewport" path1tent=        "width=device-width,         initial-scale=1.0" />      <script src=        "https://d3js.org/d3.v4.min.js">    </script></head>  <body>    <script>        // Creating the Ordinal scale.        var ordinal = d3.scaleThreshold()              // Setting domain for the scale            .domain([1, 2, 3, 4])            .range(["String1", "string2",                     "string3", "string4"]);          console.log("The value of ordinal(1) is: ",                ordinal(1));        console.log("The value of ordinal(2) is: ",                ordinal(2));        console.log("The value of ordinal(3) is: ",                ordinal(3));        console.log("When value given is not"                + " in the domain:")        console.log("The value of ordinal(4) is: ",                ordinal(10));    </script></body>  </html>
Output:
D3.js
JavaScript
Web Technologies
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
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
numpy.frompyfunc() in Python

29 Jun, 2021
numpy.frompyfunc(func, nin, nout) function allows to create an arbitrary Python function as Numpy ufunc (universal function).
Parameters: func: [A python function object ] An arbitrary python function nin: [int] Number of input arguments to that function. nout: [int] Number of objects returned by that function.Return: A Numpy universal function object.
For example, abs_value = numpy.frompyfunc(abs, 1, 1) will create a ufunc that will return the absolute values of array elements.
Code #1: 
Python3
# Python code to demonstrate the# use of numpy.frompyfuncimport numpy as np # create an array of numbersa = np.array([34, 67, 89, 15, 33, 27]) # python str function as ufuncstring_generator = np.frompyfunc(str, 1, 1) print("Original array-", a)print("After conversion to string-", string_generator(a))
Original array- [34 67 89 15 33 27]
After conversion to string- ['34' '67' '89' '15' '33' '27']
 
Code #2:  
Python3
# Python code to demonstrate# user-defined function as ufuncimport numpy as np # create an array of numbersa = np.array([345, 122, 454, 232, 334, 56, 66]) # user-defined function to check# whether a no. is palindrome or notdef fun(x):    s = str(x)    return s[::-1]== s     # 'check_palindrome' as universal functioncheck_palindrome = np.frompyfunc(fun, 1, 1)print("Original array-", a)print("Checking of number as palindrome-",                      check_palindrome(a))
Original array- [345 122 454 232 334  56  66]
Checking of number as palindrome- [False False True True False False True]
 
Note: This custom ufunc created using frompyfunc always accept a ndarray as an input argument and also return a ndarray object as output. 
Akanksha_Rai
arorakashish0911
Python numpy-Logic Functions
Python-numpy
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
Vue.js v-on:click.right Directive

08 Jul, 2020
The v-on:click.right directive is a Vue.js directive used to add a click event listener to an element. While click directive triggers the event for all kind of clicks, this directive only triggers the event when right key of mouse is clicked. First, we will create a div element with id as app and let’s apply the v-on:click.right directive to a element. Further, we can execute a function when click even occurs. 
Syntax:
v-on:click.right = "function"
Parameters: This directive holds function as a value that will be executed when the click event occurs.Example: This example uses Vue.js to toggle the visibility of a element with v-on:click.right.
HTML
<!DOCTYPE html><html>  <head>    <title>        VueJS v-on:click.right Directive    </title>      <!-- Load Vuejs -->    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js">    </script></head>  <body>    <div style="text-align:center;            width: 600px;">          <h1 style="color: green;">            GeeksforGeeks        </h1>        <b>            VueJS | v-on:click.right directive        </b>    </div>      <div id="canvas" style=            "border:1px solid #000000;            width: 600px;height: 200px;">                      <div id="app" style="text-align: center;                     padding-top: 40px;">              <button v-on:click.right=                "data = !data">Show            </button>              <h1 v-if="data">                Right key is pressed.            </h1>        </div>    </div>      <script>        var app = new Vue({            el: '#app',            data: {                data: false            }        })    </script></body>  </html>                   
Output:
Vue.JS
JavaScript
Web Technologies
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
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
URL getFile() method in Java with Examples

31 Dec, 2018
The getFile() function is a part of URL class. The function getFile() returns the file name of a specified URL. The getFile() function returns the path and the query of the URL.
Function Signature:
public String getFile()
Syntax:
url.getFile()
Parameter: This function does not require any parameter
Return Type: The function returns String Type
Below programs illustrates the use of getFile() function:
Example 1: Given a URL we will get the file using the getFile() function.
// Java program to show the// use of the function getFile()  import java.net.*;  class Solution {    public static void main(String args[])    {        // url  object        URL url = null;          try {              // create a URL            url = new URL(                "https:// www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples/");              // get the  File            String _File = url.getFile();              // display the URL            System.out.println("URL = " + url);              // display the  File            System.out.println(" File= " + _File);        }          // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}
URL = https:// www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples/
 File= /url-getprotocol-method-in-java-with-examples/

Example 2: Now see how getFile() is different from getPath(). getPath() will exclude the query but getFile() will include the query
// Java program to show the// use of the function getFile()  import java.net.*;  class Solution {    public static void main(String args[])    {        // url  object        URL url = null;          try {              // create a URL            url = new URL(                "https:// www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol");              // get the  File            String _File = url.getFile();              // display the URL            System.out.println("URL = " + url);              // display the  File            System.out.println(" File= " + _File);        }          // if any error occurs        catch (Exception e) {              // display the error            System.out.println(e);        }    }}
URL = https:// www.geeksforgeeks.org/url-getprotocol-method-in-java-with-examples?title=protocol
 File= /url-getprotocol-method-in-java-with-examples?title=protocol

Java-Functions
Java-net-package
Java-URL
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
Python program to convert float to exponential

26 Oct, 2021
Given a float number, the task is to write a Python program to convert float to exponential.
Examples:
Input: 19.0
Output: 1.900000e+01

Input: 200.2
Output: 2.002000e+02

Input: 1101.02
Output: 1.101020e+03
Approach:
We will first declare and initialise a float number.
Then we will use format method to convert the number from integer to exponential type.
Then we will print the converted value.
Syntax:
String {field_name:conversion} Example.format(value)
Errors and Exceptions:
ValueError: Error occurs during type conversion in this method.
More parameters can be included within the curly braces of our syntax. Use the format code syntax {field_name: conversion}, where field_name specifies the index number of the argument to the str.format() method, and conversion refers to the conversion code of the data type.
Example:
Python3
# Python program to convert float to exponential # Declaring the float numberfloat_number = 1101.02 # Converting the float number to exponential numberexp_number = "{:e}".format(float_number) # Printing the converted numberprint("Float Number:",float_number)print("Exponent Number:",exp_number)
  
Output:
 
Float Number: 1101.02
Exponent Number: 1.101020e+03
 
kashishsoda
Python-datatype
Technical Scripter 2020
Python
Python Programs
Technical Scripter
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
PHP | mysqli_num_rows() Function

31 Jul, 2021
The mysqli_num_rows() function is an inbuilt function in PHP which is used to return the number of rows present in the result set. It is generally used to check if data is present in the database or not. To use this function, it is mandatory to first set up the connection with the MySQL database.
Syntax:
mysqli_num_rows ( $result );

Parameters: This function accepts single parameter $result (where $result is a MySQL query set up using mysqli_query()). It is a mandatory parameter and represents the result set returned by a fetch query in MySQL.
Return Value: It returns the number of rows present in a result set. If no rows match the given criteria then it returns false instead.
Consider there is a table named geek in a MySQL database named Geeks. Below is the description of the table geek.
Below programs illustrate the mysqli_num_rows() function in PHP.
<?php    // Setting up connection with database Geeks    $connection = mysqli_connect("localhost", "root", "",                                                  "Geeks");          // Check connection    if (mysqli_connect_errno())    {        echo "Database connection failed.";    }          // query to fetch Username and Password from    // the table geek    $query = "SELECT Username, Password FROM geek";          // Execute the query and store the result set    $result = mysqli_query($connection, $query);          if ($result)    {        // it return number of rows in the table.        $row = mysqli_num_rows($result);                     if ($row)              {                 printf("Number of row in the table : " . $row);              }        // close the result.        mysqli_free_result($result);    }      // Connection close     mysqli_close($connection);?>
Output:
Number of row in the table : 4

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.
ArkadyutiBanerjee
PHP-function
PHP-MySQL
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 ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Scala Iterator toList() method with example

28 May, 2019
The toList() method belongs to the concrete value members of the AbstractIterable class and is defined in the TraversableOnce and GenTraversableOnce classes. It converts a traversable or iterator to a list but it doesn’t terminates for infinite-sized collections.
Method Definition:def toList: List[A]

def toList: List[A]

Return Type:It returns a list from the stated traversable or an iterator.>/li>
Example :
// Scala program of toList()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Declaring an iterator        val iter = Iterator(8, 9, 10, 11)                  // Applying toList method        val result = iter.toList                      // Displays output        println(result)      }}
List(8, 9, 10, 11)

Therefore, a List is generated from an iterator.Example :
// Scala program of toList()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Declaring an empty-iterator        val iter = Iterator()                  // Applying toList method        val result = iter.toList                      // Displays output        println(result)      }}
List()

Therefore, an empty List is generated from an empty-iterator.
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala Tutorial – Learn Scala with Step By Step Guide
Class and Object in Scala
Scala Lists
Scala String substring() method with example
Scala | Arrays
Operators in Scala
Scala Constructors
How to Install Scala with VSCode?
Enumeration in Scala
Scala String replace() method with example
How to use 'extent' in matplotlib.pyplot.imshow?

To use extent in matplotlib imshow(), we can use extent [left, right, bottom, top].
Create random data using numpy.
Display the data as an image, i.e., on a 2D regular raster with data and extent [−1, 1, −1, 1] arguments.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(4, 4)
plt.imshow(data, extent=[-1, 1, -1, 1])
plt.show()
Setting a default variable value to undefined in a function - JavaScript?

Let’s say we are passing the following values to a function −
300
undefined
We will now set the default value. Following is the code −
function showValue(value)
{
   if (value===undefined) {
      value=100000;
   }
   else {
      value=value;
   }
   return value;
} 
console.log("The value="+showValue(300));
console.log("The value="+showValue(undefined));
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo246.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo246.js
The value=300
The value=100000
Dijkstra's algorithm in Javascript

Dijkstra's algorithm is an algorithm for finding the shortest paths between nodes in a weighted graph. We'll use the new addEdge and addDirectedEdge methods to add weights to the edges when creating a graph. Let us look at how this algorithm works −
Create a distance collection and set all vertices distances as infinity except the source node.
Enqueue the source node in a min-priority queue with priority 0 as the distance is 0.
Start a loop till the priority queue is empty and dequeue the node with the minimum distance from it.
Update the distances of the connected nodes to the popped node if "current node distance + edge weight < next node distance", then push the node with the new distance to the queue.
Continue till the priority queue is empty.
What this algorithm basically does is assumes all nodes are at an infinite distance from the source. Then it starts taking the edges in consideration and keeps track of distances of nodes from the source updating the same if it finds a lower cost path along the way.
Let us look at this implementation in code −
djikstraAlgorithm(startNode) {
   let distances = {};

   // Stores the reference to previous nodes
   let prev = {};
   let pq = new PriorityQueue(this.nodes.length * this.nodes.length);

   // Set distances to all nodes to be infinite except startNode
   distances[startNode] = 0;
   pq.enqueue(startNode, 0);
   this.nodes.forEach(node => {
      if (node !== startNode) distances[node] = Infinity;
      prev[node] = null;
   });

   while (!pq.isEmpty()) {
      let minNode = pq.dequeue();
      let currNode = minNode.data;
      let weight = minNode.priority;
      this.edges[currNode].forEach(neighbor => {
         let alt = distances[currNode] + neighbor.weight;
         if (alt < distances[neighbor.node]) {
            distances[neighbor.node] = alt;
            prev[neighbor.node] = currNode;
            pq.enqueue(neighbor.node, distances[neighbor.node]);
         }
      });
   }
   return distances;
}
You can test this using −
let g = new Graph();
g.addNode("A");
g.addNode("B");
g.addNode("C");
g.addNode("D");
g.addNode("E");
g.addNode("F");
g.addNode("G");

g.addDirectedEdge("A", "C", 100);
g.addDirectedEdge("A", "B", 3);
g.addDirectedEdge("A", "D", 4);
g.addDirectedEdge("D", "C", 3);
g.addDirectedEdge("D", "E", 8);
g.addDirectedEdge("E", "F", 10);
g.addDirectedEdge("B", "G", 9);
g.addDirectedEdge("E", "G", 50);

console.log(g.djikstraAlgorithm("A"));
This will give the output −
{ A: 0, B: 3, C: 7, D: 4, E: 12, F: 22, G: 12 }
sqlite3 - Unix, Linux Command

sqlite3 is a terminal-based front-end to the SQLite library that can evaluate
queries interactively and display the results in multiple formats.
sqlite3 can also be used within shell scripts and other applications to provide
batch processing features.




For example, to create a new database file named "mydata.db", create
a table named "memos" and insert a couple of records into that table:


$
sqlite3 mydata.db 
SQLite version 3.1.3

Enter ".help" for instructions

sqlite>
create table memos(text, priority INTEGER); 
sqlite>
insert into memos values(’deliver project description’, 10); 
sqlite>
insert into memos values(’lunch with Christine’, 100); 
sqlite>
select * from memos; 
deliver project description|10

lunch with Christine|100

sqlite>




If no database name is supplied, the ATTACH sql command can be used
to attach to existing or create new database files.  ATTACH can also
be used to attach to multiple databases within the same interactive
session.  This is useful for migrating data between databases,
possibly changing the schema along the way.


Optionally, a SQL statement or set of SQL statements can be supplied as
a single argument.  Multiple statements should be separated by
semi-colons.


For example:


$
sqlite3 -line mydata.db ’select * from memos where priority > 20;’ 
    text = lunch with Christine

priority = 100






The interactive interpreter offers a set of meta-commands that can be
used to control the output format, examine the currently attached
database files, or perform administrative operations upon the
attached databases (such as rebuilding indices).   Meta-commands are
always prefixed with a dot (.).


A list of available meta-commands can be viewed at any time by issuing
the ’.help’ command.  For example:


sqlite>
.help 











                         csv      Comma-separated values
                         column   Left-aligned columns.  (See .width)
                         html     HTML <table> code
                         insert   SQL insert statements for TABLE
                         line     One value per line
                         list     Values delimited by .separator string
                         tabs     Tab-separated values
                         tcl      TCL list elements












sqlite>
|cc .











o The default configuration is established as follows:






mode            = LIST
separator       = "|"
main prompt     = "sqlite> "
continue prompt = "   ...> "
|cc .





o If the file
~/.sqliterc exists, it is processed first.
can be found in the user’s home directory, it is
read and processed.  It should generally only contain meta-commands.


o If the -init option is present, the specified file is processed.


o All other command line options are processed.




Advertisements


    129 Lectures 
     23 hours 

 Eduonix Learning Solutions

    5 Lectures 
     4.5 hours 

 Frahaan Hussain

    35 Lectures 
     2 hours 

 Pradeep D

    41 Lectures 
     2.5 hours 

 Musab Zayadneh

    46 Lectures 
     4 hours 

 GUHARAJANM

    6 Lectures 
     4 hours 

 Uplatz
 Print
 Add Notes
 Bookmark this page
How to get the value of the edit box in Selenium?

We can get the value of the edit box in Selenium by the following ways −
By using getText () method.
By using getText () method.
Using the class JavascriptExecutor.
Using the class JavascriptExecutor.
Code Implementation with method getText ().
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class GetValueScripting {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      String text = driver.findElement(By.className("gsc-input")).getText();
      System.out.println("Extracted text is " + text);
      driver.close();
   }
}
Code Implementation with class JavascriptExecutor.
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ExtractValueScripting {
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = "https://www.tutorialspoint.com/index.htm";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // create Javascript object
      JavascriptExecutor js = (JavascriptExecutor)driver;
      // Issue command to extract the text
      String text = js.executeScript("return document.getElementById(' gsc-i-id1').value").toString();
      System.out.println("Extracted text is" + text);
      driver.close();
   }
}
C++ program to find first digit in factorial of a number

In this article, we will be discussing a program to find the first digit in the factorial of a given number.
The basic approach for this is to find the factorial of the number and then get its first digit. But since factorials can end up being too large, we would make a small tweak.
At every point we would check for any trailing zeroes and remove if any exists. Since trailing zeroes isn’t having any effect on the first digit; our result won’t change.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int calc_1digit(int n) {
   long long int fact = 1;
   for (int i = 2; i <= n; i++) {
      fact = fact * i;
      //removing trailing zeroes
      while (fact % 10 == 0)
         fact = fact / 10;
   }
   //finding the first digit
   while (fact >= 10)
   fact = fact / 10;
   return fact;
}
int main() {
   int n = 37;
   cout << "The first digit : " << calc_1digit(n) << endl;
   return 0;
}
The first digit : 1
Node.js console.clear() Method

13 Oct, 2021
The console.clear() method is used to clear the stdout, when stdout is a TTY (Teletype) i.e. terminal it will attempt to clear the TTY. When stdout is not a TTY, this method does nothing.
The console.clear() will work differently across different operating systems and terminal types. For Linux operating systems, console.clear() operates like the clear shell command in terminal. On Windows, console.clear() will clear the current terminal viewport for the Node.js binary.
Syntax:
console.clear()
Parameters: This method does not accept any parameters.
Below programs illustrate the console.clear() method in Node.js:
In this example, first we write the node.js command in the terminal and start node.js and then write basic command
After console.clear(), the terminal will cleared same like the clear command do in the terminal
To exit Node.js terminal press Ctrl + C two times or use .exit command.
Example:
// Node.js program to demonstrate the  // Buffer.clear() Method  // Both two lines will not display// the result on screenconsole.log("GeeksforGeeks");console.log("A computer science portal");  // Clear the previous screenconsole.clear();  // Display the contentconsole.log("Clear the console screen");
Output:
Reference: https://nodejs.org/api/console.html#console_console_clear
Node.js-console-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to update NPM ?
Difference between promise and async await in Node.js
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Perl opendir Function

This function opens the directory EXPR, associating it with DIRHANDLE for processing, using the readdir function.
Following is the simple syntax for this function −
opendir DIRHANDLE, EXPR

This function returns true if successful.
Following is the example code showing its basic usage −
#!/usr/bin/perl -w

$dirname = "/tmp";

opendir ( DIR, $dirname ) || die "Error in opening dir $dirname\n";
while( ($filename = readdir(DIR))) {
   print("$filename\n");
}
closedir(DIR);
When above code is executed, it produces the following result −