code-rag-bench/online-tutorials huggingface dataset:
Rust – Strings

01 Jun, 2021
String data type makes a very important part of any programming language. Rust handles strings a bit differently from other languages.  
The String data type in Rust is of two types:
String Literal (&str)
String Object (String)
String Literal or &str are called ‘string slices’, which always point to a legitimate UTF-8 sequence. It is used when we know the value of a string at compile time. They are a set of characters and static by default.
Example 1: Declaring string literals.
Rust
fn main() {   let website:&str="geeksforgeeks.org";   let language:&str = "RUST";   println!("Website is {}",website);   println!("Language is {}",language);}
Output:
Website is geeksforgeeks.org
Language is RUST
The String Object is provided by the Standard Library in Rust. It is not a part of the core language and String is heap-allocated, growable, and not null-terminated. They are commonly created by converting them from a string slice by using the to_string() method.
Example 2: Declaring String Object and converting String Literal to String Object
Rust
fn main() {      // Declaring String Object using from() method    let str1 = String::from("Rust Articles");    println!("{}",str1);       // Converting String Literal to String Object  let str2 = "GeeksforGeeks".to_string();  println!("{}",str2);}
Output:
Rust Articles
GeeksforGeeks
Example 3: Creating an empty string and then set its value.
Rust
fn main() {   let mut str1 = String::new();   str1.push_str("GeeksForGeeks");   println!("{}",z);}
Output:
GeeksForGeeks
Rust allows many methods to be used with Strings just as JAVA does. Also, it supports many methods such as indexing, concatenation, and slicing.
Picked
Rust-basics
strings
Rust
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rust - Creating a Library
Rust - Generic Function
Rust - For and Range
Rust - Casting
Rust - References & Borrowing
Rust - Concept of Structures
Primitive Compound Datatypes in Rust
Rust - While Loop
Rust - Box Smart Pointer
Rust - Comments
Ruby | Array append() function

07 Jan, 2020
Array#append() is an Array class method which add elements at the end of the array.
Syntax: Array.append()
Parameter: – Arrays for adding elements.– elements to add
Return: Array after adding the elements at the end.
Example #1 :
# Ruby code for append() method# adding elements at the end    # declaring arraya = [18, 22, 33, 4, 5, 6]    # declaring arrayb = [5, 4, 22, 1, 88, 9]    # declaring arrayc = [18, 22, 33, 40, 50, 6]   # appending array or element at the end of the arrayputs "adding elements in a : #{a.append(b)}\n\n"   puts "adding elements in b : #{b.append("ratttt")}\n\n"   puts "adding elements in c : #{c.append(b)}\n\n"
Output :
adding elements in a : [18, 22, 33, 4, 5, 6, [5, 4, 22, 1, 88, 9]]

adding elements in b : [5, 4, 22, 1, 88, 9, "ratttt"]

adding elements in c : [18, 22, 33, 40, 50, 6, [5, 4, 22, 1, 88, 9, "ratttt"]]

Example #2 :
# Ruby code for append() method# adding elements at the end    # declaring arraya = ["abc", "xyz", "dog"]    # declaring arrayb = ["cow", "cat", "dog"]    # declaring arrayc = ["cat", "1", "dog"]   # appending array or element at the end of the arrayputs "adding elements in a : #{a.append(b)}\n\n"   puts "adding elements in b : #{b.append("ratttt")}\n\n"   puts "adding elements in c : #{c.append(b)}\n\n"
Output :
adding elements in a : ["abc", "xyz", "dog", ["cow", "cat", "dog"]]

adding elements in b : ["cow", "cat", "dog", "ratttt"]

adding elements in c : ["cat", "1", "dog", ["cow", "cat", "dog", "ratttt"]]
Ruby Array-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Case Statement
Ruby Integer abs() function with example
Ruby | Hash Class
Ruby | unless Statement and unless Modifier
Ruby | Array map() function
Ruby | String reverse Method
Ruby Mixins
Ruby | Types of Variables
Global Variable in Ruby
Hello World in Ruby
Python PIL | BoxBlur() method

14 Sep, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method.PIL.ImageFilter.BoxBlur() Blurs the image by setting each pixel to the average value of the pixels in a square box extending radius pixels in each direction. Supports float radius of arbitrary size. Uses an optimized implementation which runs in linear time relative to the size of the image for any radius value. 
Syntax: PIL.ImageFilter.BoxBlur()

Partameters: 
radius: Size of the box in one direction. Radius 0 does not blur, returns an identical image. Radius 1 takes 1 pixel in each direction, i.e. 9 pixels in total.
Image used:  
 
Python3
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter     # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")     # applying the boxblur methodim2 = im1.filter(ImageFilter.BoxBlur(0))     im2.show()
Output:  
 
Python3
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter     # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")     # applying the boxblur methodim2 = im1.filter(ImageFilter.BoxBlur(2))     im2.show()
Output:  
 
Python3
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter     # creating a image objectim1 = Image.open(r"C:\Users\sadow984\Desktop\download2.JPG")     # applying the boxblur methodim2 = im1.filter(ImageFilter.BoxBlur(8))     im2.show()
Output:  
 
gulshankumarar231
Image-Processing
Python-pil
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
Python OOPs Concepts
Iterate over a list in Python
Program to find lowest possible integer that is missing in the array in Python

Suppose we have a list of numbers called nums, we have to find the first missing positive number. In other words, the lowest positive number that does not present in the array. The array can contain duplicates and negative numbers as well.
So, if the input is like nums = [0,3,1], then the output will be 2
To solve this, we will follow these steps −
nums := a set with all positive numbers present in nums
nums := a set with all positive numbers present in nums
if nums is null, thenreturn 1
if nums is null, then
return 1
return 1
for i in range 1 to size of nums + 2, doif i is not present in nums, thenreturn i
for i in range 1 to size of nums + 2, do
if i is not present in nums, then
if i is not present in nums, then
return i
return i
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      nums = set(num for num in nums if num > 0)

      if not nums:
         return 1
      for i in range(1, len(nums) + 2):
         if i not in nums:
            return i
ob = Solution()
nums = [0,3,1]
print(ob.solve(nums))
[0,3,1]
2
Python | os.stat() method

26 May, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.stat() method in Python performs stat() system call on the specified path. This method is used to get status of the specified path.
Syntax: os.stat(path)
Parameter:path: A string or bytes object representing a valid path
Return Type: This method returns a ‘stat_result’ object of class ‘os.stat_result’ which represents the status of specified path. The returned ‘stat-result’ object has following attributes:
st_mode: It represents file type and file mode bits (permissions).
st_ino: It represents the inode number on Unix and the file index on Windows platform.
st_dev: It represents the identifier of the device on which this file resides.
st_nlink: It represents the number of hard links.
st_uid: It represents the user identifier of the file owner.
st_gid: It represents the group identifier of the file owner.
st_size: It represents the size of the file in bytes.
st_atime: It represents the time of most recent access. It is expressed in seconds.
st_mtime: It represents the time of most recent content modification. It is expressed in seconds.
st_ctime: It represents the time of most recent metadata change on Unix and creation time on Windows. It is expressed in seconds.
st_atime_ns: It is same as st_atime but the time is expressed in nanoseconds as an integer.
st_mtime_ns: It is same as st_mtime but the time is expressed in nanoseconds as an integer.
st_ctime_ns: It is same as st_ctime but the time is expressed in nanoseconds as an integer.
st_blocks: It represents the number of 512-byte blocks allocated for file.
st_rdev: It represents the type of device, if an inode device.
st_flags: It represents the user defined flags for file.
Note: Some attributes are platform dependent and are subject to availability.
Code: Use of os.stat() method
# Python program to explain os.stat() method     # importing os module import os  # pathpath = '/home/User/Documents/file.txt'  # Get the status of# the specified pathstatus = os.stat(path)    # Print the status# of the specified pathprint(status)
os.stat_result(st_mode=33188, st_ino=795581, st_dev=2056, st_nlink=1, st_uid=1000,
st_gid=1000, st_size=243, st_atime=1531567080, st_mtime=1530346690, st_ctime=1530346690)

python-os-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – tensorflow.constant()

26 Jun, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.
constant() is used to create a Tensor from tensor like objects like list.
Syntax: tensorflow.constant( value, dtype, shape, name )
Parameters:
value: It is the value that needed to be converted to Tensor.
dtype(optional): It defines the type of the output Tensor.
shape(optional): It defines the dimension of output Tensor.
name(optiona): It defines the name for the operation.
Returns: It returns a Tensor.
Example 1: From Python list
Python3
# Importing the libraryimport tensorflow as tf  # Initializing the inputl = [1, 2, 3, 4]  # Printing the inputprint('l: ', l)  # Calculating resultx = tf.constant(l)    # Printing the resultprint('x: ', x)
Output:
l:  [1, 2, 3, 4]
x:  tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32)


