code-rag-bench/online-tutorials huggingface dataset:
Program to count maximum number of distinct pairs whose differences are larger than target in Python

Suppose we have a list of numbers called nums and another value target. We have to find the maximum number of pairs where for each pair i < j, i and j are not in any other pair, and |nums[i] - nums[j]| >= target.
So, if the input is like nums = [2, 4, 6, 10, 11], target = 5, then the output will be 2, as we can get pairs: (2, 6), (5, 10)
To solve this, we will follow these steps −
N := size of A
sort the list A
ans := 0
j := N / 2
for i in range 0 to N / 2, dowhile j < N and A[j] - A[i] < target, doj := j + 1if j < N, thenans := ans + 1j := j + 1
while j < N and A[j] - A[i] < target, doj := j + 1
j := j + 1
if j < N, thenans := ans + 1j := j + 1
ans := ans + 1
j := j + 1
return ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, A, target):
      N = len(A)
      A.sort()
      ans = 0
      j = N >> 1
      for i in range(N >> 1):
         while j < N and A[j] - A[i] < target:
            j += 1
         if j < N:
            ans += 1
            j += 1
      return ans
ob = Solution()
nums = [2, 4, 6, 10, 11]
target = 5
print(ob.solve(nums, target))
[2, 4, 6, 10, 11], 5
2
Formatting float column of Dataframe in Pandas - GeeksforGeeks

21 Aug, 2020
While presenting the data, showing the data in the required format is also an important and crucial part. Sometimes, the value is so big that we want to show only desired part of this or we can say in some desired format.
Let’s see different methods of formatting integer column of Dataframe in Pandas.
Code #1 : Round off the column values to two decimal places.
# import pandas lib as pdimport pandas as pd  # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'],     'Expense': [ 21525220.653, 31125840.875, 23135428.768, 56245263.942]}  # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense'])  print("Given Dataframe :\n", dataframe)  # round to two decimal places in python pandaspd.options.display.float_format = '{:.2f}'.format  print('\nResult :\n', dataframe)
Output:
 Code #2 : Format ‘Expense’ column with commas and round off to two decimal places.
# import pandas lib as pdimport pandas as pd  # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'],        'Expense':[ 21525220.653, 31125840.875, 23135428.768, 56245263.942]}  # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense'])  print("Given Dataframe :\n", dataframe)  # Format with commas and round off to two decimal places in pandaspd.options.display.float_format = '{:, .2f}'.format  print('\nResult :\n', dataframe)
Output:
 Code #3 : Format ‘Expense’ column with commas and Dollar sign with two decimal places.
# import pandas lib as pdimport pandas as pd  # create the data dictionarydata = {'Month' : ['January', 'February', 'March', 'April'],        'Expense':[ 21525220.653, 31125840.875, 23135428.768, 56245263.942]}  # create the dataframedataframe = pd.DataFrame(data, columns = ['Month', 'Expense'])  print("Given Dataframe :\n", dataframe)  # Format with dollars, commas and round off# to two decimal places in pandaspd.options.display.float_format = '${:, .2f}'.format  print('\nResult :\n', dataframe)
Output:
varun bankapur
pandas-dataframe-program
Picked
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
sum() function in Python
Python 3 - List insert() Method

The insert() method inserts object obj into list at offset index.
Following is the syntax for insert() method −
list.insert(index, obj)

index − This is the Index where the object obj need to be inserted.
index − This is the Index where the object obj need to be inserted.
obj − This is the Object to be inserted into the given list.
obj − This is the Object to be inserted into the given list.
This method does not return any value but it inserts the given element at the given index.
The following example shows the usage of insert() method.
#!/usr/bin/python3

list1 = ['physics', 'chemistry', 'maths']
list1.insert(1, 'Biology')
print ('Final list : ', list1)
When we run above program, it produces the following result −
Final list :  ['physics', 'Biology', 'chemistry', 'maths']


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Opening and reading a file with askopenfilename in Tkinter?

When a user wants to open a file from a directory, the preferred way to do this is to display a popup where the user selects a file to Open. Like most tools and widgets, Tkinter provides us a way to open a dialog for opening a file, reading a file, saving a file. All these functionalities are part of filedialog Module in Python. Just like other widgets, filedialog needs to be imported explicitly in the notebook. There are certain other modules that contain the filedialog such as, askdirectory, askopenfilename, askopenfile, askopenfilenames, asksaveasfilename, etc.
In this example, we will define a function to open and read the file using askopenfilename.
We will define an application which contains a button to open a file and will pack the content of the file in a Label widget. In order to read the file content, we will use the read() method along with the filename.
#Import tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Create an instance of tkinter frame or window
win= Tk()
win.geometry("750x150")
#Define a function to Opening the specific file using filedialog
def open_files():
   path= filedialog.askopenfilename(title="Select a file", filetypes=(("text files","*.txt"),
("all files","*.*")))

   file= open(path,'r')
   txt= file.read()
   label.config(text=txt, font=('Courier 13 bold'))
   file.close()
   button.config(state=DISABLED)
   win.geometry("750x450")
