code-rag-bench/online-tutorials huggingface dataset:
Processing large data files with Python multithreading | by Miguel Albrecht | Towards Data Science

We spend a lot of time waiting for some data preparation task to finish —the destiny of data scientists, you would say. Well, we can speed things up. Here are two techniques that will come handy: memory mapped files and multithreading.
I had recently to extract terms and term frequencies from the Google Books Ngram corpus and found myself wondering if there are ways to speed up the task. The corpus consists of twenty-six files totalling 24GB of data. Each of the files I was interested in contains a term and other meta data, tab separated. The brute force approach of reading these files as pandas data frames was ... slow. Since we wanted only the unique terms and their match counts, I thought I would try to make it faster :-)
This technique is not new. It has been around for a long time and originated in Unix (before Linux!). Briefly, mmap bypasses the usual I/O buffering by loading the contents of a file into pages of memory. This works very well for computers with large memory footprints. That’s mostly OK with today’s desktops and laptops where having 32GB of memory is not anymore in the esoteric department. The Python library mimics most of the Unix functionality and offers a handy readline() function to extract the bytes one line at a time.
# map the entire file into memorymm = mmap.mmap(fp.fileno(), 0)# iterate over the block, until next newlinefor line in iter(mm.readline, b""):    # convert the bytes to a utf-8 string and split the fields    term = line.decode("utf-8").split("\t")
The fp is a file-pointer that was previously opened with the r+b access attribute. There you go, with this simple tweak you have made file reading twice as fast (well, the exact improvement will depend on a lot of things such as disk HW, etc).
The next technique that always helps in making things faster is adding parallelism. In our case, the task was I/O bound. That is a good fit for scaling-up —i.e. adding threads. You will find good discussions on when it is better to scale-out (multi-processing) on search engines.
Python3 has a great standard library for managing a pool of threads and dynamically assign tasks to them. All with an incredibly simple API.
# use as many threads as possible, default: os.cpu_count()+4with ThreadPoolExecutor() as threads:   t_res = threads.map(process_file, files)
The default value of max_workers for ThreadPoolExecutor is 5 threads per CPU core (as of Python v3.8). The map()API will receive a function to be applied to each member of a list and will run the function automatically when threads become available. Wow. That simple. In less than fifty minutes I had converted the 24GB input into a handy 75MB dataset to be analysed with pandas—voilà.
The complete code is on GitHub. Comments and remarks are always welcome.
PS: I added a progress bar with tqdm for each thread. I really don’t know how they manage to avoid scrambling of the lines on the screen ... It works like a charm.
UPDATE: Two years later, this came up :-)
No rights reserved
 by the author.
Database Backup from MySQL - GeeksforGeeks

19 Nov, 2019
Here, The database creating now a day is very important for daily work. The database creates from the MySQL that can be transferred from one system to another and also make it secure from the destroy. Sometimes the system gets corrupted by some faults, so the created database is clear. So there is an option to create a backup of a database from the MySQL wamp server.
The following is the step to create the backup from the wamp server:
Go to the c drive.Open the Wamp server name folder.Open the folder named bin, then open folder the MySQL.Now open the folder mysql5.7.19 (here, 5.7.19 is the version of the wamp server, there is some different version but you should go on that folder only).Then again open the bin folder.Then on the upper, on the address section just type CMD and Enter.
Go to the c drive.
Open the Wamp server name folder.
Open the folder named bin, then open folder the MySQL.
Now open the folder mysql5.7.19 (here, 5.7.19 is the version of the wamp server, there is some different version but you should go on that folder only).
Then again open the bin folder.
Then on the upper, on the address section just type CMD and Enter.
Then there is command prompt open with the address of the following step you follow. Then type,
mysqldump -u root -p harshitdb >harshitbackup.sql 
Here, the harshitdb mean the harshit is the database name which created and the db means database. after that, it creates the database and that you be to share and that was save from corrupted or from loss.
There is following address link to open the cmd (command prompt)
C:\wamp\bin\mysql\mysql5.7.19\bin>mysqldump -u root -p harshitdb > harshitbackup.sql 
Then press enter.
mysql
SQLmysql
SQL
Web Technologies
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Trigger | Student Database
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
SQL Interview Questions
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
JavaScript Remainder(%) Operator - GeeksforGeeks

