code-rag-bench/online-tutorials huggingface dataset:
What does synchronized modifier do in Java?

The synchronized keyword used to indicate that a method can be accessed by only one thread at a time. The synchronized modifier can be applied with any of the four access level modifiers.
 Live Demo
public class TestThread {
   public static Object Lock1 = new Object();
   public static Object Lock2 = new Object();
   
   public static void main(String args[]) {
      ThreadDemo1 T1 = new ThreadDemo1();
      ThreadDemo2 T2 = new ThreadDemo2();
      T1.start();
      T2.start();
   }
   private static class ThreadDemo1 extends Thread {
      public void run() {
         synchronized (Lock1) {
            System.out.println("Thread 1: Holding lock 1...");
            try { Thread.sleep(10); }
            catch (InterruptedException e) {}
            System.out.println("Thread 1: Waiting for lock 2...");
            
            synchronized (Lock2) {
               System.out.println("Thread 1: Holding lock 1 & 2...");
            }
         }
      }
   }
   private static class ThreadDemo2 extends Thread {
      public void run() {
         synchronized (Lock2) {
            System.out.println("Thread 2: Holding lock 2...");
            try { Thread.sleep(10); }
            catch (InterruptedException e) {}
            System.out.println("Thread 2: Waiting for lock 1...");
            
            synchronized (Lock1) {
               System.out.println("Thread 2: Holding lock 1 & 2...");
            }
         }
      }
   }
}
Thread 1: Holding lock 1...
Thread 2: Holding lock 2...
Thread 1: Waiting for lock 2...
Thread 2: Waiting for lock 1...
Python - Convert JSON to string - GeeksforGeeks

02 Jun, 2021
Data in transmitted across platforms using API calls. Data is mostly retrieved in JSON format. We can convert the obtained JSON data into String data for the ease of storing and working with it.
Let’s see how to convert JSON to String.
Method #1: Json to String on dummy data using “json.dumps”
Python3
import json # create a sample json a = {"name" : "GeeksforGeeks", "Topic" : "Json to String", "Method": 1} # Convert JSON to String y = json.dumps(a) print(y)print(type(y))
Output:  
Method #2: Json to String using an API using requests and “json.dumps”
Python3
import jsonimport requests # Get dummy data using an APIres = requests.get("http://dummy.restapiexample.com/api/v1/employees") # Convert data to dictdata = json.loads(res.text) # Convert dict to stringdata = json.dumps(data) print(data)print(type(data))
Output: 
 
akshaysingh98088
JSON
Picked
Python json-programs
Python-json
Python
Python Programs
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
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Matplotlib.pyplot.grid() in Python - GeeksforGeeks

21 Apr, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface.
The grid() function in pyplot module of matplotlib library is used to configure the grid lines.
Syntax: matplotlib.pyplot.grid(b=None, which=’major’, axis=’both’, \*\*kwargs)
Parameters: This method accept the following parameters.
b : This parameter is an optional parameter, whether to show the grid lines or not.
which : This parameter is also an optional parameter and it is the grid lines to apply the changes on.
axis :This parameter is also an optional parameter and it is the axis to apply the changes on.
Returns:This method does not return any value.
Below examples illustrate the matplotlib.pyplot.grid() function in matplotlib.pyplot:
Example #1:
# Implementation of matplotlib function   import matplotlib.pyplot as pltimport numpy as np      plt.plot([1, 2, 3])plt.grid()  plt.title('matplotlib.pyplot.grid() function \Example\n\n', fontweight ="bold")plt.show()
Output:
Example #2:
# Implementation of matplotlib function   import numpy as npimport matplotlib.pyplot as plt  np.random.seed(19680801)  val, res = 100, 15x = np.sin(val + res * np.random.randn(10000)) - np.cos(val + res * np.random.randn(10000))  n, bins, patches = plt.hist(x, 200,                             density = True,                             facecolor ='g',                             alpha = 0.5)  plt.grid(True)  plt.title('matplotlib.pyplot.grid() function \Example\n\n', fontweight ="bold")  plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python
Create a Pandas DataFrame from Lists
Python Booleans

Booleans represent one of two values: 
True or False.
In programming you often need to know if an expression is 
True or False.
You can evaluate any expression in Python, and get one of two 
answers, 
True or False.
When you compare two values, the expression is evaluated and Python returns 
the Boolean answer:
When you run a condition in an if statement, Python returns 
True or False:
Print a message based on whether the condition is True or 
  False:
The bool() function allows you to evaluate 
any value, and give you 
True or False 
in return,
Evaluate a string and a number:
Evaluate two variables:
Almost any value is evaluated to True if it 
has some sort of content.
Any string is True, except empty strings.
Any number is True, except 
0.
Any list, tuple, set, and dictionary are True, except 
empty ones.
The following will return True:
In fact, there are not many values that evaluate to
False, except empty values, such as (),
[], {}, 
"", the number
0, and the value None. 
And of course the value False evaluates to
False.
The following will return False:
One more value, or object in this case, evaluates to 
False, and that is if you have an object that 
is made from a class with a __len__ function that returns 
0 or 
False: 
You can create functions that returns a Boolean Value:
Print the answer of a function:
You can execute code based on the Boolean answer of a function:
Print "YES!" if the function returns True, otherwise print "NO!":
Python also has many built-in functions that return a boolean value, like the 
isinstance() 
function, which can be used to determine if an object is of a certain data type:
Check if an object is an integer or not:
The statement below would print a Boolean value, which one?
print(10 > 9)



Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
JavaScript Submit textbox on pressing ENTER?

The ENTER has the key code 13. We will use the event.keycode to check whether ENTER is
pressed or not. Following is the code −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input type="text" id="name"/>
<script>
   document.getElementById("name").addEventListener("keydown",
   function(event) {
      if (!event) {
         var event = window.event;
      }
         event.preventDefault();
      if (event.keyCode == 13){
         login();
      }
   }, false);
   function login(){
      console.log("submitted successfully....");
   }
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
When you press ENTER key, the following message would be visible on console as in the below screenshot −
TypeORM - Indices

In general, Indexing is a process to optimize the performance of a database by optimizing the data storage. It is used to quickly locate and access the data in a database. This section explains about how to use index in TypeORM. Indices are classified into different types. Let’s go through one by one in detail.
We can create index for particular column using @Index. Consider an example of Customer entity as shown below and index defined for firstName column,
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; 

@Entity() 
export class Student { 

   @PrimaryGeneratedColumn() 
   id: number; 
   
   @Index() 
   @Column() 
   firstName: string; 
   
   @Column() 
   lastName: string; 
   
   @Column() 
   age: number; 
   
   @Column() 
   address: string; 
}

@Index allow to specify name for an index as well −
@Index("Name-idx") 
@Column() 
firstName: string;

To specify Unique constraints in your column, use the below property −
{ unique: true }

For example, below is the code to specify unique index for Name column −
@Index({ unique: true }) 
@Column() 
firstName: string;

To apply indices for more than one columns, we can directly specify it after @Entity(). The sample code is as follows −
@Entity() 
@Index(["firstName", "lastName"]) @Index(["firstName", "lastName"], { unique: true })

Spatial index allows to access spatial objects. MySQL and PostgreSQL supports spacial indices. To enable spatial indices in your column, add the following property −
{ spatial: true }

Spatial type has multiple sub types such as, geometry, point, line string, polygon etc., For example, if you want to add point spatial type in your column, use below code −
@Column("point") 
@Index({ spatial: true }) 
point: string;

To disable synchronization, use the below option on @Index decorator −
{ synchronize: false }


    19 Lectures 
     50 mins

 James Coonce
 Print
 Add Notes
 Bookmark this page
MATLAB - Addition & Subtraction of Vectors

You can add or subtract two vectors. Both the operand vectors must be of same type and have same number of elements.
Create a script file with the following code −
A = [7, 11, 15, 23, 9];
B = [2, 5, 13, 16, 20];
C = A + B;
D = A - B;
disp(C);
disp(D);
When you run the file, it displays the following result −
9    16    28    39    29
5     6     2     7   -11


    30 Lectures 
     4 hours 

 Nouman Azam

    127 Lectures 
     12 hours 

 Nouman Azam

    17 Lectures 
     3 hours 

 Sanjeev

    37 Lectures 
     5 hours 

 TELCOMA Global

    22 Lectures 
     4 hours 

 TELCOMA Global

    18 Lectures 
     3 hours 

 Phinite Academy
 Print
 Add Notes
 Bookmark this page
SQL - DROP or DELETE Database

The SQL DROP DATABASE statement is used to drop an existing database in SQL schema.
The basic syntax of DROP DATABASE statement is as follows −
DROP DATABASE DatabaseName;

Always the database name should be unique within the RDBMS.
If you want to delete an existing database <testDB>, then the DROP DATABASE statement would be as shown below −
SQL> DROP DATABASE testDB;
NOTE − Be careful before using this operation because by deleting an existing database would result in loss of complete information stored in the database.
Make sure you have the admin privilege before dropping any database. Once a database is dropped, you can check it in the list of the databases as shown below −
SQL> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| AMROOD             |
| TUTORIALSPOINT     |
| mysql              |
| orig               |
| test               |
+--------------------+
6 rows in set (0.00 sec)

    42 Lectures 
     5 hours 

 Anadi Sharma

    14 Lectures 
     2 hours 

 Anadi Sharma

    44 Lectures 
     4.5 hours 

 Anadi Sharma

    94 Lectures 
     7 hours 

 Abhishek And Pukhraj

    80 Lectures 
     6.5 hours 

 Oracle Master Training | 150,000+ Students Worldwide

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
How to convert a Date into Timestamp using PHP ? - GeeksforGeeks