#Create an Empty Label to Read the content of the File
label= Label(win,text="", font=('Courier 13 bold'))
label.pack()
#Create a button for opening files
button=ttk.Button(win, text="Open",command=open_files)
button.pack(pady=30)
win.mainloop()
Running the above code will display a window which contains a button which when clicked, will open a new window to load and read the file content.
Click the "Open" button to open the file(text, "*") in the window.
Lambda Expressions in C#

A lambda expression in C# describes a pattern.
Lambda Expressions has the token => in an expression context. This is read as “goes to” operator and used when a lambda expression is declared.
Here, we are finding the first occurrence of the element greater than 50 from a list.
list.FindIndex(x => x > 50);
Above the token => is used. The same is shown below −
 Live Demo
using System;
using System.Collections.Generic;

class Demo {
   static void Main() {
      List<int> list = new List<int> { 44, 6, 34, 23, 78 };

      int res = list.FindIndex(x => x > 50);
      Console.WriteLine("Index: "+res);
   }
}
Index: 4
Prime numbers within a range in JavaScript

We are required to write a JavaScript function that takes in two numbers, say, a and b and
returns the total number of prime numbers between a and b (including a and b, if they are
prime).
For example: If a = 21, and b = 38.
The prime numbers between them are 23, 29, 31, 37
The prime numbers between them are 23, 29, 31, 37
And their count is 4
And their count is 4
Our function should return 4
Our function should return 4
The code for this will be −
const isPrime = num => {
   let count = 2;
   while(count < (num / 2)+1){
      if(num % count !== 0){
         count++;
         continue;
      };
      return false;
   };
   return true;
};
const primeBetween = (a, b) => {
   let count = 0;
   for(let i = Math.min(a, b); i <= Math.max(a, b); i++){
      if(isPrime(i)){
         count++;
      };
   };
   return count;
};
console.log(primeBetween(21, 38));
The output in the console −
4
Nearest prime less than given number n C++

We are given a number n, we need to find the nearest prime number that is less than n. We can find the number easily if we start checking from the n - 1. Let's see some examples.
Input
10
Output
7
Initialise the number n.
Write a loop that iterates from n - 1 to 1Return the first prime number that you found
Return the first prime number that you found
Return -1 if you didn't find any prime that's less than given n
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h>
using namespace std;
bool isPrime(int n) {
   if (n == 2) {
      return true;
   }
   for (int i = 2; i <= ceil(sqrt(n)); i++) {
      if (n % i == 0) {
         return false;
      }
   }
   return true;
}
int getNearestPrimeNumber(int n) {
   for (int i = n - 1; i > 1; i--) {
      if (isPrime(i)) {
         return i;
      }
   }
   return -1;
}
int main() {
   int n = 20;
   cout << getNearestPrimeNumber(n) << endl;
   return 0;
}
If you run the above code, then you will get the following result.
19
How to query JSON datatype in MySQL?

