code-rag-bench/online-tutorials huggingface dataset:
Program to find remainder without using modulo or % operator in C++

In this problem, we are given two numbers, N and D. Our task is to create a Program to find remainder without using modulo or % operator in C++.
Problem description − We need to find the remainder that will be left after dividing the number N by D. But we cannot use the modulo or % operator for this.
Let’s take an example to understand the problem
N = 53 D = 3
2
To find the remainder, a simple approach is to find the number less than N
which is the multiple of D. And the substrate the number from N. To return
the remainder.
Program to illustrate the working of our solution
 Live Demo
#include <iostream>
using namespace std;
int findRem(int N, int D) {
   int i ;
   for(i = 0; ;i++) {
      if(D * i >= N)
         break;
   }
   return N - (D * (i-1));
}
int main(){
   int N = 45, D = 6 ;
   cout<<"The remainder after dividing "<<N<<" by "<<D<<" is"<<findRem(N, D);
   return 0;
}
The remainder after dividing 45 by 6 is 3
Another solution is by using the integer value of the quotient of the dividing
which can be extracted directly by initializing it to an int value in C++. Then
multiplying it with D. And subtracting the value from N gives the remainder.
Program to illustrate the working our solution
 Live Demo
#include <iostream>
using namespace std;
int findRem(int N, int D) {
   int Q = N/D;
   int R = N - (D * Q);
   return R;
}
int main(){
   int N = 45, D = 6 ;
   cout<<"The remainder after dividing "<<N<<" by "<<D<<" is"<<findRem(N, D);
   return 0;
}
The remainder after dividing 45 by 6 is 3
Normalization vs Standardization

12 Nov, 2021
Feature scaling is one of the most important data preprocessing step in machine learning. Algorithms that compute the distance between the features are biased towards numerically larger values if the data is not scaled.
Tree-based algorithms are fairly insensitive to the scale of the features. Also, feature scaling helps machine learning, and deep learning algorithms train and converge faster.
There are some feature scaling techniques such as Normalization and Standardization that are the most popular and at the same time, the most confusing ones.
Let’s resolve that confusion.
Normalization or Min-Max Scaling is used to transform features to be on a similar scale. The new point is calculated as:
X_new = (X - X_min)/(X_max - X_min)
This scales the range to [0, 1] or sometimes [-1, 1]. Geometrically speaking, transformation squishes the n-dimensional data into an n-dimensional unit hypercube. Normalization is useful when there are no outliers as it cannot cope up with them. Usually, we would scale age and not incomes because only a few people have high incomes but the age is close to uniform.
Standardization or Z-Score Normalization is the transformation of features by subtracting from mean and dividing by standard deviation. This is often called as Z-score.
X_new = (X - mean)/Std
Standardization can be helpful in cases where the data follows a Gaussian distribution. However, this does not have to be necessarily true. Geometrically speaking, it translates the data to the mean vector of original data to the origin and squishes or expands the points if std is 1 respectively. We can see that we are just changing mean and standard deviation to a standard normal distribution which is still normal thus the shape of the distribution is not affected.
Standardization does not get affected by outliers because there is no predefined range of transformed features.
Difference between Normalization and Standardization
chhabradhanvi
Difference Between
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Compile-time and Run-time Polymorphism in Java
Difference between Internal and External fragmentation
Naive Bayes Classifiers
ML | Linear Regression
Linear Regression (Python Implementation)
Python – Convert HTML Characters To Strings

08 Dec, 2020
Prerequisites: html module
Given a string with HTML characters, the task is to convert HTML characters to a string. This can be achieved with the help of html.escape() method(for Python 3.4+), we can convert the ASCII string into HTML script by replacing ASCII characters with special characters by using html.escape() method.
By this method we can decode the HTML entities into text.
Syntax:
html.unescape(String)
We can also use Beautiful Soup which handles entity conversion. In Beautiful Soup 4, entities get decoded automatically.
Example 1: Python 3.6+
Python3
# import htmlimport html  # Create Texttext = 'Γeeks for Γeeks'  # It Converts given text To Stringprint(html.unescape(text))   # It Converts given text to HTML Entities print(html.escape(text)) 
Output:
Γeeks for Γeeks
&Gamma;eeks for &Gamma;eeks
Example 2: Python 2.6-3.3
We can use HTMLParser.unescape() from the standard library:
For Python 2.6-2.7 it’s in HtmlParser.
For Python 3 it’s in html.parser
Python3
#import htmlimport html  try:    # Python 2.6-2.7    from HTMLParser import HTMLParserexcept ImportError:    # Python 3    from html.parser import HTMLParser  # for python 3h = html.parserprint(h.unescape('Γeeks for Γeeks'))  
Output:
Γeeks for Γeeks
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python | numpy.isin() method

