code-rag-bench/online-tutorials huggingface dataset:
Rust - If let Operator - GeeksforGeeks

15 Nov, 2021
The basic difference between conventional if-else and if let is that if let uses one pattern that needs to be matched to an expression also known as scrutinee, if the pattern matches the expression then the corresponding code is executed, or in most cases that value is assigned according to it.
Syntax :
let gfg=value;
let gfg_answer=if let value_1 = expression{
}
else if let value_2=expression{
}
...
else{
}  
Example 1: Program for if let operator in Rust.
In this example the value we will have one variable gfg=”algo” and we will check it against other values.
For the first condition here if the string “cp” equals to gfg variable then gfg_answer will be assigned the value “dsa topic=cp“ because we used the concat method to add “dsa topic=” and “cp“.
let gfg_answer=if let "cp" = gfg {
   concat!("dsa topic=","cp")
} 
If this condition is not met then it will check for other else if or else conditions.
The final step is to print the value of gfg_answer.
Rust
// Rust program for if let operatorfn main() {   // string created algo assigned to gfglet gfg = "algo"; // using if let operator let gfg_answer = if let "cp" = gfg {   concat!("dsa topic=","cp")} else if let "ds" = gfg {    concat!("dsa topic=","ds")} else if let "algo" = gfg {    concat!("dsa topic=","algo")} else {    concat!("dsa topic=","not in gfg")};   // printing the gfg_answer variableprintln!("{}",gfg_answer);}
Output :
dsa topic=algo
Example 2 :
Here we will use gfg variable having value 10, and we will compare it to values and assign the variable gfg_answer according to it.
let gfg = Some(10);
let gfg_answer = if let Some(10) = gfg {
    11
}
And we will keep on checking the conditions until some condition is matched or last will be the else condition.
Finally, we will print the gfg_answer variable.
Below is the program for if let operator Rust.
Rust
// Rust program for if let operatorfn main() {   // gfg variable assigned value 10 let gfg = Some(10); // using if let operator let gfg_answer = if let Some(10) = gfg {    11} else if Some(20) == gfg {    22} else if let Some(30) = gfg {    33} else {    -1};   // printing the valueprintln!("gfg_anser={}",gfg_answer );}
Output :
gfg_answer=11
saurabh1990aror
Picked
Rust
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Generate Random Numbers in Rust Language?
Rust - Casting
Rust - For and Range
Rust - Generic Function
Rust - Creating a Library
Rust - References & Borrowing
Rust - Concept of Structures
Rust - Box Smart Pointer
Rust - Concept of Smart Pointers
Rust - While Loop
Convert JSON data Into a Custom Python Object - GeeksforGeeks

16 Dec, 2021
Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(), the return value of object_hook will be used instead of the default dict value.We can also implement custom decoders using this.Example 1 : 
Python3
# importing the moduleimport jsonfrom collections import namedtuple # creating the datadata = '{"name" : "Geek", "id" : 1, "location" : "Mumbai"}' # making the objectx = json.loads(data, object_hook =               lambda d : namedtuple('X', d.keys())               (*d.values())) # accessing the JSON data as an objectprint(x.name, x.id, x.location)
Output : 
As we can see in the above example, the namedtuple is a class, under the collections module. It contains keys that are mapped to some values. In this case, we can access the elements using keys and indexes. We can also create a custom decoder function, in which we can convert dict into a custom Python type and pass the value to the object_hook parameter which is illustrated in the next example.Example 2 :  
Python3
# importing the moduleimport jsonfrom collections import namedtuple # customDecoder functiondef customDecoder(geekDict):    return namedtuple('X', geekDict.keys())(*geekDict.values()) # creating the datageekJsonData = '{"name" : "GeekCustomDecoder", "id" : 2, "location" : "Pune"}' # creating the objectx = json.loads(geekJsonData, object_hook = customDecoder) # accessing the JSON data as an objectprint(x.name, x.id, x.location)
Output : 
We can also use SimpleNamespace class from the types module as the container for JSON objects. Advantages of a SimpleNamespace solution over a namedtuple solution: –
It is faster because it does not create a class for each object.It is shorter and simpler.
It is faster because it does not create a class for each object.
It is shorter and simpler.
Example 3 : 
Python3
# importing the moduleimport jsontry:    from types import SimpleNamespace as Namespaceexcept ImportError:    from argparse import Namespace # creating the datadata = '{"name" : "GeekNamespace", "id" : 3, "location" : "Bangalore"}' # creating the objectx = json.loads(data, object_hook = lambda d : Namespace(**d)) # accessing the JSON data as an objectprint(x.name, x.id, x.location)
Output : 
prachisoda1234
Python json-programs
Python-json
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Seaborn - Multi Panel Categorical Plots