22 Apr, 2021
Remainder operator is JavaScript is used to get the remaining value when an operand is divided by another operand. In some languages, % is considered as modulo. Modulo and Remainder work differently when the sign of both the operand is different.
In JavaScript remainder takes the sign of the dividend and to get modulo ((a % n) + n) % n should be used instead of a % n.
Syntax
remainder = var1 % var2
Example 1: This example returns the positive remainder in this case both modulo and remainder will be the same as both operands are positive.
Javascript
<script>    // Initializing variables    var a =4    var n = 2         // Calculating remainder    var rem = a%n         // Calculating modulo    var mod = ((a%n)+n)%n         // Printing result    console.log("Remainder is "+rem)    console.log("Modulo is "+mod)</script>
Output:
"Remainder is 0"
"Modulo is 0"
Example 2: This example returns negative remainder as dividend is negative.
Javascript
<script>    // Initializing variables    var a =-4    var n = 2         // Calculating remainder    var rem = a%n         // Calculating modulo    var mod = ((a%n)+n)%n         // Printing result    console.log(rem)    console.log(mod)</script>
Output:
-0
0
Example 3: Remainder with Infinity and NaN
Javascript
<script>    // Both operands are NaN    console.log(NaN%NaN)         // Dividend is NaN    console.log(NaN%2)         // Dividend is Nan and Divisor is Infinity    console.log(NaN%Infinity)         // Dividend is Infinity and Divisor is NaN    console.log(Infinity%NaN)         // Both operands are Infinity    console.log(Infinity%Infinity)         // Dividend is infinity    console.log(Infinity%5)</script>
Output:
> NaN
> NaN
> NaN
> NaN
> NaN
> NaN
arorakashish0911
javascript-operators
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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
Python PIL | ImageOps.expand() method

16 Sep, 2021
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. the ImageOps module contains a number of ‘ready-made’ image processing operations. This module is somewhat experimental, and most operators only work on L and RGB images.ImageOps.expand() adds a border to the image upon which this function is called or used. 
Syntax: PIL.ImageOps.expand(image, border = 0, fill = 0)Parameters: image : The image to size and crop. border : The border to be applied to the image in pixels. fill: This defines the pixel fill value or color value to be applied. The default value is 0 which means the color is black.Returns: An image with the required border.  
Below is the implementation of ImageOps.expand()Image used:  
 
Python3
# Importing Image and ImageOps module from PIL packagefrom PIL import Image, ImageOps     # creating a image1 objectim1 = Image.open(r"C:\Users\System-Pc\Desktop\a.jpg")     # applying expand method# using border value = 20# using fill = 50 which is brown type colorim2 = ImageOps.expand(im1, border = 20, fill = 50) im2.show()
Output:  
 
simmytarika5
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python
HTML <label> for Attribute

21 Jun, 2022
The HTML <label> for Attribute is used to specify the type of form element a label is bound to. 
Syntax:
<label for="element_id">
Attribute Values: It contains the value i.e element_id which specify the id of the element that the label is bound to. 
Example: This Example that illustrates the use of for attribute in <label> element. 
html
<!-- HTML code to illustrates label tag --><!DOCTYPE html><html> <head>    <title>        HTML | for Attribute    </title>     <style>        body {            font-size: 20px;        }    </style></head> <body style="text-align:center">     <h1 style="color:green">    GeeksforGeeks</h1>    <h2>      HTML | &lt;label&gt;for Attribute  </h2>     <form>         <!-- Starts label tag from here -->        <label for="student">            Student        </label>        <input type="radio"               name="Occupation"               id="student"               value="student">        <br>         <label for="business">            Business        </label>        <input type="radio"               name="Occupation"               id="business"               value="business">        <br>         <label for="other">            Other        </label>        <!-- Ends label tags here -->         <input type="radio"               name="Occupation"               id="other"               value="other">    </form></body> </html>
Output:
  