27 Sep, 2019
With the help of numpy.isin() method, we can see that one array having values are checked in a different numpy array having different elements with different sizes.
Syntax : numpy.isin(target_array, list)
Return : Return boolean array having same size as of target_array.
Example #1 :
In this example we can see that by using numpy.isin() method, we are able to get the boolean array if elements are matched with the target array.
# import numpyimport numpy as np  # using numpy.isin() methodgfg1 = np.array([1, 2, 3, 4, 5])lis = [1, 3, 5]gfg = np.isin(gfg1, lis)  print(gfg)
Output :
[ True False True False True]
Example #2 :
# import numpyimport numpy as np  # using numpy.isin() methodgfg1 = np.array([[1, 3], [5, 7], [9, 11]])lis = [1, 3, 11, 9]gfg = np.isin(gfg1, lis)  print(gfg)
Output :
[[ True True][False False][ True True]]
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
Ruby | Array dig() operation

08 Jan, 2020
Array#dig() : dig() is a Array class method which extracts the specific element out of the high dimension sequences.
Syntax: Array.dig()
Parameter: element position.
Return: element from a specific location in sequence, returning nil if any intermediate step is nil.
Code #1 : Example for dig() method
# Ruby code for dig() method  # declaring arraya = [18, 22, 33, 23, 5, 6]  # declaring arrayb = [[1, 4], [ 1, 1, 88, 9]]  # digputs "dig : #{a.dig(1)}\n\n"  # digputs "dig : #{b.dig(0, 1)}\n\n"  # digputs "dig : #{b.dig(1, 2)}\n\n"
Output :
dig : 22

dig : 4

dig : 88

Code #2 : Example for dig() method
# Ruby code for dig() method  # declaring arraya = [["abc"],     ["geeks", "dog"],     ["1", "2"]]  # declaring arrayb = [["cow"], ["1", "dog"]]  # digputs "dig : #{a.dig(2, 1)}\n\n"  # digputs "dig : #{a.dig(1, 1)}\n\n"  # digputs "dig : #{b.dig(1, 0)}\n\n"
Output :
dig : 2

dig : dog

dig : 1

Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Column Names within the aggregate Function in R

14 Sep, 2021
In this article we will discuss how to set column names with the aggregate function in R programming language.
The aggregate method in base R is used to divide the data frame into smaller subsets and compute a summary statistics for each of the formed groups. The function to be applied can be sum, mean, mode or any of the pre-defined aggregate methods available. This method gives a better clarity about the data. 
Syntax: aggregate(formula, data, function)
Parameters:
formula: the variable(s) of the input data frame we want to apply functions on. 
data: the data that we want to use for group by operation.
function: the function or calculation to be applied. 
The setNames() method is used to specify the name of an object and then return the object. In case of data frame, the columns can be renamed with new names, using the c() method. 
Syntax: setNames(data, col-name-vec)
Parameter : 
data – The data frame to be applied the function onto
col-name-vec – The column name vector containing the names of the columns. 
Example: Set column names with aggregate function
R
# creating a data frame data_frame <- data.frame(col1 = c(1:9),                         col2 = LETTERS[1:3])  print("Original DataFrame")print(data_frame)  # using aggregate methoddata_agg <- aggregate(col1 ~ col2, data_frame, sum)  # using setnames methoddata_mod <- setNames(data_agg,                         c("C1", "C2"))  print("Modified DataFrame")print(data_mod)
Output
[1] "Original DataFrame" 
  col1 col2 
1    1    A 
2    2    B 
3    3    C 
4    4    A 
5    5    B 
6    6    C 
7    7    A 
8    8    B 
9    9    C >
[1] "Modified DataFrame" 
  C1 C2 
1  A 12 
2  B 15 
3  C 18
The data frame columns can be explicitly mapped to lists using the list() method in R. As a result of this a generic list object with a custom name can be specified within the aggregate function usage. 
Syntax:
list(new-col-name = df$old-col-name)
Example: Set column names with aggregate function
R
# creating a data frame data_frame <- data.frame(col1 = c(1:9),                         col2 = LETTERS[1:3])  print("Original DataFrame")print(data_frame)  # using aggregate methoddata_mod <- aggregate(  list(mean = data_frame$col1),                                       list(letter = data_frame$col2),                        mean)  # printing the modified dataframe                                                  print("Modified DataFrame")print(data_mod)
Output
[1] "Original DataFrame" 
  col1 col2 