Categorical data can we visualized using two plots, you can either use the functions pointplot(), or the higher-level function factorplot().
Factorplot draws a categorical plot on a FacetGrid. Using ‘kind’ parameter we can choose the plot like boxplot, violinplot, barplot and stripplot. FacetGrid uses pointplot by default.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('exercise')
sb.factorplot(x = "time", y = pulse", hue = "kind",data = df);
plt.show()

We can use different plot to visualize the same data using the kind parameter.
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('exercise')
sb.factorplot(x = "time", y = "pulse", hue = "kind", kind = 'violin',data = df);
plt.show()

In factorplot, the data is plotted on a facet grid.
Facet grid forms a matrix of panels defined by row and column by dividing the variables. Due of panels, a single plot looks like multiple plots. It is very helpful to analyze all combinations in two discrete variables.
Let us visualize the above the definition with an example
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('exercise')
sb.factorplot(x = "time", y = "pulse", hue = "kind", kind = 'violin', col = "diet", data = df);
plt.show()

The advantage of using Facet is, we can input another variable into the plot. The above plot is divided into two plots based on a third variable called ‘diet’ using the ‘col’ parameter.
We can make many column facets and align them with the rows of the grid −
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
df = sb.load_dataset('titanic')
sb.factorplot("alive", col = "deck", col_wrap = 3,data = df[df.deck.notnull()],kind = "count")
plt.show()


    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    11 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy
 Print
 Add Notes
 Bookmark this page
How to convert binary variable to 0/1 format in an R data frame?

A binary variable is a type of variable that can take only two possible values like gender that has two categories male and female, citizenship of a country with two categories as yes and no, etc. If the binary variable is not in 0/1 format then it can be converted with the help of ifelse function. Check out the below examples to understand how it works.
Consider the below data frame −
 Live Demo
Temp<-sample(c("Hot","Cold"),20,replace=TRUE)
Response<-rnorm(20,25,3.2)
df1<-data.frame(Temp,Response)
df1
   Temp  Response
1  Cold   26.02542
2  Cold   22.39046
3  Hot    24.84536
4  Cold   25.64836
5  Hot    28.29392
6  Cold   27.58198
7  Hot    23.77825
8  Cold   30.17105
9  Cold   27.08661
10 Cold   36.36730
11 Hot    24.73742
12 Cold   23.43371
13 Hot    23.72180
14 Cold   19.81232
15 Hot    24.45042
16 Cold   30.39320
17 Cold   21.23361
18 Hot    25.21617
19 Cold   23.20461
20 Cold   25.22150
Converting Temp column of df1 to 0/1 format −
df1$Temp<-ifelse(df1$Temp=="Cold",1,0)
df1
   Temp Response
1  1    26.02542
2  1    22.39046
3  0    24.84536
4  1    25.64836
5  0    28.29392
6  1    27.58198
7  0    23.77825
8  1    30.17105
9  1    27.08661
10 1    36.36730
11 0    24.73742
12 1    23.43371
13 0    23.72180
14 1    19.81232
15 0    24.45042
16 1    30.39320
17 1    21.23361
18 0    25.21617
19 1    23.20461
20 1    25.22150
Display scientific notation as float in Python - GeeksforGeeks

30 Jun, 2021
In this article, the task is to display the scientific notation as float in Python. The scientific notation means any number expressed in the power of 10.for example- 340 can be written in scientific notation as 3.4 X102.in pythons, we use str.format() on a number with “{:e}” to format the number to scientific notation. str.format() formats the number as a float, followed by “e+” and the appropriate power of 10. For example- 340 will be displayed as 3.4e+2
Example:
-51000000000.0000000 in scientific notation results in  “5.10e+10”,where the no. after “e+”denotes power of 10-5189  in scientific notation results in  “5.189e+3”-439929  in scientific notation results in  “4.39929e+5”
Python3
# codescientific_format = "{:e}".format(512349000.000000) print(scientific_format)
Output:
5.123490e+08
In the above example, the scientific notation of 512349000.000000 will be a decimal after the first digit and the power of 10 ie- 5.123490 X 108
To only include a certain number of digits after the decimal point, we use “{:.Ne}”, where N is the number of digits.
Python3
# code# code# after decimal point,only 3 digit will be displayedprint("{:.3e}".format(345000))
Output:
3.450e+05
To display reverse of scientific numbers to float
We have to pass a variable holding the scientific format of a number, as follows:
Python3
# codex = 3.234e+4 print("{:f}".format(x))  # f represents float
Output:
32340.000000
pradiptamukherjee
Picked
Python-string-functions
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Python - tensorflow.expand_dims() - GeeksforGeeks

21 Aug, 2021
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. 
expand_dims() is used to insert an addition dimension in input Tensor.
Syntax: tensorflow.expand_dims( input, axis, name)
Parameters:
input: It is the input Tensor.
axis: It defines the index at which dimension should be inserted. If input has D dimensions then axis must have value in range  [-(D+1), D].
name(optional): It defines the name for the operation.
Returns: It returns a Tensor with expanded dimension.
Example 1:
Python3
# Importing the libraryimport tensorflow as tf # Initializing the inputx = tf.constant([[2, 3, 6], [4, 8, 15]]) # Printing the inputprint('x:', x) # Calculating resultres = tf.expand_dims(x, 1) # Printing the resultprint('res: ', res)
Output:
x: tf.Tensor(
[[ 2  3  6]
 [ 4  8 15]], shape=(2, 3), dtype=int32)
res:  tf.Tensor(
[[[ 2  3  6]]

 [[ 4  8 15]]], shape=(2, 1, 3), dtype=int32)

# shape has changed from (2, 3) to (2, 1, 3)
Example 2:
Python3
# Importing the libraryimport tensorflow as tf # Initializing the inputx = tf.constant([[2, 3, 6], [4, 8, 15]]) # Printing the inputprint('x:', x) # Calculating resultres = tf.expand_dims(x, 0) # Printing the resultprint('res: ', res)
Output:
x: tf.Tensor(
[[ 2  3  6]
 [ 4  8 15]], shape=(2, 3), dtype=int32)
res:  tf.Tensor(
[[[ 2  3  6]
  [ 4  8 15]]], shape=(1, 2, 3), dtype=int32)
  
# shape has changed from (2, 3) to (1, 2, 3)
ruhelaa48
Python-Tensorflow
Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Matplotlib legend in subplot - GeeksforGeeks

28 Nov, 2021
In this article, we will discuss how Matplotlib can be employed to add legends in subplots. We can add the legend after making the plot  by using legend() function
Syntax:
axes[position].legend(loc='best')
where, loc is the location and the  ‘best’ places the legend at the location
Approach:
Use subplots() method to create subplots in a bigger plot.
Use legend() method to add label to the curves.
Then show the plots using show() method.
Example 1:
In this example,  the scatter graph is plot with subplots of sine and cos.
Python3
# importing modulesfrom matplotlib import pyplotimport numpy  # assign value to x axisx_axis = numpy.arange(1, 20, 0.5)  # get the value of log10y_axis_log10 = numpy.log10(x_axis)  # get the value of expy_axix_exp = numpy.exp(x_axis)  # create subplots using subplot() methodfig, axes = pyplot.subplots(2)  # depicting the visualizationaxes[0].plot(x_axis, y_axis_log10, color='green', label="log10")axes[1].plot(x_axis, y_axix_exp, color='blue', label="exp")  # position at which legend to be addedaxes[0].legend(loc='best')axes[1].legend(loc='best')  # display the plotpyplot.show()
Output:
Example 2:
In this example, the scatter graph is plot with subplots of (y=x^2) and (y=x^3).
Python3
# importing modulesfrom matplotlib import pyplotimport numpy  # assign value to x axisx_axis = numpy.arange(-2, 2, 0.1)  # get the value of siney_axis_sine = numpy.sin(x_axis)  # get the value of cosy_axix_cose = numpy.cos(x_axis)  # create subplots using subplot() methodfig, axes = pyplot.subplots(2)  # depicting the visualization(scatter)axes[0].scatter(x_axis, y_axis_sine, color='green', marker='*', label="sine")axes[1].scatter(x_axis, y_axix_cose, color='blue', marker='*', label="cos")  # position at which legend to be addedaxes[0].legend(loc='best')axes[1].legend(loc='best')  # display the plotpyplot.show()
Output: 
Example 3:
Python3
# importing modulesfrom matplotlib import pyplot  # assign value to x axisx_axis = list(range(-10, 10))  # get the value of x*xy_axis1 = [x*x for x in x_axis]  # get the value of x*x*xy_axix2 = [x*x*x for x in x_axis]  # create subplots using subplot() methodfig, axes = pyplot.subplots(2)  # depicting the visualizationaxes[0].scatter(x_axis, y_axis1, color='green', marker='*', label="y=x^2")axes[1].scatter(x_axis, y_axix2, color='red', marker='*', label="y=x^3")  # position at which legend to be addedaxes[0].legend(loc='best')axes[1].legend(loc='best')  # display the plotpyplot.show()
Output:
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
Lodash _.matches() Method - GeeksforGeeks

14 Sep, 2020
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc. The _.matches method creates a function that performs a partial deep comparison between a given object and source, returning true if the given object has equivalent property values, else false.
Syntax:
_.matches(source)
Parameters: This method accepts one parameter as mentioned above and described below:
source: The object of property values to match.
Returns:  [Function] It Returns the new spec function.
Example 1:
// Requiring the lodash library  const _ = require("lodash");      // Using _.matches() methodvar geek = [ {'java' : 3, 'python' : 5, 'js' : 7},{'java' : 4, 'python' : 2, 'js' : 6}];  let gfg = _.filter(geek, _.matches({'java' : 3, 'js' : 7 }));  // Storing the Resultconsole.log(gfg)
Note: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
Output:
[Object {java: 3, js: 7, python: 5}]
Example 2:
// Requiring the lodash library  const _ = require("lodash");      // Using _.matches() methodvar objects = [  { 'a': 1, 'b': 2, 'c': 3 },  { 'a': 4, 'b': 5, 'c': 6 },   { 'a': 8, 'b': 7, 'c': 9 }];   gfg= _.filter(objects, _.matches({ 'a': 8}));// => [{ 'a': 4, 'b': 5, 'c': 6 }]  // Storing the Resultconsole.log(gfg)
Note: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
Output:
[Object {a: 8, b: 7, c: 9}]
JavaScript-Lodash
JavaScript
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?
File uploading in React.js
How to append HTML code to a div using JavaScript ?
Hide or show elements in HTML using display property
How to Open URL in New Tab using JavaScript ?
Difference Between PUT and PATCH Request
Scala String matches() method with example - GeeksforGeeks

03 Oct, 2019
The matches() method is used to check if the string stated matches the specified regular expression in the argument or not.
Method Definition: Boolean matches(String regex)Return Type: It returns true if the string matches the regular expression else it returns false.
Example #1:
// Scala program of int matches()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying matches method        val result = "Preeti".matches(".*i")                  // Displays output        println(result)              }} 
true

So, here the regular expression matches the string stated. So, it returns true.Example #2:
// Scala program of int matches()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Applying matches method        val result = "Preeti".matches(".i.*")                  // Displays output        println(result)          }} 
false

Scala
Scala-Method
Scala-Strings
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Scala Constructors
Scala String substring() method with example
Scala | Arrays
How to get the first element of List in Scala
Scala String replace() method with example
Autocomplete input suggestion using Python and Flask - GeeksforGeeks

09 Apr, 2021
In this article, we will learn how to give features like auto-completion to the data that is passed from Flask. Autocomplete basically means predicting the rest of the word when the user types something. This way human interaction also increases with every correct prediction. Let’s see how to do the same.
We will be using jquery for autocompletion.
To install flask type the below command in the terminal.
pip install flask
First, create a new directory for the project. Inside that create a new file and name it app.py.
app.py
Python3
from flask import Flask, request, render_template    app = Flask(__name__)    @app.route("/", methods=["POST", "GET"])def home():    if request.method == "GET":        languages = ["C++", "Python", "PHP", "Java", "C", "Ruby",                     "R", "C#", "Dart", "Fortran", "Pascal", "Javascript"]                  return render_template("index.html", languages=languages)    if __name__ == '__main__':    app.run(debug=True)
Then, create a new directory inside the project to hold all the HTML files and name them templates. In this file, we have an input field where the user will type a string and the jquery function will provide the suggestions.
index.html
HTML
<!DOCTYPE html><html><head>    <title>AutoComplete</title>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js">      </script>          <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js">      </script>          <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/ui-lightness/jquery-ui.css"        rel="stylesheet" type="text/css" />  </head><body>    <h1>Welcome to GFG</h1>    <input type="text" id="tags">        <script>  $( function() {    var availableTags = [        {% for language in languages %}            "{{language}}",        {% endfor %}    ];    $( "#tags" ).autocomplete({      source: availableTags    });  } );  </script>    </body></html>
To run this app open cmd or terminal and run the below command.
python app.py
Output:
Python Flask
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()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Python | Sort list according to other list order - GeeksforGeeks

11 Jun, 2021
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let’s discuss certain ways to sort list according to other list order.Method #1 : Using List comprehension List comprehension can be used to achieve this particular task. In this, we just check for each element in list 2 matches with the current tuple, and append accordingly, in a sorted manner. 
Python3
# Python3 code to demonstrate# to sort according to other list# using list comprehension # initializing list of tuplestest_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)] # initializing sort ordersort_order = ['d', 'c', 'a', 'b'] # printing original listprint ("The original list is : " + str(test_list)) # printing sort order listprint ("The sort order list is : " + str(sort_order)) # using list comprehension# to sort according to other listres = [tuple for x in sort_order for tuple in test_list if tuple[0] == x] # printing resultprint ("The sorted list is : " + str(res))
The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
The sort order list is : ['d', 'c', 'a', 'b']
The sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)]
 
  Method #2 : Using sort() + lambda + index() The shorthand to perform this particular operation, sort function can be used along with lambda with key to specify the function execution for each pair of tuple, and list order of other list is maintained using index function.  
