code-rag-bench/online-tutorials huggingface dataset:
How to traceroute using PowerShell?

Traceroute is the way to determine the hopes that the packets are passing through when requested. In the command prompt, that utility is called the tracert and we can also use that utility to trace the network packets. For example,
PS C:\> tracert google.com
Tracing route to google.com [216.58.203.142]
over a maximum of 30 hops:
1    1 ms    1 ms    1 ms 192.168.0.1
2    2 ms    2 ms    2 ms 45.114.51.246
3    8 ms    4 ms    4 ms 103.210.200.141
4    21 ms   *       * 10.10.125.29
5    6 ms    6 ms    6 ms 72.14.196.213
6    14 ms   26 ms   25 ms 108.170.248.161
7    11 ms   7 ms    6 ms 209.85.248.27
8    6 ms    6 ms    6 ms bom05s10-in-f142.1e100.net [216.58.203.142]
Trace complete.
The above example shows there is a total of 8 intermediate hops that the packet passes through to resolve the destination address.
We can also use the above utility for the local servers.
PS C:\Users\Administrator> tracert AD Tracing route to AD.automationlab.local [192.168.0.200]
over a maximum of 30 hops:
1 <1 ms <1 ms <1 ms AD [192.168.0.200] Trace complete.
Another method to determine the network packet route is through the Test-NetConnection command which supports the TraceRoute parameter.
PS C:\> Test-NetConnection -ComputerName google.com -TraceRoute
ComputerName           : google.com
RemoteAddress          : 172.217.167.174
InterfaceAlias         : Ethernet0
SourceAddress          : 192.168.0.200
PingSucceeded          : True
PingReplyDetails (RTT) : 5 ms
TraceRoute             : 192.168.0.1
                         45.114.51.246
                         0.0.0.0
                         0.0.0.0
                         72.14.196.213
                         108.170.248.161
                         108.170.232.203
                         172.217.167.174
This is the advanced utility and we can also set the maximum number of hops to pass. For example,
PS C:\> Test-NetConnection -ComputerName google.com -TraceRoute -Hops 2
WARNING: Trace route to destination 172.217.167.174 did not complete. Trace terminated :: 45.114.51.246
ComputerName           : google.com
RemoteAddress          : 172.217.167.174
InterfaceAlias         : Ethernet0
SourceAddress          : 192.168.0.200
PingSucceeded          : True
PingReplyDetails (RTT) : 6 ms
TraceRoute             : 192.168.0.1
                         45.114.51.246
To get only traceroute hopes, you can select the TraceRoute parameter.
Test-NetConnection -ComputerName google.com -TraceRoute | Select -ExpandProperty
TraceRoute
Need of Concurrent Collections in java

08 Jan, 2018
As we already know Collections which is nothing but collections of Objects where we deals with the Objects using some pre-defined methods. But There are several problems which occurs when we use Collections concept in multi-threading. The problems which occurs while using Collections in Multi-threaded application:
Most of the Collections classes objects (like ArrayList, LinkedList, HashMap etc) are non-synchronized in nature i.e. multiple threads can perform on a object at a time simultaneously. Therefore objects are not thread-safe.
Very few Classes objects (like Vector, Stack, HashTable) are synchronized in nature i.e. at a time only one thread can perform on an Object. But here the problem is performance is low because at a time single thread execute an object and rest thread has to wait.
The main problem is when one thread is iterating an Collections object then if another thread cant modify the content of the object. If another thread try to modify the content of object then we will get RuntimeException saying ConcurrentModificationException.
Because of the above reason Collections classes is not suitable or we can say that good choice for Multi-threaded applications.
To overcome the above problem SUN microSystem introduced a new feature in JDK 1.5Version, which is nothing but Concurrent Collections.
// Java program to illustrate Concurrent// Collection needimport java.util.*;class ConcurrentDemo extends Thread {    static ArrayList l = new ArrayList();    public void run()    {        try {            Thread.sleep(2000);        }        catch (InterruptedException e) {            System.out.println("Child Thread" +                       " going to add element");        }          // Child thread trying to add new        // element in the Collection object        l.add("D");    }      public static void main(String[] args)                    throws InterruptedException    {        l.add("A");        l.add("B");        l.add("c");          // We create a child thread that is         // going to modify ArrayList l.        ConcurrentDemo t = new ConcurrentDemo();        t.start();          // Now we iterate through the ArrayList        // and get exception.        Iterator itr = l.iterator();        while (itr.hasNext()) {            String s = (String)itr.next();            System.out.println(s);            Thread.sleep(6000);        }        System.out.println(l);    }}
Output:Exception in thread “main” java.util.ConcurrentModificationException
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Initialize an ArrayList in Java
How to modify the size of column in MySQL table?