1    1    A 
2    2    B 
3    3    C 
4    4    A 
5    5    B 
6    6    C 
7    7    A 
8    8    B 
9    9    C 
[1] "Modified DataFrame" 
  letter mean 
1      A    4 
2      B    5 
3      C    6
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to use Checkboxes in ReactJS?

18 Jan, 2021
A Checkbox is a GUI widget that allows the user to make a binary choice from the given options. It is very useful when the user can select from the given options only. Material UI for React has this component available for us and it is very easy to integrate.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
npm install @material-ui/lab
npm install @material-ui/icons
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete from '@material-ui/lab/Autocomplete';import Checkbox from '@material-ui/core/Checkbox';import CheckBoxOutlineBlankIcon from '@material-ui/icons/CheckBoxOutlineBlank';import CheckBoxIcon from '@material-ui/icons/CheckBox';  const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;const checkedIcon = <CheckBoxIcon fontSize="small" />;  const App = () => {    // Our sample dropdown options  const options = ['Monday', 'Tuesday', 'Thursday',   'Friday', 'Saturday', 'Sunday']    return (    <div style={{ marginLeft: '40%', marginTop: '60px' }}>      <h3>Greetings from GeeksforGeeks!</h3>      <Autocomplete        multiple        id="checkboxes-tags-demo"        options={options}        renderOption={(option, { selected }) => (          <React.Fragment>            <Checkbox              icon={icon}              checkedIcon={checkedIcon}              style={{ marginRight: 8 }}              checked={selected}            />            {option}          </React.Fragment>        )}        style={{ width: 500 }}        renderInput={(params) => (          <TextField {...params} variant="outlined"            label="Checkboxes"            placeholder="Favorites" />        )}      />    </div>  );}  export default App
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js | lerp() Function

25 Mar, 2020
The lerp() function is used to find a number between two numbers. The amt parameter can be used to specify the amount to interpolate between the two values. An amount nearer to 0.1 would mean that the final value is nearer to the first value, and nearer to 0.9 means that the value is nearer to the second value. If the value is less or more than these, then the final value would be calculated on the basis of the ratio of the two numbers.
It can be used for drawing dotted lines or creating motion along a path by finding all the intermediate points in a line.
Syntax:
lerp( start, stop, amt )
Parameters: This function accept three parameters as mentioned above and described below:
start: It is a number which denotes the first value of the two numbers.
stop: It is a number which denotes the second value of the two numbers..
amt: It is a number which denotes the amount by which a number is to be interpolated between the two numbers.
Return Value: It returns a number with the lerped value.
Below examples illustrate the lerp() function in p5.js:
Example 1:
function setup() {  createCanvas(600, 200);  textSize(20);     inputElemA = createInput(10);  inputElemA.position(30, 40);     inputElemB = createInput(100);  inputElemB.position(30, 60);     sliderElem = createSlider(0, 1, 0.5, 0.1);  sliderElem.position(30, 120);}   function draw() {  clear();  text("Enter two values between which new "        + "number would be lerped", 20, 20);  text("Move the slider to observe the amount"        + " of lerping", 20, 100);     // Convert the string value to a number  // value for lerping  inputValA = Number(inputElemA.value());  inputValB = Number(inputElemB.value());  sliderVal = sliderElem.value();     text("The amount of lerping is: "        + sliderVal, 20, 160);            text("The lerped value is: "        + lerp(inputValA, inputValB,         sliderVal), 20, 180);}
Output:
Example 2:
function setup() {  createCanvas(600, 300);  textSize(20);    sliderElem = createSlider(0, 1, 0.5, 0.1);  sliderElem.position(30, 180);    circleApos = 50;  circleBpos = 500;}  function draw() {  clear();  text("Move the slider to observe the x position "          + "of the middle circle", 20, 160);    circle(circleApos, 50, 80);  circle(circleBpos, 50, 80);    sliderVal = sliderElem.value();  lerpedVal = lerp(circleApos, circleBpos, sliderVal);    // Draw the circle at the lerped x coordinate  circle(lerpedVal, 50, 80);    text("The amount of lerping is: " + sliderVal, 20, 220);}
Output:
Online editor: https://editor.p5js.org/
Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Reference: https://p5js.org/reference/#/p5/lerp
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Switch Case in Python (Replacement)

13 Jun, 2022
What is the replacement of Switch Case in Python?
Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping.
Python3
# Function to convert number into string# Switcher is dictionary data type heredef numbers_to_strings(argument):    switcher = {        0: "zero",        1: "one",        2: "two",    }     # get() method of dictionary data type returns    # value of passed argument if it is present    # in dictionary otherwise second argument will    # be assigned as default value of passed argument    return switcher.get(argument, "nothing") # Driver programif __name__ == "__main__":    argument=0    print (numbers_to_strings(argument))
This code is analogous to the given code in C++ : 
CPP
#include<bits/stdc++.h>using namespace std; // Function to convert number into stringstring numbers_to_strings(int argument){    switch(argument) {        case 0:            return "zero";        case 1:            return "one";        case 2:            return "two";        default:            return "nothing";    };}; // Driver programint main(){    int argument = 0;    cout << numbers_to_strings(argument);    return 0;}
Output: 
Zero
But In Python 3.10 and after that, Python will support this:
 it’s my example code:
Python3
def number_to_string(argument):    match argument:        case 0:            return "zero"        case 1:            return "one"        case 2:            return "two"        case default:            return "something"  if __name__ = "__main__":    argument = 0    number_to_string(argument)
It is similar to that of switch cases in C++, Java, etc.
This article is contributed by Shashank Mishra (Gullu). 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 if you want to share more information about the topic discussed above. 
ddeevviissaavviittaa
nhatphuc2021b
rishabsaini261
harshmaster07705
varshagumber28
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Function that takes an interface type as value and pointer in Golang

17 May, 2020
Functions are generally the block of codes or statements in a program that gives the user the ability to reuse the same code which ultimately saves the excessive use of memory, acts as a time saver and more importantly, provides better readability of the code. So basically, a function is a collection of statements that perform some specific task and return the result to the caller. A function can also perform some specific task without returning anything.
Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.).
In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface. But you are allowed to create a variable of an interface type and this variable can be assigned with a concrete type value that has the methods the interface requires. Or in other words, the interface is a collection of methods as well as it is a custom type.
Now you can create a function that takes interface type as a value and pointer. To understand this concept see the below example:
// Golang Function that takes an interface// type as value and pointerpackage main  import "fmt"  // taking an interfacetype CoursePrice interface {    show(int)}  // taking a function that accept// CoursePrice interface as an valuefunc show(cp CoursePrice, fee int) {    cp.show(fee)}  // taking a structtype Dsa struct {    Price int}  func (c Dsa) show(fee int) {    c.Price = fee}  // taking a structtype Placement struct {    Price int}  // function accepting a pointerfunc (p *Placement) show(fee int) {    p.Price = fee}  // main functionfunc main() {      first := Dsa{Price: 2499}    second := Placement{Price: 9999}      // calling the function    show(first, 1999)      // calling the function    // by passing the address    show(&second, 7999)      fmt.Println("DSA Course Fee:", first.Price)    fmt.Println("Placement100 Course Fee:", second.Price)}
Output:
DSA Course Fee: 2499
Placement100 Course Fee: 7999

Golang-Program
Picked
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
How to iterate over an Array using for loop in Golang?
Structures in Golang
Loops in Go Language
Time Durations in Golang
Constants- Go Language
Strings in Golang
time.Parse() Function in Golang With Examples
Go Variables
Class and Object in Golang
gcc command in Linux with examples

21 Nov, 2021
GCC stands for GNU Compiler Collections which is used to compile mainly C and C++ language. It can also be used to compile Objective C and Objective C++. The most important option required while compiling a source code file is the name of the source program, rest every argument is optional like a warning, debugging, linking libraries, object file etc. The different options of gcc command allow the user to stop the compilation process at different stages. 
Syntax:  
gcc [-c|-S|-E] [-std=standard]
Example: This will compile the source.c file and give the output file as a.out file which is default name of output file given by gcc compiler, which can be executed using ./a.out  
gcc source.c
Most Useful Options with Examples: Here source.c is the C program code file. 
-o opt: This will compile the source.c file but instead of giving default name hence executed using ./opt, it will give output file as opt. -o is for output file option. 
gcc source.c -o opt
-Werror: This will compile the source and show the warning if any error is there in the program, -W is for giving warnings. 
gcc source.c -Werror -o opt
-Wall: This will check not only for errors but also for all kinds warning like unused variables errors, it is good practice to use this flag while compiling the code. 
gcc source.c -Wall -o opt
-ggdb3: This command give us permissions to debug the program using gdb which will be described later, -g option is for debugging. 
gcc -ggdb3 source.c -Wall -o opt
-lm : This command link math.h library to our source file, -l option is used for linking particular library, for math.h we use -lm. 
gcc -Wall source.c -o opt -lm
-std=c11 :This command will use the c11 version of standards for compiling the source.c program, which allows to define variable under loop initializations also using newer standards version is preferred. 
gcc -Wall -std=c11 source.c -o opt
-c : This command compile the program and give the object file as output, which is used to make libraries. 
-v : This option is used for the verbose purpose. 
sagar0719kumar
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
TCP Server-Client implementation in C
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
Cat command in Linux with examples
jQuery querySelector() Vs querySelectorAll() Methods

23 Dec, 2020
querySelector() and querySelectorAll() are two jQuery functions which helps the HTML elements to be passed as a parameter by using CSS selectors (‘id’, ‘class’) can be selected.
querySelector() Method: The querySelector() method returns the first element within the document which matches a specified CSS selector(s). If multiple elements occurs, then it returns the result for only the first matching element.
Syntax:
document.querySelector(selectors);
It returns the first element which matches the selector.
querySelectorAll() Method: The querySelectorAll() method returns all the elements within the document which matches the specified CSS selector(s). It returns all the elements that matches with the selector in the form of a static NodeList object which is a collection of nodes. To access each element, we usually use a loop. Each element can be accessed via an index. The index starts with 0. The property length can be used to get the number of elements that matches the specified selector.
Syntax:
document.querySelectorAll(selectors);
It returns all the elements which match the selector.
document.querySelectorAll(selectors)[i];
It returns the element at index i in the list.
Difference between querySelector() and querySelectorAll() Method:
HTML code:
HTML
<!DOCTYPE html><html>  <body style="text-align:center;">      <h1 style="color:#006600">        GeeksforGeeks    </h1>      <div class="test-btn">text</div>    <div class="test-btn">text</div>    <div class="test-btn">text</div>    <div class="test-btn">text</div>      <button onClick="qselector()">        querySelector    </button>      <button onClick="qselectorall()">        querySelectorAll    </button>      <script>        function qselector() {            document.querySelector(".test-btn")                .style.color = "#006600";        }          function qselectorall() {            var x = document                .querySelectorAll(".test-btn");              for (var i = 0; i < x.length; i++) {                x[i].style.color = "#006600";            }        }     </script></body>  </html>
Output:
Before clicking any button:
After clicking querySelector button:
After clicking querySelectorAll button:
Differences: As seen above, querySelector() methodcan only be used to access a single element while querySelectorAll() method can be used to access all elements which match with a specified CSS selector. To return all matches, querySelectorAll has to be used, while to return a single match, querySelector is used.
HTML-Misc
jQuery-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
K’th Smallest/Largest Element using STL

14 Jun, 2022
Given an array and a number k where k is smaller than size of array, we need to find the k’th smallest element in the given array. Examples:
Input : arr[] = {7, 10, 4, 3, 20, 15}
            k = 2
Output : 4
Smallest element is 3. Second smallest
is 4.

Input : arr[] = {7, 10, 4, 3, 3, 15}
            k = 2
Output : 4
Even if there are more than one occurrences
of 3, answer should be 4.

Input :arr[] = {7, 10, 4, 3, 20, 15}
          k = 4
Output : 10
We use set in C++ STL. 1) Insert all elements into a set. 2) Traverse the set and print k-th element. 
CPP
// STL based C++ program to find k-th smallest// element.#include <bits/stdc++.h>using namespace std; int kthSmallest(int arr[], int n, int k){ // Insert all elements into the set set<int> s; for (int i = 0; i < n; i++)  s.insert(arr[i]);  // Traverse set and print k-th element auto it = s.begin(); for (int i = 0; i < k - 1; i++)  it++; return *it;} int main(){ int arr[] = { 12, 3, 5, 7, 3, 19 }; int n = sizeof(arr) / sizeof(arr[0]), k = 2; cout << "K'th smallest element is "  << kthSmallest(arr, n, k); return 0;}
Output:
K'th smallest element is 5 
Time complexity: O(n Log n). Note that set in STL uses a self-balancing BST internally and therefore time complexity of search and insert operations is O(log n). 
Auxiliary Space: O(n) where n is size of array
Related Posts : 
K’th Smallest/Largest Element in Unsorted Array | Set 1K’th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst Case Linear Time) This article is contributed by Roshan Halwai. 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.
technophpfij
Order-Statistics
STL
Arrays
Arrays
STL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python assert keyword