Example 2: From Python tuple
Python3
# Importing the libraryimport tensorflow as tf  # Initializing the inputl = (1, 2, 3, 4)  # Printing the inputprint('l: ', l)  # Calculating resultx = tf.constant(l, dtype = tf.float64)    # Printing the resultprint('x: ', x)
Output:
l:  (1, 2, 3, 4)
x:  tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)



Python-Tensorflow
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Plotly with Pandas and Cufflinks

Pandas is a very popular library in Python for data analysis. It also has its own plot function support. However, Pandas plots don't provide interactivity in visualization. Thankfully, plotly's interactive and dynamic plots can be built using Pandas dataframe objects.
We start by building a Dataframe from simple list objects.
data = [['Ravi',21,67],['Kiran',24,61],['Anita',18,46],['Smita',20,78],['Sunil',17,90]]
df = pd.DataFrame(data,columns = ['name','age','marks'],dtype = float)

The dataframe columns are used as data values for x and y properties of graph object traces. Here, we will generate a bar trace using name and marks columns.
trace = go.Bar(x = df.name, y = df.marks)
fig = go.Figure(data = [trace])
iplot(fig)

A simple bar plot will be displayed in Jupyter notebook as below −
Plotly is built on top of d3.js and is specifically a charting library which can be used directly with Pandas dataframes using another library named Cufflinks.
If not already available, install cufflinks package by using your favourite package manager like pip as given below −
pip install cufflinks
or
conda install -c conda-forge cufflinks-py