Use JSON data type from MySQL to work with JSON. Let us first create a table −
mysql> create table DemoTable
-> (
-> StudentName json
-> );
Query OK, 0 rows affected (0.74 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('["John", "Chris", "Robert","David","Sam"]');
Query OK, 1 row affected (0.33 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+---------------------------------------------+
| StudentName                                 |
+---------------------------------------------+
| ["John", "Chris", "Robert", "David", "Sam"] |
+---------------------------------------------+
1 row in set (0.00 sec)
Here is how you can query JSON data type −
mysql> SELECT *from DemoTable WHERE JSON_CONTAINS(StudentName, '["Chris"]');
This will produce the following output −
+---------------------------------------------+
| StudentName                                 |
+---------------------------------------------+
| ["John", "Chris", "Robert", "David", "Sam"] |
+---------------------------------------------+
1 row in set (0.04 sec)
How to add users and groups to the local groups on Windows System using PowerShell?

To add users to the local groups using PowerShell, we need to use the Add-LocalGroupMember command (Module − Microsoft.PowerShell.LocalAccounts).
Add-LocalGroupMember -Group "Administrators" -Member
"NewLocalUser","labdomain\Alpha","Labdomain\ITSecurity"
The above command adds 2 users (NewLocalUser (Local) and Alpha (Domain)) and one Domain Security Group ITSecurity to the Local Administrators group.
You can also use the other local group name instead of Administrators.
To add the new users in the local group on the remote system(s) use the Invoke-Command method. For example,
Invoke-Command -ComputerName Test1-Win2k12, Test1-Win2k16{
   Add-LocalGroupMember -Group "Administrators" -Member
   "NewLocalUser","labdomain\Alpha","Labdomain\ITSecurity"
}
Please note − To run the above command, the remote server must use the PS version 5.1 or advance version.
You can also use the command prompt if you don’t have the PS version 5.1 or higher to add users to the group using the below command syntax.
net localgroup groupname username /add
For example,
net localgroup Administrators "labdomain\alpha" /add
In the above example, we are adding LabDomain user Alpha to the local Administrators group. You can replace the Administrators with the other group name. For the local user/group, we just need to provide the username or group name without specifying the domain. For example,
net localgroup Administrators "NewLocalUser" /add
To add the above commands remotely,
Invoke-Command -ComputerName Test1-Win2k12, Test1-Win2k16 -ScriptBlock{
   Net Localgroup Administrators "LabDomain\Alpha" /add
}
What is CGI in Python ? - GeeksforGeeks

10 Feb, 2022
CGI stands for Common Gateway Interface in Python which is a set of standards that explains how information or data is exchanged between the web server and a routine script. This interface is used by web servers to route information requests supplied by a browser or we can say that CGI is customary for external gateway programs to interface with information servers such as HTTP servers. A CGI script is invoked by an HTTP server, usually to course user input which is submitted through an HTML <FORM> or an <ISINDEX> element.
Whenever we click on a hyperlink to browse a particular web page or URL, our browser interacts with the HTTP web server and asks for the same URL (or filename). Web Server then parses the URL and looks for the same filename. If that file is found, then that file is sent back to the browser, otherwise, an error message is sent indicating that we are demanding the wrong file. Web browser takes the response from a web server and displays it, then whether it is the received file from the webserver or an error message. But, conversely, it is possible to set up the HTTP server so that whenever a specific file is requested, then that file is not sent back, but instead, it is executed as a program, and whatever that program output is, that is sent back to our browser for display. This same function is called the Common Gateway Interface (or CGI) and the programs which are executed are called CGI scripts. In python, these CGI programs are Python Script.
Example:Let us take a sample URL which passes two values to first_cgi.py program using GET method:/cgi-bin/first_cgi.py?your_name=Piyush&company_name=GeeksforGeeks
Below is the first_cgi.py script to handle the input given by the above sample URL. Here we will use cgi module which will makes it very easy to access the passed information  
Python3
#!/usr/bin/python  # Import CGI and CGIT moduleimport cgi, cgitb                # to create instance of FieldStorage # class which we can use to work # with the submitted form dataform = cgi.FieldStorage()      your_name = form.getvalue('your_name')      # to get the data from fieldscomapny_name = form.getvalue('company_name')     print ("Content-type:text/html\n")print ("<html>")print ("<head>")print ("<title>First CGI Program</title>")print ("</head>")print ("<body>")print ("<h2>Hello, %s is working in %s</h2>"        % (your_name, company_name))  print ("</body>")print ("</html>")
Output:
 Hello, Piyush is working in GeeksforGeeks 

reenadevi98412200
Python-CGI
python-utility
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
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python program to convert a list to string
Python String | replace()
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
JavaScript Date Set Methods

Set Date methods let you set date values (years, 
months, days, hours, minutes, seconds, milliseconds) for a Date Object.
Set Date methods are used for setting a part of a date:
The setFullYear() method sets the year of a date object. In this example to 2020:
The setFullYear() method can optionally set month and day:
The setMonth() method sets the month of a date object (0-11):
The setDate() method sets the day of a date object (1-31):
The setDate() method can also be used to add days to a date:
If adding days shifts the month or year, the changes are handled automatically by the Date object.
The setHours() method sets the hours of a date object (0-23):
The setMinutes() method sets the minutes of a date object (0-59):
The setSeconds() method sets the seconds of a date object (0-59):
Dates can easily be compared.
The following example compares today's date with January 14, 2100:
JavaScript counts months from 0 to 11. January is 0. December is 11.
For a complete Date reference, go to our:
Complete JavaScript Date Reference.
The reference contains descriptions and examples of all Date properties and 
methods.
Use the correct Date method to set the year of a date object to 2020.
const d = new Date();
d.;

Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to convert a value of one type to another type in SQL server - GeeksforGeeks

07 Dec, 2020
Convert means to change the form or value of something. The CONVERT() function in SQL server is used to convert a value of one type to another type.
Syntax :
SELECT CONVERT 
( target_type ( length ), expression ) 

Parameters used :
target_type –It is the target data type to which the to expression will be converted, e.g: INT, BIT, SQL_VARIANT, etc.
length –It provides the length of the target_type. Length is not mandatory. Default length is set to 30.
expression –expression is anything that will be converted.
Example-1 :To convert a decimal to an integer :In below example, the CONVERT() function is used to convert the decimal number 7.85 to an integer.
SELECT CONVERT(INT, 7.85) AS Result;

Output :
Example-2 :To convert a decimal to another decimal :In below example, the CONVERT() function is used to convert the decimal number 8.99 to another decimal number with zero scales.
SELECT CAST(8.99 AS DEC(2, 0)) 
AS Result;
Output :
Example-3 :To convert a string to a datetime value :In below example, the CONVERT() function is used to convert the string ‘2020-05-14’ to a datetime value.
SELECT CONVERT(DATETIME, '2020-05-14') 
AS Result;
Output :
Example-4 :To convert a datetime value to a string :In below example, the CONVERT() function is used to convert the current date and time to a string with a definite style.
SELECT  CONVERT(VARCHAR, GETDATE(), 13) 
AS Result;
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Composite Key in SQL
SQL using Python
SQL | DROP, TRUNCATE
SQL indexes
SQL | Date functions
What is Temporary Table in SQL?
Window functions in SQL
How to Concat Two Columns Into One With the Existing Column Name in MySQL?
How to change the size of text on a label in Tkinter?

The label widget in Tkinter is used to display text and images in a Tkinter application. In order to change the properties of the label widget such as its font-property, color, background color, foreground color, etc., you can use the configure() method.
If you want to change the size of the text in a Label widget, then you can configure the font=('font-family font-size style') property in the widget constructor.
# Import the required libraries
from tkinter import *
import tkinter.font as tkFont

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

# Set the size of the tkinter window
win.geometry("700x350")

def font_style():
   label.config(font=('Helvetica bold', 26))

# Create a Label
label = Label(win, text="Click the Button to Change the Font Style.", font=('Times', 24))
label.pack()

b1 = Button(win, text="Change the Label Size", command=font_style)
b1.pack()

win.mainloop()
When you run the above code, it will display a window with a label widget and a button to change the font style of the label.
Now, click the "Change the Label Size" button and it will modify the font style of the label.
JavaScript Number - NaN

Unquoted literal constant NaN is a special value representing Not-a-Number. Since NaN always compares unequal to any number, including NaN, it is usually used to indicate an error condition for a function that should return a valid number.
Note − Use the isNaN() global function to see if a value is an NaN value.
The syntax to use NaN is −
var val = Number.NaN;

Try the following example to learn how to use NaN.
<html>
   <head>      
      <script type = "text/javascript">
         <!--
            function showValue() {
               var dayOfMonth = 50;
               
               if (dayOfMonth < 1 || dayOfMonth > 31) {
                  dayOfMonth = Number.NaN
                  alert("Day of Month must be between 1 and 31.")
               }
               Document.write("Value of dayOfMonth : " + dayOfMonth );
            }
         //-->
      </script>      
   </head>
   
   <body>
      <p>Click the following to see the result:</p>      
      <form>
         <input type = "button" value = "Click Me" onclick = "showValue();" />
      </form>      
   </body>
</html>
Click the following to see the result:

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
Creating Junction Points - GeeksforGeeks

05 Oct, 2020
Junction Points (also commonly referred to as NTFS Junction or Directory Junction) is a type of reparse point which contains a link to a directory that acts as an alias of that directory. Junction points are a Windows exclusive feature, absent in other operating systems. Compatibility with Legacy Windows OS and less privilege requirement makes Junction Points a good alternative for symlinks. In this article, we will take a look at methods used for the creation of junction points on Windows OS.
Description of the command :
Mklink /J Link Target
Description of command as follows.
/J      : Creates a Directory Junction
Link    : Specifies the new symbolic link name.
Target  : Specifies the path (relative or absolute) that the new link refers to.

Note –The above text is a stripped-out section out of mklink help page.
Creating a Junction Point :Junction points can be created both relatively or absolutely, but they would always refer to the Target path in an absolute manner. Therefore, regardless of whether the link was created using relative paths or using absolute paths, the final target path would be absolute.
In the following example we would be creating an Junction Point to the Directory having C:\suga path in our Operating System.
To create a junction point at a different path (C:\Users\Public\), the command would look as follows.
mklink /J "C:\Users\Public\Junction_PT" "C:\suga"

Note –We have provided both source and Target paths as absolute, for the sake of simplicity.
Where C:\Users\Public\Junction_PT is the full path to our newly created junction. After the execution of the above command, a Directory Junction would be created at the Link path, which could be confirmed by its entry of type <JUNCTION> in the output of dir command on the newly created junction’s parent directory.
Volume in drive C has no label.
Volume Serial Number is 2C7D-7820

Directory of C:\Users\Public

09/18/2020  06:22 PM    <DIR>          .
09/18/2020  06:22 PM    <DIR>          ..
09/18/2020  09:28 AM    <DIR>          Documents
06/22/2020  11:25 PM    <DIR>          Downloads
09/18/2020  06:22 PM    <JUNCTION>     Junction_PT [C:\suga]
06/22/2020  11:25 PM    <DIR>          Music
06/22/2020  11:37 PM    <DIR>          Pictures
06/22/2020  11:25 PM    <DIR>          Videos
              0 File(s)              0 bytes
              8 Dir(s)  36, 849, 307, 648 bytes free

Note –Bolded the field we are interested in.The junction point (Junction_PT) would have a similar appearance to this.
File & Disk Management
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Memory Management in Operating System
Difference between Internal and External fragmentation
Program for Least Recently Used (LRU) Page Replacement algorithm
Mutex lock for Linux Thread Synchronization
Logical and Physical Address in Operating System
File Allocation Methods
States of a Process in Operating Systems
Shortest Remaining Time First (Preemptive SJF) Scheduling Algorithm
Dining Philosopher Problem Using Semaphores
Producer Consumer Problem using Semaphores | Set 1
How to Convert Int to Bytes in Python? - GeeksforGeeks

23 Dec, 2020

An int object can be used to represent the same value in the format of the byte. The integer represents a byte, is stored as an array with its most significant digit (MSB) stored at either the start or end of the array. 
Method 1: int.tobytes()
An int value can be converted into bytes by using the method int.to_bytes(). The method is invoked on an int value, is not supported by Python 2 (requires minimum Python3) for execution.
Syntax: int.to_bytes(length, byteorder)
Arguments : 
length – desired length of the array in bytes .
byteorder – order of the array to carry out conversion of an int to bytes. byteorder can have values as either “little” where most significant bit is stored at the end and least at the beginning, or big, where MSB is stored at start and LSB at the end. 
Exceptions : 
OverflowError is returned in case the integer value length is not large enough to be accommodated in the length of the array. 
The following programs illustrate the usage of this method in Python : 
Python3
 

 
 










# declaring an integer value 
integer_val = 5
  
# converting int to bytes with length  
# of the array as 2 and byter order as big 
bytes_val = integer_val.to_bytes(2, 'big') 
  
# printing integer in byte representation 
print(bytes_val) 






b'\x00\x05'
Python3
 

 
 










# declaring an integer value 
integer_val = 10
  
# converting int to bytes with length  
# of the array as 5 and byter order as  
# little 
bytes_val = integer_val.to_bytes(5, 'little') 
  
# printing integer in byte representation 
print(bytes_val) 






b'\n\x00\x00\x00\x00'
Method 2: Converting integer to string and string to bytes 
This approach works is compatible in both Python versions, 2 and 3. This method doesn’t take the length of the array and byteorder as arguments. 
An integer value represented in decimal format can be converted to string first using the str() function , which takes as argument the integer value to be converted to the corresponding string equivalent.
This string equivalent is then converted to a sequence of bytes by choosing the desired representation for each character, that is encoding the string value. This is done by the str.encode() method.
Python3
 

 
 










# declaring an integer value 
int_val = 5
  
# converting to string 
str_val = str(int_val) 
  
# converting string to bytes 
byte_val = str_val.encode() 
print(byte_val) 






b'5'

python-basics


Python

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
Enumerate() in Python
Read a file line by line in Python
Defaultdict in Python
Different ways to create Pandas Dataframe
sum() function in Python
Iterate over a list in Python
How to Install PIP on Windows ?
Deque in Python
Python String | replace()
Convert integer to string in Python
POSIX Function strftime() in Perl

You can use the POSIX function strftime() in Perl to format the date and time with the help of the following table. Please note that the specifiers marked with an asterisk (*) are locale-dependent.
Let's check the following example to understand the usage −
 Live Demo
#!/usr/local/bin/perl
use POSIX qw(strftime);
$datestring = strftime "%a %b %e %H:%M:%S %Y", localtime;
printf("date and time - $datestring\n");
# or for GMT formatted appropriately for your locale:
$datestring = strftime "%a %b %e %H:%M:%S %Y", gmtime;
printf("date and time - $datestring\n");
When the above code is executed, it produces the following result −
date and time - Sat Feb 16 07:10:23 2013
date and time - Sat Feb 16 14:10:23 2013
Data Structures | Hash | Question 5 - GeeksforGeeks

20 May, 2019
Given the following input (4322, 1334, 1471, 9679, 1989, 6171, 6173, 4199) and the hash function x mod 10, which of the following statements are true?i. 9679, 1989, 4199 hash to the same valueii. 1471, 6171 hash to the same valueiii. All elements hash to the same valueiv. Each element hashes to a different value(GATE CS 2004)(A) i only(B) ii only(C) i and ii only(D) iii or ivAnswer: (C)Explanation:
Hash function given is mod(10).
9679, 1989 and 4199 all these give same hash value i.e 9
1471 and 6171 give hash value 1 
Quiz of this Question
UzairGhauri
Data Structures
Data Structures-Hash
Hash
Data Structures
Data Structures
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
Advantages and Disadvantages of Linked List
C program to implement Adjacency Matrix of a given Graph
Introduction to Data Structures | 10 most commonly used Data Structures
Difference between Singly linked list and Doubly linked list
FIFO vs LIFO approach in Programming
Data Structures | Stack | Question 6
Bit manipulation | Swap Endianness of a number
Data Structures | Queue | Question 11
Data Structures | Stack | Question 4
How to open a new tab using Selenium WebDriver?

We can open a new tab with Selenium. The Keys.chord and sendKeys methods are used for this. Multiple keys can be passed simultaneously with the Keys.chord method. A group of strings or keys can be passed as parameters to that method.
The Keys.CONTROL and Keys.ENTER are passed as parameters to the Keys.chord method here. This is stored as a string value and finally passed as a parameter to the sendKeys method.
String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER);
driver.findElement(By.xpath("//*[text()='Company']")).sendKeys(nwtb);
Code Implementation.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class OpnLinkNwTab{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait of 4 seconds
      driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // Keys.Chord string
      String nwtb = Keys.chord(Keys.CONTROL,Keys.ENTER);
      // open the link in new tab, Keys.Chord string passed to sendKeys
      driver.findElement(
      By.xpath("//*[text()='Company']")).sendKeys(nwtb);
   }
}
How to select records beginning with certain numbers in MySQL?