Supported Browsers: The browser supported by HTML | <label>for Attribute are listed below:
Google Chrome 
Edge version 12 and above
Internet Explorer 
Firefox
Opera 
Safari 
satyamm09
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
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
When to use the readAllBytes() method of InputStream in Java 9?

Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown.
The reallAllBytes() method can't automatically close the InputStream instance. When it can reach the end of a stream, the further invocations of this method can return an empty byte array. We can use this method for simple use cases where it is convenient to read all bytes into a byte array and not intended for reading input streams with a large amount of data.
public byte[] readAllBytes() throws IOException
In the below example, we have created a "Technology.txt" file in a "C:\Temp" folder with simple data: { "JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"}.
import java.nio.*;
import java.nio.file.*;
import java.io.*;
import java.util.stream.*;
import java.nio.charset.StandardCharsets;

public class ReadAllBytesMethodTest {
   public static void main(String args[]) {
      try(InputStream stream = Files.newInputStream(Paths.get("C://Temp//Technology.txt"))) {
         // Convert stream to string
         String contents = new String(stream.readAllBytes(), StandardCharsets.UTF_8);

         // To print the string content
         System.out.println(contents);
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}
"JAVA", "PYTHON", "JAVASCRIPT", "SELENIUM", "SCALA"
Draw Concentric Circles with VIBGYOR Using Turtle in Python

20 Oct, 2020
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc.
Following steps are used :
Importing turtle module
Set a screen
Make Turtle object
Define a method for circle with dynamic radius and colour.
Write text by setting turtle object at required position.
Below is the implementation :
Python3
# import turtle packageimport turtle # Screen objectsc = turtle.Screen() # Screen background colorsc.bgcolor('black') # turtle objectpen = turtle.Turtle() # turtle widthpen.width(4)  # function to draw a circle of# rad radius and col colordef circle(col, rad, val):       pen.color(col)    pen.circle(rad)    pen.up()         # set position for space    pen.setpos(0, val)    pen.down()  # function to write text# by setting positionsdef text():       pen.color('white')    pen.up()    pen.setpos(-100, 140)    pen.down()    pen.write("Concentric VIBGYOR",              font = ("Verdana", 15))    pen.up()    pen.setpos(-82, -188)    pen.down()    pen.write("Using Turtle Graphics",              font = ("Verdana", 12))    pen.hideturtle()  # Driver code if __name__ == "__main__" :     # VIBGYOR color list    col = ['violet', 'indigo', 'blue',         'green', 'yellow', 'orange',         'red']   # 7 Concentric circles  for i in range(7):           # function call      circle(col[i], -20*(i+1), 20*(i+1))   # function call  text()
Concentric Vibgyor
pulkitagarwal03pulkit
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to generate a random phone number using Python?

27 Mar, 2021
In this article, we will learn how to generate a random phone number using Python. In general, Indian phone numbers are of 10 digits and start with 9, 8, 7, or 6.
Approach:
We will use the random library to generate random numbers.
The number should contain 10 digits.
The first digit should start with 9 or 8 or 7 or 6, we will use randint() method.
The remaining 9 digits will also be generated using the randint() method.
Examples:
The generated random phone numbers would looklike:
9980231467
8726189362
Implementation:
Python3
# import moduleimport random as r  ph_no = []  # the first number should be in the range of 6 to 9ph_no.append(r.randint(6, 9))  # the for loop is used to append the other 9 numbers.# the other 9 numbers can be in the range of 0 to 9.for i in range(1, 10):    ph_no.append(r.randint(0, 9))  # printing the numberfor i in ph_no:    print(i, end="")
Output:
8349603502
Python-random
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
Java - The LinkedHashSet Class

This class extends HashSet, but adds no members of its own.
LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set.
That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted.
The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically.
Following is the list of constructors supported by the LinkedHashSet.
HashSet( )
This constructor constructs a default HashSet.
HashSet(Collection c)
This constructor initializes the hash set by using the elements of the collection c.
LinkedHashSet(int capacity)
This constructor  initializes the capacity of the linkedhashset to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
LinkedHashSet(int capacity, float fillRatio)
This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments.
The following program illustrates several of the methods supported by LinkedHashSet −
import java.util.*;
public class HashSetDemo {

   public static void main(String args[]) {
      // create a hash set
      LinkedHashSet hs = new LinkedHashSet();
      
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      System.out.println(hs);
   }
}
This will produce the following result −
[B, A, D, E, C, F]
Python | Add one string to another

22 May, 2019
Concatenation of two strings have been discussed multiple times over various languages. But the task of adding one string to other is quite easy task in Python. Knowledge of performing this task has many application. Let’s discuss certain ways in which this can be performed.
Method #1 : Using += operator
This operator can be used to perform this particular task of concatenating the string. This is quite simpler than the traditional methods that are employed in other languages, like using a dedicated function to perform this particular task.
# Python code to demonstrate# Adding one string to another# Using += operator  # initializing string test_string = "GFG"  # initializing add_stringadd_string = " is best"  # printing original string print("The original string : " + str(test_string))  # printing original add string print("The add string : " + str(add_string))  # Using += operator# adding one string to another test_string += add_string  # print resultprint("The concatenated string is : " + test_string)
The original string : GFG
The add string :  is best
The concatenated string is : GFG is best

 
Method #2 : Using join()
One can also perform this very task of the concatenation of string using the join function. The advantage this method holds over the above method is when we have many strings to concatenate rather than just two.
# Python code to demonstrate# Adding one string to another# Using join()  # initializing string test_string = "GFG"  # initializing add_stringadd_string = " is best"  # printing original string print("The original string : " + str(test_string))  # printing original add string print("The add string : " + str(add_string))  # Using join()# adding one string to another res = "".join((test_string, add_string))  # print resultprint("The concatenated string is : " + res)
The original string : GFG
The add string :  is best
The concatenated string is : GFG is best

Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
ReactJS - Props Overview

The main difference between state and props is that props are immutable. This is why the container component should define the state that can be updated and changed, while the child components should only pass data from the state using props.
When we need immutable data in our component, we can just add props to reactDOM.render() function in main.js and use it inside our component.
import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.headerProp}</h1>
            <h2>{this.props.contentProp}</h2>
         </div>
      );
   }
}
export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App headerProp = "Header from props..." contentProp = "Content
   from props..."/>, document.getElementById('app'));