18 Jan, 2021
The Task is to convert a Date to a timestamp using PHP. The task can be done by using the strtotime() function in PHP. It is used to convert English textual date-time description to a UNIX timestamp. The UNIX timestamp represents the number of seconds between a particular date and the Unix Epoch. 
Syntax:
strtotime ($EnglishDateTime, $time_now)
Example:  
PHP
// PHP program to convert the date // to timestamp <?php  $date = "2020-09-23";$timestamp1 = strtotime($date);echo $timestamp1; echo "<br>";   $date2 = "24-09-2020";$timestamp2 = strtotime($date2);echo $timestamp2; echo "<br>";   $date3 = "16 May 2019";$timestamp3 = strtotime($date3);echo $timestamp3;?>?>
Output:
160081920016009056001557964800
PHP-date-time
PHP-Misc
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to delete an array element based on key in PHP?
Easy Text Annotation in a Jupyter Notebook | by Siphu Langeni, MS | Towards Data Science

At the heart of any sentiment analysis project is a good set of labeled data. Pre-labeled datasets can be found on various sites all over the internet. But...
What if you have come up with a custom dataset that has no labels?
What if you have to provide those labels before proceeding with your project?
What if you are not willing to pay to outsource the task of labeling?
I was recently faced with this very issue while retrieving text data from the Twitter Streaming API for a sentiment analysis project. I quickly discovered annotating the data myself would be a painful task without a good tool. This was the inspiration behind building tortus, a tool that makes it easy to label your text data within a Jupyter Notebook!
Begin by installing tortus and enabling the appropriate nbextentions.
$ pip install tortus$ jupyter nbextension enable --py widgetsnbextension
After opening a Jupyter Notebook, read your data into a pandas dataframe.
import pandas as pdmovie_reviews = pd.read_csv('movie_reviews.csv')
Import the package and create an instance of Tortus.
from tortus import Tortustortus = Tortus(df, text, num_records=10, id_column=None, annotations=None, random=True, labels=['Positve', 'Negative', 'Neutral'])
df: A dataframe with texts that need to be annotated. This will be the dataframe that you read into pandas earlier.
text: The name of the column containing the text to be annotated. This should be a string.
num_records: Number of records to annotate in one tortus session. This must be an integer and defaults to 10 records.
id_column: The name of the column containing ID of the text. If there is no such column in your dataframe, leave the default set to None. The ID given will then be the index of the original dataframe. This may be helpful if you need to join datasets at a later time.
annotations: The dataframe with annotations previously created in this tool. It will have the correct columns to be used in subsequent annotations. Records in this dataframe will be excluded when the annotate method is called to prevent duplication. The default is set to None if you have no previous annotations for this dataset.
random: Determines if records are loaded into the annotation widget randomly or sequentially. The default is set to True.
labels: A list of annotation labels. Labels must be strings. The default is [‘Positive', ‘Negative', ‘Neutral'].
Use the annotate method to access the annotation widget.
tortus.annotate()
After annotations are complete, they can be stored to a variable where they can later be accessed for analysis.
annotations = tortus.annotations
If you require future annotations, pass this dataframe as an argument in a subsequent instance of tortus.
This wraps up this short tutorial on how to use tortus to easily add labels to your text data.
To go to the package on PyPI, click here.
To view the entire source code, click here.
If you find this package helpful in your annotation tasks or you have questions or suggestions for improvements, please feel free to connect with me on LinkedIn and share your feedback.
How to Install two python modules with same name?

This is not possible with the pip. All of the packages on PyPI have unique names. Packages often require and depend on each other, and assume the name will not change. Even if you manage to put the code on Python path, when importing a module, python searches the paths in sys.path by order and stops at first match. So whatever module it finds first, it'll stop at that. 
You best bet is to copy all the code from the libraries to you codebase, change the module name of either and then import it.
If you're importing modules with same name from different packages, you can do it as follows:
>>> from foo import bar as first_bar
>>> from baz import bar as second_bar
What is a TestNG xml file in TestNG?

The testng.xml file has the numerous uses as listed below −
Test cases are executed in groups.
Test cases are executed in groups.
Test methods can be included or excluded in the execution.
Test methods can be included or excluded in the execution.
The execution of multiple test cases from multiple java class files can be triggered.
The execution of multiple test cases from multiple java class files can be triggered.
Comprises names of the folder, class, method.
Comprises names of the folder, class, method.
Capable of triggering parallel execution.
Capable of triggering parallel execution.
Test methods belonging to groups can be included or excluded in the execution.
Test methods belonging to groups can be included or excluded in the execution.
Code implementation of TestNG.xml file
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name = "Cycle1">
   <test name = "Tutorialspoint">
      <classes>
         <class name = "Test1" />
         <methods>
            <exclude name= “Login.*”/>
         </methods>
      </classes>
   </test>
</suite>
Here as per the xml file, all the test methods with starting name Login will be excluded from test execution.
@Test
public void VerifyPay(){
   System.out.println("Verify payment is successful”);
}
@Test
public void LoginAdmin(){
   System.out.println("Login is successful in admin”);
}
@Test
public void LoginSystem(){
   System.out.println("Login is successful”);
}
Here as per the java class file, only VerifyPay() will be executed since all methods starting with the name Login will be excluded from test execution.
ReactJS | Introduction to Babel - GeeksforGeeks

08 Jan, 2021
Introduction to Babel Babel is a very famous transpiler that basically allows us to use future JavaScript in today’s browsers. In simple words, it can convert the latest version of JavaScript code into the one that the browser understands. The latest standard version which JavaScript follows is ES2020 which is not fully supported by all the browsers and hence we make use of a tool such as ‘babel’ so that we can convert it into the code that today’s browser understands.
What is transpiler? It is a tool that is used to convert source code into another source code that is of the same level. That is why it is also known as a source-to-source compiler. Both the codes are equivalent in nature, considering the fact that one works with the specific version of the browser and one doesn’t. 
Note: It is also good to note that a compiler is totally different from a transpiler as the transpiler converts source code into another source code at the same abstraction level, whereas the compiler converts code into a lower level code generally. Like in Java, the source code is converted to byte Code which is lower level and not equivalent.
Why do we need Babel? The main reason we need babel is that it gives us the privilege to make use of the latest things JavaScript has to offer without worrying about whether it will work in the browser or not. 
Simple Example Before installing and making use of all the features of the Babel tool, let’s see a simple code of the latest standard version of ES2017 and see what happens to it when we pass it into the babel engine. 
Code:  
Javascript
// sample new version javascript codeconst fun = (x) => {x*2}; const a = () => {}; const b = (x) => x; [1, 2, 3].map((n)=> n+1);
Some of the above code is not supported in some browsers, so after transpiling through Babel we will get:  
Javascript
// after transpiling"use strict"; var fun = function fun(x) {  x * 2;}; var a = function a() {}; var b = function b(x) {  return x;}; [1, 2, 3].map(function (n) {  return n + 1;});
In the next article, we will learn how to install Babel and will also see more examples of it. 
shubhamyadav4
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need 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?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
How to set the default value for an HTML <select> element ?
How to calculate the number of days between two dates in javascript?
How to create footer to stay at the bottom of a Web page?
Underscore.JS - findWhere method

_.findWhere(list, properties)

Looks through each value in the list, returning first matched pair that matches the key-value pairs listed in properties.
var _ = require('underscore');

var list = [{"title": "Learn Java", "Author": "Sam", "Cost": 100},
   {"title": "Learn Scala", "Author": "Joe", "Cost": 200},
   {"title": "Learn C", "Author": "Sam", "Cost": 200} ]
   
//Example 1. find a book whose author is Sam
var result = _.findWhere(list, { "Author": "Sam" });
console.log(result);

//Example 2. find a book whose cost is 200
var result = _.findWhere(list, { "Cost": 200 });
console.log(result);
Save the above program in tester.js. Run the following command to execute this program.
\>node tester.js

{ title: 'Learn Java', Author: 'Sam', Cost: 100 }
{ title: 'Learn Scala', Author: 'Joe', Cost: 200 }

 Print
 Add Notes
 Bookmark this page
Struts 2 - XML Based Validators

Following is the list of various types of field level and non-field level validation available in Struts2 −
<field name = "birthday">
   <field-validator type = "date">
      <param name = "min">01/01/1990</param>
      <param name = "max">01/01/2000</param>
      <message>
         Birthday must be within ${min} and ${max}
      </message>
   </field-validator>
</field>
<field name = "percentage">
   <field-validator type = "double">
      <param name = "minExclusive">0.123</param>
      <param name = "maxExclusive">99.98</param>
      <message>
         Percentage needs to be between ${minExclusive}
         ${maxExclusive} (exclusive)
      </message>
   </field-validator>
</field>
<field name = "myEmail">
   <field-validator type = "email">
      <message>
         Must provide a valid email
      </message>
   </field-validator>
</field>
A Non-Field Level validator that validates based on regular expression supplied.
<field-validator type = "expression">
   <param name = "expression">....</param>
   <message>
      Failed to meet Ognl Expression  .... 
   </message>
</field-validator>
<field name = "age">
   <field-validator type = "int">
      <param name = "min">5</param>
      <param name = "max">50</param>
      <message>
         Age needs to be between ${min} and ${max}
      </message>
   </field-validator>
</field>
<field name = "myStrangePostcode">
   <field-validator type = "regex">
      <param name = "fieldName">myStrangePostcode</param>
         <param name = "expression">
         <![CDATA[([aAbBcCdD][123][eEfFgG][456])]]>
      </param>
   </field-validator>
</field>
<field name = "username">
   <field-validator type = "required">
      <message>
         username must not be null
      </message>
   </field-validator>
</field>
<field name = "username">
   <field-validator type = "requiredstring">
     <param name = "trim">true</param>
     <message>
         username must not be null
      </message>
   </field-validator>
</field>
<field name = "username">
   <field-validator type = "stringlength">
      <param name = "minLength">10</param>
      <param name = "maxLength">10</param>
      <param name = "trim">true</param>
      <message>
         Your username needs to be 10 characters long
      </message>
   </field-validator>
</field>
<field-validator type = "url">
   <param name = "fieldName">myHomePageURL</param>
   <message>
     Invalid homepage url
   </message>
</field-validator>
 Print
 Add Notes
 Bookmark this page
Python - How to rename multiple column headers in a Pandas DataFrame with Dictionary?

To rename multiple column headers, use the rename() method and set the dictionary in the columns parameter. At first, let us create a DataFrame −
dataFrame = pd.DataFrame({"Car": ['BMW', 'Mustang', 'Tesla', 'Mustang', 'Mercedes', 'Tesla', 'Audi'],"Cubic Capacity": [2000, 1800, 1500, 2500, 2200, 3000, 2000],"Reg Price": [7000, 1500, 5000, 8000, 9000, 6000, 1500],"Units Sold": [ 200, 120, 150, 120, 210, 250, 220]
})
Creating a dictionary to rename columns. The key and value pairs as old name and new name −
dictionary = {'Car': 'Car Name','Cubic Capacity': 'CC','Reg Price': 'Registration Price','Units Sold': 'Units Purchased'
}
Use rename() and set the dictionary as columns −
dataFrame.rename(columns=dictionary, inplace=True)
Following is the code −
import pandas as pd

# creating dataframe
dataFrame = pd.DataFrame({"Car": ['BMW', 'Mustang', 'Tesla', 'Mustang', 'Mercedes', 'Tesla', 'Audi'],"Cubic Capacity": [2000, 1800, 1500, 2500, 2200, 3000, 2000],"Reg Price": [7000, 1500, 5000, 8000, 9000, 6000, 1500],"Units Sold": [ 200, 120, 150, 120, 210, 250, 220]
})

print"DataFrame ...\n",dataFrame

# creating a dictionary to rename columns
# key and value pairs as old name and new name
dictionary = {'Car': 'Car Name','Cubic Capacity': 'CC','Reg Price': 'Registration Price','Units Sold': 'Units Purchased'
}

# using rename() and setting the dictionary as columns
dataFrame.rename(columns=dictionary, inplace=True)

print"\nUpdated DataFrame ...\n",dataFrame
This will produce the following output −
DataFrame ...
        Car   Cubic Capacity   Reg Price   Units Sold
0       BMW             2000        7000          200
1   Mustang             1800        1500          120
2     Tesla             1500        5000          150
3   Mustang             2500        8000          120
4  Mercedes             2200        9000          210
5     Tesla             3000        6000          250
6      Audi             2000        1500          220

Updated DataFrame ...
   Car Name    CC   Registration Price   Units Purchased
0       BMW  2000                 7000               200
1   Mustang  1800                 1500               120
2     Tesla  1500                 5000               150
3   Mustang  2500                 8000               120
4  Mercedes  2200                 9000               210
5     Tesla  3000                 6000               250
6      Audi  2000                 1500               220
Determine if two filename paths refer to the same File in Java

The method java.io.File.equals() is used to find if the two file names refer to the same File in Java. This method requires a single parameter i.e.the file object that is to be compared to the other file object. It returns if the file objects are same and false otherwise.
A program that demonstrates this is given as follows −
 Live Demo
import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file1 = new File("demo1.txt");
         File file2 = new File("demo2.txt");
         boolean flag = file1.equals(file2);
         System.out.print("The two file names refer to the same file? " + flag);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}
The output of the above program is as follows −
The two file names refer to the same file? false
Now let us understand the above program.
The method java.io.File.equals() is used to find if the two file names refer to the same File in Java. The boolean value returned by the method is printed. A code snippet that demonstrates this is given as follows −
try {
   File file1 = new File("demo1.txt");
   File file2 = new File("demo2.txt");
   boolean flag = file1.equals(file2);
   System.out.print("The two file names refer to the same file? " + flag);
} catch(Exception e) {
   e.printStackTrace();
}
Angular Material 7 - SideNav

The <mat-sidenav>, an Angular Directive, is used to create a side navigation bar and main content panel with material design styling and animation capabilities.
<mat-sidenav-container> - Represents the main container.
<mat-sidenav-container> - Represents the main container.
<mat-sidenav-content> - Represents the content panel.
<mat-sidenav-content> - Represents the content panel.
<mat-sidenav> - Represents the side panel.
<mat-sidenav> - Represents the side panel.
In this chapter, we will showcase the configuration required to draw a sidenav control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatSidenavModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatSidenavModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified CSS file app.component.css.
.tp-container {
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
   background: #eee;
}
.tp-section {
   display: flex;
   align-content: center;
   align-items: center;
   height: 60px;
   width:100px;   
}
Following is the content of the modified HTML host file app.component.html.
<mat-sidenav-container class = "tp-container">
   <mat-sidenav mode = "side" opened>
      <section class = "tp-section">
         <span>File</span>
      </section>
      <section class = "tp-section">
         <span>Edit</span>
      </section>
   </mat-sidenav>
   <mat-sidenav-content>Main content</mat-sidenav-content>
</mat-sidenav-container>
Verify the result.
As first, we've created a main container spanning the complete page.
As first, we've created a main container spanning the complete page.
Then side nav is created using mat-sidenav and content panel using mat-sidenav-content.
Then side nav is created using mat-sidenav and content panel using mat-sidenav-content.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to encode the string in android?

This example demonstrate about How to encode the string 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.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center_horizontal"
   android:layout_marginTop="30dp"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/edit_query"
      android:layout_width="match_parent"
      android:layout_height="wrap_content" />
   <Button
      android:id="@+id/buttonPanel"
      android:text="Check"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/text"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken editext, button and textview. When user click on button after inserting value in edittext,it will do encode.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   TextView text;
   EditText edit_query;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      edit_query = findViewById(R.id.edit_query);
      text = findViewById(R.id.text);
      findViewById(R.id.buttonPanel).setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (!edit_query.getText().toString().isEmpty()) {
               String encode = Base64.encodeToString(edit_query.getText().toString().getBytes(), Base64.DEFAULT);
               text.setText(encode);
            }
         }
      });
}
}
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 –
In the above result, we have encoded and appened to textview.
Click here to download the project code
Program to recover decode XORed array in Python