We can modify a column size with the help of ALTER command. Let us see how to modify
column size. Suppose we are defining any column with some size. At the time of inserting if we
are giving more size in comparison to the one we defined, then an error will generate.
The above problem can be reduced while modifying the size. For more understanding, we can
create a table with the help of CREATE command −
mysql> CREATE table ModifyColumnNameDemo
-> (
-> id int,
-> StudentName varchar(10)
-> );
Query OK, 0 rows affected (0.45 sec)
After creating a table successfully,we can insert records into the table with the help of INSERT
command.
mysql> INSERT into ModifyColumnNameDemo values(1,'CarolTaylor');
ERROR 1406 (22001): Data too long for column 'StudentName' at row 1
From the above query, we are getting the error 1406. This error can be resolved while modifying
column. We can use the ALTER command for this. The following is the syntax −
ALTER table yourTableName modify column_name;
Applying the above query to modify the size of column to some size −
mysql> ALTER table ModifyColumnNameDemo modify StudentName varchar(200);
Query OK, 0 rows affected (1.54 sec)
Records: 0 Duplicates: 0 Warnings: 0
After that we can check that the size of column name ‘StudentName’ is size 200.The query is as
follows −
mysql> DESC ModifyColumnNameDemo;
The following is the output −
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
|id | int(11) | YES          |      | NULL|         |
| StudentName | varchar(200) | YES  |     | NULL    |       |
+-------------+--------------+------+-----+---------+-------+
2 rows in set (0.04 sec)
Look at the StudentName column above, the size has been changed to 200. Now we can insert
a record into the table and we won’t get any error. Let’s check −
mysql> INSERT into ModifyColumnNameDemo values(1,'CarolTaylor');
Query OK, 1 row affected (0.14 sec)
The above record have been inserted into the table successfully. We can display the record
inserted above with the help of SELECT command −
mysql> SELECT * from ModifyColumnNameDemo;
The following is the output −
| id | StudentName |
+------+-------------+
| 1 | CarolTaylor|
+------+-------------+
1 row in set (0.00 sec)
Look at the above output, the record has been inserted successfully after modifying the size of
column.
HTML <canvas> Tag

17 Mar, 2022
The <canvas> tag in HTML is used to draw graphics on a web page using JavaScript. It can be used to draw paths, boxes, texts, gradients, and adding images. By default, it does not contain borders and text. 
Note: The <canvas> tag is new in HTML5.
Syntax: 
<canvas id = "script"> Contents... </canvas>
Attributes: The tag accepts two attributes as mentioned above and described below.
height: This attribute is used to set the height of the canvas.
width: This attribute is used to set the width of the canvas.
Example 1: 
HTML
<!DOCTYPE html><html>    <body>                  <!-- canvas Tag starts here -->        <canvas id = "GeeksforGeeks" width = "200"             height = "100" style = "border:1px solid black">        </canvas>        <!-- canvas Tag ends here -->              </body></html>
Output:  
Example 2: 
HTML
<!DOCTYPE html><html>          <body>        <!-- HTML code to illustrate canvas tag -->        <canvas id = "geeks" height = "200" width = "200"            style = "border:1px solid black">        </canvas>                  <script>            var c = document.getElementById("geeks");            var cx = c.getContext("2d");            cx.beginPath();            cx.arc(100, 100, 90, 0, 2 * Math.PI);            cx.stroke();        </script>                </body></html>
Output: 
Example 3: 
HTML
<!DOCTYPE html><html>    <body>                  <!-- canvas tag starts here -->        <canvas id = "geeks" width = "200" height = "200"            style = "border:1px solid black">        </canvas>        <!-- canvas tag ends here -->                  <script>            var c=document.getElementById("geeks");            var cx = c.getContext("2d");            var grd = cx.createRadialGradient(100,                             100, 5, 100, 100, 100);            grd.addColorStop(0, "red");            grd.addColorStop(1, "green");            cx.fillStyle = grd;            cx.fillRect(0, 0, 200, 200);        </script>            </body></html>
Output: 
Supported Browsers:  
Google Chrome 4.0
Internet Explorer 9.0
Firefox 2.0
Opera 9.0
Safari 3.1
arorakashish0911
shubhamyadav4
HTML-Tags
Picked
HTML
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
What is ‘this’ reference in Java?

The this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.
Using “this” you can −
Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
class Student {
   int age;
   Student(int age) {
      this.age = age;
   }
}
Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
class Student {
   int age
   Student() {
      this(20);
   }
   Student(int age) {
      this.age = age;
   }
}
 Live Demo