Python3
# Python code to demonstrate# to sort according to other list# using sort() + lambda + index() # initializing list of tuplestest_list = [ ('a', 1), ('b', 2), ('c', 3), ('d', 4)] # initializing sort ordersort_order = ['d', 'c', 'a', 'b'] # printing original listprint ("The original list is : " + str(test_list)) # printing sort order listprint ("The sort order list is : " + str(sort_order)) # using sort() + lambda + index()# to sort according to other list# test_list.sort(key = lambda(i, j): sort_order.index(i)) # works in python 2test_list.sort(key = lambda i: sort_order.index(i[0])) # works in python 3 # printing resultprint ("The sorted list is : " + str(test_list))
The original list is : [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
The sort order list is : ['d', 'c', 'a', 'b']
The sorted list is : [('d', 4), ('c', 3), ('a', 1), ('b', 2)]
 
Kiran Kotari
varshagumber28
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
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
Python | Pandas Index.contains() - GeeksforGeeks

16 Oct, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Index.contains() function return a boolean indicating whether the provided key is in the index. If the input value is present in the Index then it returns True else it returns False indicating that the input value is not present in the Index.
Syntax: Index.contains(key)
Parameters :Key : Object
Returns : boolean
Example #1: Use Index.contains() function to check if the given date is present in the Index.
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['2015-10-31', '2015-12-02', '2016-01-03',                            '2016-02-08', '2017-05-05'])  # Print the Indexidx
Output :
Let’s check if ‘2016-02-08’ is present in the Index or not.
# Check if input date in present or not.idx.contains('2016-02-08')
Output :As we can see in the output, the function has returned True indicating that the value is present in the Index. Example #2: Use Index.contains() function to check if the input month is present in the Index or not.
# importing pandas as pdimport pandas as pd  # Creating the Indexidx = pd.Index(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',               'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'])  # Print the Indexidx
Output :
Let’s check if ‘May’ is present in the Index or not
# to check if the input month is# part of the Index or not.idx.contains('May')
Output :
Akanksha_Rai
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
Aptitude | JavaScript Course Quiz 3 | Question 10 - GeeksforGeeks

