code-rag-bench/online-tutorials huggingface dataset:
How to add table row in a table using jQuery? - GeeksforGeeks

23 Apr, 2019
jQuery can be used to add table rows dynamically. This can be used in web applications where the user may need to add more rows if required.
Steps to add table row:
The required markup for the row is constructed.markup = "<tr><td> + information + </td></tr>"
markup = "<tr><td> + information + </td></tr>"
The table body is selected to which the table rows to be added.tableBody = $("table tbody")
tableBody = $("table tbody")
Finally the markup is added to the table body.tableBody.append(markup)
tableBody.append(markup)
Example:
<!DOCTYPE html><html>  <head>    <title>        How to add table row in jQuery?    </title>          <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">    </script>          <style>        table {            margin: 25px 0;            width: 200px;        }          table th, table td {            padding: 10px;            text-align: center;        }          table, th, td {            border: 1px solid;        }    </style></head>  <body>    <h1 style="color: green">        GeeksForGeeks    </h1>          <b>How to add table row in jQuery?</b>          <p>        Click on the button below to        add a row to the table    </p>          <button class="add-row">        Add row    </button>          <table>        <thead>            <tr>                <th>Rows</th>            </tr>        </thead>        <tbody>            <tr>                <td>This is row 0</td>            </tr>        </tbody>    </table>          <!-- Script to add table row -->    <script>        let lineNo = 1;        $(document).ready(function () {            $(".add-row").click(function () {                markup = "<tr><td>This is row "                     + lineNo + "</td></tr>";                tableBody = $("table tbody");                tableBody.append(markup);                lineNo++;            });        });     </script></body></html>                    
Output:
Before clicking the button:
After clicking the button 4 times:
jQuery-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
Set the value of an input field in JavaScript
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Build an Application for Screen Rotation Using Python - GeeksforGeeks

30 Sep, 2021
In this article, we are going to write a python script for screen rotation and implement it with GUI. 
The display can be modified to four orientations using some methods from the rotatescreen module, it is a small Python package for rotating the screen in a system.
pip install rotate-screen
Step 1) Import the required module in the python script.
Python3
# Import required moduleimport rotatescreen
 Step 2) Create an object of rotatescreen.get_primary_display() to access the main screen of the system. 
Python3
# Accessing the main screenrotate_screen = rotatescreen.get_primary_display()
 Step 3) Now use various methods to rotate the screen.
set_landscape(), Rotate Up
set_portrait_flipped(), Rotate Left
set_landscape_flipped(), Rotate Down
set_portrait(), Rotate Right
Python3
# Methods to change orientation # for landscaperotate_screen.set_landscape() # portrait at leftrotate_screen.set_portrait_flipped() # landscape at downrotate_screen.set_landscape_flipped() # portrait at rightrotate_screen.set_portrait()
 Below is the complete program of the above approach along with GUI implementation.
Python3
# Import required modulesfrom tkinter import *import rotatescreen  # User defined function# for rotating screendef Screen_rotation(temp):    screen = rotatescreen.get_primary_display()    if temp == "up":        screen.set_landscape()    elif temp == "right":        screen.set_portrait_flipped()    elif temp == "down":        screen.set_landscape_flipped()    elif temp == "left":        screen.set_portrait()  # Creating tkinter objectmaster = Tk()master.geometry("100x100")master.title("Screen Rotation")master.configure(bg='light grey')  # Variable classes in tkinterresult = StringVar()  # Creating buttons to change orientationButton(master, text="Up", command=lambda: Screen_rotation(    "up"), bg="white").grid(row=0, column=3)Button(master, text="Right", command=lambda: Screen_rotation(    "right"), bg="white").grid(row=1, column=6)Button(master, text="Left", command=lambda: Screen_rotation(    "left"), bg="white").grid(row=1, column=2)Button(master, text="Down", command=lambda: Screen_rotation(    "down"), bg="white").grid(row=3, column=3)  mainloop() # this code belongs to Satyam kumar (ksatyam858)
Output:
abhigoya
saurabh1990aror
Python Tkinter-exercises
Python-tkinter
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Compute Log Normal Probability Density in R Programming - dlnorm() Function - GeeksforGeeks

25 Jun, 2020
dlnorm() function in R Language is used to compute the log normal value of the probability density function. It also creates a plot of the log normal density.
Syntax: dlnorm(vec)
Parameters:vec: x-values for normal density
Example 1:
# R program to compute# log normal probability density  # Creating x-values for densityx <- seq(1, 10, by = 1)  # Calling dlnorm() functiony <- dlnorm(x)y
Output:
 [1] 0.398942280 0.156874019 0.072728256 0.038153457 0.021850715 0.013354538
 [7] 0.008581626 0.005739296 0.003965747 0.002815902

