code-rag-bench/online-tutorials huggingface dataset:
Difference between Horizontal and Vertical micro-programmed Control Unit

04 Jan, 2022
Prerequisite – Hardwired v/s Micro-programmed Control Unit 
The control unit (CU) is the engine that runs the entire functions of a computer with the help of control signals in the proper sequence. In the micro-programmed control unit approach, the control signals that are associated with the operations are stored in special memory units. It is convenient to think of sets of control signals that cause specific micro-operations to occur as being “micro-instructions”. The sequences of micro-instructions could be stored in an internal “control” memory. 
The micro-programmed control unit can be classified into two types based on the type of Control Word stored in the Control Memory, viz., Horizontal micro-programmed control unit and Vertical micro-programmed control unit. 
In the Horizontal micro-programmed control unit, the control signals are represented in the decoded binary format, i.e., 1 bit/CS. Here ‘n’ control signals require n bit encoding. On the other hand. 
In a Vertical micro-programmed control unit, the control signals are represented in the encoded binary format. Here ‘n’ control signals require log2n bit encoding. 
Example: Consider a hypothetical Control Unit that supports 4 k words. The Hardware contains 64 control signals and 16 Flags. What is the size of control word used in bits and control memory in a byte using: a) Horizontal Programming b) Vertical programming
Solution:
a)For Horizontal 

64 bits for 64 signals % 16 bits for flags
Control Word Size = 64 + 16 = 80 bits

Control Memory = 4 kW = ( (4* 80) / 8 ) = 40 kByte


b)For Vertical
6 bits for 64 signals i.e log264
4 bits for 16 flags i.e log216
12 bits for 4K words i.e log2(4*1024)

Control Word Size = 4 + 6 + 12 = 22 bits

Control Memory = 4 kW = ( (4* 22) / 8 ) = 11 kByte
VaibhavRai3
MridulGain
Picked
Technical Scripter 2018
Computer Organization & Architecture
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
OptionalDouble getAsDouble() method in Java with examples

30 Jul, 2019
OptionalDouble help us to create an object which may or may not contain a double value. The getAsDouble() method returns value If a value is present in OptionalDouble object, otherwise throws NoSuchElementException.
Syntax:
public double getAsDouble()

Parameters: This method accepts nothing.
Return value: This method returns the value described by this OptionalDouble.
Exception: This method throws NoSuchElementException if no value is present
Below programs illustrate getAsDouble() method:
Program 1:
// Java program to demonstrate// OptionalDouble.getAsDouble() method  import java.util.OptionalDouble;  public class GFG {      public static void main(String[] args)    {          // Create an OptionalDouble instance        OptionalDouble opDouble            = OptionalDouble.of(44356.455);          System.out.println("OptionalDouble: "                           + opDouble.toString());          // Get value in this instance        // using getAsDouble()        System.out.println("Value in OptionalDouble = "                           + opDouble.getAsDouble());    }}
OptionalDouble: OptionalDouble[44356.455]
Value in OptionalDouble = 44356.455

Program 2:
// Java program to demonstrate// OptionalDouble.getAsDouble() method  import java.util.OptionalDouble;  public class GFG {      public static void main(String[] args)    {          try {              // Create an OptionalDouble instance            OptionalDouble opDouble = OptionalDouble.empty();              System.out.println("OptionalDouble: "                               + opDouble.toString());              // Get value in this instance            // using getAsDouble()            System.out.println("Value in OptionalDouble = "                               + opDouble.getAsDouble());        }        catch (Exception e) {              System.out.println("Exception: " + e);        }    }}
OptionalDouble: OptionalDouble.empty
Exception: java.util.NoSuchElementException: No value present

References: https://docs.oracle.com/javase/10/docs/api/java/util/OptionalDouble.html#getAsDouble()
Akanksha_Rai
Java - util package
Java-Functions
Java-OptionalDouble
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to remove rows from data frame in R that contains NaN?

The NaN values are referred to as the Not A Number in R. It is also called undefined or unrepresentable but it belongs to numeric data type for the values that are not numeric, especially in case of floating-point arithmetic. To remove rows from data frame in R that contains NaN, we can use the function na.omit.
 Live Demo
Consider the below data frame −
x1<−sample(c(NaN,5,10),20,replace=TRUE)
x2<−sample(c(NaN,0,1),20,replace=TRUE)
df1<−data.frame(x1,x2)
df1
x1 x2
1 NaN NaN
2 10 0
3 NaN NaN
4 NaN NaN
5 NaN NaN
6 NaN NaN
7 5 1
8 5 1
9 5 NaN
10 10 NaN
11 5 NaN
12 NaN NaN
13 NaN NaN
14 NaN NaN
15 10 1
16 10 0
17 NaN NaN
18 NaN 1
19 NaN NaN
20 5 1
Removing rows with NaN from df1 −
df1<−na.omit(df1)
df1
x1 x2
2 10 0
7 5 1
8 5 1
15 10 1
16 10 0
20 5 1
 Live Demo