Suppose we have a hidden array arr with n non-negative integers. Now this array is encoded into another array enc of length n-1. So here enc[i] = arr[i] XOR arr[i+1]. If we have the encoded enc array and an integer first, that is the first element of actual array, we have to find the original array.
So, if the input is like enc = [8,3,2,7], first = 4, then the output will be [4, 12, 15, 13, 10].
To solve this, we will follow these steps −
arr := an array with only one element first
arr := an array with only one element first
for i in range 0 to size of enc - 1, doinsert arr[i] XOR enc[i] at the end of arr
for i in range 0 to size of enc - 1, do
insert arr[i] XOR enc[i] at the end of arr
insert arr[i] XOR enc[i] at the end of arr
return arr
return arr
Let us see the following implementation to get better understanding −
 Live Demo
def solve(enc, first):
   arr = [first]
   for i in range(0, len(enc)):
      arr.append(arr[i] ^ enc[i])
   return arr

enc = [8,3,2,7]
first = 4
print(solve(enc, first))
[8,3,2,7], 4
[4, 12, 15, 13, 10]
HTML | <object> height Attribute - GeeksforGeeks

28 Jun, 2019
The HTML <object> height attribute is used to specify the height of the object element in terms of pixel.
Syntax:
<object height="pixels">
Attribute Values:
pixels: It holds the height of the object in terms of pixels.
Below example illustrates the <object> height attribute in HTML:
Example:
<!DOCTYPE html> <html>   <head>    <title>        HTML object height Attribute    </title></head>  <body style="text-align:center;">           <h2>HTML object height Attribute</h2>           <object id="myobject" width="400"                height="200" data= "https://media.geeksforgeeks.org/wp-content/uploads/geek-8.png">     </object>   </body>   </html>
Output:
Supported Browsers: The browser supported by HTML object height attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
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)
Design a web page using HTML and CSS
Angular File Upload
Form validation using jQuery
DOM (Document Object Model)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Evaluation of Boolean expression