Example 2:
# R program to compute# log normal probability density  # Creating x-values for densityx <- seq(1, 10, by = 0.1)  # Calling dlnorm() functiony <- dlnorm(x)  # Plot a graphplot(y)
Output:
R-Statistics
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
Remove rows with NA in one column of R DataFrame
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to check if a given character is a number/letter in Java?

The Character class is a subclass of Object class and it wraps a value of the primitive type char in an object. An object of type Character contains a single field whose type is char. We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.
public class CharacterIsNumberOrDigitTest {
   public static void main(String[] args) {
      String str = "Tutorials123";
      for(int i=0; i < str.length(); i++) {
         Boolean flag = Character.isDigit(str.charAt(i));
         if(flag) {
            System.out.println("'"+ str.charAt(i)+"' is a number");
         }
         else {
            System.out.println("'"+ str.charAt(i)+"' is a letter");
         }
      }
   }
}
'T' is a letter
'u' is a letter
't' is a letter
'o' is a letter
'r' is a letter
'i' is a letter
'a' is a letter
'l' is a letter
's' is a letter
'1' is a number
'2' is a number
'3' is a number
C++ Program to Swap Two Numbers

There are two ways to create a program to swap two numbers. One involves using a temp variable and the second way does not use a third variable. These are explained in detail as follows −
The program to swap two numbers using a temp variable is as follows.
 Live Demo
#include <iostream >
using namespace std;
int main() {
   int a = 10, b = 5, temp;
   temp = a;
   a = b;
   b = temp;
   cout<<"Value of a is "<<a<<endl;
   cout<<"Value of b is "<<b;
   return 0;
}
Value of a is 5
Value of b is 10
In the above program, there are two variables a and b that store the two numbers. First, the value of a is stored in temp. Then, the value of b is stored in a. Lastly, the value of temp is stored in b. After this, the values in a and b are swapped.
temp = a;
a = b;
b = temp;
Then the values of a and b are displayed.
cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;
The program to swap two numbers without using a third variable is as follows −
 Live Demo
#include <iostream>
using namespace std;
int main() {
   int a = 10, b = 5;
   a = a+b;
   b = a-b;
   a = a-b;
   cout<<"Value of a is "<<a<<endl;
   cout<<"Value of b is "<<b;
   return 0;
}
Value of a is 5
Value of b is 10
In the above program, first the sum of a and b is stored in a. Then, the difference of a and b is stored in b. Finally, the difference of a and b is stored in b. At the end of this, the values in a and b are swapped.
a = a+b;
b = a-b;
a = a-b;
Then the values of a and b are displayed.
cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;
PLSQL | CONVERT Function - GeeksforGeeks

19 Sep, 2019
The string in PL/SQL is actually a sequence of characters with an optional size specification.The characters could be numeric, letters, blank, special characters or a combination of all.The CONVERT function in PLSQL is used to convert a string from one character set to another.Generally, the destination character set contains a representation of all the characters defined in the source character set.If in any case, a character does not exist in the destination character set, a replacement character appears. These replacement characters can be defined as part of a character set definition.
Syntax:
CONVERT( string1, char_set_to [, char_set_from] )
Parameters Used –
string1 –It is used to specify the string to be converted. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.char_set_to –It is used to specify the character set to which the string needs to be converted.char_set_from –It is an optional parameter which is used to specify the character set from which the string needs to be converted.
string1 –It is used to specify the string to be converted. It can be any of the datatypes CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB.
char_set_to –It is used to specify the character set to which the string needs to be converted.
char_set_from –It is an optional parameter which is used to specify the character set from which the string needs to be converted.
Note – Both the destination and source character set arguments can be either literals or columns containing the name of the character set.
Available Character Sets:
US7ASCII : US 7-bit ASCII character set
WE8DEC : West European 8-bit character set
WE8HP : HP West European Laserjet 8-bit character set
F7DEC : DEC French 7-bit character set
WE8EBCDIC500 : IBM West European EBCDIC Code Page 500
WE8PC850 : IBM PC Code Page 850
WE8ISO8859P1 : ISO 8859-1 West European 8-bit character set
Supported Versions of Oracle/PLSQL:
Oracle 12cOracle 11gOracle 10gOracle 9iOracle 8i
Oracle 12c
Oracle 11g
Oracle 10g
Oracle 9i
Oracle 8i
Example:
DECLARE 
   Test_String string(10) := 'A B C D';
   Test_String2 string(20) := 'E Ä Ê Í';
   
BEGIN 
   dbms_output.put_line(CONVERT(Test_String, 'US7ASCII', 'WE8ISO8859P1')); 
   dbms_output.put_line(CONVERT(Test_String2, 'US7ASCII')); 
   