public class This_Example {
   // Instance variable num
   int num = 10;
   This_Example() {
      System.out.println("This is an example program on keyword this");
   }
   This_Example(int num) {
      // Invoking the default constructor
      this();
      // Assigning the local variable num to the instance variable num
      this.num = num;
   }
   public void greet() {
      System.out.println("Hi Welcome to Tutorialspoint");
   }
   public void print() {
      // Local variable num
      int num = 20;
      // Printing the local variable
      System.out.println("value of local variable num is : "+num);
      // Printing the instance variable
      System.out.println("value of instance variable num is : "+this.num);
      // Invoking the greet method of a class
      this.greet();
   }
   public static void main(String[] args) {
      // Instantiating the class
      This_Example obj1 = new This_Example();
      // Invoking the print method
      obj1.print();
      // Passing a new value to the num variable through parametrized constructor
      This_Example obj2 = new This_Example(30);
      // Invoking the print method again
      obj2.print();
   }
}
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint
How to Convert Data URI to File then append to FormData?

07 May, 2020
A data URI is a base64 encoded string that represents a file (i.e., instead of specifying the URL of the file, you can insert the content of the file in a webpage). When a browser encounters a URI, it decodes and constructs the original file. DataURIs are most commonly used on the web for images. When a webpage wants a file from another webpage, the URI of the file can be conveniently shared by the FormData object which can take the URI as a (key, value) pair and sends it using XMLHttpRequest.
Example:
Input: 1. DataURI for a file.
       2. fileName. // To store the file
Output: fileName - [ObjectFile]
Procedure: This process can be completed in 3 steps.
Step 1: DataURI is taken as the input.URI can be directly given as the input or it can be obtained using the function canvas.toDataURL(type[optional],value for image quality 0 to 1[optional]) in case of canvas object.
Step 2: DataURI is converted into a Blob(Binary Large Object-Stores any kind of data in binary format such as images, audio, and video)object file.
Step 3: Blob object file is appended in FormData object instance {key : value}.
Example: Suppose there is a DataURI for an image of type ‘gif’.Input: URI for an image.Program:
<script type="text/javascript">    var inputURL ="";      var blobObject = blobCreationFromURL(inputURL);      // Create Blob file from URL    function blobCreationFromURL(inputURI) {          var binaryVal;          // mime extension extraction        var inputMIME = inputURI.split(',')[0].split(':')[1].split(';')[0];          // Extract remaining part of URL and convert it to binary value        if (inputURI.split(',')[0].indexOf('base64') >= 0)            binaryVal = atob(inputURI.split(',')[1]);          // Decoding of base64 encoded string        else            binaryVal = unescape(inputURI.split(',')[1]);          // Computation of new string in which hexadecimal        // escape sequences are replaced by the character         // it represents          // Store the bytes of the string to a typed array        var blobArray = [];        for (var index = 0; index < binaryVal.length; index++) {            blobArray.push(binaryVal.charCodeAt(index));        }          return new Blob([blobArray], {            type: inputMIME        });    }      var fdataobj = new FormData();      // Create formdata object and append the object    // file to the name 'Blob file'    fdataobj.append("Blob File", blobObject);      // FormData object content is displayed in alert box.    for (var pair of fdataobj.entries()) {        alert('GeeksforGeeks\n' + pair[0] + '–' + pair[1])    }</script>
Output: The output of the FormData object will be displayed in the alert box as a name and ‘object file’ value pair. The object file can be read using the FileReader object of JavaScript which will read the object file and can be displayed using any of the JavaScript display techniques.
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python - Get a sorted list of random integers with unique elements - GeeksforGeeks

11 May, 2020
Given lower and upper limits, generate a sorted list of random numbers with unique elements, starting from start to end.
Examples:
Input: num = 10, start = 100, end = 200
Output: [102, 118, 124, 131, 140, 148, 161, 166, 176, 180]

Input: num = 5, start = 1, end = 100
Output: [37, 49, 64, 84, 95]

To generate random numbers in Python, randint() function of random module is used.
Syntax:
randint(start, end)

randint() accepts two parameters: a starting point and an ending point. Both should be integers and the first value should always be less than the second.
Below is the implementation.
# Python program to create # a sorted list of unique random # numbers    import random    # Function to generate a sorted list  # of random numbers in a given# range with unique elementsdef createRandomSortedList(num, start = 1, end = 100):    arr = []    tmp = random.randint(start, end)          for x in range(num):                  while tmp in arr:            tmp = random.randint(start, end)                      arr.append(tmp)              arr.sort()          return arr   # Driver's codeprint(createRandomSortedList(10, 100, 200))print(createRandomSortedList(5)))
Output:
[102, 118, 124, 131, 140, 148, 161, 166, 176, 180]
[37, 49, 64, 84, 95]

Python list-programs
Python-Sorted
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
Linear gradient with rainbow color

To create a linear gradient that looks like rainbow color, you can try to run the following code\
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <style>
         #demo {
            height: 100px;
            background: linear-gradient(to right, red,orange,yellow,green,blue,indigo,violet);
         }
      </style>
   </head>
   <body>
      <h2>Linear Gradient</h2>
      <div id = "demo">Rainbow</div><br>
   </body>