10 May, 2019
What will be the output of the following code?
<script> document.write(NaN == NaN);</script>
(A) true(B) false(C) 1(D) 0Answer: (B)Explanation: Equality operator (== and ===) cannot be used to test a value against NaN. Use Number.isNaN() or isNaN() instead.Hence, it is not equal.Quiz of this Question
Aptitude
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Aptitude | Wipro Mock Test | Question 3
C | C Quiz - 113 | Question 1
Aptitude | Wipro Mock Test | Question 1
Aptitude | Wipro Mock Test | Question 2
Aptitude | Wipro Mock Test | Question 4
Aptitude | Wipro Mock Test | Question 5
Aptitude | Wipro Mock Test | Question 6
Aptitude | Wipro Mock Test | Question 7
Aptitude | Wipro Mock Test | Question 8
Aptitude | Wipro Mock Test | Question 9
4 Dimensional Array in C/C++ - GeeksforGeeks

18 Feb, 2022
Prerequisite :Array in C/C++, More on array
A four-dimensional (4D) array is an array of array of arrays of arrays or in other words 4D array is a array of 3D array.More dimensions in an array means more data be held, but also means greater difficulty in managing and understanding arrays.
Declaration of a Multidimensional Array in C:Syntax:
data_type array_name[i1][i2][i3][i4].........[in];
where each i is a dimension, and in is the size of final dimension.
Examples:1. int student[4][5][6][7];int designates the array type integer.student is the name of our 4D array.Our array can hold 840 integer-type elements. This number is reached by multiplying the value of each dimension. In this case: 4x5x6x7=840.
2. float country[5][6][5][6][5];Array country is a five-dimensional array.It can hold 4500 floating-point elements (5x6x5x6x5=4500).
Program :
// C Program to input 4D Matrix and print it.#include <stdio.h>int main(){    // variable declaration used for indexes    int i, j, k, l, size;      // Array declaration    int a[2][2][2][2];      // size of array    size = 2;      // elements input    a[0][0][0][0] = 5;    a[0][0][0][1] = 3;    a[0][0][1][0] = 5;    a[0][0][1][1] = 3;    a[0][1][0][0] = 6;    a[0][1][0][1] = 7;    a[0][1][1][0] = 6;    a[0][1][1][1] = 7;    a[1][0][0][0] = 8;    a[1][0][0][1] = 9;    a[1][0][1][0] = 8;    a[1][0][1][1] = 9;    a[1][1][0][0] = 9;    a[1][1][0][1] = 7;    a[1][1][1][0] = 9;    a[1][1][1][1] = 7;      // Printing the values    for (i = 0; i < size; i++) {        for (j = 0; j < size; j++) {            for (k = 0; k < size; k++) {                for (l = 0; l < size; l++) {                    printf("Value of a[%d][%d][%d][%d] :- %d ",                                    i, j, k, l, a[i][j][k][l]);                    printf("\n");                }            }        }    }    return 0;}
Value of a[0][0][0][0] :- 5 
Value of a[0][0][0][1] :- 3 
Value of a[0][0][1][0] :- 5 
Value of a[0][0][1][1] :- 3 
Value of a[0][1][0][0] :- 6 
Value of a[0][1][0][1] :- 7 
Value of a[0][1][1][0] :- 6 
Value of a[0][1][1][1] :- 7 
Value of a[1][0][0][0] :- 8 
Value of a[1][0][0][1] :- 9 
Value of a[1][0][1][0] :- 8 
Value of a[1][0][1][1] :- 9 
Value of a[1][1][0][0] :- 9 
Value of a[1][1][0][1] :- 7 
Value of a[1][1][1][0] :- 9 
Value of a[1][1][1][1] :- 7