END;  
Output:
A B C D
E A E I
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SQL Trigger | Student Database
SQL | Views
CTE in SQL
Difference between DELETE, DROP and TRUNCATE
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between DDL and DML in DBMS
SQL Interview Questions
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Difference between Where and Having Clause in SQL
Bokeh - ColumnDataSource

Most of the plotting methods in Bokeh API are able to receive data source parameters through ColumnDatasource object. It makes sharing data between plots and ‘DataTables’.
A ColumnDatasource can be considered as a mapping between column name and list of data. A Python dict object with one or more string keys and lists or numpy arrays as values is passed to ColumnDataSource constructor.
Below is the example
from bokeh.models import ColumnDataSource
data = {'x':[1, 4, 3, 2, 5],
   'y':[6, 5, 2, 4, 7]}
cds = ColumnDataSource(data = data)
This object is then used as value of source property in a glyph method. Following code generates a scatter plot using ColumnDataSource.
from bokeh.plotting import figure, output_file, show
from bokeh.models import ColumnDataSource
data = {'x':[1, 4, 3, 2, 5],
   'y':[6, 5, 2, 4, 7]}
cds = ColumnDataSource(data = data)
fig = figure()
fig.scatter(x = 'x', y = 'y',source = cds, marker = "circle", size = 20, fill_color = "grey")
show(fig)
Instead of assigning a Python dictionary to ColumnDataSource, we can use a Pandas DataFrame for it.
Let us use ‘test.csv’ (used earlier in this section) to obtain a DataFrame and use it for getting ColumnDataSource and rendering line plot.
from bokeh.plotting import figure, output_file, show
import pandas as pd
from bokeh.models import ColumnDataSource
df = pd.read_csv('test.csv')
cds = ColumnDataSource(df)
fig = figure(y_axis_type = 'log')
fig.line(x = 'x', y = 'pow',source = cds, line_color = "grey")
show(fig)
 Print
 Add Notes
 Bookmark this page
User-Defined Exceptions in Python

Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError. This is useful when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
   raise Networkerror("Bad hostname")
except Networkerror,e:
   print e.args
Check if a File is hidden in C#

To retrieve the attributes of a file, use the FileAttributes Eumeration. It has various members like compressed, directory, hidden, etc.
To check if a file is hidden, use the hidden member name.
If the FileAttributes.hidden is set that would mean the file is hidden. Firstly, get the path to find the attributes.
FileAttributes attributes = File.GetAttributes(path);

If the following is set, that would mean the file is now hidden using the hidden member name.
 File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden);
Console.WriteLine("The {0} file is hidden.", path);
HTML <a> target Attribute

21 Jun, 2022
The HTML <a> target Attribute is used to specify where to open the link. 
Syntax:
<a target="_blank | _self | _parent | _top | framename"\> 
Attribute Values: 
_blank: It opens the link in a new window.
_self: It is the default value. It opens the linked document in the same frame.
_parent: It opens the linked document in the parent frameset.
_top: It opens the linked document in the full body of the window.
framename: It opens the linked document in the named frame.
Example: In this example, the GeeksforGeeks link will open in the new tab.
HTML
<!DOCTYPE html><html> <body>    <h2>GeeksforGeeks</h2>      <p>Welcome to        <a href="https://www.geeksforgeeks.org/"           target="_blank">            GeeksforGeeks        </a>    </p>  </body> </html>
Output:
HTML <a> target attribute
Example: This example illustrates the use of the Target attribute in the <a> element. 
HTML
<!DOCTYPE html><html> <head>    <title> HTML a target Attribute </title></head> <body>    <center>        <h1>GeeksforGeeks</h1>        <h2>HTML a Target Attribute</h2>          <p>Welcome to            <a href="https://ide.geeksforgeeks.org/"               id="GFG"               target="_self">                GeeksforGeeks            </a>        </p>      </center></body> </html>
Output:
HTML <a> target attribute
Supported Browsers: 
Google Chrome version
Edge version 12 and above
Internet Explorer 
Firefox version
Opera 
Safari 
arorakashish0911
shubhamyadav4
chhabradhanvi
bhaskargeeksforgeeks
satyamm09
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Python | Pandas Timedelta.days

14 Jan, 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.
Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedelta and is interchangeable with it in most cases. Timedelta.days property in pandas.Timedelta is used to return Number of days.
Syntax: Timedelta.days
Parameters: None
Returns: return Number of days
Code #1:
# importing pandas as pd import pandas as pd   # Create the Timedelta object td = pd.Timedelta('3 days 06:05:01.000030')   # Print the Timedelta object print(td)   print(td.days)
3 days 06:05:01.000030
3

Code #2:
# importing pandas as pd import pandas as pd   # Create the Timedelta object td = pd.Timedelta('1 days 7 hours')   # Print the Timedelta object print(td)   print(td.days)
1 days 07:00:00
1