</html>
Difference between an Integer and int in Java

A Java both int and Integer are used to store integer type data the major difference between both is type of int is primitive while Integer is of class type.This difference become significant when concept of OOPs comes in picture during development as int follows the principle of primitive data type while Integer behave as a wrapper class.
Following are the important differences between int and Integer.
JavaTester.java
 Live Demo
public class JavaTester {
   public static void main(String args[]){
      Integer a = new Integer("456");
      // Casting not possible
      // int a = (int)"456";
      // Casting not possible
      // int c="456";
      // Casting possible using methods
      // from Integer Wrapper class
      int b = Integer.parseInt("456");
      System.out.print(b);
   }
}
456
Setting null values with an HTML <select> using AngularJS.

To set null values, here is the controller −
function display($scope) {
   $scope.obj ={"selected":null};
   $scope.objects = [{id: 1, value: "Yes"}, {id: 0, value: "No"}]
}
The following is the template −
<div ng-controller = "display">
   <select ng-model = "obj.selected"
      ng-options = "value.id as value.value for value in objects">
      <option value = "">Unknown</option>
   </select>
<br/>
   {{obj}}
</div>
Python 3  - IF Statement

The IF statement is similar to that of other languages. The if statement contains a logical expression using which the data is compared and a decision is made based on the result of the comparison.
if expression:
   statement(s)

If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. In Python, statements in a block are uniformly indented after the : symbol. If boolean expression evaluates to FALSE, then the first set of code after the end of   block is executed.
#!/usr/bin/python3

var1 = 100
if var1:
   print ("1 - Got a true expression value")
   print (var1)

var2 = 0
if var2:
   print ("2 - Got a true expression value")
   print (var2)
print ("Good bye!")
When the above code is executed, it produces the following result −
1 - Got a true expression value
100
Good bye!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
Get the last day of month in Java

The getActualMaximum() method returns the maximum value that the specified calendar field could have, based on the time value of this Calendar.
Import the following package to work with Calendar class in Java,
import java.util.Calendar;
Create a calendar object.
Calendar cal = Calendar.getInstance();
Use the getActualMaximum() method to get the last day of the month.
int res = cal.getActualMaximum(Calendar.DATE);
The following is an example.
 Live Demo
import java.util.Calendar;
public class Main {
   public static void main(String[] args) {
      Calendar cal = Calendar.getInstance();
      int res = cal.getActualMaximum(Calendar.DATE);
      System.out.println("Today's Date = " + cal.getTime());
      System.out.println("Last Date of the current month = " + res);
   }
}
Today's Date = Mon Nov 19 13:48:18 UTC 2018
Last Date of the current month = 30
How to Select single column of a Pandas Dataframe? - GeeksforGeeks

01 Oct, 2020
In this article, we will discuss how to select a single column in a data frame. Now let us try to implement this using Python.
First, let’s create a dataframe 
Python3
# importing pandas as libraryimport pandas as pd    # creating data frame:df = pd.DataFrame({'name': ['Akash', 'Ayush', 'Ashish',                            'Diksha', 'Shivani'],                                        'Age': [21, 25, 23, 22, 18],                                        'Interest': ['Coding', 'Playing', 'Drawing',                                'Akku', 'Swimming']})  print("The original data frame")df
Output:
Method 1: Using Dot(dataframe.columnname) returns the complete selected column 
Python3
# using dot methodprint("Single column value using dataframe.dot")print(df.Interest)
Output:
Method 2: Using dataframe[columnname] method: There are some problems that may occur with using dataframe.dot are as follows: 
Through dot method, we cannot Select column names with spaces. 
Ambiguity may occur when we Select column names that have the same name as methods for example max method of dataframe. 
We cannot Select multiple columns using dot method. 
We cannot Set new columns using dot method.
Because of the above reason dataframe[columnname] method is used widely.
Python3
# using dataframe[columnname]methodprint("Single column value using dataframe[]")print(df['Interest'])
Output:
Another Example now if we want to select the column Age.
Python3
# using dataframe[columnname]methodprint("Single column value using dataframe[]")print(df['Age'])
Output:
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 ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
How to display a directory list in HTML?

Use the dir tag in HTML to display directory list. This is very similar to <ul> tag but do not use <dir> since it is deprecated now.
The following is the attribute −
You can try to run the following code to show a directory list in HTML −
<!DOCTYPE html>
<html>
   <head>
      <title>HTML dir Tag</title>
   </head>
   <body>
      <p>The following are the values:</p>
      <dir>
         <li>car</li>
         <li>bike</li>
         <li>ship</li>
      </dir>
   </body>
</html>
Double.CompareTo Method in C# with Examples