First, import cufflinks along with other libraries such as Pandas and numpy which can configure it for offline use.
import cufflinks as cf
cf.go_offline()

Now, you can directly use Pandas dataframe to display various kinds of plots without having to use trace and figure objects from graph_objs module as we have been doing previously.
df.iplot(kind = 'bar', x = 'name', y = 'marks')

Bar plot, very similar to earlier one will be displayed as given below −
Instead of using Python lists for constructing dataframe, it can be populated by data in different types of databases. For example, data from a CSV file, SQLite database table or mysql database table can be fetched into a Pandas dataframe, which eventually is subjected to plotly graphs using Figure object or Cufflinks interface.
To fetch data from CSV file, we can use read_csv() function from Pandas library.
import pandas as pd
df = pd.read_csv('sample-data.csv')
If data is available in SQLite database table, it can be retrieved using SQLAlchemy library as follows −
import pandas as pd
from sqlalchemy import create_engine
disk_engine = create_engine('sqlite:///mydb.db')
df = pd.read_sql_query('SELECT name,age,marks', disk_engine)
On the other hand, data from MySQL database is retrieved in a Pandas dataframe as follows −
import pymysql
import pandas as pd
conn = pymysql.connect(host = "localhost", user = "root", passwd = "xxxx", db = "mydb")
cursor = conn.cursor()
cursor.execute('select name,age,marks')
rows = cursor.fetchall()
df = pd.DataFrame( [[ij for ij in i] for i in rows] )
df.rename(columns = {0: 'Name', 1: 'age', 2: 'marks'}, inplace = True)

    12 Lectures 
     53 mins

 Pranjal Srivastava
 Print
 Add Notes
 Bookmark this page
Program to Divide two 8 Bit numbers in 8051 Microprocessor

Here we will see the division operation. This operation will be used to divide two 8-bit numbers using this 8051 microcontroller. The register A and B will be used in this operation. No other registers can be used for division. The result of the division has two parts. The quotient part and the remainder part. Register A will hold Quotient, and register B will hold Remainder.
We are taking two number 0EH and 03H at location 20H and 21H, After dividing the result will be stored at location 30H and 31H.
      MOV R0, #20H ; set source address 20H to R0
      MOV R1, #30H ; set destination address 30H to R1
      MOV A, @R0 ; take the first operand from source to register A
      INC R0 ; Point to the next location
      MOV B, @R0 ; take second operand from source to register B
      DIV AB ; Divide A by B
      MOV @R1, A ; Store Quotient to 30H
      INC R1 ; Increase R1 to point to the next location
      MOV @R1, B ; Store Remainder to 31H
HALT: SJMP HALT ; Stop the program
8051 provides DIV AB instruction. By using this instruction, the division can be done. In some other microprocessors like 8085, there was no DIV instruction. In that microprocessor, we need to use repetitive Subtraction operations to get the result of the division.
When the denominator is 00H, the overflow flag OV will be 1. otherwise it is 0 for division.
How to interactively validate an Entry widget content in tkinter?