export default App;
This will produce the following result.
You can also set default property values directly on the component constructor instead of adding it to the reactDom.render() element.
import React from 'react';

class App extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.headerProp}</h1>
            <h2>{this.props.contentProp}</h2>
         </div>
      );
   }
}
App.defaultProps = {
   headerProp: "Header from props...",
   contentProp:"Content from props..."
}
export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));
Output is the same as before.
The following example shows how to combine state and props in your app. We are setting the state in our parent component and passing it down the component tree using props. Inside the render function, we are setting headerProp and contentProp used in child components.
import React from 'react';

class App extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
         header: "Header from props...",
         content: "Content from props..."
      }
   }
   render() {
      return (
         <div>
            <Header headerProp = {this.state.header}/>
            <Content contentProp = {this.state.content}/>
         </div>
      );
   }
}
class Header extends React.Component {
   render() {
      return (
         <div>
            <h1>{this.props.headerProp}</h1>
         </div>
      );
   }
}
class Content extends React.Component {
   render() {
      return (
         <div>
            <h2>{this.props.contentProp}</h2>
         </div>
      );
   }
}
export default App;
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));
The result will again be the same as in the previous two examples, the only thing that is different is the source of our data, which is now originally coming from the state. When we want to update it, we just need to update the state, and all child components will be updated. More on this in the Events chapter.
Getting cosine and hyperbolic cosine in Julia – cos(), cosh() and cosd() Methods