The Double.CompareTo() method in C# is used to compare this instance to a specified object or Double object and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object or Double object.
The syntax is as follows −
public int CompareTo (double val);
public int CompareTo (object val);
Above, the value val in the 1st syntax is a double-precision floating-point number to compare, whereas val for the 2nd syntax is an object to compare.
Let us now see an example −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      double d1 = 150d;
      double d2 = 150d;
      Console.WriteLine("Double1 Value = "+d1);
      Console.WriteLine("Double2 Value = "+d2);
      Console.WriteLine("Are both the double values equal? = "+d1.CompareTo(d2));
   }
}
This will produce the following output −
Double1 Value = 150
Double2 Value = 150
Are both the double values equal? = 0
Let us now see another example −
 Live Demo
using System;
public class Demo {
   public static void Main() {
      double d1 = 20d;
      object d2 = 20d;
      Console.WriteLine("Double1 Value = "+d1);
      Console.WriteLine("Double2 Value = "+d2);
      Console.WriteLine("Are both the double values equal? = "+d1.CompareTo(d2));
   }
}
This will produce the following output −
Double1 Value = 20
Double2 Value = 20
Are both the double values equal? = 0
How to draw a line on a Tkinter canvas?

Tkinter Canvas widget can be used for multiple purposes such as drawing shapes, objects, creating graphics and images. To draw a line on a Canvas, we can use create_line(x,y,x1,y1, **options) method.
In Tkinter, we can draw two types of lines: simple and dashed. We can specify the type of line using the dash property.
# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the tkinter window
win.geometry("700x350")

# Create a canvas widget
canvas=Canvas(win, width=500, height=300)
canvas.pack()

# Add a line in canvas widget
canvas.create_line(100,200,200,35, fill="green", width=5)

win.mainloop()
Running the above code will display a line on the Canvas widget.
How to Create a Photo Mosaic in Python | by Bilal Himite | Towards Data Science

While many online websites can generate photo mosaics, in this article we will look under the hood of photomosaics and create a Python script that can create them.
A mosaic is a pattern made from small colored pieces held in place by mortar. They are usually used as decoration on walls or floors.
A photo mosaic on the other hand is a photo made from tiling smaller photos.
To create a photomosaic we need the main photo and a list of tile photos. Tile photos should be of different colors and luminosity levels for better results.
Then, the procedure is as follows:
Pixelate the main photo.Replace every pixel with the tile photo closest to it in color.
Pixelate the main photo.
Replace every pixel with the tile photo closest to it in color.
Sounds easy, right? Well, there are more things we should do. But we’ll do that in the next section.
We will place all tile photos inside a folder named tiles.
First of all, we need to import some modules. We will use them later and explain what do they do.
Then, we need to define the path for the tiles and the main photo, along with the tile size.
To get all the files inside the tiles folder, we will use glob.
We will import the tiles using Pillow (PIL)’s Image class and resize them.
We, then, calculate the average color for every tile and keep it in an array.
To pixelate the main photo, we will scale it down using Pillow’s resize method. We will resize it so that every pixel in the resized photos is exactly the size of a tile in the original photo.
Now, we need to find, for every pixel in the resized photo, the tile that has the closest average color to it.
We won’t worry about the mathematical definition of “close” and what is a norm or a distance. But if you’re interested, colors are 3D vectors (RGB instead of XYZ), so it’s the same as the distance between 2 points in 3D space. Which can be defined as follows (the Euclidean distance):
To do this efficiently, we will use a k-d tree (No need to understand how it works), which is implemented in scipy’s spatial module.
We have to create a KDTree from our list of average colors, then use the query method to search.
Now, we only have to draw the tiles into an output photo.
We can play with the settings to get different results.
We can make our script run directly from a terminal. We will use the following syntax:
python3 mosaic.py main_photo_path tiles_path tile_width tile_height output_path
We have to replace the sources and settings code part with this:
The final script becomes:
We have seen how to create a simple photo mosaic in Python. Although it works perfectly as expected, we can improve it by favoring the use of different tile photos when possible, or by allowing brightness/saturation adjustment.
Ruby | Array delete_at() operation - GeeksforGeeks

31 Jul, 2021
Array#delete_at() : delete_at() is a Array class method which deletes the arrays elements at the mentioned index. 
Syntax:  Array.delete_at()

Parameter:  index - value at specific index value to delete

Return:  deleted element, nil - if the index value is out of range
Code #1 : Example for delete_at() method
Ruby
# Ruby code for delete_at() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # deleteputs "delete : #{a.delete_at(5)}\n\n" # delete# printing if no such element is foundputs "delete : #{b.delete_at(0)}\n\n" # deleteputs "delete : #{c.delete_at(20)}\n\n"
Output : 
delete : 6

delete : 1

delete : 
Code #2 : Example for delete_at() method 
Ruby
# Ruby code for delete_at() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, nil, nil, 50, 6] # deleteputs "delete : #{a.delete_at(5)}\n\n" # delete# printing if no such element is foundputs "delete : #{b.delete_at(0)}\n\n" # deleteputs "delete : #{c.delete_at(20)}\n\n"
Output : 
delete : nil