y1<−sample(c(NaN,rnorm(5)),20,replace=TRUE)
y2<−sample(c(NaN,rnorm(2)),20,replace=TRUE)
df2<−data.frame(y1,y2)
df2
y1 y2
1 0.71997269 NaN
2 0.31324492 NaN
3 0.71997269 −0.1903841
4 1.23101131 −0.1903841
5 0.09512564 −0.1903841
6 0.71997269 0.3998648
7 −0.14221014 −0.1903841
8 0.09512564 NaN
9 NaN NaN
10 1.23101131 0.3998648
11 −0.14221014 0.3998648
12 1.23101131 NaN
13 NaN 0.3998648
14 0.71997269 NaN
15 0.09512564 NaN
16 0.31324492 NaN
17 NaN NaN
18 0.09512564 0.3998648
19 1.23101131 0.3998648
20 0.71997269 −0.1903841
Removing rows with NaN from df2 −
df2<−na.omit(df2)
df2
y1 y2
3 0.71997269 −0.1903841
4 1.23101131 −0.1903841
5 0.09512564 −0.1903841
6 0.71997269 0.3998648
7 −0.14221014 −0.1903841
10 1.23101131 0.3998648
11 −0.14221014 0.3998648
18 0.09512564 0.3998648
19 1.23101131 0.3998648
20 0.71997269 −0.1903841
Java Generics - Unbounded Types Erasure

Java Compiler replaces type parameters in generic type with Object if unbounded type parameters are used.
package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args) {
      Box<Integer> integerBox = new Box<Integer>();
      Box<String> stringBox = new Box<String>();

      integerBox.add(new Integer(10));
      stringBox.add(new String("Hello World"));

      System.out.printf("Integer Value :%d\n", integerBox.get());
      System.out.printf("String Value :%s\n", stringBox.get());
   }
}

class Box<T> {
   private T t;

   public void add(T t) {
      this.t = t;
   }

   public T get() {
      return t;
   }   
}
In this case, java compiler will replace T with Object class and after type erasure,compiler will generate bytecode for the following code.
package com.tutorialspoint;

public class GenericsTester {
   public static void main(String[] args) {
      Box integerBox = new Box();
      Box stringBox = new Box();

      integerBox.add(new Integer(10));
      stringBox.add(new String("Hello World"));

      System.out.printf("Integer Value :%d\n", integerBox.get());
      System.out.printf("String Value :%s\n", stringBox.get());
   }
}

class Box {
   private Object t;

   public void add(Object t) {
      this.t = t;
   }

   public Object get() {
      return t;
   }   
}
In both case, result is same −
Integer Value :10
String Value :Hello World


    16 Lectures 
     2 hours 

 Malhar Lathkar

    19 Lectures 
     5 hours 

 Malhar Lathkar

    25 Lectures 
     2.5 hours 

 Anadi Sharma

    126 Lectures 
     7 hours 

  Tushar Kale

    119 Lectures 
     17.5 hours 

 Monica Mittal

    76 Lectures 
     7 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
C program to compare two files and report mismatches

In the C programming language, the programmer can excess the files and read and write content in them.
A file is a simple memory block that can store information, here we are concerned with text only.
In this program, we will compare two files and report mismatches that occur. These files are almost identical but may have some characters that are different. Also, the program will return the line and position of the file at which the first mismatch occurs.
Step 1: Open both the file with pointer at the starting.
Step 2: Fetch data from file as characters one by one.
Step 3: Compare the characters. If the characters are different then return the line and position of the error character.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void compareFiles(FILE *file1, FILE *file2){
   char ch1 = getc(file1);
   char ch2 = getc(file2);
   int error = 0, pos = 0, line = 1;
   while (ch1 != EOF && ch2 != EOF){
      pos++;
      if (ch1 == '\n' && ch2 == '\n'){
         line++;
         pos = 0;
      }
      if (ch1 != ch2){
         error++;
         printf("Line Number : %d \tError"
         " Position : %d \n", line, pos);
      }
      ch1 = getc(fp1);
      ch2 = getc(fp2);
   }
   printf("Total Errors : %d\t", error);
}
int main(){
   FILE *file1 = fopen("file1.txt", "r");
   FILE *file2 = fopen("file2.txt", "r");
   if (file1 == NULL || file2 == NULL){
      printf("Error : Files not open");
      exit(0);
   }
   compareFiles(file1, file2);
   fclose(file1);
   fclose(file2);
   return 0;
}
// content of the files
File1 : Hello!
Welcome to tutorials Point
File2: Hello!
Welcome to turoials point
Line number: 2 Error position: 15
Total error : 1
GATE | GATE-CS-2014-(Set-1) | Question 44 - GeeksforGeeks