Code #3:
# importing pandas as pd import pandas as pd import datetime  # Create the Timedelta object td = pd.Timedelta(datetime.timedelta(days = 3, hours = 7, seconds = 8))   # Print the Timedelta object print(td)   print(td.days)
3 days 07:00:08
3

Python pandas-timedelta
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python – Double each List element

01 Mar, 2020
Sometimes, while working with data, we have just a simple application in which we require to double the contents of a list and make it 100% increase in its magnitude. This is having application in web development and machine learning domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loopThis the brute force way in which this task can be performed. In this, we just add the same element again to that index element and all the contents of list are added to itself i.e doubled.
# Python3 code to demonstrate # Double List# using loop  # Initializing listtest_list = [12, 67, 98, 34, 43]  # printing original listprint("The original list is : " + str(test_list))  # Double List# using loopres = []for ele in test_list:    res.append(ele + ele)      # printing result print ("Double List is : " + str(res))
The original list is : [12, 67, 98, 34, 43]
Double List is : [24, 134, 196, 68, 86]

 
Method #2 : Using list comprehensionThis task can also be performed using list comprehension. This is similar to above function. Just the difference is that its compact and one liner.
# Python3 code to demonstrate # Double List# using list comprehension  # Initializing listtest_list = [12, 67, 98, 34, 43]  # printing original listprint("The original list is : " + str(test_list))  # Double List# using list comprehensionres = [ele + ele for ele in test_list]      # printing result print ("Double List is : " + str(res))
The original list is : [12, 67, 98, 34, 43]
Double List is : [24, 134, 196, 68, 86]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | sympy.bernoulli() method

14 Jul, 2019
With the help of sympy.bernoulli() method, we can find the Bernoulli number and Bernoulli polynomial in SymPy.
Syntax: bernoulli(n)
Parameter:n – It denotes the nth bernoulli number.
Returns: Returns the nth bernoulli number.
Example #1:
# import sympy from sympy import * n = 4print("Value of n = {}".format(n))   # Use sympy.bernoulli() method nth_bernoulli = bernoulli(n)        print("Value of nth bernoulli number : {}".format(nth_bernoulli))  
Output:
Value of n = 4
Value of nth bernoulli number : -1/30

Syntax: bernoulli(n, k)
Parameter:n – It denotes the order of the bernoulli polynomial.k – It denotes the variable in the bernoulli polynomial.
Returns: Returns the expression of the bernoulli polynomial or its value.
Example #2:
# import sympy from sympy import * n = 5k = symbols('x')print("Value of n = {} and k = {}".format(n, k))   # Use sympy.bernoulli() method nth_bernoulli_poly = bernoulli(n, k)        print("The nth bernoulli polynomial : {}".format(nth_bernoulli_poly))  
Output:
Value of n = 5 and k = x
The nth bernoulli polynomial : x**5 - 5*x**4/2 + 5*x**3/3 - x/6

Example #3:
# import sympy from sympy import * n = 4k = 3print("Value of n = {} and k = {}".format(n, k))   # Use sympy.bernoulli() method nth_bernoulli_poly = bernoulli(n, k)        print("The nth bernoulli polynomial value : {}".format(nth_bell_poly))  
Output:
Value of n = 4 and k = 3
The nth bernoulli polynomial value : 10*x1**2*x3 + 15*x1*x2**2

SymPy
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python | Sum of squares in list

12 Mar, 2019
Python being the language of magicians can be used to perform many tedious and repetitive tasks in a easy and concise manner and having the knowledge to utilize this tool to the fullest is always useful. One such small application can be finding sum of squares of list in just one line. Let’s discuss certain ways in which this can be performed.
Method #1 : Using reduce() + lambdaThe power of lambda functions to perform lengthy tasks in just one line, allows it combined with reduce which is used to accumulate the subproblem, to perform this task as well. Works with only Python 2.
# Python code to demonstrate  # sum of squares # using reduce() + lambda  # initializing listtest_list = [3, 5, 7, 9, 11]  # printing original list print ("The original list is : " + str(test_list))  # using reduce() + lambda# sum of squares res = reduce(lambda i, j: i + j * j, [test_list[:1][0]**2]+test_list[1:])  # printing resultprint ("The sum of squares of list is : " + str(res))
The original list is : [3, 5, 7, 9, 11]
The sum of squares of list is : 285

 
Method #2 : Using map() + sum()The similar solution can also be obtained using the map function to integrate and sum function to perform the summation of the squared number.
# Python3 code to demonstrate  # sum of squares # using sum() + max()  # initializing listtest_list = [3, 5, 7, 9, 11]  # printing original list print ("The original list is : " + str(test_list))  # using sum() + max()# sum of squares res = sum(map(lambda i : i * i, test_list))  # printing resultprint ("The sum of squares of list is : " + str(res))
The original list is : [3, 5, 7, 9, 11]
The sum of squares of list is : 285