03 Mar, 2022
Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code, so that failure of these doesn’t allow the code to execute further. 
In simpler terms, we can say that assertion is the boolean expression that checks if the statement is True or False. If the statement is true then it does nothing and continues the execution, but if the statement is False then it stops the execution of the program and throws an error.
Let us look at the flowchart of the assertion.
In python, assert keyword helps in achieving this task. This statement takes as input a boolean condition, which when returns true doesn’t do anything and continues the normal flow of execution, but if it is computed to be false, then it raises an AssertionError along with the optional message provided. 
Syntax : assert condition, error_message(optional) 
Parameters : condition : The boolean condition returning true or false. error_message : The optional argument to be printed in console in case of AssertionError
Returns : Returns AssertionError, in case the condition evaluates to false along with the error message which when provided. 
Python3
# Python 3 code to demonstrate# working of assert # initializing numbera = 4b = 0 # using assert to check for 0print("The value of a / b is : ")assert b != 0print(a / b)
Output : 
AssertionError: 
Python3
# Python 3 code to demonstrate# working of assert # initializing numbera = 4b = 0 # using assert to check for 0print("The value of a / b is : ")assert b != 0, "Zero Division Error"print(a / b)
Output:
AssertionError: Zero Division Error
This has a much greater utility in Testing and Quality Assurance role in any development domain. Different types of assertions are used depending upon the application. Below is the simpler demonstration of a program that only allows only the batch with all hot food to be dispatched, else rejects the whole batch.
Python3
# Python 3 code to demonstrate# working of assert# Application # initializing list of foods temperaturesbatch = [ 40, 26, 39, 30, 25, 21] # initializing cut temperaturecut = 26 # using assert to check for temperature greater than cutfor i in batch:    assert i >= 26, "Batch is Rejected"    print (str(i) + " is O.K" )
Output : 
40 is O.K
26 is O.K
39 is O.K
30 is O.K
Runtime Exception : 
AssertionError: Batch is Rejected
nikhilaggarwal3
ignorantadventurer
python-basics
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Python OOPs Concepts
C Program to print numbers from 1 to N without using semicolon? - GeeksforGeeks