10 Sep, 2021
A canonical set of items is given below
S --> L. > R
Q --> R.
On input symbol < the set has
(A) a shift-reduce conflict and a reduce-reduce conflict.(B) a shift-reduce conflict but not a reduce-reduce conflict.(C) a reduce-reduce conflict but not a shift-reduce conflict.(D) neither a shift-reduce nor a reduce-reduce conflict.Answer: (D)Explanation: The question is asked with respect to the symbol  ‘ < '  which is not present in the given canonical set of items. Hence it is neither a shift-reduce conflict nor a reduce-reduce conflict on symbol ‘<'.
Hence D is the correct option.
But if the question would have asked with respect to the symbol  ‘ > ‘  then it would have been a shift-reduce conflict.
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersGATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti AcharyaWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0038:16 / 52:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Sn5eIxvrNBc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2014-(Set-1)
GATE-GATE-CS-2014-(Set-1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2007 | Question 64
ALTER TABLE to add a composite primary key in MySQL?

To add composite primary key, use the ALTER command. Let us first create a demo table
The query to create a table.
mysql> create table CompositePrimaryKey
   -> (
   -> Id int,
   -> StudentName varchar(100),
   -> Age int
   -> );
Query OK, 0 rows affected (0.56 sec)
Haven’t added composite primary key above till now. Let us now check with the help of desc command.
mysql> desc CompositePrimaryKey;
The following is the output.
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id          | int(11)      | YES  |     | NULL    |       |
| StudentName | varchar(100) | YES  |     | NULL    |       |
| Age         | int(11)      | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.09 sec)

Look at the above sample output, there is no primary keyword. This itself says that no composite primary key is available.
Now, let us use ALTER command to add composite primary key. The query is as follows.
mysql>  ALTER table CompositePrimaryKey add primary key(Id,StudentName);
Query OK, 0 rows affected (1.26 sec)
Records: 0  Duplicates: 0  Warnings: 0
Above, I have added composite primary key with the column name “Id” and “StudentName”. To check the same, we can use DESC command. The query is as follows.
mysql> DESC CompositePrimaryKey;
Here is the output.
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| Id          | int(11)      | NO   | PRI | NULL    |       |
| StudentName | varchar(100) | NO   | PRI | NULL    |       |
| Age         | int(11)      | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

As we can see in the above output, “PR” means we have successfully added composite primary key on column Id and StudentName.
How to automate menu box/pop up of right click in Python Selenium?

We can automate right click action with Selenium webdriver in Python by using the ActionChains class. We have to create an object of the ActionChains class and then apply the relevant method on it.
In order to move the mouse to the element on which right click is to be performed, we shall use the move_to_element method and pass the element locator as a parameter.
Then apply context_click method to perform the right click. Finally, use the perform method to actually carry out these actions. Also, we have to add the statement from selenium.webdriver.common.action_chains import ActionChains in our code to work with ActionChains class.
a = ActionChains(driver)
m= driver.find_element_by_id("hot-spot")
a.move_to_element(m)
a.context_click().perform
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.alert import Alert
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#launch URL
driver.get("https://the-internet.herokuapp.com/context_menu")
#object of ActionChains
a = ActionChains(driver)
#identify element
m = driver.find_element_by_id("hot-spot")
#move mouse over element
a.move_to_element(m)
#perform right-click
a.context_click().perform()
#switch to alert
al = driver.switch_to.alert
#get alert text
s = al.text
print("Alert text: ")
print(s)
#accept alert
al.accept()
#close browser
driver.quit()
Sum of XOR of all pairs in an array in C++

In this problem, we are given an array arr[] of n integers. Our task is to create a program to find the sum of XOR of all pairs in an array.
Input: arr[] = {5, 1, 4}
Output: 10
Explanation: the sum of all pairs:
5 ^ 1 = 4
1 ^ 4 = 5
5 ^ 4 = 1
sum = 4 + 5 + 1 = 10
One simple approach to solve this problem is to run nested loops and find all pairs of numbers. Find XOR of each pair and add them to the sum.
Initialise sum = 0
Step 1: for(i -> 0 to n). Do:
   Step 1.1: for( j -> i to n ). Do:
      Step 1.1.1: update sum. i.e. sum += arr[i] ^ arr[j].