We write a program in 8085 in the assembly language just for the evaluation of only wo Boolean expressions of 4 variables by using the interface of logic controller. The output of the program should be logically tested automatically by the output by the input changing from the inputs from 0000, 0001, ... to 1111 just to press any key.
Let us say we want to evaluate the following Boolean expressions.
First of all, truth table for the Boolean expressions is written down as shown in the following table.
The inputs of the PQRS gets connected to PB3, PB2, PB1, and PB0 of 8255 respectively. The output terminal of X and Y outputs gets connected to the PA1 and PA0, respectively. The Program Port C should be lower just for the output and to be connected to PC3-0 of the lines of the input PB3-0. We just increment the value in the Port C by just lowering by lower by 1just whenever we press a key. This results in the increment of the port B, rather for the depression of every key. The interface of the logic controller just provides a buffer of 12 output lines and also a buffer of 12 input lines to the user. The output lines 12 just gets connected to the lower Ports of A and C (lower) of 8255 on the ALS kit. The output status of each of these lines of output of 8255 gets displayed by using the light emitting diodes called as (LED). In the Fig below, the connections get connected for the making of only one of the made to only one of the output lines of 8255 as shown below.
Values within parenthesis correspond to each other. Similarly, those outside parentheses correspond to each other. For example, if PB7 input is a1, the buffer output will also be a1, the inverter output will be 0, and the LED will be On.
The truth table is stored in memory as a look up table, say from location C100H. The following values (corresponding to X and Y in the LS bit positions) are stored in consecutive locations starting from C100H.
02, 00, 02, 00, 02, 00, 02, 00, 01, 01, 02, 00, 00, 03, 00, 00
; FILE NAME BOOLEAN.ASM
ORG C100H
TABLE DB 02H, 00H, 02H, 00H, 02H, 00H, 02H, 00H
DB 01H, 01H, 02H, 00H, 00H, 03H, 00H, 00H