delete : 

delete : cat
 
varshagumber28
Ruby Array-class
Ruby Collections
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Enumerator each_with_index function
Ruby For Beginners
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | Array collect() operation
Ruby | Types of Variables
Ruby Mixins
Ruby | Module
Ruby | Array shift() function
Ruby | Array reject() function
Ruby | String concat Method
Python | Unpacking nested tuples - GeeksforGeeks

17 Sep, 2019
Sometimes, while working with Python list of tuples, we can have a problem in which we require to unpack the packed tuples. This can have a possible application in web development. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehensionThis task can be performed using list comprehension in which we iterate for tuples and construct the desired tuple. This technique is useful in case we know the exact number of tuple elements and positioning.
# Python3 code to demonstrate working of# Unpacking nested tuples# using list comprehension  # initialize listtest_list = [(4, (5, 'Gfg')), (7, (8, 6))]  # printing original listprint("The original list is : " + str(test_list))  # Unpacking nested tuples# using list comprehensionres = [(x, y, z) for x, (y, z) in test_list]  # printing resultprint("The unpacked nested tuple list is : " + str(res))
The original list is : [(4, (5, 'Gfg')), (7, (8, 6))]
The unpacked nested tuple list is : [(4, 5, 'Gfg'), (7, 8, 6)]

 
Method #2 : Using list comprehension + “*” operatorMany times, there might be a case in which we don’t know the exact number of element in tuple and also the element count is variable among tuples. The “*” operator can perform the task of this variable unpacking.
# Python3 code to demonstrate working of# Unpacking nested tuples# using list comprehension + * operator  # initialize listtest_list = [(4, (5, 'Gfg')), (7, (8, 6))]  # printing original listprint("The original list is : " + str(test_list))  # Unpacking nested tuples# using list comprehension + * operatorres = [(z, *x) for z, x in test_list]  # printing resultprint("The unpacked nested tuple list is : " + str(res))
The original list is : [(4, (5, 'Gfg')), (7, (8, 6))]
The unpacked nested tuple list is : [(4, 5, 'Gfg'), (7, 8, 6)]

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python 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
How to convert Boolean to String in JavaScript?

You can try to run the following to learn how to convert Boolean to String in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <p>Convert Boolean to String</p>
      <script>
         var myBool = false;
         document.write("<br>String : " + String(myBool));
      </script>
   </body>
</html>
Convert a string representation of list into list in Python

As python handles various data types, we will come across a situation where a list will appear in form of a string. In this article we will see how to convert a string into a list.
We first apply the strip method to remove the square brackets and then apply the split function. The split function with a comma as its parameter create the list from the string.
 Live Demo
stringA = "[Mon, 2, Tue, 5,]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = stringA.strip('][').split(', ')
# Result and its type
print("final list", res)
print(type(res))
Running the above code gives us the following result −
Given string [Mon, 2, Tue, 5,]
final list ['Mon', '2', 'Tue', '5,']
The json module can make a direct conversion from string to list. We just apply the function by passing the string as a parameter. We can only consider numerical elements here.
 Live Demo
import json
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = json.loads(stringA)
# Result and its type
print("final list", res)
print(type(res))
Running the above code gives us the following result −
Given string [21,42, 15]
final list [21, 42, 15]
The ast module gives us literal_eval which can directly convert the string into a list. We just supply the string as a parameter to the literal_eval method. We can only consider numerical elements here.
 Live Demo
import ast
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = ast.literal_eval(stringA)
# Result and its type
print("final list", res)
print(type(res))
Running the above code gives us the following result −
Given string [21,42, 15]
final list [21, 42, 15]
Delete first and last element from a LinkedList in Java

The first element can be deleted from a LinkedList by using the method java.util.LinkedList.removeFirst(). This method does not have any parameters and it returns the first element of the LinkedList.
The last element can be deleted from a LinkedList by using the method java.util.LinkedList.removeLast(). This method does not have any parameters and it returns the last element of the LinkedList.
A program that demonstrates this is given as follows −
 Live Demo
import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Apple");
      l.add("Mango");
      l.add("Pear");
      l.add("Orange");
      l.add("Guava");
      System.out.println("The LinkedList is: " + l);
      l.removeFirst();
      l.removeLast();
      System.out.println("The LinkedList is: " + l);
   }
}
The LinkedList is: [Apple, Mango, Pear, Orange, Guava]
The LinkedList is: [Mango, Pear, Orange]
Now let us understand the above program.
The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −
LinkedList<String> l = new LinkedList<String>();
l.add("Apple");
l.add("Mango");
l.add("Pear");
l.add("Orange");
l.add("Guava");
System.out.println("The LinkedList is: " + l);
The methods LinkedList.removeFirst() and LinkedList.removeLast() is used to remove the elements at the beginning and end of the Linked List respectively. Then the LinkedList is again displayed. A code snippet which demonstrates this is as follows −
l.removeFirst();
l.removeLast();
System.out.println("The LinkedList is: " + l);
How to style images with CSS?