Step 2: return sum.
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
using namespace std;
int findXORSum(int arr[], int n) {
   int sum = 0;
   for (int i = 0; i < n; i++)
    for (int j = i + 1; j < n; j++)
    sum += (arr[i]^arr[j]);
   return sum;
}
int main() {
   int arr[] = { 5, 1, 4 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"Sum of XOR of all pairs in an array is "<<findXORSum(arr, n);
   return 0;
}
Sum of XOR of all pairs in an array is 10
The time complexity of the algorithm is O(n2) and is not the most efficient solution to the problem.
An efficient solution to the problem is using the bit manipulation technique.
Here, we will consider bits of the number and at each position. And apply the below formula find the intermediate sum,
(number of set bits) * (number of unset bits) * (2^(bit_position))
To find the final sum, we will add the intermediate sum of all bits.
Our solution is for the 64-bit integer value. For this approach, we need the number of bits.
Initialize sum = 0, setBits = 0, unsetBits = 0.
Step 1: Loop for i -> 0 to 64. repeat steps 2, 3.
Step 2: Reset setBits and unsetBits to 0.
Step 3: For each element of the array find the value of setBits and unsetBits. At ith position.
Step 4: update sum += (setBits * unsetBits * (2i))
Program to illustrate the working of our solution,
 Live Demo
#include <iostream>
#include <math.h>
using namespace std;
long findXORSum(int arr[], int n) {
   long sum = 0;
   int unsetBits = 0, setBits = 0;
   for (int i = 0; i < 32; i++) {
      unsetBits = 0; setBits = 0;
      for (int j = 0; j < n; j++) {
         if (arr[j] % 2 == 0)
            unsetBits++;
         else
            setBits++;
         arr[j] /= 2;
      }
      sum += ( unsetBits*setBits* (pow(2,i)) );
   }
   return sum;
}
int main() {
   int arr[] = { 5, 1, 4, 7, 9};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"Sum of XOR of all pairs in an array is "<<findXORSum(arr, n);
   return 0;
}
Sum of XOR of all pairs in an array is 68
Java program to find the square root of a given number

The process of finding the square root of a number can be divided into two steps. One step is to find integer part and the second one is for fraction part.
Define value n to find the square root of.
Define variable i and set it to 1. (For integer part)
Define variable p and set it to 0.00001. (For fraction part)
While i*i is less than n, increment i.
Step 4 should produce the integer part so far.
While i*i is less than n, add p to i.
Now i have the square root value of n.
Live Demo
public class SquareRoot {
   public static void main(String args[]){
      int n = 24;
      double i, precision = 0.00001;
      for(i = 1; i*i <=n; ++i);
      for(--i; i*i < n; i += precision);
      System.out.println("Square root of given number "+i);
   }
}
Square root of given number 4.898979999965967
How to style labels with CSS?

To style labels with CSS, the code is as follows −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      margin: 20px;
   }
   span {
      font-size: 18px;
      font-weight: 600;
      color: white;
      padding: 8px;
   }
   .success {
      background-color: #4caf50;
   }
   .info {
      background-color: #2196f3;
   }
   .warning {
      background-color: #ff9800;
   }
   .danger {
      background-color: #f44336;
   }
   .other {
      background-color: #e7e7e7;
      color: black;
   }
</style>
</head>
<body>
<h1>Labels Example</h1>
<span class="success">Success</span>
<span class="info">Info</span>
<span class="warning">Warning</span>
<span class="danger">Danger</span>
<span class="other">Other</span>
</body>
</html>
The above code will produce the following output −
C Program for sparse matrix

In a given matrix, when most of the elements are zero then, we call it as sparse matrix. Example − 3 x3 matrix
1 1 0
0 0 2
0 0 0
In this matrix, most of the elements are zero, so it is sparse matrix.
Check whether a matrix is a sparse matrix or not.
Let us assume ZERO in the matrix is greater than (row * column)/2.
Let us assume ZERO in the matrix is greater than (row * column)/2.
Then, the matrix is a sparse matrix otherwise not.
Then, the matrix is a sparse matrix otherwise not.
Following is the program to check whether the given matrix is sparse matrix or not −
 Live Demo
#include<stdio.h>
#include<stdlib.h>
int main(){
   int row,col,i,j,a[10][10],count = 0;
   printf("Enter row\n");
   scanf("%d",&row);
   printf("Enter Column\n");
   scanf("%d",&col);
   printf("Enter Element of Matrix1\n");
   for(i = 0; i < row; i++){
      for(j = 0; j < col; j++){
         scanf("%d",&a[i][j]);
      }
   }
   printf("Elements are:\n");
   for(i = 0; i < row; i++){
      for(j = 0; j < col; j++){
         printf("%d\t",a[i][j]);
      }
      printf("\n");
   }
   /*checking sparse of matrix*/
   for(i = 0; i < row; i++){
      for(j = 0; j < col; j++){
         if(a[i][j] == 0)
            count++;
      }
   }
   if(count > ((row * col)/2))
      printf("Matrix is a sparse matrix \n");
   else
      printf("Matrix is not sparse matrix\n");
}
When the above program is executed, it produces the following result −
Run 1:
Enter row
3
Enter Column
2
Enter Element of Matrix1
1 0 2 0 2 0
Elements are:
1 0
2 0
2 0
Matrix is not sparse matrix
Run 2:
Enter row
3
Enter Column
2
Enter Element of Matrix1
1 0 0 0 0 0
Elements are:
1 0
0 0
0 0
Matrix is a sparse matrix
Python | Passing dictionary as keyword arguments