ORG C000H

PA EQU D8H
PB EQU D9H
PC EQU DAH
CTRL EQU DBH

MVI A, 10001010B
OUT CTRL ; Configure 8255 ports

LOOP: IN PB
ANI 0FH ; Now A will contain PQRS input value

LXI H, TABLE
ADD L
MOV L, A ; Point HL to proper row in the truth table

MOV A, M
OUT PA ; Output XY from truth table to display
JMP LOOP
Go - Type Conversion

Type conversion is a way to convert a variable from one data type to another data type. For example, if you want to store a long value into a simple integer then you can type cast long to int. You can convert values from one type to another using the cast operator. Its syntax is as follows −
type_name(expression)

Consider the following example where the cast operator causes the division of one integer variable by another to be performed as a floating number operation.
package main

import "fmt"

func main() {
   var sum int = 17
   var count int = 5
   var mean float32
   
   mean = float32(sum)/float32(count)
   fmt.Printf("Value of mean : %f\n",mean)
}
When the above code is compiled and executed, it produces the following result −
Value of mean : 3.400000


    64 Lectures 
     6.5 hours 

 Ridhi Arora

    20 Lectures 
     2.5 hours 

 Asif Hussain

    22 Lectures 
     4 hours 

 Dilip Padmanabhan

    48 Lectures 
     6 hours 

 Arnab Chakraborty

    7 Lectures 
     1 hours 

 Aditya Kulkarni

    44 Lectures 
     3 hours 

 Arnab Chakraborty
 Print
 Add Notes
 Bookmark this page