Validating the content is a necessary part of any featured application where we allow only the required data to be processed. An Entry Widget in tkinter is used to display single line text Input. However, we can validate the Entry widget to accept only digits or alphabets.
Let us first create an Entry widget that accepts only digits input. So initially, we will create an Entry widget and using register(callback) function, we will call to validate the Entry widget which validates whenever a key is stroked. It returns a string that can be used to call a function. Then, calling the callback function to validate the entry widget as,
entrywidget.config(validate="key", validatecommand=(callback,'%d'))
Validatecommand supports other values such as, %d, %i, %W, %P, %s, %v, etc.
#Import the required library
from tkinter import *
#Create an instance of tkinter frame or window
win = Tk()
def callback(input):
   if input.isdigit():
      print(input)
      return True
   elif input=="":
      print(input)
      return True
   else:
      print(input)
      return False
#Create an entry widget
entry= Entry(win)
fun= win.register(callback)
entry.config(validate="key", validatecommand=(fun, '%P'))
entry.pack()
win.mainloop()
Running the above code will display a window that contains an Entry widget which accepts only digits and prints the key strokes on the console.
In the output screen, enter any character. You will find that you can enter only digits, thus the entry widget is validated.
base64.b85encode() in Python - GeeksforGeeks

26 Mar, 2020
With the help of base64.b85encode() method, we can encode the string by using base85 alphabet into the binary form.
Syntax : base64.b85encode(string)
Return : Return the encoded string.
Example #1 :In this example we can see that by using base64.b85encode() method, we are able to get the encoded string which can be in binary form by using this method.
# import base64from base64 import b85encode  s = b'GeeksForGeeks'# Using base64.b85encode() methodgfg = b85encode(s)  print(gfg)
Output :
b’M`dMeb4G7+M`dMea{‘
 Example #2 :
# import base64from base64 import b85encode  s = b'I love python'# Using base64.b85encode() methodgfg = b85encode(s)  print(gfg)
Output :
b’Ng!-*c4Z)Nd30!RZU’
Python base64-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
How do I send a DELETE keystroke to a text field using Selenium with Python?

We can send a DELETE keystroke to a text field using Selenium webdriver with Python. First of all, we have to identify the text field with the help of any locators like xpath, css, id, and so on.
We can enter a text in the text field with the send_keys method. The value to be entered is passed as parameter to the method. To delete a key, we can pass Keys.BACKSPACE as a parameter to the send_keys method.
l = driver.find_element_by_id("gsc−i−id1")
l.send_keys("Sel")
l.send_keys(Keys.BACKSPACE)
To delete all the keys entered simultaneously, we have to pass CTRL+A and BACKSPACE as parameters to the send_keys method.
l = driver.find_element_by_id("gsc−i−id1")
l.send_keys("Sel")
l.send_keys(Keys.CONTROL + 'a', Keys.BACKSPACE)
Also, to use the Keys class, we have to add the import statement from selenium.webdriver.common.keys import Keys in our code.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
#set geckodriver.exe path
driver = webdriver.Firefox(executable_path="C:\\geckodriver.exe")
driver.implicitly_wait(0.5)
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element and enter text
l = driver.find_element_by_id("gsc−i−id1")
l.send_keys("Sel")
#delete a key
l.send_keys(Keys.BACKSPACE)
print("Value after deleting a single key")
print(l.get_attribute('value'))
#wait for some time
time.sleep(0.8)
#delete all keys at once
l.send_keys(Keys.CONTROL + 'a', Keys.BACKSPACE)
print("Value after deleting entire key")
print(l.get_attribute('value'))
#close driver session
driver.quit()
numpy.ndarray.T

This function belongs to ndarray class. It behaves similar to numpy.transpose.
import numpy as np 
a = np.arange(12).reshape(3,4) 

print 'The original array is:' 
print a 
print '\n'  