Use:An 4D array can be used to store a collection of data, for example we input 3 coordinates & 1 time, i.e., x, y, z, t and we want to check whether there is collision between two vehicles or not.
vitkaodessit
sheikhdani669
cpp-array
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TCP Server-Client implementation in C
Exception Handling in C++
Multithreading in C
'this' pointer in C++
Arrow operator -> in C/C++ with Examples
Ways to copy a vector in C++
Smart Pointers in C++ and How to Use Them
Multiple Inheritance in C++
Understanding "extern" keyword in C
How to split a string in C/C++, Python and Java?
How to read value from string.xml in Android?

This example demonstrates how to read value from string.xml in Android.
Step 1  − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2  − Add the following code to res/values/strings.xml
<resources>
   <string name="app_name">Sample</string>
   <string name="NameOfTheString">Test string</string>
</resources>
Step 3  − Add the following code to res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
   xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      android:text="@string/NameOfTheString"
      app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Step 4  − Add the following code to src/MainActivity.java
package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }
}
Step 5  – Add the following code to app/manifests/AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
Java Generics - Bounded Type Parameters

There may be times when you'll want to restrict the kinds of types that are allowed to be passed to a type parameter. For example, a method that operates on numbers might only want to accept instances of Number or its subclasses. This is what bounded type parameters are for.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound.
Following example illustrates how extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces). This example is Generic method to return the largest of three Comparable objects −
public class MaximumTest {
   // determines the largest of three Comparable objects
   