To style images with CSS, you need to use properties such as height, width, - moz-opacity, etc. Let us see how to create a transparent image with - moz-opacity CSS property:
The -moz-opacity property of an image is used to set the opacity of an image. This property is used to create a transparent image in Mozilla. IE uses filter:alpha(opacity=x) to create transparent images.
You can try to run the following code to style an image and set opacity with CSS:
<html>
   <head>
   </head>
   <body>
      <img style = "border:1px solid red;-moz-opacity:0.2;filter:alpha(opacity=50);"
         src = "https://www.tutorialspoint.com/assets/videotutorials/courses/css_online_training/380_course_215_image.jpg" />
   </body>
</html>
GATE | GATE-CS-2009 | Question 43 - GeeksforGeeks

06 Oct, 2021
Consider two transactions T1 and T2, and four schedules S1, S2, S3, S4 of T1 and T2 as given below:
T1 = R1[X] W1[X] W1[Y]
T2 = R2[X] R2[Y] W2[Y]
S1 = R1[X] R2[X] R2[Y] W1[X] W1[Y] W2[Y]
S2 = R1[X] R2[X] R2[Y] W1[X] W2[Y] W1[Y]
S3 = R1[X] W1[X] R2[X] W1[Y] R2[Y] W2[Y]
S4 = R2[X] R2[Y] R1[X] W1[X] W1[Y] W2[Y]
Which of the above schedules are conflict-serializable?
(A) S1 and S2(B) S2 and S3(C) S3 only(D) S4 onlyAnswer: (B)Explanation: There can be two possible serial schedules T1 T2 and T2 T1. The serial schedule T1 T2 has the following sequence of operationsR1[X] W1[X] W1[Y] R2[X] R2[Y] W2[Y]And the schedule T2 T1 has the following sequence of operations.R2[X] R2[Y] W2[Y] R1[X] W1[X] W1[Y]The Schedule S2 is conflict-equivalent to T2 T1 and S3 is conflict-equivalent to T1 T2Quiz of this Question
vikesh0610
GATE-CS-2009
GATE-GATE-CS-2009
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2015 (Set 1) | Question 42
GATE | GATE-CS-2014-(Set-1) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE-CS-2004 | Question 3
Reduce Array Size to The Half in C++

Suppose we have an array arr. We can choose a set of integers and remove all the occurrences of these integers in the array. We have to find the minimum size of the set so that at least half of the integers of the array are removed. So for example, if arr = [3,3,3,3,5,5,5,2,2,7], then the output will be 2. This is because if we choose {3,7} this will make the new array [5,5,5,2,2] which has size 5 (this is equal to half of the size of the old array). Possible sets of size 2 are {3,5},{3,2},{5,2}. Selecting set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.
To solve this, we will follow these steps −
Define a map m, n := size of arr, store the frequency of each element present in arr into map m
Define a map m, n := size of arr, store the frequency of each element present in arr into map m
define an array called temp, sz := n, and ret := 0
define an array called temp, sz := n, and ret := 0
for each key-value pair it in minsert the value of it into temp
for each key-value pair it in m
insert the value of it into temp
insert the value of it into temp
sort the temp array
sort the temp array
for I in range 0 to the size of tempif sz <= n / 2, then break from loopincrease ret by 1decrease sz by temp[i]
for I in range 0 to the size of temp
if sz <= n / 2, then break from loop
if sz <= n / 2, then break from loop
increase ret by 1
increase ret by 1
decrease sz by temp[i]
decrease sz by temp[i]
return ret
return ret
Let us see the following implementation to get a better understanding −
 Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int minSetSize(vector<int>& arr) {
      unordered_map <int, int> m;
      int n = arr.size();
      for(int i = 0; i < n; i++){
         m[arr[i]]++;
      }
      vector <int> temp;
      unordered_map <int, int> :: iterator it = m.begin();
      int sz = n;
      int ret = 0;
      while(it != m.end()){
         temp.push_back(it->second);
         it++;
      }
      sort(temp.rbegin(), temp.rend());
      for(int i = 0; i < temp.size(); i++){
         if(sz <= n / 2)break;
         ret++;
         sz -= temp[i];
      }
      return ret;
   }
};
main(){
   vector<int> v = {3,3,3,3,5,5,5,2,2,7};
   Solution ob;
   cout << (ob.minSetSize(v));
}
[3,3,3,3,5,5,5,2,2,7]
2
Combining aggregate and non-aggregate values in SQL using Joins and Over clause - GeeksforGeeks