print 'Array after applying the function:' 
print a.T
The output of the above program would be −
The original array is:
[[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]

Array after applying the function:
[[ 0 4 8]
 [ 1 5 9]
 [ 2 6 10]
 [ 3 7 11]]


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
array_merge_recursive() function in PHP

The array_merge_recursive() function merges one or more arrays into one array recursively. The difference between this function and array_merge() is that if two or more elements have the same key, the array_merge_recursive() function forms the value as an array. In this case, array_merge() function considers the last one.
array_merge_recursive(arr1, arr2, arr3, ...)

arr1 − Initial array to merge
arr1 − Initial array to merge
arr2 − Another array
arr2 − Another array
arr3 − Another array
arr3 − Another array
The array_merge_recursive() function returns an array in which the elements of all arrays passed in parameters are merged.
The following is an example that merges two array with a key repeated in the second array. In this case the array_merge_recursive() function forms the value as an array.
 Live Demo
<?php
   $arr1 = array("p"=>"one","q"=>"two");
   $arr2 = array("q"=>"three","r"=>"four");
   print_r(array_merge_recursive($arr1,$arr2));
?>
Array
(
   [p] => one
   [q] => Array
      (
         [0] => two
         [1] => three
      )
      [r] => four
)
DAX Date & Time - WEEKNUM function

Returns the week number for the given date and year according to the return_type value. The week number indicates where the week falls numerically within a year.
WEEKNUM (<date>, [<return_type>]) 

date
Date in datetime format.
return_type
A number that determines the return value −
1 - Week begins on Sunday. Weekdays are numbered 1 through 7.
2 - Week begins on Monday. Weekdays are numbered 1 through 7.
If omitted, the default value is 1.
An integer, in the range 1 to 53.
DAX uses datetime data type to work with dates and times.
If the source data is in a different format, DAX implicitly converts the data to datetime to perform calculations.
By default, the WEEKNUM function uses a calendar convention in which the week containing January 1 is considered to be the first week of the year.
Note − The ISO 8601 calendar standard, widely used in Europe, defines the first week as the one with the majority of days (four or more) falling in the New Year.
This means that for years in which there are three days or less in the first week of January, the WEEKNUM function returns week numbers that are different from the ISO 8601 definition.
= WEEKNUM ("Oct 2, 2016", 1) returns 41. 
= WEEKNUM ("Dec 31, 2016", 1) returns 53. 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
PyQt5 QCalendarWidget - Setting Date Edit (Pop-Up) Accept Delay Property - GeeksforGeeks

13 Dec, 2021
In this article, we will see how we can set/change the date edit accept delay property of the QCalendarWidget. This property holds the time an inactive date edit is shown before its contents are accepted. If the calendar widget’s date edit is enabled, this property specifies the amount of time (in milliseconds) that the date edit remains open after the most recent user input. Once this time has elapsed, the date specified in the date edit is accepted and the popup is closed. By default, the delay is defined to be 1500 milliseconds (1.5 seconds).
The date edit pop-up appear when we try to select using a keyboard, the lesser the value of delay pop-will get closed more quickly
In order to do this we will use setDateEditAcceptDelay method with the QCalendarWidget object.Syntax : calendar.setDateEditAcceptDelay(n)Argument : It takes integer argumentReturn : It return None  
Below is the implementation  
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys  class Window(QMainWindow):     def __init__(self):        super().__init__()         # setting title        self.setWindowTitle("Python ")         # setting geometry        self.setGeometry(100, 100, 650, 400)         # calling method        self.UiComponents()         # showing all the widgets        self.show()     # method for components    def UiComponents(self):         # creating a QCalendarWidget object        self.calendar = QCalendarWidget(self)         # setting geometry to the calendar        self.calendar.setGeometry(50, 10, 400, 250)         # setting cursor        self.calendar.setCursor(Qt.PointingHandCursor)         # removing special cursor        self.calendar.unsetCursor()         # setting accept delay value        self.calendar.setDateEditAcceptDelay(2000)  # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output : 
 
clintra
arorakashish0911
Python PyQt-QCalendarWidget
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Selecting rows in pandas DataFrame based on conditions
Adding a legend to a Matplotlib boxplot with multiple plots on the same axis

To add a legend to a matplotlib boxplot with multiple plots on the same axis, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create random data, a and b, using numpy.
Create random data, a and b, using numpy.
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add an axes to the current figure as a subplot arrangement.
Add an axes to the current figure as a subplot arrangement.
Make a box and whisker plot using boxplot() method with different facecolors.
Make a box and whisker plot using boxplot() method with different facecolors.
To place the legend, use legend() method with two boxplots, bp1 and bp2, and ordered label for legend elements.
To place the legend, use legend() method with two boxplots, bp1 and bp2, and ordered label for legend elements.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np

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

a = np.random.rand(100, 2)
b = np.random.rand(100, 2)

fig = plt.figure()
ax = fig.add_subplot(111)

bp1 = ax.boxplot(a, positions=[1, 3], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C0"))
bp2 = ax.boxplot(a, positions=[0, 2], notch=True, widths=0.35, patch_artist=True, boxprops=dict(facecolor="C2"))
ax.legend([bp1["boxes"][0], bp2["boxes"][0]], ["Box Plot 1", "Box Plot 2"], loc='upper right')

plt.show()
How to change the font size of legend in base R plot?

In base R, we can use legend function to add a legend to the plot. For example, if we want to create a histogram with legend on top-right position then we can use legend("topright",legend="Normal Distribution") and if we want to change the font size then we need to as cex argument as shown below:
legend("topright",legend="Normal Distribution",cex=2)
 Live Demo
Consider the below histogram −
x<−rnorm(5000)
hist(x)
Adding legend of different sizes −
legend("topright",legend="Normal Distribution",cex=1)
legend("topleft",legend="Histogram of",cex=1.5)
How do we mix two strings and generate another in java?

Strings are used to store a sequence of characters in Java, they are treated as objects. The String class of the java.lang package represents a String.
You can create a String either by using the new keyword (like any other object) or, by assigning value to the literal (like any other primitive datatype).
String stringObject = new String("Hello how are you");
String stringLiteral = "Welcome to Tutorialspoint";
You can concatenate Strings in Java in the following ways −
Using the "+" operator − Java Provides a concatenation operator using this, you can directly add two String literals
import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      //Concatenating the two Strings
      String result = str1+str2;
      System.out.println(result);
   }
}
Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap
Java
Using the concat() method − The concat() method of the String class accepts a String value, adds it to the current String and returns the concatenated value.
import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      //Concatenating the two Strings
      String result = str1.concat(str2);
      System.out.println(result);
   }
}
Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap
Using StringBuffer and StringBuilder classes − StringBuffer and StringBuilder classes are those that can be used as alternative to String when modification needed.
These are similar to String except they are mutable. These provide various methods for contents manipulation. The append() method of these classes accepts a String value and adds it to the current StringBuilder object.
import java.util.Scanner;
public class StringExample {
   public static void main(String args[]) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the first string: ");
      String str1 = sc.next();
      System.out.println("Enter the second string: ");
      String str2 = sc.next();
      StringBuilder sb = new StringBuilder(str1);
      //Concatenating the two Strings
      sb.append(str2);
      System.out.println(sb);
   }
}
Enter the first string:
Krishna
Enter the second string:
Kasyap
KrishnaKasyap
Pure Functions in JavaScript