26 Mar, 2020
The cos() is an inbuilt function in julia which is used to calculate cosine of the specified radian values.
Syntax: cos(x)
Parameters:
x: Specified radian values.
Returns: It returns the calculated cosine of the specified radian values.
Example:
# Julia program to illustrate # the use of cos() method  # Getting cosine of the specified# radian values.println(cos(0))println(cos(30))println(cos(90))println(cos(44))
Output:
1.0
0.15425144988758405
-0.4480736161291702
0.9998433086476912
The cosh() is an inbuilt function in julia which is used to calculate hyperbolic cosine of the specified values.
Syntax: cosh(x)
Parameters:
x: Specified values.
Returns: It returns the calculated hyperbolic cosine of the specified values.
Example:
# Julia program to illustrate # the use of cosh() method  # Getting cosine of the specified values.println(cosh(0))println(cosh(30))println(cosh(90))println(cosh(45))
Output:
1.0
5.343237290762231e12
6.102016471589204e38
1.7467135528742547e19
The cosd() is an inbuilt function in julia which is used to calculate cosine of the specified value in degrees.
Syntax: cosd(x)
Parameters:
x: Specified value in degrees.
Returns: It returns the calculated cosine of the specified value in degrees.
Example:
# Julia program to illustrate # the use of cosd() method  # Getting cosine of the specified value # in degreeprintln(cosd(0))println(cosd(30))println(cosd(90))println(cosd(45))
Output:
1.0
0.8660254037844386
0.0
0.7071067811865476
Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Exception handling in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Get number of elements of array in Julia - length() Method
Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)
NamedTuple in Julia
Find maximum element along with its index in Julia - findmax() Method
Searching in Array for a given element in Julia
Difference Between MATLAB and Julia
Getting the maximum value from a list in Julia - max() Method
Join an array of strings into a single string in Julia - join() Method
Difference between 2NF and 3NF in DBMS

02 Aug, 2021
1. Second Normal Form (2NF) : A relation is said to be in second normal form when it is already in first normal form and there is no partial functional dependency that is no non-prime attribute should be functionally dependent on prime attribute. It was given by E.F Codd in 1971. If the candidate key comprises of only single attribute and relation is in 1NF then it is already in 2NF. The concept of checking relation for 2NF applies when there is composite candidate key that is candidate key comprises of more than one attribute. 
Example: Consider a relation R(A, B, C, D) with functional dependencies: {AB–>CD, BC–>D}  
Closure of (AB)={A, B, C, D} 
So AB is a candidate key. The relation R is in 1NF as relational DBMS does not allow multi-valued or composite attribute. In AB–>CD (AB is candidate key and C, D is non-prime) In BC–>D (BC is non-prime and D is non-prime which is allowed in 2NF) The relation R is in 2NF as no prime attribute is deriving non prime attribute that is there is no partial functional dependency. The relation R is not in 3NF as non-prime attribute is deriving non-prime attribute. 
2. Third Normal Form (3NF) : A relation is said to be in third normal form when it is already in first normal and second normal forms and every non prime attribute is non-transitively dependent on superkey of relation or in simple language there is no transitive functional dependency. It was also given by E.F Codd in 1971. In this form duplication of data is reduced and referential integrity is ensured. A relation R having functional dependency A–>B is in 3NF if either of the conditions given below are true .  
A is a superkey.  B is prime attribute, that is B is the part of candidate key.  
A is a superkey.  
B is prime attribute, that is B is the part of candidate key.  
Example:- Consider a relation R(A, B, C) having functional dependency {AB–>C, C–>A} 
Closure of (AB)={A, B, C}
Closure of (BC)={A, B, C}
Candidate keys are-{AB, BC} 
The relation R is in 1NF as relational DBMS does not allow multi-valued or composite attribute.  
AB-->C(prime deriving prime)
C-->A(prime deriving prime)
So the relation R is in 2NF and in 3NF also because there is no prime deriving non-prime and no non-prime deriving non-prime that is there is no partial functional dependency and no transitive functional dependency. 
Difference between 2NF and 3NF :  
 
simmytarika5
Picked
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
Difference between Clustered and Non-clustered index
Introduction of DBMS (Database Management System) | Set 1
Introduction of B-Tree
SQL Trigger | Student Database
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Class getCanonicalName() method in Java with Examples

