code-rag-bench/online-tutorials huggingface dataset:
Synchronizing Threads in Python

The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.
The acquire(blocking) method of the new lock object is used to force threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock.
If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.
The release() method of the new lock object is used to release the lock when it is no longer required.
#!/usr/bin/python
import threading
import time
class myThread (threading.Thread):
   def __init__(self, threadID, name, counter):
      threading.Thread.__init__(self)
      self.threadID = threadID
      self.name = name
      self.counter = counter
   def run(self):
      print "Starting " + self.name
   # Get lock to synchronize threads
      threadLock.acquire()
      print_time(self.name, self.counter, 3)
      # Free lock to release next thread
      threadLock.release()
def print_time(threadName, delay, counter):
   while counter:
      time.sleep(delay)
      print "%s: %s" % (threadName, time.ctime(time.time()))
      counter -= 1
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
   t.join()
print "Exiting Main Thread"
When the above code is executed, it produces the following result −
Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread
Instruction type MOV r, M in 8085 Microprocessor

In 8085 Instruction set, MOV r, M is an instruction where the 8-bit data content of the memory location as pointed by HL register pair will be moved to the register r. Thus this is an instruction to load register r with the 8-bit value from a specified memory location whose 16-bit address is in HL register pair.
As r can have any of the seven values, there are seven opcodes for this type of instruction.
r = A, B, C, D, E, H, or L

It occupies only 1-Byte in memory. MOV E, M is an example instruction of this type. It is a 1-Byte instruction. Suppose E register content is DBH, H register content is 40H, and L register content is 50H. Let us say location 4050H has the data value AAH. When the 8085 executes this instruction, the contents of E register will change to AAH, as shown below.
(E)
(HL)
(4050H)
The timing diagram for this MOV E, M instruction is as follows −
Summary − So this instruction MOV E, M requires 1-Byte, 2-Machine Cycles (Opcode Fetch, Memory Read) and 7 T-States for execution as shown in the timing diagram.
MySQL query to check how to get time difference

Let us first create a table −
mysql> create table DemoTable1570
   -> (
   -> ArrivalTime datetime
   -> );