The optimal solution to select records beginning with certain numbers, use MySQL LIKE operator. Let us first create a table −
mysql> create table DemoTable
(
   ClientId bigint,
   ClientName varchar(40)
);
Query OK, 0 rows affected (0.82 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(23568777,'Chris Brown');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(9085544,'John Doe');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values(9178432,'John Doe');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(9078482,'David Miller');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+--------------+
| ClientId | ClientName   |
+----------+--------------+
| 23568777 | Chris Brown  |
| 9085544  | John Doe     |
| 9178432  | John Doe     |
| 9078482  | David Miller |
+----------+--------------+
4 rows in set (0.00 sec)
Following is the query to select records beginning with certain numbers in MySQL −
mysql> select *from DemoTable where ClientId LIKE '90%';
This will produce the following output −
+----------+--------------+
| ClientId | ClientName   |
+----------+--------------+
| 9085544  | John Doe     |
| 9078482  | David Miller |
+----------+--------------+
2 rows in set (0.00 sec)
Bootstrap 4 .justify-content-* class

To align flex items, use the justify-content-* class.
Use any of the following to align flex items at the start, end, around, and between.
justify-content-start – Align Flex items at the start
justify-content-end  - Align Flex items at the end
justify-content-around – Align  flex items around on different screen sizes
justify-content-between  - Alex flex items in between on difference screen sizes
Let us see an example to set the flex items at the start −
<div class="d-flex justify-content-start bg-primary mb-5">
  <div class="p-2 bg-danger">RANK 1</div>
  <div class="p-2 bg-secondary">RANK 2</div>
  <div class="p-2 bg-warning">RANK3</div>
</div>
The following is the example to implement the justify-content-* class −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
</head>

<body>

<div class="container mt-3">
  <div class="d-flex justify-content-start bg-primary mb-5">
    <div class="p-2 bg-danger">RANK 1</div>
    <div class="p-2 bg-secondary">RANK 2</div>
    <div class="p-2 bg-warning">RANK3</div>
  </div>
  <div class="d-flex justify-content-end bg-info mb-5">
    <div class="p-2 bg-danger">RANK 1</div>
    <div class="p-2 bg-primary">RANK 2</div>
    <div class="p-2 bg-warning">RANK 3</div>
  </div>
  <div class="d-flex justify-content-around bg-warning mb-5">
    <div class="p-2 bg-danger">RANK 1</div>
    <div class="p-2 bg-info">RANK 2</div>
    <div class="p-2 bg-secondary">RANK 3</div>
  </div>
</div>

</body>
</html>
YAML - Full Length Example

The following full-length example specifies the construct of YAML which includes symbols and various representations which will be helpful while converting or processing them in JSON format. These attributes are also called as key names in JSON documents. These notations are created for security purposes. 
The above YAML format represents various attributes of defaults, adapter, and host with various other attributes. YAML also keeps a log of every file generated which maintains a track of error messages generated. On converting the specified YAML file in JSON format we get a desired output as mentioned below −
defaults: &defaults
   adapter:  postgres
   host:     localhost

development:
   database: myapp_development
   <<: *defaults

test:
   database: myapp_test
   <<: *defaults
Let’s convert the YAML to JSON format and check on the output.
{
   "defaults": {
      "adapter": "postgres",
      "host": "localhost"
   },
   "development": {
      "database": "myapp_development",
      "adapter": "postgres",
      "host": "localhost"
   },
   "test": {
      "database": "myapp_test",
      "adapter": "postgres",
      "host": "localhost"
   }
}
The defaults key with a prefix of “ <<: *” is included as and when required with no need to write the same code snippet repeatedly.

    33 Lectures 
     44 mins

 Tarun Telang
 Print
 Add Notes
 Bookmark this page
Shuffle elements of ArrayList with Java Collections

In order to shuffle elements of ArrayList with Java Collections, we use the Collections.shuffle() method. The java.util.Collections.shuffle() method randomly permutes the list using a default source of randomness.
Declaration −The java.util.Collections.shuffle() method is declared as follows −
public static void shuffle(List <?> list)
Let us see a program to shuffle elements of ArrayList with Java Collections −
 Live Demo
import java.util.*;
public class Example {
   public static void main (String[] args) {
      ArrayList<Integer> list = new ArrayList<Integer>();
      list.add(1);
      list.add(2);
      list.add(7);
      list.add(8);
      list.add(3);
      list.add(9);
      System.out.println("Original list : " + list);
      Collections.shuffle(list); // shuffling the list
      System.out.println("Shuffled list : " + list);
   }
}
Original list : [1, 2, 7, 8, 3, 9]
Shuffled list : [3, 8, 7, 9, 1, 2]
CSS | Shadow Effect - GeeksforGeeks

04 Dec, 2018
The shadow effect property in CSS is used to add text and images shadow in HTML document.
Text Shadow: The CSS text-shadow property is used to display the text with shadow. This property holds the pixel length, breadth, and width of the shadow and the color of the shadow.
Syntax:
Text-shadow: 3px 3px 3px green;
Example:
<!DOCTYPE html><html>    <head>        <title>text-shadow property</title>        <style>            h1 {                color: green;                text-shadow: 3px 3px 3px lightgreen;            }        </style>    </head>    <body>        <h1>Geeks For Geeks | A computer Science portal for Geeks</h1>    </body></html>                    
Output:
TextBox Shadow: The CSS boxShadow property applies shadow to the text box. This property hold the pixel length, breadth, and width of the shadow and the color of the shadow.
Syntax:
boxShadow: 3px 3px 3px green;
Example:
<!DOCTYPE html><html>     <head>         <title>box shadow property</title>         <style>               #Gfg {                   width: 220px;                   height: 50px;                   background-color: green;                   color: white;               }          </style>          <script>                  // function that show Shadow Effect.               function Shadow() {                  document.getElementById("Gfg").style.boxShadow                                            = "5px 5px 5px gray";               }          </script>     </head>     <body>          <button onclick = "Shadow()">Click to see Shadow</button>          <div id = "Gfg">            <h1>GeeksforGeeks</h1>          </div>     </body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Advanced
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
numpy.left_shift() in Python - GeeksforGeeks

28 Nov, 2018
numpy.left_shift() function is used to Shift the bits of an integer to the left.
The bits are shifted to the left by appending arr2 0s(zeroes) at the right of arr1. Since the internal representation of numbers is in binary format, this operation is equivalent to multiplying arr1 by 2**arr2. For example, if the number is 5 and we want to 2 bit left shift then after left shift 2 bit the result will be 5*(2^2) = 20
Syntax : numpy.left_shift(arr1, arr2, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘left_shift’)
Parameters :arr1 : array_like of integer typearr2 : array_like of integer typeNumber of zeros to append to arr1.The value of arr2 should be positive integer.
out : [ndarray, optional] A location into which the result is stored.  -> If provided, it must have a shape that the inputs broadcast to.  -> If not provided or None, a freshly-allocated array is returned.
**kwargs : allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.
where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return : array of integer type.Return arr1 with bits shifted arr2 times to the left. This is a scalar if both arr1 and arr2 are scalars.
Code #1 : Working
# Python program explaining# left_shift() function  import numpy as geekin_num = 5bit_shift = 2  print ("Input  number : ", in_num)print ("Number of bit shift : ", bit_shift )     out_num = geek.left_shift(in_num, bit_shift) print ("After left shifting 2 bit  : ", out_num) 
Output :
Input  number :  5
Number of bit shift :  2
After left shifting 2 bit  :  20

 Code #2 :
# Python program explaining# left_shift() function  import numpy as geek  in_arr = [2, 8, 15]bit_shift =[3, 4, 5]   print ("Input array : ", in_arr) print ("Number of bit shift : ", bit_shift)    out_arr = geek.left_shift(in_arr, bit_shift) print ("Output array after left shifting: ", out_arr) 
Output :
Input array :  [2, 8, 15]
Number of bit shift :  [3, 4, 5]
Output array after left shifting:  [ 16 128 480]

 
Python numpy-Binary Operation
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
When to use self over $this in PHP ? - GeeksforGeeks

29 Jun, 2021
The self and this are two different operators which are used to represent current class and current object respectively. self is used to access static or class variables or methods and this is used to access non-static or object variables or methods. So use self when there is a need to access something which belongs to a class and use $this when there is a need to access a property belonging to the object of the class.self operator: self operator represents the current class and thus is used to access class variables or static variables because these members belongs to a class rather than the object of that class. Syntax:  
self::$static_member
Example 1: This is the basic example which shows the use of self operator.  
php
<?php class GFG {    private static $static_member = "GeeksForGeeks";     function __construct() {        echo self::$static_member;        // Accessing static variable    }} new GFG();?>
Output:  
GeeksForGeeks
Example 2: This example is a demo of exploiting polymorphic behavior in php using self.  
php
<?php class GFG {    function print() {        echo 'Parent Class';    }     function bar() {        self::print();    }} class Child extends GFG {    function print() {        echo 'Child Class';    }} $parent = new Child();$parent->bar();?>
Output: 
Parent Class:
Here the parent class method runs because the self operator represents the class, thus we see that the main class method is the method of the parent class only. $this operator: $this, as the ‘$’ sign suggest, is an object. $this represents the current object of a class. It is used to access non-static members of a class. Syntax:  
$that->$non_static_member;
Example 1: This is the basic example which shows the use of $this operator. 
php
<?phpclass GFG {    private $non_static_member = "GeeksForGeeks";     function __construct() {        echo $this->$non_static_member;        // accessing non-static variable    }} new GFG();?>
Output:  
GeeksForGeeks
Example 2: This example is a demo of polymorphic behavior in php using self.  
php
<?php class GFG {    function print() {        echo 'Parent Class';    }     function bar() {        $this->print();    }} class Child extends GFG {    function print() {        echo 'Child Class';    }} $parent = new Child();$parent->bar();?>
Output:  
Child Class
Here, there is no reference to any class and the object which is pointing the child class is calling the method defined in the child class. This is an example of dynamic polymorphism in PHP.  
sweetyty
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
Download file from URL using PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to pass JavaScript variables to PHP ?
Split a comma delimited string into an array in PHP
How to get parameters from a URL string in PHP?
How to remove specific elements from a NumPy array ? - GeeksforGeeks

21 Apr, 2021
In this article, we will discuss how to remove specific element from the NumPy Array. The delete() method will be used to do the same.
Syntax:
numpy.delete(array_name,index_value)
Where array_name is the name of the array to be deleted and index-value is the index of the element to be deleted.
For example, we are having an array with 5 elements, 
array1=[1,2,3,4,5]
The indexing starts from 0 to n-1. If we want to delete 2, then 2 element index is 1. So, we can specify 
np.delete(array1,1)
If we want to delete multiple elements i.e. 1,2,3,4,5 at a time, you can specify all index elements in a list.
np.delete(array1,[0,1,2,3,4])
Below are some examples where we remove specific elements in a NumPy array. 
Example 1:
Program to create an array with 5 elements and delete 1st element.
Python3
# import numpy as npimport numpy as np  # create an array with 5 elementsa = np.array([1, 2, 3, 4, 5])  # display aprint(a)  # delete 1 st elementprint("remaining elements after deleting 1st element ",      np.delete(a, 0))
Output:
[1 2 3 4 5]
remaining elements after deleting 1st element  [2 3 4 5]
Example 2:
Program to create an array with 5 elements and delete 1st and last element.
Python3
# import numpy as npimport numpy as np  # create an array with 5 # elementsa = np.array([1, 2, 3, 4, 5])  # display aprint(a)  # delete 1 st elementprint("remaining elements after deleting 1st and last element ",      np.delete(a, [0, 4]))
Output:
[1 2 3 4 5]
remaining elements after deleting 1st and last element  [2 3 4]
Example 3:
Deleting 4th element.
Python3
#import numpy as npimport numpy as np  # create an array with 10 elementsa = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])  # display aprint(a)  # delete  4 th  elementprint("remaining elements after deleting 4th element ",      np.delete(a, 3))
Output:
[ 1  2  3  4  5  6  7  8  9 10]
remaining elements after deleting 4th element  [ 1  2  3  5  6  7  8  9 10]
Picked
Python numpy-Indexing
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()