Python list-programs
Python
Python Programs
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 ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python | Split string into list of characters
Remove newline, space and tab characters from a string in Java

To remove newline, space and tab characters from a string, replace them with empty as shown below.
replaceAll("[\\n\\t ]", "");
Above, the new line, tab, and space will get replaced with empty, since we have used replaceAll()
The following is the complete example.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      String originalStr = "Demo\n\tText";
      System.out.println("Original String with tabs, spaces and newline: \n"+originalStr);
      originalStr = originalStr.replaceAll("[\\n\\t ]", "");
      System.out.println("\nString after removing tabs, spaces and new line: "+originalStr);
   }
}
Original String with tabs, spaces and newline:
Demo
Text
String after removing tabs, spaces and new line: DemoText
Session Objects – Python requests

07 Jun, 2022
Session object allows one to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance and will use urllib3’s connection pooling. So, if several requests are being made to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase. A session object all the methods as of requests.
Let us illustrate the use of session objects by setting a cookie to a URL and then making a request again to check if the cookie is set. 
Python3
# import requests moduleimport requests # create a session objects = requests.Session() # make a get requests.get('https://httpbin.org / cookies / set / sessioncookie / 123456789') # again make a get requestr = s.get('https://httpbin.org / cookies') # check if cookie is still setprint(r.text)
Output  One can check that cookie was still set when the request was made again. Sessions can also be used to provide default data to the request methods. This is done by providing data to the properties on a Session object: 
Python3
# import requests moduleimport requests # create a session objects = requests.Session() # set username and passwords.auth = ('user', 'pass') # update headerss.headers.update({'x-test': 'true'}) # both 'x-test' and 'x-test2' are sents.get('https://httpbin.org / headers', headers ={'x-test2': 'true'}) # print objectprint(s)
Output 
shreelakshmijoshi1
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
What is an Optional parameter in C#?

By default, all parameters of a method are required. A method that contains optional parameters does not force to pass arguments at calling time. It means we call method without passing the arguments.
The optional parameter contains a default value in function definition. If we do not pass optional argument value at calling time, the default value is used.
Thera are different ways to make a parameter optional.
 Live Demo
using System;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         OptionalMethodWithDefaultValue(5);
         //Value2 is not passed as it is optional
         OptionalMethodWithDefaultValue(5, 10);
         //Value2 is passed
         Console.ReadLine();
      }
      public static void OptionalMethodWithDefaultValue(int value1, int value2 = 5){
         Console.WriteLine($"Sum is {value1 + value2}");
      }
   }
}
The output of the above code is
Sum is 10
Sum is 15
In the above example, the method OptionalMethodWithDefaultValue(int value1, int value2 = 5) value2 is having default value 5. So if no arguments is passed for value2 while calling it will take the default value 5 and if an argument is passed for value2 then the default value is overridden.
 Live Demo
using System;
using System.Runtime.InteropServices;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         OptionalMethodWithDefaultValue(5);
         OptionalMethodWithDefaultValue(5, 10);
         Console.ReadLine();
      }
      public static void OptionalMethodWithDefaultValue(int value1, [Optional]int value2){
         Console.WriteLine($"Sum is {value1 + value2}");
      }
   }
}
The output of the above code is
Sum is 5
Sum is 15
Here for the [Optional] attribute is used to specify the optional parameter.
Also, it should be noted that optional parameters should always be specified at the end of the parameters. For ex − OptionalMethodWithDefaultValue(int value1 = 5, int value2) will throw exception.
using System;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         OptionalMethodWithDefaultValue(5);
         OptionalMethodWithDefaultValue(5, 10);
         Console.ReadLine();
      }
      public static void OptionalMethodWithDefaultValue(int value1 = 5, int value2){
         Console.WriteLine($"Sum is {value1 + value2}");
      }
   }
}
Error − Optional Parameters must appear after all required parameters.
Python | How and where to apply Feature Scaling?

27 Sep, 2021
Feature Scaling or Standardization: It is a step of Data Pre Processing that is applied to independent variables or features of data. It basically helps to normalize the data within a particular range. Sometimes, it also helps in speeding up the calculations in an algorithm.
Package Used: 
sklearn.preprocessing
Import:  
 from sklearn.preprocessing import StandardScaler