09 May, 2022
A Pure Function is a function (a block of code) that always returns the same result if the same arguments are passed. It does not depend on any state or data change during a program’s execution. Rather, it only depends on its input arguments.
Also a pure function does not produce any observable side effects such as network requests or data mutation etc.
Let’s see the below JavaScript Function:
function calculateGST( productPrice ) {
    return productPrice * 0.05;
}
The above function will always return the same result, if we pass the same productPrice. In other words, its output doesn’t get affected by any other values / state changes. So we can call “calculateGST” function a Pure Function.
Now, let’s see one more function below:
var tax = 20;
function calculateGST( productPrice ) {
    return productPrice * (tax / 100) + productPrice;
}
Pause a second and can you guess whether the above function is Pure or not ?
If you guessed that it is isn’t, you are right! It is not a pure function as the output is dependent on an external variable “tax”. So if the tax value is updated somehow, then we will get a different output though we pass the same productPrice as a parameter to the function.
But here we need to make an important note:
Note: If a pure function calls a pure function, this isn’t a side effect and the calling function is still considered pure. (Example: using Math.max() inside a function)
Below are some side effects (but not limited to) which a function should not produce in order to be considered as a pure function –
Making a HTTP request
Mutating data
Printing to a screen or console
DOM Query/Manipulation
Math.random()
Getting the current time
morganthemosaic
javascript-functions
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
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
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 ?
How to determine if an array contains a specific value in PHP?