25 Jan, 2022
The getCanonicalName() method of java.lang.Class class is used to get the canonical name of this class, which is the canonical name as defined by the Java Language Specification. The method returns the canonical name of this class in the form of String. Syntax:  
public String getCanonicalName()
Parameter: This method does not accept any parameter.Return Value: This method returns the canonical name of this class in the form of String. Below programs demonstrate the getCanonicalName() method.Example 1: 
Java
// Java program to demonstrate getCanonicalName() method import java.util.*; public class Test {    public static void main(String[] args)        throws ClassNotFoundException    {         // returns the Class object for this class        Class myClass = Class.forName("Test");         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the canonical name of myClass        // using getCanonicalName() method        System.out.println("CanonicalName of myClass: "                           + myClass.getCanonicalName());    }}
Output:  
Class represented by myClass: class Test
CanonicalName of myClass: Test
Example 2: 
Java
// Java program to demonstrate getCanonicalName() method import java.util.*; class Main {     public Object obj;     Main()    {         class Arr {        };         obj = new Arr();    }     public static void main(String[] args)        throws ClassNotFoundException    {        Main t = new Main();         // returns the Class object        Class myClass = t.obj.getClass();         System.out.println("Class represented by myClass: "                           + myClass.toString());         // Get the canonical name of myClass        // using getCanonicalName() method        System.out.println("CanonicalName of myClass: "                           + myClass.getCanonicalName());    }}
Output:  
Class represented by myClass: class Main$1Arr
CanonicalName of myClass: null
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getCanonicalName– 
adnanirshad158
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Resize a SVG image ?

02 Mar, 2021
Resizing an SVG image cannot be done by simply using CSS height and width property to the img tag. To resize the SVG image, follow these steps:
Method1: The SVG image will be taking 100% of all the width and height available to it. To make the image of the desired size set the CSS height and width property of the image
Example 1:
CSS
<!DOCTYPE html> <html> <style>   svg{      height: 200px;   }  </style>  <body>     <svg xmlns="http://www.w3.org/2000/svg">             <image href= "https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190710102234/download3.png"        />     </svg> </body>   </html>
Output:
Method 2: Directly modify the .svg file and set the width and height to the desired value. Below is how the XML file will look, if an SVG image is present
<svg height="40px" width="60px" . . . . . . ></svg>
Example 2:
HTML
<!DOCTYPE html><html>    <body>        <h1>My first SVG</h1>          <svg width="40" height="60">            <rect width="40"                   height="60"                   style="fill: rgb(0, 0, 255); stroke-width: 10; stroke: rgb(0, 0, 0);" />        </svg>    </body></html>
Output:
HTML-SVG
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
p5.js | createSlider() Function

09 Jul, 2019
The createSlider() function in p5.js is used to create a slider (input) element in the DOM (Document Object Model). This function includes the p5.dom library. Add the following syntax in the head section.
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.11/addons/p5.dom.min.js"></script>
Syntax:
createSlider( min, max, value, step )
Parameters: This function accepts four parameters as mentioned above and described below:
min: It holds the minimum value of the slider.
max: It holds the maximum value of the slider.
value: It holds the default value of the slider.
step: It holds the step size of the slider.
Below programs illustrates the createSlider() function in p5.js:
Example: This example uses createSlider() function to change the r value of the background-color (in rgb format) using a slider.
// Create a variable for the slider objectvar color_slider;  function setup() {        // Create a canvas of given size    createCanvas(600, 300);          // Create the slider    color_slider = createSlider(0, 255, 125);          // Set the position of slider on the canvas    color_slider.position(150, 200);}  function draw() {        // Get the value of the slider    // using .value() function    col = color_slider.value();          // Set the value of the background-color    background(col, 200, 100);}                    
Output:
Reference: https://p5js.org/reference/#/p5/createSlider
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to specify an index while creating a Series in Pandas?

Pandas series is 1-Dimensional ndarray with labeled data, which means every value present in a series is having a label representation which is nothing but each data have thor on index values.
The index can be label names (object data) or it can be values. By default, it will assign an index value from 0 - n-1 (n is the length of series values). And it has the ability to define index values.
Pandas Series function has an index keyword for specifying index values, and it takes input as an array with any kind of data in it. The data can be integers, floating-point numbers, text data, DateTime, and more.
Let’s see how we can specify index values at the time of Series creation.
import pandas as pd

Countries = ['Australia', 'Iceland', 'India', 'United Kingdom', 'United States']
Capitals = ['Canberra', 'Reykjavik', 'New Delhi', 'London', 'Washington D.C']