Query OK, 0 rows affected (0.87 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1570 values('2019-10-15 5:10:00');
Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable1570 values('2019-10-15 23:00:00');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1570 values('2019-10-15 23:10:00');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1570 values('2019-10-15 16:10:00');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1570;
This will produce the following output
+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-10-15 05:10:00 |
| 2019-10-15 23:00:00 |
| 2019-10-15 23:10:00 |
| 2019-10-15 16:10:00 |
+---------------------+
4 rows in set (0.00 sec)
The current date is as follows −
mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2019-10-15 22:26:14 |
+---------------------+
1 row in set (0.00 sec)
Following is the query to get time difference −
mysql> select * from DemoTable1570
   -> where ArrivalTime > now() - interval 5 hour;
This will produce the following output
+---------------------+
| ArrivalTime         |
+---------------------+
| 2019-10-15 23:00:00 |
| 2019-10-15 23:10:00 |
+---------------------+
2 rows in set (0.00 sec)
What does close() function do in Python?

The function close() closes an open file. For example: 
f = open('my_file', 'r+')
my_file_data = f.read()
f.close()
 The above code opens 'my_file'in read mode then stores the data it reads from my_file in my_file_data and closes the file. When you open a file, the operating system gives a file handle to read/write the file. You need to close it once you are done using the file. If your program encounters an error and doesn't call f.close(), you didn't release the file. To make sure it doesn't happen, you can use with open(...) as syntax as it automatically closes files regardless of whether an error was encountered:
 with open('my_file', 'r+') as f:
    my_file_data = f.read()
W3.CSS - Forms

W3.CSS has a very beautiful and responsive CSS for form designing. The following CSS are used −
w3-group
Represents a bordered container. Can be used to group a label and input.
w3-input
Beautifies an input control.
w3-label
Beautifies a label.
w3-checkbox w3-checkmark
Beautify a checkbox/ radio button.
<html>
   <head>
      <title>The W3.CSS Forms</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://www.w3schools.com/lib/w3.css">
   </head>
   
   <body>
      <form class = "w3-container w3-card-8">
         <div class = "w3-group">
            <input class = "w3-input" type = "text" style = "width:90%" required>
            <label class = "w3-label">User Name</label>
         </div>
         
         <div class = "w3-group">
            <input class = "w3-input" type = "text" style = "width:90%" required>
            <label class = "w3-label">Email</label>
         </div>
         
         <div class = "w3-group">
            <textarea class = "w3-input" style = "width:90%" required></textarea>
            <label class = "w3-label">Comments</label>
         </div>
         <div class = "w3-row">
            <div class = "w3-half">
               <label class = "w3-checkbox">
                  <input type = "checkbox" checked = "checked">
                  <div class = "w3-checkmark"></div> Married
               </label>
               <br>
               <label class = "w3-checkbox">
                  <input type = "checkbox">
                  <div class = "w3-checkmark"></div> Single
               </label>
               <br>
               <label class = "w3-checkbox">
                  <input type = "checkbox" disabled>
                  <div class = "w3-checkmark"></div> Don't know (Disabled)
               </label>
               <br>
               <br>
            </div>
            
            <div class = "w3-half">
               <label class = "w3-checkbox">
                  <input type = "radio" name = "gender" value = "male" checked>
                  <div class = "w3-checkmark"></div> Male
               </label>
               <br>
               <label class = "w3-checkbox">
                  <input type = "radio" name = "gender" value = "female">
                  <div class = "w3-checkmark"></div> Female
               </label>
               <br>
               <label class = "w3-checkbox">
                  <input type = "radio" name = "gender" value = "female" disabled>
                  <div class = "w3-checkmark"></div> Don't know (Disabled)
               </label>
            </div>
         </div>
      </form>
   </body>
</html>
Verify the result.
 Print
 Add Notes
 Bookmark this page
Difference between the | and || or operator in php

'|' operator is a bitwise OR operator and is used to set the bit to 1 if any of the corresponding bit is 1.
'||' is a logical Or operator and works on complete operands as whole.
Following example, shows usage of '|' vs '||' operators.
 Live Demo
<!DOCTYPE html>
<html>
<head>
   <title>PHP Example</title>
</head>
<body>
   <?php
      $x = 1; // 0001
      $y = 2; // 0010

      print('$x | $y = ');
      echo $x | $y;
      print("<br/>");
      print('$x || $y = ');
      echo $x || $y;
   ?>
</body>
</html>
$x | $y = 3
$x || $y = 1
MySQL - AVG Function

MySQL AVG function is used to find out the average of a field in various records.
To understand AVG function, consider an employee_tbl table, which is having following records −
mysql> SELECT * FROM employee_tbl;
+------+------+------------+--------------------+
|  id  | name | work_date  | daily_typing_pages |
+------+------+------------+--------------------+
|   1  | John | 2007-01-24 |        250         |
|   2  | Ram  | 2007-05-27 |        220         |
|   3  | Jack | 2007-05-06 |        170         |
|   3  | Jack | 2007-04-06 |        100         |
|   4  | Jill | 2007-04-06 |        220         |
|   5  | Zara | 2007-06-06 |        300         |
|   5  | Zara | 2007-02-06 |        350         |
+------+------+------------+--------------------+
7 rows in set (0.00 sec)
Now, suppose based on the above table you want to calculate average of all the dialy_typing_pages, then you can do so by using the following command −
mysql> SELECT AVG(daily_typing_pages)
   -> FROM employee_tbl;
+-------------------------+
| AVG(daily_typing_pages) |
+-------------------------+
|         230.0000        |
+-------------------------+
1 row in set (0.03 sec)
You can take average of various records set using GROUP BY clause. Following example will take average all the records related to a single person and you will have average typed pages by every person.
mysql> SELECT name, AVG(daily_typing_pages)
   -> FROM employee_tbl GROUP BY name;
+------+-------------------------+
| name | AVG(daily_typing_pages) |
+------+-------------------------+
| Jack |        135.0000         |
| Jill |        220.0000         |
| John |        250.0000         |
| Ram  |        220.0000         |
| Zara |        325.0000         |
+------+-------------------------+
5 rows in set (0.20 sec)

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Create gradient translucent windows in Java Swing

With JDK 7, we can create a gradient based translucent window using swing very easily. Following are the steps needed to make a gradient-based translucent window.
 Make the background of JFrame transparent first.
frame.setBackground(new Color(0,0,0,0));
 Create a gradient paint, and fill the panel.
JPanel panel = new javax.swing.JPanel() {
   protected void paintComponent(Graphics g) {
      Paint p = new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),
       getWidth(), getHeight(), new Color(R, G, B, 255), true);
      Graphics2D g2d = (Graphics2D)g;
      g2d.setPaint(p);
      g2d.fillRect(0, 0, getWidth(), getHeight());
   }
}
 Assign the panel as a content pane to the frame.
frame.setContentPane(panel);
See the example below of a window with gradient-based translucency.
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Paint;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UnsupportedLookAndFeelException;

public class Tester {
   public static void main(String[] args)        
      throws ClassNotFoundException, InstantiationException,        
      IllegalAccessException, UnsupportedLookAndFeelException {
       
      JFrame.setDefaultLookAndFeelDecorated(true);
      // Create the GUI on the event-dispatching thread
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            createWindow();                      
         }
      });
   }

   private static void createWindow() {          
      JFrame frame = new JFrame("Translucent Window");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      createUI(frame);
      frame.setVisible(true);          
   }

   private static void createUI(JFrame frame){
      frame.setLayout(new GridBagLayout());
      frame.setSize(200, 200);            
      frame.setLocationRelativeTo(null);
      frame.setBackground(new Color(0,0,0,0));

      JPanel panel = new javax.swing.JPanel() {
         protected void paintComponent(Graphics g) {
            if (g instanceof Graphics2D) {
               final int R = 100;
               final int G = 100;
               final int B = 100;                
               Paint p =
                  new GradientPaint(0.0f, 0.0f, new Color(R, G, B, 0),
                  getWidth(), getHeight(), new Color(R, G, B, 255), true);
               Graphics2D g2d = (Graphics2D)g;
               g2d.setPaint(p);
               g2d.fillRect(0, 0, getWidth(), getHeight());
            } else {
               super.paintComponent(g);
            }
         }
      };
      panel.setLayout(new GridBagLayout());
      panel.add(new JButton("Hello World"));
      frame.setContentPane(panel);
   }
}
Test Environment

Test Environment consists of elements that support test execution with software, hardware and network configured. Test environment configuration must mimic the production environment in order to uncover any environment/configuration related issues.
Determine if test environment needs archiving in order to take back ups.
Determine if test environment needs archiving in order to take back ups.
Verify the network configuration.
Verify the network configuration.
Identify the required server operating system, databases and other components.
Identify the required server operating system, databases and other components.
Identify the number of license required by the test team.
Identify the number of license required by the test team.
It is the combination of hardware and software environment on which the tests will be executed. It includes hardware configuration, operating system settings, software configuration, test terminals and other support to perform the test.
A typical Environmental Configuration for a web-based application is given below:
Web Server - IIS/Apache
Database - MS SQL
OS - Windows/ Linux
Browser - IE/FireFox
Java version : version 6

    80 Lectures 
     7.5 hours 

 Arnab Chakraborty

    10 Lectures 
     1 hours 

 Zach Miller

    17 Lectures 
     1.5 hours 

 Zach Miller

    60 Lectures 
     5 hours 

 John Shea

    99 Lectures 
     10 hours 

 Daniel IT

    62 Lectures 
     5 hours 

 GlobalETraining
 Print
 Add Notes
 Bookmark this page
Python Pandas - Convert the Timedelta to a NumPy timedelta64

To convert the Timedelta to a NumPy timedelta64, use the timedelta.to_timedelta64() method.
At first, import the required libraries −
import pandas as pd
Create a Timedelta object −
timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')

Display the Timedelta −
print("Timedelta...\n", timedelta)
Convert the Timedelta to a NumPy timedelta64 −
timedelta.to_timedelta64()

Following is the code −
import pandas as pd

# TimeDeltas is Python’s standard datetime library uses a different representation timedelta’s
# create a Timedelta object
timedelta = pd.Timedelta('2 days 11 hours 22 min 25 s 50 ms 45 ns')

# display the Timedelta
print("Timedelta...\n", timedelta)

# Convert the Timedelta to a NumPy timedelta64.
res = timedelta.to_timedelta64()

# Return the result
print("\nConverting the Timedelta to a NumPy timedelta64....\n", res)
This will produce the following code −
Timedelta...
2 days 11:22:25.050000045

Converting the Timedelta to a NumPy timedelta64....
213745050000045 nanoseconds
jQuery | unbind() Method

20 Feb, 2019
The unbind() Method is an inbuilt method in jQuery which is used to remove any selected event handlers. This method can be used to remove particular event handler, or stop specific functions. It works on any event handler using an event object.
Note: If no parameters are provided, the method works on all event handlers from the specified element.Syntax:
$(selector).unbind(event, function, eventObj)
Parameters: This method accepts three parameters as mentioned above and described below:
event: It is an optional parameter which is used to specify events (one or more) to remove them from the elements.
function: It is an optional parameter which is used to specify the name of the function to unbind from the specified event for the element.
eventObj: It is an optional parameter which is used to specify the event object to remove from the event binding function.
Example 1: This example describes the unbind() method to remove event handler from selected element.
<!DOCTYPE html>  <html>    <head>     <title>         jQuery unbind() Method    </title>           <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script> </head>           <body style = "text-align:center;">           <h1 style = "color:green;" >          GeeksForGeeks      </h1>                   <button>         Click Here     </button>               <!-- Script to illustrates unbind() method -->    <script>        $(document).ready(function() {            $("h1").click(function() {                $(this).slideToggle();            });                          $("button").click(function() {                $("h1").unbind();            });        });    </script></body>    </html> 
Output:
Before click anywhere:
After clicking on the element h1:
After clicking on the button event will not work:
Example 2: This example describes the unbind() method to remove event handler from selected element.
<!DOCTYPE html>  <html>    <head>     <title>         jQuery unbind() Method    </title>           <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>          <style>        h1 {            border: 1px solid black;            height: 100px;            padding-top: 35px;            background: green;            color: white;        }    </style></head>          <body style = "text-align:center;">           <h1>GeeksForGeeks</h1>            <button>         Remove event handler from geeks for geeks    </button>           <!-- Script to illustrates unbind() method -->       <script>        $(document).ready(function() {            $("h1").click(function() {                $(this).slideToggle();            });                          $("button").click(function() {                $("h1").unbind();            });        });    </script></body>    </html> 
Output:
Before click anywhere:
After clicking on the element h1:
After clicking on the button event will not work:
jQuery-Events
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Check if two List objects are equal