28 Aug, 2019
Many times while working with Python dictionaries, due to advent of OOP Paradigm, Modularity is focussed in different facets of programming. Hence there can be many use cases in which we require to pass a dictionary as argument to a function. But this required the unpacking of dictionary keys as arguments and it’s values as argument values. Let’s discuss a method in which this can be performed.
Method : Using ** ( splat ) operatorThis operator is used to unpack a dictionary, and while passing in a function this can possibly unpack a dictionary and achieve the required task of mapping the keys to arguments and it’s values to argument values.
# Python3 code to demonstrate working of# Passing dictionary as keyword arguments# Using ** ( splat ) operator  # Helper function to demo this taskdef test_func(a = 4, b = 5):    print("The value of a is : " + str(a))    print("The value of b is : " + str(b))  # initializing dictionarytest_dict = {'a' : 1, 'b' : 2}  # printing original dictionaryprint("The original dictionary is : " + str(test_dict))  # Testing with default values print("The default function call yields : ")test_func()  print("\r")  # Passing dictionary as keyword arguments# Using ** ( splat ) operatorprint("The function values with splat operator unpacking : ")test_func(**test_dict)
The original dictionary is : {'a': 1, 'b': 2}
The default function call yields : 
The value of a is : 4
The value of b is : 5

The function values with splat operator unpacking : 
The value of a is : 1
The value of b is : 2

Python dictionary-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Split string on Kth Occurrence of Character

17 Jun, 2021
Many problems of the split have been dealt with in the past, but sometimes, one can also encounter this problem in which we need to split the string on the Kth occurrence of a character. Let’s discuss certain ways in which this problem can be solved. 
Method #1 : Using split() + join() The split and join method can perform this particular task. In this, we split the string on basis of character and according to K, we perform a rejoin using the nested join method.  
Python3
# Python3 code to demonstrate working of# Split string on Kth Occurrence of Character# Using split() + join() # initializing stringtest_str = "Geeks_for_Geeks_is_best" # split charsplt_char = "_" # initializing KK = 3 # printing original stringprint("The original string is : " + str(test_str)) # Using split() + join()# Split string on Kth Occurrence of Charactertemp = test_str.split(splt_char)res = splt_char.join(temp[:K]), splt_char.join(temp[K:]) # printing resultprint("Is list after Kth split is : " + str(list(res)))
The original string is : Geeks_for_Geeks_is_best
Is list after Kth split is : ['Geeks_for_Geeks', 'is_best']
 Method #2 : Using regex This problem can also be solved using the regex to perform this particular task. Along with slicing, the finditer method of regex library can help to achieve this particular task. 
Python3
# Python3 code to demonstrate working of# Split string on Kth Occurrence of Character# Using regeximport re # initializing stringtest_str = "Geeks_for_Geeks_is_best" # split charsplt_char = "_" # initializing KK = 3 # printing original stringprint("The original string is : " + str(test_str)) # Using regex# Split string on Kth Occurrence of Charactertemp = [x.start() for x in re.finditer(splt_char, test_str)]res1 = test_str[0:temp[K - 1]]res2 = test_str[temp[K - 1] + 1:]res = (res1 + " " + res2).split(" ") # printing resultprint("Is list after Kth split is : " + str(res))
The original string is : Geeks_for_Geeks_is_best
Is list after Kth split is : ['Geeks_for_Geeks', 'is_best']
Method #3: Using maxsplit from split  
You can use the split itself to get the kth number the second parameter of the method split, that is the max split, then you have your string.  
Probably the easiest way
Python3
test_str = "Geeks for geeks" K = 1 #kth occurrence new_str, rest = test_str.split(" ", K)                                #or if you want a list                                new_str_list = test_str.split(" ", K) print(new_str)print(rest) print(f'list: {new_str_list}')
Geeks
for geeks
list: ['Geeks', 'for geeks']
raulmyron
simmytarika5
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
Matplotlib.ticker.AutoMinorLocator Class in Python