The formula used in Backend Standardization replaces the values with their Z scores. 
Mostly the Fit method is used for Feature scaling 
fit(X, y = None)
Computes the mean and std to be used for later scaling.
Python
import pandas as pdfrom sklearn.preprocessing import StandardScaler # Read Data from CSVdata = read_csv('Geeksforgeeks.csv')data.head() # Initialise the Scalerscaler = StandardScaler() # To scale datascaler.fit(data)
Why and Where to Apply Feature Scaling? The real-world dataset contains features that highly vary in magnitudes, units, and range. Normalization should be performed when the scale of a feature is irrelevant or misleading and not should Normalise when the scale is meaningful.
The algorithms which use Euclidean Distance measures are sensitive to Magnitudes. Here feature scaling helps to weigh all the features equally.
Formally, If a feature in the dataset is big in scale compared to others then in algorithms where Euclidean distance is measured this big scaled feature becomes dominating and needs to be normalized. 
Examples of Algorithms where Feature Scaling matters 1. K-Means uses the Euclidean distance measure here feature scaling matters. 2. K-Nearest-Neighbours also require feature scaling. 3. Principal Component Analysis (PCA): Tries to get the feature with maximum variance, here too feature scaling is required. 4. Gradient Descent: Calculation speed increase as Theta calculation becomes faster after feature scaling.
Note: Naive Bayes, Linear Discriminant Analysis, and Tree-Based models are not affected by feature scaling. In Short, any Algorithm which is Not Distance-based is Not affected by Feature Scaling. 
Akanksha_Rai
marcosarcticseal
Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Getting started with Machine Learning
Agents in Artificial Intelligence
Search Algorithms in AI
ML | Monte Carlo Tree Search (MCTS)
Introduction to Recurrent Neural Network
Markov Decision Process
Count the number of a special day between two dates by using PL/SQL - GeeksforGeeks

06 Dec, 2019
Prerequisite – PL/SQL Introduction, Decision Making in PL/SQL
Write a pl/sql program to input two dates and print number of Sundays between those two dates.
Explanation:Before each iteration of the loop, condition is evaluated. If it evaluates to TRUE, sequence_of_statements is executed. If condition evaluates to FALSE or NULL, the loop is finished and control resumes after the END LOOP statements.
Note:The only difference between simple loop and while loop is simple execute first and then it will check condition, so simple loop execute at least once and in while loop first it will check condition and then execute.
Example-1:
Input: Enter value for date1: 01-SEP-19 
      Enter value for date2: 29-SEP-19

Output: no of Sundays : 5 
Example-2:
Input: Enter value for date1: 01-SEP-19
      Enter value for date2: 15-SEP-19

Output: no of Sundays: 3 
Code:
--declare the variables D1 and D2.--type of variable is Date.SQL> DECLARE        D1 Date;        D2 Date;        Cnt Number:=0;    BEGIN         D1:='&Date1';        D2:='&Date2';        D1:=next_day(D1-1, 'SUNDAY');   --check the condition by using while loop.        while(D1<=D2)    LOOP        Cnt:=Cnt+1;        D1:=D1+7;    END LOOP;        dbms_output.put_line('no of Sundays:'||Cnt);    END;    /--end of program
Output:
Enter value for date1: 01-SEP-19
old 5: Begin D1:='&Date1';
new 5: Begin D1:='01-SEP-19';

Enter value for date2: 29-SEP-19
old   6:  D2:='&Date2';
new   6:  D2:='29-SEP-19';
no of Sundays:5 
PL/SQL procedure successfully completed.
Advantages:-By using while loop first it checks condition and then execute, So We count easily the number of a special day between two dates.
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | DROP, TRUNCATE
Composite Key in SQL
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL indexes
SQL | Date functions
What is Temporary Table in SQL?
Window functions in SQL
SQL | ALTER (ADD, DROP, MODIFY)
Clear LRU Cache in Python - GeeksforGeeks