27 Jan, 2019
Equals(Object) Method which is inherited from the Object class is used to check if a specified List<T> object is equal to another List<T> object or not.
Syntax:
public virtual bool Equals (object obj);
Here, obj is the object which is to be compared with the current object.
Return Value: This method return true if the specified object is equal to the current object otherwise it returns false.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# program to if a List object// is equal to another List objectusing System;using System.Collections.Generic;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // Creating an List<T> of Integers        List<int> firstlist = new List<int>();          // Adding elements to List        firstlist.Add(17);        firstlist.Add(19);        firstlist.Add(21);        firstlist.Add(9);        firstlist.Add(75);        firstlist.Add(19);        firstlist.Add(73);          // Checking whether firstlist is        // equal to itself or not        Console.WriteLine(firstlist.Equals(firstlist));    }}
True

Example 2:
// C# program to if a List object// is equal to another List objectusing System;using System.Collections.Generic;  class Geeks {      // Main Method    public static void Main(String[] args)    {          // Creating a List of strings        List<string> list1 = new List<string>();          // Inserting elements in List        list1.Add("DS");        list1.Add("C++");        list1.Add("Java");        list1.Add("JavaScript");          // Creating an List<T> of Integers        List<int> list2 = new List<int>();          // Adding elements to List        list2.Add(78);        list2.Add(44);        list2.Add(27);        list2.Add(98);        list2.Add(74);          // Checking whether list1 is        // equal to list2 or not        Console.WriteLine(list1.Equals(list2));          // Creating a List of integers        List<int> list3 = new List<int>();          // Assigning list2 to list3        list3 = list2;          // Checking whether list3 is        // equal to list2 or not        Console.WriteLine(list3.Equals(list2));    }}
False
True

Note: If the current instance is a reference type, the Equals(Object) method checks for reference equality.
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
C# | Delegates
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Class and Object
C# | Constructors
C# | Replace() Method
C# | Encapsulation
Extension Method in C#
What is Scrambling in Digital Electronics ?

31 May, 2022
A computer network is designed to send information from one point to another. Data that we send can either be digital or analog. Also, signals that represent data can also be digital or analog. Thus to send data by using signals, we must be able to convert the data into signals, this conversion can be Analog to Analog, Analog to Digital, Digital to Analog, or Digital to Digital. Digital to Digital conversion involves three techniques – Line Coding, Block Coding, and Scrambling. Line Coding is always needed, whereas Block Coding and Scrambling may or may not be needed depending upon the need. Scrambling is a technique that does not increase the number of bits and does provide synchronization. The problem with techniques like Bipolar AMI(Alternate Mark Inversion) is that continuous sequence of zero’s create synchronization problems one solution to this is Scrambling. 
Prerequisite: Block Coding, Line Coding 
There are two common scrambling techniques:
B8ZS(Bipolar with 8-zero substitution)HDB3(High-density bipolar3-zero)
B8ZS(Bipolar with 8-zero substitution)
HDB3(High-density bipolar3-zero)
B8ZS(Bipolar with 8-zero substitution): This technique is similar to Bipolar AMI except when eight consecutive zero-level voltages are encountered they are replaced by the sequence, “000VB0VB”. 
Note:
V(Violation), is a non-zero voltage which means the signal has the same polarity as the previous non-zero voltage. Thus it is a violation of the general AMI technique.
B(Bipolar), is also a non-zero voltage level that is in accordance with the AMI rule (i.e., opposite polarity from the previous non-zero voltage).
Example: Data = 100000000
  
Note: Both figures (left and right one) are correct, depending upon the last non-zero voltage signal of the previous data sequence (i.e., sequence before current data sequence “100000000”). 
HDB3(High-density bipolar3-zero): In this technique, four consecutive zero-level voltages are replaced with a sequence “000V” or “B00V”. Rules for using these sequences:
If the number of nonzero pulses after the last substitution is odd, the substitution pattern will be “000V”, this helps in maintaining a total number of nonzero pulses even.
If the number of nonzero pulses after the last substitution is even, the substitution pattern will be “B00V”. Hence even the number of nonzero pulses is maintained again.
Example: Data = 1100001000000000 
Output explanation: After representing the first two 1’s of data we encounter four consecutive zeros. Since our last substitutions were two 1’s(thus the number of non-zero pulses is even). So, we substitute four zeros with “B00V”. 
Note: Zero non-zero pulses are also even.
singhankitasingh066
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Initialize empty array of given length