03 Mar, 2022
How to print numbers from 1 to N without using any semicolon in C. 
C
#include<stdio.h>#define N 100 // Add your code here to print numbers from 1// to N without using any semicolon
What code to add in above snippet such that it doesn’t contain semicolon and prints numbers from 1 to N?We strongly recommend you to minimize your browser and try this yourself firstMethod 1 (Recursive) 
C
// A recursive C program to print all numbers from 1// to N without semicolon#include<stdio.h>#define N 10 int main(int num){    if (num <= N && printf("%d ", num) && main(num + 1))    {    }    }
Output: 
1 2 3 4 5 6 7 8 9 10 
See this for complete run. Thanks to Utkarsh Trivedi for suggesting this solution.Method 2 (Iterative) 
C
// An iterative C program to print all numbers from 1// to N without semicolon#include<stdio.h>#define N 10 int main(int num, char *argv[]){while (num <= N && printf("%d ", num) && num++){}}
Output: 
1 2 3 4 5 6 7 8 9 10 
See this for complete run. Thanks to Rahul Huria for suggesting this solution.How do these solutions work? main() function can receive arguments. The first argument is argument count whose value is 1 if no argument is passed to it. The first argument is always program name.  
C
#include<stdio.h> int main(int num, char *argv[]){   printf("num = %d\n", num);   printf("argv[0] = %s ", argv[0]);}
Output: 
num = 1 
argv[0] = <file_name>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
maveriek
simmytarika5
c-puzzle
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Multidimensional Arrays in C / C++
rand() and srand() in C/C++
Left Shift and Right Shift Operators in C/C++
fork() in C
Command line arguments in C/C++
Core Dump (Segmentation fault) in C/C++
Substring in C++
Function Pointer in C
TCP Server-Client implementation in C
Structures in C
Nth Natural Number | Practice | GeeksforGeeks