21 Apr, 2020
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.
The matplotlib.ticker.AutoMinorLocator class is used to find minor tick positions based on the positions of major ticks dynamically. The major ticks need to be evenly spaced along with a linear scale.
Syntax: class matplotlib.ticker.AutoMinorLocator(n=None)
parameter:
n: it represents the number of subdivisions of the interval between major ticks. If n is omitted or None, it automatically sets to 5 or 4.
Methods of the class:
tick_values(self, vmin, vmax): Given vmin and vmax it returns the value of the located ticks.
Example 1:
import pandas as pdimport matplotlib.pyplot as pltfrom matplotlib import ticker  data = [    ('Area 1', 'Bar 1', 2, 2),    ('Area 2', 'Bar 2', 1, 3),    ('Area 1', 'Bar 3', 3, 2),    ('Area 2', 'Bar 4', 2, 3),]  df = pd.DataFrame(data, columns =('A', 'B',                                  'D1', 'D2'))  df = df.set_index(['A', 'B'])df.sort_index(inplace = True)  # Remove the index names for the plot,# or it'll be used as the axis labeldf.index.names = ['', '']  ax = df.plot(kind ='barh', stacked = True)  minor_locator = ticker.AutoMinorLocator(2)  ax.yaxis.set_minor_locator(minor_locator)  ax.set_yticklabels(df.index.get_level_values(1))ax.set_yticklabels(df.index.get_level_values(0).unique(),                   minor = True)  ax.set_yticks(np.arange(0.5, len(df), 2),               minor = True)  ax.tick_params(axis ='y', which ='minor',                direction ='out', pad = 50)  plt.show()
Output:
Example 2:
from pylab import * import matplotlibimport matplotlib.ticker as ticker    # Setting minor ticker size to 0, # globally.matplotlib.rcParams['xtick.minor.size'] = 0  # Create a figure with just one # subplot.fig = figure()ax = fig.add_subplot(111)  # Set both X and Y limits so that# matplotlibax.set_xlim(0, 800)  # Fixes the major ticks to the places# where desired (one every hundred units)ax.xaxis.set_major_locator(ticker.FixedLocator(range(0,                                                     801,                                                      100)))ax.xaxis.set_major_formatter(ticker.NullFormatter())  # Add minor tickers AND labels for themax.xaxis.set_minor_locator(ticker.AutoMinorLocator(n = 2))ax.xaxis.set_minor_formatter(ticker.FixedFormatter(['AB %d' % x                                                     for x in range(1, 9)]))  ax.set_ylim(-2000, 6500, auto = False)  # common attributes for the bar plotsbcommon = dict(    height = [8500],    bottom = -2000,       width = 100)          bars = [[600, 'green'],        [700, 'red']]for left, clr in bars:    bar([left], color = clr, **bcommon)        show()
Output:
Python-matplotlib
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
move_by_offset – Action Chains in Selenium Python

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around move_by_offset method on Action Chains in Python Selenium. move_by_offset method is used for moving the mouse to an offset from current mouse position.Syntax –
move_by_offset(xoffset, yoffset)
xoffset: X offset to move to, as a positive or negative integer.
yoffset: Y offset to move to, as a positive or negative integer.
Example –one can use move mouse method as an Action chain as below –
move_by_offset(100, 200)

To demonstrate, move_by_offset method of Action Chains in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program –
# import webdriverfrom selenium import webdriver  # import Action chains from selenium.webdriver.common.action_chains import ActionChains  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # create action chain objectaction = ActionChains(driver)  # move the cursoraction.move_by_offset(200, 200)  # perform the operationaction.perform()
Output –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby/TK - Standard Dailog Box 

Dialog boxes are a type of window used in applications to get some information from the user, inform them that some event has occurred, confirm an action and more.
The appearance and usage of dialog boxes is usually quite specifically detailed in a platform's style guide. Tk comes with a number of dialog boxes built-in for common tasks, and which help you conform to platform specific style guidelines.
Ruby/Tk provides several dialogs to let the user select files or directories. The open variant on the dialog is used when you want the user to select an existing file, while the save variant is used to choose a file to save. There are four variants, which can be used −
Tk.getOpenFile − To have one open file dialog box.
Tk.getOpenFile − To have one open file dialog box.
Tk.getSaveFile − To have one save file dialog box.
Tk.getSaveFile − To have one save file dialog box.
Tk.chooseDirectory − To have one choose directory dialog box.
Tk.chooseDirectory − To have one choose directory dialog box.
Tk.chooseColor − To have one choose color dialog box.
Tk.chooseColor − To have one choose color dialog box.
Following example will explain how to create Open file dialog box.
require 'tk'

root = TkRoot.new
root.title = "Window"

button_click = Proc.new {
   Tk.getOpenFile
}

button = TkButton.new(root) do
   text "button"
   pack("side" => "left",  "padx"=> "50", "pady"=> "50")
end

button.comman = button_click

Tk.mainloop
This will produce the following result −
Following example will explain how to create Choose Color dialog box.
require 'tk'

root = TkRoot.new
root.title = "Window"

button_click = Proc.new {
   Tk.chooseColor
}

button = TkButton.new(root) do
   text "button"
   pack("side" => "left",  "padx"=> "50", "pady"=> "50")
end

button.comman = button_click

Tk.mainloop
This will produce the following result −

    46 Lectures 
     9.5 hours 

 Eduonix Learning Solutions

    97 Lectures 
     7.5 hours 

 Skillbakerystudios

    227 Lectures 
     40 hours 

 YouAccel

    19 Lectures 
     10 hours 

 Programming Line

    51 Lectures 
     5 hours 

 Stone River ELearning

    39 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
reflect.ValueOf() Function in Golang with Examples - GeeksforGeeks

03 May, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ValueOf() Function in Golang is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program.
Syntax:
func ValueOf(i interface{}) Value

Parameters: This function takes the following parameters:
i: This parameter is the interface.
Return Value: This function returns the new Value initialized to the concrete value stored in the interface i.
Below examples illustrate the use of above method in Golang:
Example 1:
// Golang program to illustrate// reflect.ValueOf() Function   package main   import (    "fmt"    "reflect")   // Main functionfunc main() {       a := []int{2, 5}           var b reflect.Value = reflect.ValueOf(&a)       b = b.Elem()           fmt.Println("Slice :", a)           //use of ValueOf method       b = reflect.Append(b, reflect.ValueOf(80))    fmt.Println("Slice after appending data:", b)   }        
Output:
Slice : [2 5]
Slice after appending data: [2 5 80]