06 Dec, 2019
Prerequisite: List in Python
As we know Array is a collection of items stored at contiguous memory locations. In Python, List (Dynamic Array) can be treated as Array. In this article, we will learn how to initialize an empty array of some given size.
Let’s see different Pythonic ways to do this task.
Method 1 –
Syntax:
list1 = [0] * size
list2 = [None] * size

# initializes all the 10 spaces with 0’sa = [0] * 10   # initializes all the 10 spaces with Noneb = [None] * 10   # initializes all the 10 spaces with A'sc = ['A'] * 5   # empty list which is not null, it's just empty.d = []   print (a, "\n", b, "\n", c, "\n", d);
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 
[None, None, None, None, None, None, None, None, None, None] 
['A', 'A', 'A', 'A', 'A'] 
[]

 Method 2 – Use loops just like C and assign the size.
Syntax:
a = [0 for x in range(size)] #using loops

a = []b = []  # initialize the spaces with 0’s with # the help of list comprehensionsa = [0 for x in range(10)]print(a)  # initialize multi-array b = [ [ None for y in range( 2 ) ]             for x in range( 2 ) ]               print(b)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

[[None, None], [None, None]]

 Method 3 – Using Numpy to create empty array.
import numpy  # create a simple array with numpy empty()a = numpy.empty(5, dtype=object)print(a)  # create multi-dim array by providing shapematrix = numpy.empty(shape=(2,5),dtype='object')print(matrix)
Output:
[None None None None None]

[[None None None None None]
 [None None None None None]]

Picked
Python list-programs
Python
Python Programs
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Redis - List Lindex Command

Redis LINDEX command is used to get the element at the index in the list stored at the key. The index is zero-based, so 0 means the first element, 1 the second element, and so on. Negative indices can be used to designate elements starting at the tail of the list. Here, -1 means the last element, -2 means the penultimate, and so forth.
String reply, the requested element, or nil when the index is out of range.
Following is the basic syntax of Redis LINDEX command.
redis 127.0.0.1:6379> LINDEX KEY_NAME INDEX_POSITION

redis 127.0.0.1:6379> LPUSH list1 "foo" 
(integer) 1 
redis 127.0.0.1:6379> LPUSH list1 "bar" 
(integer) 2 
redis 127.0.0.1:6379> LINDEX list1 0 
"foo" 
redis 127.0.0.1:6379> LINDEX list1 -1 
"bar" 
redis 127.0.0.1:6379> LINDEX list1 5 
nil 


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
as_integer_ratio() in Python for reduced fraction of a given rational

In this tutorial, we are going to write a program that returns two numbers whose ratio is equal to the given float value. We have a method called as_integer_ratio() that helps to achieve our goal.
Let's see some examples.
Input:
1.5
Output:
3 / 2
Input:
5.3
Output:
5967269506265907 / 1125899906842624
Let's examine the code.
# initializing the float value
float_value = 1.5
# getting integers tuple using the as_integer_ratio() method
integers = float_value.as_integer_ratio()
# printing the integers
print(f'{integers[0]} / {integers[1]}')
If you run the above code, you will get the following results.
3 / 2

Let's see another example.
# initializing the float value
float_value = 5.3
# getting integers tuple using the as_integer_ratio() method
integers = float_value.as_integer_ratio()
# printing the integers
print(f'{integers[0]} / {integers[1]}')
If you run the above code, you will get the following results.
5967269506265907 / 1125899906842624

If you have any queries in the tutorial, ask them in the comment section.
SQLAlchemy Core - Executing Expression

In the previous chapter, we have learnt SQL Expressions. In this chapter, we shall look into the execution of these expressions.
In order to execute the resulting SQL expressions, we have to obtain a connection object representing an actively checked out DBAPI connection resource and then feed the expression object as shown in the code below.
conn = engine.connect()
The following insert() object can be used for execute() method −
ins = students.insert().values(name = 'Ravi', lastname = 'Kapoor')
result = conn.execute(ins)
The console shows the result of execution of SQL expression as below −
INSERT INTO students (name, lastname) VALUES (?, ?)
('Ravi', 'Kapoor')
COMMIT
Following is the entire snippet that shows the execution of INSERT query using SQLAlchemy’s core technique −
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String
engine = create_engine('sqlite:///college.db', echo = True)
meta = MetaData()