Given a positive integer N. You have to find Nth natural number after removing all the numbers containing digit 9.

Example 1:
Input:
N = 8
Output:
8
Explanation:
After removing natural numbers which contains
digit 9, first 8 numbers are 1,2,3,4,5,6,7,8
and 8th number is 8.
Example 2:
Input:
N = 9
Output:
10
Explanation:
After removing natural numbers which contains
digit 9, first 9 numbers are 1,2,3,4,5,6,7,8,10
and 9th number is 10.

 
Your Task:
You don't need to read input or print anything. Complete the function findNth() which accepts an integer N as input parameter and return the Nth number after removing all the numbers containing digit 9.

Expected Time Complexity: O(logN)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ N ≤ 1012 
0
nk01879122 weeks ago
//simple one-line solution Java
class Solution {   long findNth(long N){       //convert to base 9, that's all there's to it.\       return Long.parseLong(Long.toString(N,9));          }}
+2
akashmr10962 months ago
class Solution {
    long findNth(long N)
    {
        String result = new String();
        while(N >= 1) {
            result = (N % 9) + result;
            N = N/9;
        }
        
        return Long.parseLong(result);
    }
}
0
abhinavsinghbiz2 months ago
C++ Code,O(log9(N)),Run Time=0.0
long long findNth(long long N){       long long ans=0,rem,i=0;       while(N!=0){           rem=N%9;           ans+=rem*pow(10,i);           N/=9;           i++;       }       return ans;   }
0
sunghunet2 months ago
// C++ Version
long long findNth(long long N, long long M=9) {
    long long alpha=0, beta=1;
    while( N > 0 ) {
        alpha += (beta * (N%M));
        N/=M;
        beta*=10;
    }
    return alpha;
}
 
+3
sunghunet2 months ago
# Python Version
class Solution:
    def findNth(self, N, M:int=9):
        alpha, beta=0, 1
        while( N>0 ):
            alpha += (beta * (int(N)%M))
            N/=M
            beta*=10
        