10 Jul, 2020
The LRU is the Least Recently Used cache. LRU Cache is a type of high-speed memory, that is used to quicken the retrieval speed of frequently used data. It is implemented with the help of Queue and Hash data structures.
Note: For more information, refer to Python – LRU Cache
Python’s functool module has provided functionality to interact with the LRU Cache since Python 3.2. The functool module offers a decorator that can be placed atop a Class of a function in Python. When used on functions that require large amounts of variable access and change operations, using the LRU Cache offers massive speed-up.
Example:
import functools  @functools.lru_cache(maxsize = None)def gfg():    # insert function logic here    pass
Alternatively, the maxsize can be changed to suit one’s own preference. The value is measured in kbs, and maxsize takes an integer argument
After the use of the cache, cache_clear() can be used for clearing or invalidating the cache.
Example 1:
import functools   @functools.lru_cache(maxsize = None)def fib(n):     if n < 2:         return n     return fib(n-1) + fib(n-2)  fib(30)  # Before Clearingprint(fib.cache_info())  fib.cache_clear()  # After Clearingprint(fib.cache_info())
Output:
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)
CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)
Example 2: Additionally one can also call cache_clear() from another function as well
import functools   @functools.lru_cache(maxsize = None)def fib(n):     if n < 2:         return n     return fib(n-1) + fib(n-2)  def gfg():    fib.cache_clear()  fib(30)  # Before Clearingprint(fib.cache_info())  gfg()  # After Clearingprint(fib.cache_info())
Output:
CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)
CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)
These methods have limitations as they are individualized, and the cache_clear() function must be typed out for each and every LRU Cache utilizing the function. We can overcome this problem, by using Python’s inbuilt garbage collection module to collect all objects that have LRU Cache Wrappers, and iteratively clear each object’s cache.
Example:
import gcimport functools  @functools.lru_cache(maxsize = None)def gfg():    # insert function logic here    pass  @functools.lru_cache(maxsize = None)def gfg1():    # insert function logic here    pass  @functools.lru_cache(maxsize = None)def gfg2():    # insert function logic here    pass  gfg()gfg1()gfg2()  gc.collect()  # All objects collectedobjects = [i for i in gc.get_objects()            if isinstance(i, functools._lru_cache_wrapper)]  # All objects clearedfor object in objects:    object.cache_clear()
Python functools-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
Big Data Analytics - Text Analytics

In this chapter, we will be using the data scraped in the part 1 of the book. The data has text that describes profiles of freelancers, and the hourly rate they are charging in USD. The idea of the following section is to fit a model that given the skills of a freelancer, we are able to predict its hourly salary.
The following code shows how to convert the raw text that in this case has skills of a user in a bag of words matrix. For this we use an R library called tm. This means that for each word in the corpus we create variable with the amount of occurrences of each variable.
library(tm)
library(data.table)  

source('text_analytics/text_analytics_functions.R') 
data = fread('text_analytics/data/profiles.txt') 
rate = as.numeric(data$rate) 
keep = !is.na(rate) 
rate = rate[keep]  

### Make bag of words of title and body 
X_all = bag_words(data$user_skills[keep]) 
X_all = removeSparseTerms(X_all, 0.999) 
X_all 

# <<DocumentTermMatrix (documents: 389, terms: 1422)>> 
#   Non-/sparse entries: 4057/549101 
# Sparsity           : 99% 
# Maximal term length: 80 
# Weighting          : term frequency - inverse document frequency (normalized) (tf-idf) 

### Make a sparse matrix with all the data 
X_all <- as_sparseMatrix(X_all)

Now that we have the text represented as a sparse matrix we can fit a model that will give a sparse solution. A good alternative for this case is using the LASSO (least absolute shrinkage and selection operator). This is a regression model that is able to select the most relevant features to predict the target.
train_inx = 1:200
X_train = X_all[train_inx, ] 
y_train = rate[train_inx]  
X_test = X_all[-train_inx, ] 
y_test = rate[-train_inx]  

# Train a regression model 
library(glmnet) 
fit <- cv.glmnet(x = X_train, y = y_train,  
   family = 'gaussian', alpha = 1,  
   nfolds = 3, type.measure = 'mae') 
plot(fit)  

# Make predictions 
predictions = predict(fit, newx = X_test) 
predictions = as.vector(predictions[,1]) 
head(predictions)  

# 36.23598 36.43046 51.69786 26.06811 35.13185 37.66367 
# We can compute the mean absolute error for the test data 
mean(abs(y_test - predictions)) 
# 15.02175

Now we have a model that given a set of skills is able to predict the hourly salary of a freelancer. If more data is collected, the performance of the model will improve, but the code to implement this pipeline would be the same.

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    18 Lectures 
     1.5 hours 

 Pranjal Srivastava, Harshit Srivastava

    23 Lectures 
     2 hours 

 John Shea

    18 Lectures 
     1.5 hours 

 Pranjal Srivastava

    46 Lectures 
     3.5 hours 

 Pranjal Srivastava

    37 Lectures 
     3.5 hours 

 Pranjal Srivastava, Harshit Srivastava
 Print
 Add Notes
 Bookmark this page
8051 Program to Multiply two 8 Bit numbers

Now we will try to multiply two 8-bit numbers using this 8051 microcontroller. The register A and B will be used for multiplication. No other registers can be used for multiplication. The result of the multiplication may exceed the 8-bit size. So the higher order byte is stored at register B, and lower order byte will be in the Accumulator A after multiplication.
We are taking two number FFH and FFH at location 20H and 21H, After multiplying the result will be stored at location 30H and 31H.  
        MOV R0, #20H;set source address 20H to R0
    MOV R1, #30H;set destination address 30H to R1

        MOV A, @R0;take the first operand from source to register A
        INCR0; Point to the next location
        MOV B,@R0;take the second operand from source to register B

        MUL AB ;Multiply A and B

        MOV @R1, B; Store higher order byte to 30H
        INC R1; Increase R1 to point to the next location
        MOV @R1, A;Store lower order byte to 31H