students = Table(
   'students', meta, 
   Column('id', Integer, primary_key = True), 
   Column('name', String), 
   Column('lastname', String), 
)

ins = students.insert()
ins = students.insert().values(name = 'Ravi', lastname = 'Kapoor')
conn = engine.connect()
result = conn.execute(ins)
The result can be verified by opening the database using SQLite Studio as shown in the below screenshot −
The result variable is known as a ResultProxy object. It is analogous to the DBAPI cursor object. We can acquire information about the primary key values which were generated from our statement using ResultProxy.inserted_primary_key as shown below −
result.inserted_primary_key
[1]
To issue many inserts using DBAPI’s execute many() method, we can send in a list of dictionaries each containing a distinct set of parameters to be inserted.
conn.execute(students.insert(), [
   {'name':'Rajiv', 'lastname' : 'Khanna'},
   {'name':'Komal','lastname' : 'Bhandari'},
   {'name':'Abdul','lastname' : 'Sattar'},
   {'name':'Priya','lastname' : 'Rajhans'},
])

This is reflected in the data view of the table as shown in the following figure −

    21 Lectures 
     1.5 hours 

 Jack Chan
 Print
 Add Notes
 Bookmark this page
C library function - srand()

The C library function void srand(unsigned int seed) seeds the random number generator used by the function rand.
Following is the declaration for srand() function.
void srand(unsigned int seed)
seed − This is an integer value to be used as seed by the pseudo-random number generator algorithm.
seed − This is an integer value to be used as seed by the pseudo-random number generator algorithm.
This function does not return any value.
The following example shows the usage of srand() function.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main () {
   int i, n;
   time_t t;
   
   n = 5;
   
   /* Intializes random number generator */
   srand((unsigned) time(&t));

   /* Print 5 random numbers from 0 to 50 */
   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
38
45
29
29
47


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
How to do UI testing with Selenium?

We can do UI testing with Selenium webdriver. To achieve this, we have to follow the steps listed below which can be applied to any script developed to test the UI of the application −
Step1 − Object of Webdriver should be created. For example,
WebDriver driver = new ChromeDriver();
The above piece of code is used to create a webdriver instance and initiate the script execution in the Chrome browser.
Step2 − Launch the URL on which we want to perform the UI testing. For example,
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
The above piece of code shall launch the URL passed as a parameter to the get method.
Step3 − Identify webelement with the help of any of the locators like id, class, name, tagname, link text, partial link text, css or xpath. The method - findElement is used to identify the element with these locators. For example,
WebElement elm = driver.findElement(By.tagName("h4"));
The above code is used to identify an element with the help of the locator tagname.
Step4 − After the element has been located, perform an action on it like inputting a text, clicking, and so on. For example,
elm.sendKeys("Selenium");
The above code is used to input a text on the element identified in Step3.
Step5 − Validate the impact on the webpage on performing the operation in Step4. For example,
Assert.assertEquals(s, "Selenium");
The above code is used to compare and verify if the actual value is equal to expected value - Selenium.
Step6 − Execute the test and record the result created with a test framework.
Step7 − Finish the test by quitting the webdriver session. For example,
driver.quit();
Code Implementation
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
public class NewTest {
   @Test
   public void f() {
      System.setProperty("webdriver.chrome.driver", "chromedriver");
      //webdriver instance
      WebDriver driver = new ChromeDriver();
      // implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //url launch
      driver.get("https://www.tutorialspoint.com/index.htm");
      //element identify
      WebElement elm = driver.findElement(By.tagName("input"));
      //perform action - input text
      elm.sendKeys("Selenium");
      String s = elm.getAttribute("value");
      //validate result with Assertion
      Assert.assertEquals(s, "Selenium");
      //quit browser
      driver.quit();
   }
}
How to represent all values of X-axis or Y-axis on the graph in R using ggplot2 package?

If we have many unique elements or repeated in a column of an R data frame and create a graph using that column, either on X-axis or Y-axis then R automatically choses the axes labels, this might not display all the unique values of the column in the plot. Therefore, we can use scale_x_continuous function or scale_y_continuous function with labels depending on our requirement to display the column values.
Consider the below data frame −
 Live Demo
x<-1:10
y<-rpois(10,2)
df<-data.frame(x,y)
df
x y
1 1 1
2 2 1
3 3 5
4 4 3
5 5 3
6 6 0
7 7 2
8 8 5
9 9 2
10 10 4
Loading ggplot2 package and creating a point chart between x and y by displaying all values of x axis −
library(ggplot2) ggplot(df,aes(x,y))+geom_point()+scale_x_continuous(labels=as.character(x),breaks=x)
Creating a point chart between x and y by displaying all values of Y axis −
ggplot(df,aes(x,y))+geom_point()+scale_y_continuous(labels=as.character(y),breaks=y)
How to Fix: ‘numpy.float64’ object cannot be interpreted as an integer - GeeksforGeeks

19 Dec, 2021
In this article, we are going to see how to fix:  ‘numpy.float64’ object cannot be interpreted as an integer.
When a function or operation is applied to an object of the wrong type, a type error is raised. The ‘numpy.float64’ object cannot be interpreted as an integer is one example of this type of problem. Let’s see what we can do about that.
if we give a float number in a range() in python, it results in a ”numpy.float64’ object that cannot be interpreted as an integer ‘ error.
range() function: The range() function returns a number series that starts at 0 and increments by 1 before stopping at a specified value.
syntax: range(start,stop,step)
Python3
# codeimport numpy as np  # an array of float valuesarr = np.array([1.5, 2.5, 3.5])    # we loop to print out range of values # at each indexfor i in range(len(arr)):    print(range(arr[i]))
Output:
TypeError: ‘numpy.float64’ object cannot be interpreted as an integer
when we have a list of values, and we want to change their type to prevent errors.
 We can use the .astype() function and give the argument “int”.  astype() function: When we need to convert a certain array of data from one type to another, the method comes in helpful.
Parameters
dtype:  refers to data type of list, or dict of column name
copy: boolean value,in default it’s set to True
errors: {‘raise’, ‘ignore’}, default  is ‘raise’
Python3
# codeimport numpy as np  # an array of float valuesarr = np.array([1.5, 2.5, 3.5])  arr = arr.astype(int)  # we loop to print out range of values# at each indexfor i in range(len(arr)):    print(range(arr[i]))
Output:
range(0, 1)
range(0, 2)
range(0, 3)
Here we will int() function to cast the array object before getting into range.
Python3
# codeimport numpy as np  # an array of float valuesarr = np.array([1.5, 2.5, 3.5])    # we loop to print out range of values# at each indexfor i in range(len(arr)):    print(range(int(arr[i])))
Output:
range(0, 1)
range(0, 2)
range(0, 3)
Picked
Python How-to-fix
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
How to add colors to nodes in JavaFX?

You can apply colors to nodes in JavaFX using the setFill() and setStroke() methods. The setFill() method adds color to the surface area of the node whereas the setStroke() method applies color to the boundary of the node.
Both methods accept an object of the javafx.scene.paint.Paint class as a parameter. It is the base class for the color and gradients that are used to fill the shapes and backgrounds with color.
The javafx.scene.paint.Color class in JavaFX is a subclass of the Paint and it encapsulates all the colors in RGB color space (as its properties).
To apply color to a geometrical shape or background or the stroke of shape, you need to invoke the respective method by passing a Color object representing the desired color.
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Ellipse;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
public class ColorExample extends Application {
   public void start(Stage stage) {
      //Drawing a circle
      Circle circle = new Circle(75.0f, 65.0f, 40.0f );
      //Drawing a Rectangle
      Rectangle rect = new Rectangle(150, 30, 100, 65);
      //Drawing an ellipse
      Ellipse ellipse = new Ellipse(330, 60, 60, 35);
      //Drawing Polygon
      Polygon poly = new Polygon(410, 60, 430, 30, 470, 30, 490, 60, 470, 100, 430, 100 );
      //Color by name
      circle.setFill(Color.CHOCOLATE);
      circle.setStrokeWidth(5);
      circle.setStroke(Color.DARKRED);
      //Using RGB
      rect.setFill(Color.rgb(150, 0, 255));
      rect.setStrokeWidth(5);
      rect.setStroke(Color.DARKRED);
      //Using HSB
      ellipse.setFill(Color.hsb(50, 1, 1));
      ellipse.setStrokeWidth(5);
      ellipse.setStroke(Color.DARKRED);
      //Using web
      poly.setFill(Color.web("#E9967A"));
      poly.setStrokeWidth(5);
      poly.setStroke(Color.DARKRED);
      //Setting the stage
      Group root = new Group(circle, ellipse, rect, poly);
      Scene scene = new Scene(root, 600, 150);
      stage.setTitle("Setting Colors");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}
MATLAB | Change the color of background pixels by OTSU Thresholding - GeeksforGeeks

15 Sep, 2021
MATLAB also called Matrix Laboratory is a numerical computing environment and a platform for programming language. it was designed and developed by MathWorks. MATLAB is a framework that allows you to perform matrix manipulations, implementing algorithms, plotting functions and data, creating user-interfaces and interfacing with programs that are written in different programming languages i.e. C, C++, Python, Java etc..OTSU Thresholding : OTSU thresholding is a segmentation algorithm through which we can segment an image into two or more than two regions. This algorithm checks on every single threshold if it can separate the two kinds of pixels optimally.By OTSU thresholding we separate the foreground and background pixels.Approach:  
Read the image using imread() function and convert it to gray image using rgb2gray() function.Graythresh the image using greythresh() function.Detect the foreground and background pixels of the image.Pick the background pixels and color them blue.
Read the image using imread() function and convert it to gray image using rgb2gray() function.
Graythresh the image using greythresh() function.
Detect the foreground and background pixels of the image.
Pick the background pixels and color them blue.
Below is the implementation of above approach –  
MATLAB
% read the rgb image.I = imread('leena.png');  % convert it to gray image using rgb2gray() function. Ig = rgb2gray(I);    % apply inbuilt otsu thresholding and% convert the image to binary image.      T = graythresh(Ig);        Tg = T*255;  % detect foreground and background% pixels of the binary image.              m = Ig > Tg                  figure, imshow(m)         I1 = I(:, :, 1);             I2 = I(:, :, 2);I3 = I(:, :, 3);I1(~m) = 0;I2(~m) = 0; % in background pixels, take the third% channel and color it blue.I3(~m) = 255;                In=cat(3, I1, I2, I3);figure, imshow(In);
Input Image:  
Output:  
 
surindertarika1234
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Fuzzy Logic | Introduction
Basics of API Testing Using Postman
Principal Component Analysis with Python
Markov Decision Process
ML | What is Machine Learning ?
OpenCV - Overview
Q-Learning in Python
How to create a REST API using Java Spring Boot
Getting Started with System Design
Getting factorial of a number in Julia - factorial() Method - GeeksforGeeks

21 Apr, 2020
The factorial() is an inbuilt function in julia which is used to return the factorial of the specified number n.
Syntax: factorial(n::Integer)
Parameters:
n: Specified number
Returns: It returns the factorial of the specified number n.
Example 1:
# Julia program to illustrate # the use of factorial() method  # Getting the factorial of # the specified numberprintln(factorial(0))println(factorial(1))println(factorial(2))
Output:
1
1
2

Example 2:
# Julia program to illustrate # the use of factorial() method  # Getting the factorial of # the specified numberprintln(factorial(5))println(factorial(7))println(factorial(big(20)))println(factorial(big(15)))
Output:
120
5040
2432902008176640000
1307674368000

Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Get array dimensions and size of a dimension in Julia - size() Method
Getting the maximum value from a list in Julia - max() Method
Searching in Array for a given element in Julia
Find maximum element along with its index in Julia - findmax() Method
Working with Date and Time in Julia
Working with Excel Files in Julia
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Exception handling in Julia
Functions in Julia
Replacing elements of a collection in Julia - replace() and replace!() Methods
How to make legend key fill transparent in ggplot2 in R? - GeeksforGeeks

30 Jun, 2021
In this article, we will see how to make legend key fill transparent in ggplot2 in R Programming Language. 
Note: Here we will be using a line graph, the same can be applied to any other plot.
Let us first draw a regular plot, so that the difference is apparent.
Example:
R
# Load Packagelibrary("ggplot2")  # Create DataFrameDF <- data.frame(X = rnorm(50),                                         Y = rnorm(50),                 Users = c("User1", "User2", "User3",                           "User4", "User5"))  # Generate LineGraph from DataFrame # using ggplot2ggplot(DF,aes(X, Y, color = Users))+  geom_line(size = 1)
Output:
LineGraph with Default Legend Keys
As you can see clearly in the above plot, Legend Keys have a grey background. So now we are going to convert it into transparent by using theme() function. theme() in itself is a very big function containing lots of theme elements that we can apply to the plot for making our plot look presentable. To change the background of Legend keys, we use legend.key, which specifies the background underneath legend keys. 
Syntax : theme(legend.key)
Parameter :
legend.key : For specify background underneath legend keys. we assign element_rect function as the value of it.
Return : Theme Of the plot
Further, we specify the element_rect() function as a value of legend.key, which is often used for backgrounds and borders. It also has some parameters for customization such as fill, color, size, and linetype but here for make fill the Legend Keys with transparent background, we will use only fill parameter out of them.
Syntax : element_rect(fill)
Parameter :
fill : fill with color.
return : Modifications on backgrounds and borders.
Syntax:
theme(legend.key = element_rect(fill))
Example:
R
# Load ggplot2 Packagelibrary("ggplot2")  # Create DataFrame for PlottingDF <- data.frame(X = rnorm(50),                                         Y = rnorm(50),                 Users = c("User1", "User2", "User3",                            "User4", "User5"))  # Generate LineGraph with transparent fill # of Legend Keys.ggplot(DF,aes(X, Y, color = Users))+  geom_line(size = 1)+  theme(legend.key = element_rect(fill = "transparent"))
Output:
LineGraph with transparent filled Legend Keys
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to filter R dataframe by multiple conditions?
Plot mean and standard deviation using ggplot2 in R
Time Series Analysis in R