        return alpha
-3
hemantsoni2 months ago
+1
choudharymanojloul844
This comment was deleted.
+3
manishbit233 months ago
// TC O(N) , ASC O(1)
long long number=0;
long long curr=1;
while(N){
   number += curr*(N%9);
   N/=9;
   curr=curr*10
}
return number;
+2
cs21m0593 months ago
convert to base 9. Thats all
0
keshariamanindian
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
MySQL LIMIT clause equivalent for SQL SERVER?

Firstly, we need to create a table to understand the limit clause (as we want for SQL server).We will create a table with the help of CREATE command.
mysql> CREATE table limitDemo
-> (
-> id int,
-> primary key(id)
-> );
Query OK, 0 rows affected (0.58 sec)
After that, let us insert records into the table −
mysql> INSERT into limitDemo values(1);
Query OK, 1 row affected (0.16 sec)

mysql> INSERT into limitDemo values(2);
Query OK, 1 row affected (0.12 sec)

mysql> INSERT into limitDemo values(3);
Query OK, 1 row affected (0.11 sec)

mysql> INSERT into limitDemo values(4);
Query OK, 1 row affected (0.10 sec)

mysql> INSERT into limitDemo values(5);
Query OK, 1 row affected (0.12 sec)

mysql> INSERT into limitDemo values(6);
Query OK, 1 row affected (0.13 sec)

mysql> INSERT into limitDemo values(7);
Query OK, 1 row affected (0.15 sec)

mysql> INSERT into limitDemo values(8);
Query OK, 1 row affected (0.09 sec)

mysql> INSERT into limitDemo values(9);
Query OK, 1 row affected (0.14 sec)
Displaying all the records with the help of SELECT statement −
mysql> SELECT * from limitDemo;

The following is the output
+----+
| id |
+----+
| 1  |
| 2  |
| 3  |
| 4  |
| 5  |
| 6  | 
| 7  |
| 8  |
| 9  |
+----+
9 rows in set (0.00 sec)
Let us see the query of limit clause and begin with the syntax −
SELECT column_name1........N from yourTableName limit integervalue offset integervalue;

Now, I am applying the above query −
mysql> SELECT id from limitDemo limit 5 offset 2;
The following is the output
+----+
| id |
+----+
| 3  |
| 4  |
| 5  |
| 6  |
| 7  |
+----+
5 rows in set (0.00 sec)
C++ Program to Split the array and add the first part to the end?

Here we will see how to split an array, and add the first part after splitting at the end position. Suppose the array contents are {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}. We want to cut this intro two parts. The first part is from index 0 to 3 (split size 4), and second part is rest. After adding the first part at the end, the array elements will be like this {4, 5, 6, 7, 8, 9, 0, 1, 2, 3}. To solve this problem, we will follow this algorithm.
begin
   for i := 0 to k, do
      x := arr[0]
      for j := 0 to n-2, do
         arr[j] := arr[j+1]
      done
      arr[n-1] := x
   done
end
 Live Demo
#include<iostream>
using namespace std;
void splitArray(int arr[], int n, int k){
   for(int i = 0; i<k; i++){
      int x = arr[0]; //take the first number
      for(int j = 0; j<= n-2; j++){
         arr[j] = arr[j+1];
      }
      arr[n-1] = x;
   }
}
main() {
   int data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
   int n = sizeof(data)/sizeof(data[0]);
   int i;
   cout << "Enter split size: ";
   cin >> i;
   splitArray(data, n, i);
   for(int i = 0; i <n;i++){
      cout << data[i] << " ";
   }
}
Enter split size: 4
4 5 6 7 8 9 0 1 2 3
How to check if a string is a valid keyword in C#?

To check if a string is a valid keyword, use the IsValidIdentifier method.
The IsValidIdentifier method checks whether the entered value is an identifier or not. If it’s not an identifier, then it’s a keyword in C#.
Let us see an example, wherein we have set the CodeDomProvider and worked with the IsValiddentifier method −
CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
Let us see the complete codeL
 Live Demo
using System;
using System.IO;
using System.CodeDom.Compiler;

namespace Program {
   class Demo {
      static void Main(string[] args) {
   
         string str1 = "amit";
         string str2 = "for";

         CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");

         // checking for str1
         if (provider.IsValidIdentifier(str1)) {
            Console.WriteLine("{0} is an identifier", str1);
         } else {
            Console.WriteLine("{0} is a Valid Keyword in C#", str1);
         }

         // checking for str2
         if (provider.IsValidIdentifier(str2)) {
            Console.WriteLine("{0} is an identifier", str2);
         } else {
            Console.Write("{0} is a Valid Keyword in C#", str2);
         }
      }
   }
}
amit is an identifier
for is a Valid Keyword in C#
LISP - Loop For Construct

The loop for construct allows you to implement a for-loop like iteration as most common in other languages.
It allows you to
set up variables for iteration
set up variables for iteration
specify expression(s) that will conditionally terminate the iteration
specify expression(s) that will conditionally terminate the iteration
specify expression(s) for performing some job on each iteration
specify expression(s) for performing some job on each iteration
specify expression(s), and expressions for doing some job before exiting the loop
specify expression(s), and expressions for doing some job before exiting the loop
The for loop for construct follows several syntax −
(loop for loop-variable in <a list>
   do (action)
)

(loop for loop-variable from value1 to value2
   do (action)
)

Create a new source code file named main.lisp and type the following code in it −
(loop for x in '(tom dick harry)
   do (format t " ~s" x)
)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
TOM DICK HARRY

Create a new source code file named main.lisp and type the following code in it −
(loop for a from 10 to 20
   do (print a)
)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 

Create a new source code file named main.lisp and type the following code in it −
(loop for x from 1 to 20
   if(evenp x)
   do (print x)
)
When you click the Execute button, or type Ctrl+E, LISP executes it immediately and the result returned is −
2 
4 
6 
8 
10 
12 
14 
16 
18 
20