HALT:   SJMP HALT ; Stop the program
8051 provides MULAB instruction. By using this instruction, the multiplication can be done. In some other microprocessors like8085, there was no MUL instruction. In that microprocessor, we need to use repetitive ADD operations to get the result of the multiplication. 
When the result is below255, the overflow flag OV is low, otherwise, it is 1.
How to convert a JSON string into a JavaScript object?

Javascript has provided JSON.parse() method to convert a JSON into an object. Once JSON is parsed we can able to access the elements in the JSON.
var obj = JSON.parse(JSON);
It takes a JSON and parses it into an object so as to access the elements in the provided JSON.
In the following example, a JOSN is assigned to a variable and converted it into an object and later on displayed the values of the elements in the JSON as shown in the output.
Live Demo
<html>
<body>
<script>
   var json = '{"name": "Malinga", "age": 32, "country": "srilanka"}';
   var obj = JSON.parse(json);
   document.write(obj.name + "</br>");
   document.write(obj.age + "</br>");
   document.write(obj.country);
</script>
</body>
</html>
Malinga
32
srilanka
Live Demo
<html>
<body>
<script>
   var json = '{"company": "Tutorialspoint", "Product": "Tutorix", "city": "Hyderabad"}';
   var obj = JSON.parse(json);
   document.write(obj.company+ "</br>");
   document.write(obj.Product+ "</br>");
   document.write(obj.city);
</script>
</body>
</html>
Tutorialspoint
Tutorix
Hyderabad
How BEFORE INSERT triggers can be used to emulate CHECK CONSTRAINT for inserting values in the table?

As we know that MySQL supports foreign key for referential integrity but it does not support CHECK constraint. But we can emulate them by using triggers. It can be illustrated with the help of an example given below −
Suppose we have a table named ‘car’ which can have the fix syntax registration number like two letters, a dash, three digits, a dash, two letters as follows −
mysql> Create table car (number char(9));
Query OK, 0 rows affected (0.32 sec)

mysql> Insert into car values('AB-235-YZ');
Query OK, 1 row affected (0.10 sec)
The above value is a valid one but what about the value that we are going to insert in the next query.
mysql> insert into car values('AB-2X5-YZ');
Query OK, 1 row affected (0.04 sec)
The above value is not a valid one because it contains a character between digits which is against the fixed syntax we are using.
Creating BEFORE INSERT trigger to emulate CHECK CONSTRAINT for inserting the values −
Now, we can create a trigger as follows to prevent such kind of insertion −
mysql> delimiter //
mysql> create trigger car_insert_value before insert on car
    -> for each row
    -> begin
    ->     if new.number not rlike '^[[:alpha:]]{2}-[[:digit:]]{3}-[[:alpha:]]{2}$'
    ->     then
    ->         signal sqlstate '45000' set message_text = 'Not a valid Number';
    ->     end if;
    -> end //
Query OK, 0 rows affected (0.15 sec)
mysql> Delimiter ;

mysql> Delete from car;
Query OK, 2 rows affected (0.06 sec)
Now, when we will try to insert the incorrect number, the above-created trigger will stop us to do so and will throw an error as follows −
mysql> insert into car values('AB-2X5-YZ');
ERROR 1644 (45000): Not a Valid Number
But, we can insert the valid values as follows −
mysql> insert into car values('AB-235-YZ');
Query OK, 1 row affected (0.04 sec)
Default arguments  in Python

A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −
 Live Demo
#!/usr/bin/python
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print "Name: ", name
print "Age ", age
return;
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35
Python | Pandas dataframe.get_value()

19 Nov, 2018
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 dataframe.get_value() function is used to quickly retrieve single value in the data frame at passed column and index. The input to the function is the row label and the column label.
Syntax: DataFrame.get_value(index, col, takeable=False)
Parameters :index : row labelcol : column labeltakeable : interpret the index/col as indexers, default False
Returns : value : scalar value
For link to CSV file Used in Code, click here
Example #1: Use get_value() function to find the value of salary in the 10th row
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # Print the dataframedf
# applying get_value() function df.get_value(10, 'Salary')
Output : 
Example #2: Use get_value() function and pass the column index value rather than name.
Note : We can also use integer indexer value of columns by setting the takeable parameter=True.
# importing pandas as pdimport pandas as pd  # Creating the dataframe df = pd.read_csv("nba.csv")  # column index value of "Name" column is 0# We have set takeable = True# to interpret the index / col as indexerdf.get_value(4, 0, takeable = True)
Output :
Python pandas-dataFrame
Python pandas-dataFrame-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Create a Pandas DataFrame from Lists