27 May, 2021
Given an array and a specific value, we have to determine whether the array contains that value or not. So there is two popular way to determine that the specific value is in the array or not. One procedure is using by loop and other one is in_array() function. By using loop to get the specific value present or not is time-consuming compared to in_array() function so here we will skip the loop one and use the in_array() function.Below programs illustrate how to determine if an array contains a specific value:Program 1:  
php
<?php//array containing elements$names = array('Geeks', 'for', 'Geeks'); //search element$item = 'Geeks';if(in_array($item, $names)){        //the item is there    echo "Your element founded";}else{        //the item isn't there    echo "Element is not found";}?>
Output:  
Your element founded
Program 2: In this example the in_array function perform in strict mode, it will also check the type of array elements. 
php
<?php$name = array("Python", "Java", "C#", 3);         //Searching pythonif (in_array("python", $name, TRUE))  {  echo "found \n";  }else  {  echo "not found \n";  }       //Searching 3if (in_array(3, $name, TRUE))  {  echo "found \n";  }else  {  echo "not found \n";  }     //Searching Javaif (in_array("Java", $name, TRUE))  {  echo "found \n";  }else  {  echo "not found \n";  } ?>
Output:  
not found 
found 
found 
Program 3:  
php
<?php$arr= array('gfg', 1, 17); if (in_array('gfg', $arr)) {    echo " gfg \n";} if (in_array(18, $arr)) {    echo "18 found with strict check\n";}?>
Output:  
gfg 
In the above example, the array contains string “gfg” and two numbers 1 and 17. The if statement calls in_array() function which checks if the given item as the parameter is present in the given array or not. If the function returns true, the if statement is executed. 
akshaysingh98088
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Move all zeroes to end of array using List Comprehension in Python

21 Nov, 2018
Given an array of random numbers, Push all the zeros of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).
Examples:
Input :  arr = [1, 2, 0, 4, 3, 0, 5, 0]
Output : arr = [1, 2, 4, 3, 5, 0, 0, 0]

Input : arr  = [1, 2, 0, 0, 0, 3, 6]
Output : arr = [1, 2, 3, 6, 0, 0, 0]

We have existing solution for this problem please refer Move all zeroes to end of array link. We will solve this problem in python using List Comprehension in a single line of code.
# Function to append all zeros at the end # of arraydef moveZeros(arr):          # first expression returns a list of    # all non zero elements in arr in the     # same order they were inserted into arr    # second expression returns a list of     # zeros present in arr    return [nonZero for nonZero in arr if nonZero!=0] + \           [Zero for Zero in arr if Zero==0]  # Driver functionif __name__ == "__main__":    arr = [1, 2, 0, 4, 3, 0, 5, 0]    print (moveZeros(arr))
Output:
[1, 2, 4, 3, 5, 0, 0, 0]

This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python list-programs
python-list
Arrays
Python
python-list
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
ReactJS – useRef hook

In this article, we are going to see how to create a reference to any DOM element in a functional component.
This hook is used to access any DOM element in a component and it returns a mutable ref object which will be persisted as long as the component is placed in the DOM.
If we pass a ref object to any DOM element, then the .current property to the corresponding DOM node elements will be added whenever the node changes.
const refContainer = useRef(initialValue);
In this example, we will build a React application that passes the ref object to two input fields.
When clicked on a button, it will automatically fetch the data of these input fields.
App.jsx
import React, { useRef } from 'react';

function App() {

   const email = useRef(null);
   const username = useRef(null);

   const fetchEmail = () => {
      email.current.value = 'rahul@gmail.com';
      email.current.focus();
   };
   const fetchUsername = () => {
      username.current.value = 'RahulBansal123';
      username.current.focus();
   };
   return (
      <>
         <div>
            <h1>Tutorialspoint</h1>
         </div>
         <div>
            <input placeholder="Username" ref={username} />
            <input placeholder="Email" ref={email} />
         </div>
         <button onClick={fetchUsername}>Username</button>
         <button onClick={fetchEmail}>Email</button>
      </>
   );
}
export default App;
In the above example, when the Username or Email button is clicked, the fetchUsername and fetchEmail function is called respectively which pass the ref object to the input fields and change its value from NULL to some text.
This will produce the following result.
Lodash _.isNil() Method

05 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.isNil() method is used to check if the value is null or undefined. If the value is nullish then returns true otherwise it returns false.
Syntax:
_.isNil(value)
Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to check.
Return Value: This method returns true if the value is nullish, else false.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Javascript
// Requiring the lodash library  const _ = require("lodash");       // Use of _.isNil()  // method let gfg = _.isNil(null);         // Printing the output  console.log(gfg);
 Output:
true
 
Example 2:  
Javascript
// Requiring the lodash library  const _ = require("lodash");       // Use of _.isNil()  // method let gfg = _.isNil(void 0);         // Printing the output  console.log(gfg);
 Output:
true
Example 3:  
Javascript
// Requiring the lodash library  const _ = require("lodash");       // Use of _.isNil()  // method let gfg = _.isNil(NaN);         // Printing the output  console.log(gfg);
 Output:
false
 
JavaScript-Lodash
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
Roadmap to Learn JavaScript For Beginners
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 ?
How to play audio repeatedly using HTML5 ?

14 Jul, 2020
This article will show you how an audio file can be played repeatedly on a web page. This is done by using the loop attribute of the <audio> tag. It is used to restart the audio again and again after loading the web page. This can be used in situations where the audio has to be looped until it is specifically stopped, like in the case of background music on a web page.
Syntax:
<audio loop>
Example:
html
<!DOCTYPE html><html>  <head>    <title>        How to play an audio repeatedly        using HTML5?    </title></head>  <body>    <h1 style="color: green;">        GeeksForGeeks    </h1>    <b>        How to play an audio repeatedly        using HTML5?    </b>      <p><b>Non Looping Audio</b></p>      <audio controls>        <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3"        type="audio/mp3">    </audio>        <p><b>Looping Audio</b></p>        <!-- Using the loop attribute -->    <audio controls loop>        <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190625153922/frog.mp3"        type="audio/mp3">    </audio></body>  </html>
Output: 
Supported Browsers:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Opera 10.5
Safari 4.0 
HTML-Misc
HTML5
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Angular File Upload
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to pass arguments to shell script in crontab ?

18 Jul, 2021
In this article, we will discuss how to schedule shell scripts in contrab and to pass necessary parameters as well.
First, let’s create a simple script that we will be scheduled to run every 2 minutes. The below is a simple script that calculates the sum of all parameters passed and prints them to STDOUT along with the time the script was run.
#! /usr/bin/sh
SUM=0
for i in $@ 
do 
    SUM=`expr $SUM + $i`
done
echo "$SUM was calculated at `date`"
Note: #! /usr/bin/sh (specifying the path of script interpreter) is necessary if wish to make the script executable.
Assuming we have saved this script as  my_script.sh under our home directory, we can make it executable by entering the following command in our terminal:
chmod +x my_script.sh
We can test our script if it is working properly:
./my_script.sh 1 2 3 4 5
15 was calculated at Thursday 01 July 2021 01:24:04 IST 2021
The crontab scheduling expression has the following parts:
To schedule our script to be executed, we need to enter the crontab scheduling expression into the crontab file. To do that, simply enter the following in the terminal:
crontab -e
You might be prompted to select an editor, choose nano and append the following line to the end of the opened crontab file:
*/2 * * * * /home/$(USER)/my_script.sh 1 2 3 4 5 >> /home/$(USER)/output.txt
where $(USER) can be replaced with your username. Save changes and exit. This will schedule our shell script to run every 2 minutes with 1 2 3 4 5 as command-line arguments and write the output to /home/$(USER)/ouput.txt.
Note: There are a few things to keep in mind before scheduling cron jobs:
All cron jobs are scheduled in the local time zone in which the system where the jobs are being scheduled operates. This could be troublesome if jobs are being scheduled on servers with multinational personnel using it. Especially if the users also belong to countries that follow Daylight Savings Time practice.
All cron jobs run in their own isolated, anonymous shell sessions and their output to STDOUT (if any) must be directed to a file if we wish to see them.
All cron jobs run in the context of the user for which they were scheduled. It is therefore always good practice to provide an absolute path to scripts and output files to avoid any confusion and cluttering.
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Image to PDF in Python?

04 Dec, 2020
img2pdf is an open source Python package to convert images to pdf format. It includes another module Pillow which can also be used to enhance image (Brightness, contrast and other things)
Use this command to install the packages
pip install img2pdf
 Below is the implementation:
Image can be converted into pdf bytes using img2pdf.convert() functions provided by img2pdf module, then the pdf file opened in wb mode and is written with the bytes.
# Python3 program to convert image to pfd# using img2pdf library  # importing necessary librariesimport img2pdffrom PIL import Imageimport os  # storing image pathimg_path = "C:/Users/Admin/Desktop/GfG_images/do_nawab.png"  # storing pdf pathpdf_path = "C:/Users/Admin/Desktop/GfG_images/file.pdf"  # opening imageimage = Image.open(img_path)  # converting into chunks using img2pdfpdf_bytes = img2pdf.convert(image.filename)  # opening or creating pdf filefile = open(pdf_path, "wb")  # writing pdf files with chunksfile.write(pdf_bytes)  # closing image fileimage.close()  # closing pdf filefile.close()  # outputprint("Successfully made pdf file")
Output:
Successfully made pdf file
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.