    79 Lectures 
     7 hours 

 Arnold Higuit
 Print
 Add Notes
 Bookmark this page
Python - String Matrix Concatenation - GeeksforGeeks

13 Jan, 2022
Sometimes, while working with Matrix we can have a problem in which we have Strings and we need a universal concatenation of all the String present in it. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + join()We can solve this problem using the list comprehension as a potential shorthand to the conventional loops that we may use to perform this particular task. We just join the elements extracted and put them into a as a single string.
# Python3 code to demonstrate# String Matrix Concatenation# Using list comprehension  # initializing listtest_list = [["geeksforgeeks", " is", " best"], [" I", " Love"], [" Gfg"]]  # printing original listprint("The original list : " + str(test_list))  # using list comprehension# count of all the elements in listres = "".join([ele for sub in test_list for ele in sub])  # print resultprint("The Matrix Concatenation is : " + str(res))
The original list : [['geeksforgeeks', ' is', ' best'], [' I', ' Love'], [' Gfg']]
The Matrix Concatenation is : geeksforgeeks is best I Love Gfg

 
Method #2 : Using chain() + join()This particular problem can also be solved using the chain function instead of list comprehension in which we use the conventional join function to join.
# Python3 code to demonstrate# String Matrix Concatenation # Using chain() + join()from itertools import chain  # initializing listtest_list = [["geeksforgeeks", " is", " best"], [" I", " Love"], [" Gfg"]]  # printing original listprint("The original list : " + str(test_list))  # using chain() + join()# String Matrix Concatenationres = "".join(list(chain(*test_list)))  # print resultprint("The Matrix Concatenation is : " + str(res))
The original list : [['geeksforgeeks', ' is', ' best'], [' I', ' Love'], [' Gfg']]
The Matrix Concatenation is : geeksforgeeks is best I Love Gfg

simmytarika5
Python list-programs
Python matrix-program
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
JasmineJS - afterEach()

Like beforeEach(), afterEach() works exactly the same way. It executes after the execution of the spec block. Let us modify the previous example using the following code.
var currentVal = 0; 

afterEach(function() { 
   currentVal = 5;  
});  

describe("Different Methods of Expect Block",function() { 
   it("first call ", function() { 
      expect(currentVal).toEqual(0);     
   });     
   
   it("second call ",  function() { 
      expect(currentVal).toEqual(5);     
   });
});
In the above example, while running the first spec block the value of the currentVal is 0. Hence, it will pass the test case but after running the first it block, Jasmine compile ran the afterEach() block, which makes the value of the currentVal to 5. Hence it also satisfies the second case and yields a green screenshot as an output.
 Print
 Add Notes
 Bookmark this page