Example 2:
// Golang program to illustrate// reflect.ValueOf() Function   package main   import (    "fmt"    "reflect")   // Main function func main() {       src := reflect.ValueOf([]int{10, 20, 32})           dest := reflect.ValueOf([]int{1, 2, 3})      // use of ValueOf() method    fmt.Println(src, dest)}
Output:
[10 20 32] [1 2 3]

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
strings.Replace() Function in Golang With Examples
Arrays in Go
How to Split a String in Golang?
fmt.Sprintf() Function in Golang With Examples
Golang Maps
Slices in Golang
Inheritance in GoLang
Different Ways to Find the Type of Variable in Golang
Interfaces in Golang
p5.js | print() function - GeeksforGeeks

12 Apr, 2019
The print() function in p5.js writes the content on console area of the web browser. It is helpful for looking at the data a program is producing which helps in debugging the code. The elements can be separated by using quotes (“”) and joined with the addition operator (+). Use print(‘\n’) to display blank line.
Syntax:
print(c)
Parameters: The function accepts single parameter c which stores the any combination of Number, String, Object, Boolean, Array to print.
Below program illustrates the print() function in p5.js:
Example 1: This example uses print() function to display the content on console.
function setup() {      // Create canvas of given size    createCanvas(400, 400);          // print function call    print("Hello GeeksForGeeks");}  function draw() {          // Set the background color    background(220);}
Output:
Example 2: This example uses print() function to display the content on console.
function setup() {      // Create canvas of given size    createCanvas(400, 400);          // print function call    for(let i = 0; i < 4; i++) {        for(let j = 0; j < i; j++) {            print("*");        }        print("\n");    }}  function draw() {          // Set the background color    background(220);}
Output:
Reference: https://p5js.org/reference/#/p5/print
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Getting last element of an array in Julia - last() Method - GeeksforGeeks

26 Mar, 2020
The last() is an inbuilt function in julia which is used to return the last element of the specified iterable collection.
Syntax: last(coll)
Parameters:
coll: Specified iterable collection.
Returns: It returns the last element of the specified iterable collection.
Example 1:
# Julia program to illustrate # the use of last() method   # Getting the last element of # the specified iterable collection# or 1D arrayprintln(last(1:2:3))println(last(5:10))println(last([3, 5, 7, 9]))println(last([2, 4, 6, 8]))
Output:
3
10
9
8

Example 2:
# Julia program to illustrate # the use of last() method   # Getting the last element of # the specified 2D and 3D arrayprintln(last([3 5; 7 9]))println(last(["a" "b"; "c" "d"]))println(last(cat([1 2; 3 4], [5 6; 7 8],                 [2 2; 3 4], dims = 3)))println(last(cat(["a" "b"; "c" "d"],                  ["e" "f"; "g" "h"],                  ["i" "j"; "k" "l"], dims = 3)))
Output:
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
Storing Output on a File in Julia
Formatting of Strings in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Manipulating matrices in Julia
Creating array with repeated elements in Julia - repeat() Method
while loop in Julia
Get array dimensions and size of a dimension in Julia - size() Method
numpy.ones() in Python - GeeksforGeeks

21 Feb, 2022
The numpy.ones() function returns a new array of given shape and type, with ones. 
Syntax: numpy.ones(shape, dtype = None, order = 'C') 
Parameters : 
shape : integer or sequence of integers
order  : C_contiguous or F_contiguous
         C-contiguous order in memory(last index varies the fastest)
         C order means that operating row-rise on the array will be slightly quicker
         FORTRAN-contiguous order in memory (first index varies the fastest).
         F order means that column-wise operations will be faster. 
dtype : [optional, float(byDefault)] Data type of returned array.  
Returns :  
ndarray of ones having given shape, order and datatype.
 
Python
# Python Program illustrating# numpy.ones method import numpy as geek b = geek.ones(2, dtype = int)print("Matrix b : \n", b) a = geek.ones([2, 2], dtype = int)print("\nMatrix a : \n", a) c = geek.ones([3, 3])print("\nMatrix c : \n", c)
Output :  
Matrix b : 
 [1 1]

Matrix a : 
 [[1 1]
 [1 1]]

Matrix c : 
 [[ 1.  1.  1.]
 [ 1.  1.  1.]
 [ 1.  1.  1.]]
Reference : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.ones.html Note : Ones, unlike zeros and empty, does not set the array values to zero or random values respectively.Also, these codes won’t run on online-ID. Please run them on your systems to explore the working.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
avtarkumar719
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Convert integer to string in Python
How to decode a string after encoding in JavaScript?

To encode a string we need encodeURIComponent() or encodeURI() and to decode a string we need decodeURIComponent() or decodeURI(). Initially, we have used escape() to encode a string but since it is deprecated we are now using encodeURI().
encodeURIComponent(string);
decodeURIComponent(string);
In the following example, initially, a string is taken and encoded using encodeURI() and later decoded using decodeURI(). Later on both the encoded and decoded results were displayed in the output.
Live Demo
<html>
<body>
<p id = "encoding"></p>
<script>
   var str = "Tutorix is the best e-learning platform";
   var enc = encodeURI(str);
   var dec = decodeURI(enc);
   var res = "After encoding: " + enc + "
   </br>" + "After Decoding: " + dec;
   document.getElementById("encoding").innerHTML = res;
</script>
</body>
</html>
After encoding: Tutorix%20is%20the%20best%20e-learning%20platform
After Decoding: Tutorix is the best e-learning platform
Bootstrap 4 .card-img-bottom class

Use the card-img-bottom class in Bootstrap 4 to place an image at the bottom inside a Bootstrap 4 card.
Set the card body, and within that, the card title and card text −
<div class="card-body">
  <h4 class="card-title">Quantitative Aptitude</h4>
  <p class="card-text">For Entrance Exams</p>
  <a href="#" class="btn btn-primary">Sample Questions</a>
</div>
Now set image with class “card-img-bottom”−
<img class="card-img-bottom" src="Image-Source" alt="alt text" style="width:100%">
Let us see an example to learn how to implement Bootstrap 4 .card-img-bottom 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">
    <h3>Quantitative Aptitude Questions Answers</h3>
    <div class="card" style="width:400px">
      <div class="card-body">
        <h4 class="card-title">Quantitative Aptitude</h4>
        <p class="card-text">For Entrance Exams</p>
        <a href="#" class="btn btn-primary">Sample Questions</a>
      </div>
      <img class="card-img-bottom" src="https://www.tutorialspoint.com/videotutorials/images/numerical_ability_home.jpg" alt="QA" style="width:100%">
    </div>
  </div>
 </body>
</html>
Progress Bars in Python (and pandas!) | by Peter Nistrup | Towards Data Science

Time and estimate the progress of your functions in Python (and pandas!)
In this article I’ll try to break my own record for the shortest, most concise article ever, so without further ado, let’s go!
tqdm is a package for Python that enables you to instantly create progress bars and estimate TTC (Time To Completion) for your functions and loops!
Simply install tqdm using pip in your favorite terminal and you’re ready to go:
pip install tqdm
Using tqdm is really quite easy, simply import tqdm:
>>> from tqdm import tqdm, tqdm_notebook
And any time you see a loop somewhere in your code you can simply wrap it in either tdqm()or tqdm_notebook()if you’re working in a Jupyter Notebook environment. You can give your progress-bars a description as well, using the desc= argument:
Once you’ve imported tqdm, you can initiate the method: tqdm.pandas() or if you’re running your code in a Jupyter Notebook environment use:
>>> from tqdm._tqdm_notebook import tqdm_notebook>>> tqdm_notebook.pandas()
Then you can simply replace all your .apply() functions with .progress_apply() it’s really that simple!
Thanks for reading! I’ve found that people seem to enjoy this style of fast and to-the-point articles, similar to my Exploring your data with just 1 line of Python article, so hopefully you enjoyed this as well!
If you want to see and learn more, be sure to follow me on Medium🔍 and Twitter 🐦
Matplotlib.pyplot.axhspan() in Python - GeeksforGeeks

27 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The axhspan() function in pyplot module of matplotlib library is used to add a horizontal span (rectangle) across the axis.
Syntax: matplotlib.pyplot.axhspan(ymin, ymax, xmin=0, xmax=1, **kwargs)
Parameters: This method accept the following parameters that are described below:
ymin: This parameter is the lower limit of the horizontal span in data units.
ymax: This parameter is the upper limit of the horizontal span in data units.
xmin: This parameter is the lower limit of the vertical span in data units.
xmax: This parameter is the upper limit of the vertical span in data units.
Returns: This returns the Polygon.
Below examples illustrate the matplotlib.pyplot.axhspan() function in matplotlib.pyplot:
Example 1:
import matplotlib.pyplot as plt    # xmin = 0 and xmax = 1 is the# default valueplt.axhspan(0.25, 0.75, facecolor ='r', alpha = 0.7)
Output:
Example 2:
#Implementation of matplotlib functionimport numpy as np import matplotlib.pyplot as plt     t = np.arange(-2, 3, .01) s = np.sin(np.pi * t)     plt.plot(t, s, color ='black') plt.axhline(y = 1, color ='black')   plt.axvline(x = 1, color ='black') plt.axvline(x = 0.5, ymin = 0.75, linewidth = 8,            color ='green')   plt.axhline(y =.5, xmin = 0.25, xmax = 0.75,            color ='black')     plt.axhspan(0.25, 0.75, facecolor ='0.5', alpha = 0.5) plt.axvspan(2.25, 2.55, facecolor ='green', alpha = 0.5)   plt.title('matplotlib.pyplot.axhspan() Example\n',          fontsize=14, fontweight='bold')  plt.show()
Output:
Matplotlib Pyplot-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Convert integer to string in Python