31 Aug, 2021
Prerequisite – Aggregate functions in SQL, Joins in SQLAggregate functions perform a calculation on a set of values and return a single value. Now, consider an employee table EMP and a department table DEPT with following structure:
Table – EMPLOYEE TABLE
Table – DEPARTMENT TABLE
And the following results are needed:
DISPLAY NAME, SAL, JOB OF EMP ALONG WITH MAX, MIN, AVG, TOTAL SAL OF THE EMPS DOING THE SAME JOB.DISPLAY DEPTNAME WITH NUMBER OF EMP WORKING IN IT.
DISPLAY NAME, SAL, JOB OF EMP ALONG WITH MAX, MIN, AVG, TOTAL SAL OF THE EMPS DOING THE SAME JOB.
DISPLAY DEPTNAME WITH NUMBER OF EMP WORKING IN IT.
The aggregated values can’t be directly used with non-aggregated values to obtain a result. Thus one can use the following concepts:
1. Using Joins –
Create a sub-table containing the result of aggregated values.Using Join, use the results from the sub-table to display them with non-aggregated values.
Create a sub-table containing the result of aggregated values.
Using Join, use the results from the sub-table to display them with non-aggregated values.
Solutions for problem 1 using JOIN:
SELECT ENAME, SAL, EMP.JOB, 
            SUBTABLE.MAXSAL, SUBTABLE.MINSAL, 
            SUBTABLE.AVGSAL, SUBTABLE.SUMSAL
FROM EMP
INNER JOIN
        (SELECT JOB, MAX(SAL) MAXSAL, MIN(SAL) 
                MINSAL, AVG(SAL) AVGSAL, SUM(SAL) SUMSAL 
         FROM EMP 
          GROUP BY JOB) SUBTABLE
                  ON EMP.JOB = SUBTABLE.JOB; 
Output for sample data:
2. Using ‘Over’ clause –
OVER CLAUSE ALONG WITH PARTITION BY IS USED TO BRAKE UP DATA INTO PARTITIONS.THE SPECIFIED FUNCTION OPERATES FOR EACH PARTITION.
OVER CLAUSE ALONG WITH PARTITION BY IS USED TO BRAKE UP DATA INTO PARTITIONS.
THE SPECIFIED FUNCTION OPERATES FOR EACH PARTITION.
Solutions for problem 2 using OVER Clause:
SELECT DISTINCT(DNAME),
COUNT(ENAME) OVER (PARTITION BY EMP.DEPTNO) EMP
FROM EMP
RIGHT OUTER JOIN DEPT
ON EMP.DEPTNO=DEPT.DEPTNO
ORDER BY EMP DESC; 
 
allenben
DBMS-SQL
SQL-Clauses
SQL-Clauses-Operators
SQL-Functions
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Views
SQL Interview Questions
SQL | GROUP BY
Difference between DDL and DML in DBMS
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
Extract a particular element from a nested array in MongoDB

Extract a particular element from a nested array with the help of dot(.) notation. Let us first create a collection with documents −
> db.extractParticularElementDemo.insertOne(
...    {
...       "_id" : 101,
...       "StudentName" : "John",
...       "StudentInformation" : [
...          {
...             "Age" : 21,
...             "StudentPersonalInformation" : [
...                {
...                   "StudentNickName" : "Mike",
...                   "StudentFamilyDetails" : [
...                      {
...                         "FatherName" : "Carol"
...                      }
...                   ]
...                },
...                {
...                   "StudentAnotherName" : "David",
...                   "StudentFamilyDetails" : [
...                      {
...                         "FatherName" : "Robert"
...                      }
...                   ]
...                }
...             ]
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 101 }
Following is the query to display all documents from a collection with the help of find() method −
> db.extractParticularElementDemo.find().pretty();
This will produce the following output −
{
   "_id" : 101,
   "StudentName" : "John",
   "StudentInformation" : [
      {
         "Age" : 21,
         "StudentPersonalInformation" : [
            {
               "StudentNickName" : "Mike",
               "StudentFamilyDetails" : [
                  {
                     "FatherName" : "Carol"
                  }
            ]
         },
         {
            "StudentAnotherName" : "David",
            "StudentFamilyDetails" : [
               {
                  "FatherName" : "Robert"
               }
         ]
      }
   ]
}
]
}
Following is the query to extract particular element from a nested array −
> db.extractParticularElementDemo.find(
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':'Carol'},
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':1,"_id":0}
... ).pretty();
This will produce the following output −
{
   "StudentInformation" : [
      {
         "StudentPersonalInformation" : [
            {
               "StudentFamilyDetails" : [
                  {
                  }
                  "FatherName" : "Carol"
               ]
            },
            {
               "StudentFamilyDetails" : [
                  {
                     "FatherName" : "Robert"
                  }
               ]
            }
         ]
      }
   ]
}