Seaborn - Importing Datasets and Libraries

In this chapter, we will discuss how to import Datasets and Libraries. Let us begin by understanding how to import libraries.
Let us start by importing Pandas, which is a great library for managing relational (table-format) datasets. Seaborn comes handy when dealing with DataFrames, which is most widely used data structure for data analysis.
The following command will help you import Pandas −
# Pandas for managing datasets
import pandas as pd

Now, let us import the Matplotlib library, which helps us customize our plots.
# Matplotlib for additional customization
from matplotlib import pyplot as plt

We will import the Seaborn library with the following command −
# Seaborn for plotting and styling
import seaborn as sb

We have imported the required libraries. In this section, we will understand how to import the required datasets.
Seaborn comes with a few important datasets in the library. When Seaborn is installed, the datasets download automatically.
You can use any of these datasets for your learning. With the help of the following function you can load the required dataset
load_dataset()

In this section, we will import a dataset. This dataset loads as Pandas DataFrame by default. If there is any function in the Pandas DataFrame, it works on this DataFrame.
The following line of code will help you import the dataset −
# Seaborn for plotting and styling
import seaborn as sb
df = sb.load_dataset('tips')
print df.head()

The above line of code will generate the following output −
   total_bill  tip   sex    smoker day  time   size
0    16.99    1.01   Female  No    Sun  Dinner  2
1    10.34    1.66   Male    No    Sun  Dinner  3
2    21.01    3.50   Male    No    Sun  Dinner  3
3    23.68    3.31   Male    No    Sun  Dinner  2
4    24.59    3.61   Female  No    Sun  Dinner  4

To view all the available data sets in the Seaborn library, you can use the following command with the get_dataset_names() function as shown below −
import seaborn as sb
print sb.get_dataset_names()

The above line of code will return the list of datasets available as the following output
[u'anscombe', u'attention', u'brain_networks', u'car_crashes', u'dots', 
u'exercise', u'flights', u'fmri', u'gammas', u'iris', u'planets', u'tips', 
u'titanic']