# create series
s = pd.Series(Capitals, index=Countries)

print(s)
The expected result of this above code is a pandas Series with labeled index and text data. Here the index values are the list of names of some countries and data is respected capital cities for those countries.
We have created a two-python list for holding country names and capital city names. And sent those two lists pandas Series Contractor (pd.Series() function). Capital city names are Series data and country names are indexes.
Specifying index names can be achieved by assigning a python list (countries list) to the index keyword of the pandas Series function. One thing we should remember here is the length of index data must be the same as the length of series data. Otherwise, it will raise ValueError.
Australia              Canberra
Iceland               Reykjavik
India                 New Delhi
United Kingdom           London
United States    Washington D.C
dtype: object
Both indexes and values present in this above output block are object data types. In the above example, we have specified index labels separately at the time of Series creation.
# importing pandas packages
import pandas as pd

dictionary = {'a':'A','c':"C",'d':'D','e':'E'}

#creating a series with null data
s_obj = pd.Series(dictionary)

print(s_obj)
If we use the python dictionary as data to the pandas Series constructor then it will take keys of the dictionary as indexes and values as elements of the series object.
a   A
c   C
d   D
e   E
dtype: object
We can specify the indexes of a series object by using the keys of the python dictionary.
C Program to check whether the triangle is equilateral, isosceles or scalene

Triangle consists of three sides and three angles. Based on the three sides, there are three types of triangle −
Equilateral triangle: All three sides are equal.
Isosceles triangle: All two sides are equal.
Scalene triangle: No sides are equal.
Follow the algorithm given below for writing the respective program.
Step 1: Declare three sides of triangle.
Step 2: Enter three sides at run time.
Step 3: If side1 == side2 && side2 == side3
Go to step 6
Step 4: If side1 == side2 || side2 == side3 || side3 == side1
Go to Step 7
Step 5: Else
Go to step 8
Step 6: Print the triangle is equilateral.
Step 7: Print the triangle is isosceles.
Step 8: Print the triangle is scalene.
Following is the C program to check whether the triangle is equilateral, isosceles or scalene −
 Live Demo
#include<stdio.h>
int main(){
   int side1, side2, side3;
   printf("Enter sides of triangle:");
   scanf("%d%d%d",&side1,&side2,&side3);
   if(side1 == side2 && side2 == side3)
      printf("The Given Triangle is equilateral\n");
   else if(side1 == side2 || side2 == side3 || side3 == side1)
      printf("The given Triangle is isosceles\n");
   else
      printf("The given Triangle is scalene\n");
   return 0;
}
Let us compile and run the above program that will produce the following result −
Run1:
Enter sides of triangle:3 4 6
The given Triangle is scalene
Run2 :
Enter sides of triangle:2 2 5
The given Triangle is isosceles
Run 3:
Enter sides of triangle:5 5 5
The Given Triangle is equilateral
GATE | GATE CS 2020 | Question 27 - GeeksforGeeks

26 May, 2021
Let R be the set of all binary relations on the set {1, 2, 3}. Suppose a relation is chosen from R at random. The probability that the chosen relation is reflexive (round off to 3 decimal places) is ________ .
Note – This question was Numerical Type.(A) 0.125(B) 0.25(C) 0.50(D) 0.625Answer: (A)Explanation: The probability that the chosen relation is reflexive on a set with n elements:
= (number of reflexive relations) / (total number of relations)
= (2n2-n) / (2n2) 
Given, size (number of elements) of set is 3 (i.e., {1, 2, 3}). Therefore,
= (232-3) / (232) 
= (26) / (29)
= 1 / (23)
= 1 / 8
= 0.125 
Option (A) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Mongoose | insertMany() Function - GeeksforGeeks