   public static <T extends Comparable<T>> T maximum(T x, T y, T z) {
      T max = x;   // assume x is initially the largest
      
      if(y.compareTo(max) > 0) {
         max = y;   // y is the largest so far
      }
      
      if(z.compareTo(max) > 0) {
         max = z;   // z is the largest now                 
      }
      return max;   // returns the largest object   
   }
   
   public static void main(String args[]) {
      System.out.printf("Max of %d, %d and %d is %d\n\n", 
         3, 4, 5, maximum( 3, 4, 5 ));

      System.out.printf("Max of %.1f,%.1f and %.1f is %.1f\n\n",
         6.6, 8.8, 7.7, maximum( 6.6, 8.8, 7.7 ));

      System.out.printf("Max of %s, %s and %s is %s\n","pear",
         "apple", "orange", maximum("pear", "apple", "orange"));
   }
}
This will produce the following result −
Max of 3, 4 and 5 is 5

Max of 6.6,8.8 and 7.7 is 8.8

Max of pear, apple and orange is pear


    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
Lucky number and a sum | Practice | GeeksforGeeks

Given a number N.Find the minimum Lucky number, the sum of whose digits is equal to N.
Note:-Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. 

Example 1:
Input:
N=29
Output:
44777
Explanation:
44777 is the smallest number whose 
digit-sum(4+4+7+7+7) is equal to 29.

Example 2:
Input:
N=9
Output:
-1
Explanation:
There is no lucky number whose digit-sum
is equal to 9.