DataFrames store data in the form of rectangular grids by which the data can be over viewed easily. Each row of the rectangular grid contains values of an instance, and each column of the grid is a vector which holds data for a specific variable. This means that rows of a DataFrame do not need to contain, values of same data type, they can be numeric, character, logical, etc. DataFrames for Python come with the Pandas library, and they are defined as two-dimensional labeled data structures with potentially different types of columns.
For more details on DataFrames, visit our tutorial on pandas.

    11 Lectures 
     4 hours 

 DATAhill Solutions Srinivas Reddy

    11 Lectures 
     2.5 hours 

 DATAhill Solutions Srinivas Reddy
 Print
 Add Notes
 Bookmark this page
Append list of dictionary and series to a existing Pandas DataFrame in Python - GeeksforGeeks

31 Aug, 2021
In this article, we will discuss how values from a list of dictionaries or Pandas Series can be appended to an already existing pandas dataframe. For this purpose append() function of pandas, the module is sufficient.
Syntax: DataFrame.append(other, ignore_index=False, verify_integrity=False, sort=None)
Parameters :other : DataFrame or Series/dict-like object, or list of theseignore_index : If True, do not use the index labels.verify_integrity : If True, raise ValueError on creating index with duplicates.sort : Sort columns if the columns of self and other are not aligned. The default sorting is deprecated and will change to not-sorting in a future version of pandas. Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.
Returns: appended : DataFrame
Approach 
Import module
Create data frame or series
Create a list with dictionaries
Append this list to existing data frame or series
Example 1: 
Python
# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({    'Employs Name': ['Rishabh', 'Rahul', 'Suraj', 'Mukul', 'Vinit'],    'Location': ['Saharanpur', 'Meerut', 'Saharanpur', 'Meerut', 'Saharanpur'],    'Pay': [21000, 22000, 23000, 24000, 22000]}) # print dataframeprint("\n  ***  Original DataFrames  **  \n")print(df)  # create dictionariesdicts = [{'Employs Name': 'Anuj', 'Location': 'Meerut', 'Roll No': 30000},         {'Employs Name': 'Arun', 'Location': 'Saharanpur', 'Roll No': 32000}] # print dictionariesprint("\n  **  Dictionary  ** ")print(dicts)  # combined datadf = df.append(dicts, ignore_index=True, sort=False) # print combined dataframeprint("\n\n  **  Combined Data  **\n")print(df)
Output:
Example 2: 
Python
# import pandasimport pandas as pd # create dataframedf = pd.DataFrame({    'Name': ['Mukul', 'Rohit', 'Suraj', 'Rohan', 'Rajan'],    'Course': ['BBA', 'BCA', 'MBA', 'BCA', 'BBA'],    'Roll No': [21, 22, 23, 24, 25]}) # print dataframeprint("\n  ***  Original DataFrames  ** ")display(df)  # create seriess6 = pd.Series(['Vedansh', 'MBA', 29], index=['Name', 'Course', 'Roll No']) # print seriesprint("\n  ***  series  ** ")print(s6) # create dictionariesdicts = [{'Name': 'Aakash', 'Course': 'BCA', 'Roll No': 30}] # print dictionariesprint("\n  **  Dictionary  ** ")print(dicts)  # combined datadf = df.append(dicts, ignore_index=True, sort=False)print("\n  **  Combined Data  **")display(df)
Output:
clintra
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Printing Integer between Strings in Java

Following is the Java program to print integer between Strings −
 Live Demo
public class Demo{
   public static void main(String[] args){
      System.out.println("The equals symbol is present between two integer values ");
      System.out.println(45+5 + "=" +(56+11));
      System.out.println(45+5 + " equals symbol " +(56+11));
   }
}
The equals symbol is present between two integer values
50=67
50 equals symbol 67
A class named Demo contains the main function that prints integer values between two strings.
JavaScript String - bold() Method

This method causes a string to be displayed as bold as if it were in a <b> tag.
The syntax for bold() method is as follows −
string.bold( )

Returns the string with <bold> tag.
Try the following example.
<html>
   <head>
      <title>JavaScript String bold() Method</title>
   </head>
   
   <body>   
      <script type = "text/javascript">
         var str = new String("Hello world");
         alert(str.bold());
      </script>      
   </body>
</html>
<b>Hello world</b>


    25 Lectures 
     2.5 hours 

 Anadi Sharma

    74 Lectures 
     10 hours 

 Lets Kode It

    72 Lectures 
     4.5 hours 

 Frahaan Hussain

    70 Lectures 
     4.5 hours 

 Frahaan Hussain

    46 Lectures 
     6 hours 

 Eduonix Learning Solutions

    88 Lectures 
     14 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page