20 May, 2020
The insertMany() function is used to insert multiple documents into a collection. It accepts an array of documents to insert into the collection.
Installation of mongoose module:
You can visit the link Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js
You can visit the link Install mongoose module. You can install this package by using this command.npm install mongoose
npm install mongoose
After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose
npm version mongoose
After that, you can just create a folder and add a file for example index.js, To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
const mongoose = require('mongoose');  // Database connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks', {    useNewUrlParser: true,    useCreateIndex: true,    useUnifiedTopology: true});  // User modelconst User = mongoose.model('User', {    name: { type: String },    age: { type: Number }});  // Function callUser.insertMany([    { name: 'Gourav', age: 20},    { name: 'Kartik', age: 20},    { name: 'Niharika', age: 20}]).then(function(){    console.log("Data inserted")  // Success}).catch(function(error){    console.log(error)      // Failure});
Steps to run the program:
The project structure will look like this:Make sure you have install mongoose module using following command:npm install mongooseRun index.js file using below command:node index.jsAfter running above command, your can see the data is inserted into the database. You can use any GUI tool or terminal to see the database, like I have used Robo3T GUI tool as shown below:
The project structure will look like this:
Make sure you have install mongoose module using following command:npm install mongoose
npm install mongoose
Run index.js file using below command:node index.js
node index.js
After running above command, your can see the data is inserted into the database. You can use any GUI tool or terminal to see the database, like I have used Robo3T GUI tool as shown below:
So this is how you can use mongoose insertMany() function to insert multiple documents into the collection in MongoDB and Node.js.
Mongoose
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Aggregation in MongoDB
Mongoose Populate() Method
MongoDB - Check the existence of the fields in the specified collection
How to build a basic CRUD app with Node.js and ReactJS ?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
How to remove n elements from the end of a given array in JavaScript ? - GeeksforGeeks

01 Apr, 2021
In this article, we will learn how to remove the last n elements from the end of the given array in JavaScript. This can be achieved using two approaches:
The splice() method in JavaScript is used to modify an array by adding or removing elements from it. This method accepts the index from which the modification has to be made and the number of elements to delete. The index from which the deletion has to start can be found out by subtracting the number of elements from the length of the array. 
Syntax:
array.splice(start, deleteCount);
Example:
HTML
<html>  <body>    <h1 style="color: green;">      GeeksforGeeks    </h1>    <b>      How to remove n elements from the end      of a given array in JavaScript?    </b>    <script>        // Define the array      let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];        console.log("Original Array:", arr);        // Define the number of elements to remove      let elemsToDelete = 3;        // Using the splice() method to remove from      // the last nth index for n elements      arr.splice(arr.length - elemsToDelete,                 elemsToDelete);        console.log("Modified Array:", arr);    </script>  </body></html>
Output:
Original Array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Modified Array: [1, 2, 3, 4, 5, 6]
The pop() method in JavaScript is used to remove the last element from the array. This can be repeated in a loop of n iterations to remove the last n elements of the array using the while loop.
Syntax:
array.pop();
Example:
HTML
<html>  <body>    <h1 style="color: green;">      GeeksforGeeks    </h1>    <b>      How to remove n elements from the end      of a given array in JavaScript?    </b>    <script>        // Define the array      let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];        console.log("Original Array:", arr);        // Define the number of elements to remove      let elemsToDelete = 5;        // Loop for the number of elements      // to delete      while (elemsToDelete--)          // Pop the last element from the        // end of the array        arr.pop();        console.log("Modified Array:", arr);    </script>  </body></html>
Output:
Original Array: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Modified Array: [1, 2, 3, 4]
javascript-array
JavaScript-Methods
JavaScript-Questions
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
Remove elements from a Dictionary using Javascript

To remove an element from the dictionary, we first need to check if it exists in the dictionary.
We'll use the hasKey method for that. Then we can directly delete it using the delete operator.
We'll return a Boolean so that the place where we call this method can know whether the key already existed or not in the dictionary. 
delete(key) {
   if(this.hasKey(key)) {
      delete this.container[key];
      return true;
   }
   return false;
}
You can test this using − 
const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");

myMap.display(); myMap.delete("key2");

myMap.display();
This will give the output −
{ key1: 'value1', key2: 'value2' }
{ key1: 'value1' }
In ES6, you have the delete method to remove values from the map. For example, 
const myMap = new Map([
   ["key1", "value1"],
   ["key2", "value2"]
]);
myMap.delete("key2");

console.log(myMap.has("key1"))
console.log(myMap.has("key2"))
This will give the output −
True
False