Your Task:
You don't need to read input or print anything.Your task is to complete the function minimumLuckyNumber() which takes a number N as input parameters and returns the minimum Lucky number(in the form of a string) whose digit-sum is equal to N. If there is no lucky number whose digit-sum is equal to N, then return -1.

Expected Time Complexity:O(N)
Expected Auxillary Space:O(1)

Constraints:
1<=N<=105
Note:The answer may not fit in 64 bit integer representations.
0
Annanya Mathur1 year ago
Annanya Mathur
string minimumLuckyNumber(int n) {
        int c=0;        string r="";        while(n>0)        {            if(n%7==0)            {r+='7';             n=n-7;            c=1;}            else            {r+='4';            n=n-4;            }            if(n==0)            return r;        }        if(c==0)        return "-1";
    }
0
nitin verma1 year ago
nitin verma
how to time exceed ??
class Solution:    def minimumLuckyNumber(self,N):        #code here        k = 4        l = 7        s = ''        while(N>0):            if N%7 == 0:                N = N - l                s = s + '7'            else:                N = N - k                s = s + '4'        if N == 0:            return s        else:            return -1
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.
Declare syntax error in MySQL Workbench?

The DECLARE syntax must between BEGIN and END. The syntax is as follows −
BEGIN
DECLARE yourVariableName1 dataType,
DECLARE yourVariableName2 dataType,
.
.
.
.
END
Here is the query to avoid DECLARE syntax error in MySQL −
mysql> DELIMITER //
mysql> create procedure declare_Demo()
   -> BEGIN
   -> DECLARE Name varchar(100);
   -> SET Name: ='John';
   -> SELECT Name;
   -> END
   -> //
Query OK, 0 rows affected (0.17 sec)
mysql> DELIMITER ;
Call the stored procedure with the help of CALL command. The syntax is as follows −
CALL yourStoredProcedureName();
The query is as follows −
mysql> call declare_Demo();
The following is the output −
+------+
| Name |
+------+
| John |
+------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)
ZonedDateTime equals() method in Java with Examples - GeeksforGeeks

10 May, 2019
The equals() method of ZonedDateTime class in Java is used to compare this ZonedDateTime to the another date-time object passed as parameter. The comparison is based on the offset date-time and the zone. Only objects of type ZonedDateTime are compared with each other and other types return false. The value to be returned by this method is determined as follows:
if both ZonedDateTime are equal, then true is returned.
if both ZonedDateTime are not equal, then false is returned.
Syntax:
public boolean equals(Object obj)

Parameters: This method accepts a single parameter obj which represents the object to compare with this ZonedDateTime. This is a mandatory parameter and it should not be null.
Return value: This method returns true if both ZonedDateTime are equal else false.
Below programs illustrate the equals() method:Program 1:
// Java program to demonstrate// ZonedDateTime.equals() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create ZonedDateTime objects        ZonedDateTime zoneddatetime1            = ZonedDateTime.parse("2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");          ZonedDateTime zoneddatetime2            = ZonedDateTime.parse("2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");          // apply equals()        boolean value = zoneddatetime1.equals(zoneddatetime2);          // print result        System.out.println("Both ZonedDateTime are equal: " + value);    }}
Both ZonedDateTime are equal: true

Program 2:
// Java program to demonstrate// ZonedDateTime.equals() method  import java.time.*;  public class GFG {    public static void main(String[] args)    {          // create ZonedDateTime objects        ZonedDateTime zoneddatetime1            = ZonedDateTime.parse("2018-12-06T19:21:12.123+05:30[Asia/Calcutta]");          ZonedDateTime zoneddatetime2            = ZonedDateTime.parse("2018-12-16T20:28:33.213+05:30[Asia/Calcutta]");          // apply equals()        boolean value = zoneddatetime1.equals(zoneddatetime2);          // print result        System.out.println("Both ZonedDateTime are equal: " + value);    }}
Both ZonedDateTime are equal: false

Reference:https://docs.oracle.com/javase/10/docs/api/java/time/ZonedDateTime.html#equals(java.lang.Object)
Kirti_Mangal
Java-Functions
Java-time package
Java-ZonedDateTime
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Stream In Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Internal Working of HashMap in Java
Checked vs Unchecked Exceptions in Java
Strings in Java
StringBuilder Class in Java with Examples
numpy.insert

This function inserts values in the input array along the given axis and before the given index. If the type of values is converted to be inserted, it is different from the input array. Insertion is not done in place and the function returns a new array. Also, if the axis is not mentioned, the input array is flattened.
The insert() function takes the following parameters −
numpy.insert(arr, obj, values, axis)

Where,
arr
Input array
obj
The index before which insertion is to be made
values
The array of values to be inserted
axis
The axis along which to insert. If not given, the input array is flattened
import numpy as np 
a = np.array([[1,2],[3,4],[5,6]]) 

print 'First array:' 
print a 
print '\n'  

print 'Axis parameter not passed. The input array is flattened before insertion.'
print np.insert(a,3,[11,12]) 
print '\n'  
print 'Axis parameter passed. The values array is broadcast to match input array.'

print 'Broadcast along axis 0:' 
print np.insert(a,1,[11],axis = 0) 
print '\n'  

print 'Broadcast along axis 1:' 
print np.insert(a,1,11,axis = 1)
Its output would be as follows −
First array:
[[1 2]
 [3 4]
 [5 6]]

Axis parameter not passed. The input array is flattened before insertion.
[ 1 2 3 11 12 4 5 6]

Axis parameter passed. The values array is broadcast to match input array.
Broadcast along axis 0:
[[ 1 2]
 [11 11]
 [ 3 4]
 [ 5 6]]

Broadcast along axis 1:
[[ 1 11 2]
 [ 3 11 4]
 [ 5 11 6]]


    63 Lectures 
     6 hours 

 Abhilash Nelson

    19 Lectures 
     8 hours 

 DATAhill Solutions Srinivas Reddy

    12 Lectures 
     3 hours 

 DATAhill Solutions Srinivas Reddy

    10 Lectures 
     2.5 hours 

 Akbar Khan

    20 Lectures 
     2 hours 

 Pruthviraja L

    63 Lectures 
     6 hours 

 Anmol
 Print
 Add Notes
 Bookmark this page
Scala Map exists() method with example - GeeksforGeeks

13 Aug, 2019
The exists() method is utilized to check if the given predicate satisfy the elements of the map or not.
Method Definition: def exists(p: ((A, B)) => Boolean): Boolean
Return Type: It returns true if the stated predicate holds true for some elements of the map else it returns false.
Example #1:
// Scala program of exists()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map("geeks" -> 5, "for" -> 3)                  // Applying exists method        val result = m1.exists(x => x._1 == "for" && x._2 == 3)                  // Displays output        println(result)          }}
true

So, here the stated predicate is true for the second key-value pair so true is returned.Example #2:
// Scala program of exists()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map("geeks" -> 5, "for" -> 3)                  // Applying exists method        val result = m1.exists(x => x._1 == "geeks" && x._2 == 3)                  // Displays output        println(result)          }}
false

Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in Scala
Scala | Traits
Scala ListBuffer
Scala | Case Class and Case Object
Hello World in Scala
Scala | Functions - Basics
Scala | Try-Catch Exceptions
Scala | Decision Making (if, if-else, Nested if-else, if-else if)
Comments In Scala
Scala List map() method with example
Difference between Cost Variance and Schedule Variance - GeeksforGeeks

16 May, 2019
Prerequisite – Cost Variance (CV) and Schedule Variance (SV)Cost Variance (CV):Cost variance is basically related with the budget of the project. Cost variance is the difference of the actual cost and the expected cost. Cost Variance is calculated by taking the difference of the Earned Value and the Actual Cost.
Schedule Variance (SV):Schedule variance basically related with the scheduled time for the project. Schedule variance is the measurement of deviation of consumed time from the scheduled time. Scheduled Variance is calculated by taking difference between Earned Value and Planned Value.
Example:The budget of a project is at 1, 00, 000 dollar. It has to be completed in 9 months but after one month it is found that only 10 percent of the project is completed and the cost at the end of one month is 10, 000 dollar. The planned completion should have been 15 percent.
Then the Cost Variance (CV) and Schedule Variance (SV) will be:
Actual Cost, 
= 1, 00, 000 dollar

Planned Value, 
= 15% * 1, 00, 000 
= 15, 000 dollar

Earned Value, 
= 10% * Rs. 1, 00, 000 
= 10, 000 dollar

Cost Variance (CV), 
= Earned Value – Actual Cost 
= 10, 000 - 1, 00, 000
= - 90, 000

Schedule Variance (SV), 
= Earned Value - Planned Value
= 10, 000 - 15, 000
= -5, 000 
Conclusion: Cost Variance (CV) is negative which means the project is over budget and Schedule Variance (SV) is negative that means the project is behind the schedule.
Difference between Cost Variance and Schedule Variance:
CV = EV - AC
SV = EV - PV
Difference Between
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Stack vs Heap Memory Allocation
Differences between JDK, JRE and JVM
Types of Software Testing
Software Engineering | COCOMO Model
Functional vs Non Functional Requirements
Software Engineering | Coupling and Cohesion
Software Engineering | Spiral Model