code-rag-bench/online-tutorials huggingface dataset:
PyQt5 – Set color to a status bar

26 Mar, 2020
In this article, we will see how to set a color to a status bar. By default, there is no color to a status bar but PyQt5 provides us a feature to edit the color of status bar. We can do this by using setStyleSheet() method.
self.statusBar().setStyleSheet(“background-color : yellow”)
Argument : It takes string as argument.
Action performed : It sets color to status bar.
Code:
from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys    class Window(QMainWindow):    def __init__(self):        super().__init__()          # set the title        self.setWindowTitle("Python")          # setting  the geometry of window        self.setGeometry(60, 60, 600, 400)          # setting status bar message        self.statusBar().showMessage("This is status bar")          # setting color to status bar        self.statusBar().setStyleSheet("background-color : pink")          # creating a label widget        self.label_1 = QLabel("Status bar", self)          # moving position        self.label_1.move(100, 100)          # setting up the border        self.label_1.setStyleSheet("border :1px solid blue;")          # resizing label        self.label_1.adjustSize()          # show all the widgets        self.show()    # create pyqt5 appApp = QApplication(sys.argv)  # create the instance of our Windowwindow = Window()  # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python
Node.js console.log() Function

14 Oct, 2021
The console.log() function from console class of Node.js is used to display the messages on the console. It prints to stdout with newline.
Syntax:
console.log( [data][, ...] )

Parameter: This function contains multiple parameters which are to be printed.
Return type: The function returns the passed parameters.
Below program demonstrates the working of console.log() function:
Program 1:
function GFG(name) {     console.log("hello " + name);}  // when parameters are passedGFG("Geeksforgeeks");
Output:
Program 2:
function GFG(name) {     console.log("hello " + name);}  // No parameters are passedGFG();
Output:
NodeJS-function
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Program for Reversal algorithm for array rotation

22 Jun, 2022
Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.
Example :
Input :  arr[] = [1, 2, 3, 4, 5, 6, 7]
         d = 2
Output : arr[] = [3, 4, 5, 6, 7, 1, 2] 

Rotation of the above array by 2 will make array
# Python program for reversal algorithm of array rotation # Function to reverse arr[] from index start to enddef rverseArray(arr, start, end):    while (start < end):        temp = arr[start]        arr[start] = arr[end]        arr[end] = temp        start += 1        end = end-1 # Function to left rotate arr[] of size n by ddef leftRotate(arr, d):    n = len(arr)    rverseArray(arr, 0, d-1)    rverseArray(arr, d, n-1)    rverseArray(arr, 0, n-1) # Function to print an arraydef printArray(arr):    for i in range(0, len(arr)):        print (arr[i]) # Driver function to test above functionsarr = [1, 2, 3, 4, 5, 6, 7]leftRotate(arr, 2) # Rotate array by 2printArray(arr) # This code is contributed by Devesh Agrawal
Output :
3 4 5 6 7 1 2
Time Complexity : O(n)Auxiliary Space : O(1)
Please refer complete article on Reversal algorithm for array rotation for more details!
rachitggupta2
chandramauliguptach
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to add two numbers
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
Appending to list in Python dictionary
Python | Convert a list into a tuple
Add a key:value pair to dictionary in Python
Python | Check if a variable is string
Python Program for Bubble Sort
Python program to check if a string contains all unique characters

23 May, 2022
To implement an algorithm to determine if a string contains all unique characters. Examples: 
Input : s = “abcd” Output: True “abcd” doesn’t contain any duplicates. Hence the output is True.
Input : s = “abbd” Output: False “abbd” contains duplicates. Hence the output is False.
One solution is to create an array of boolean values, where the flag at the index i indicates whether character i in the alphabet is contained in the string. The second time you see this character you can immediately return false. You can also return false if the string length exceeds the number of unique characters in the alphabet.  
Python
def isUniqueChars(st):     # String length cannot be more than    # 256.    if len(st) > 256:        return False     # Initialize occurrences of all characters    char_set = [False] * 128     # For every character, check if it exists    # in char_set    for i in range(0, len(st)):         # Find ASCII value and check if it        # exists in set.        val = ord(st[i])        if char_set[val]:            return False         char_set[val] = True     return True # driver codest = "abcd"print(isUniqueChars(st))
True
 
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(1), no extra space required so it is a constant.
Count the frequencies of characters using Counter() function
If the keys in frequency dictionary(gives the count of distinct characters) is equal to length of string then print True else False
Below is the implementation:
Python3
from collections import Counter  def isUniqueChars(string):     # Counting frequency    freq = Counter(string)     if(len(freq) == len(string)):        return True    else:        return False  # driver codest = "abcd"print(isUniqueChars(st))# This code is contributed by vikkycirus
Output:
True
Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(26), in total there are 26 letters in alphabet and no extra space required so it is a constant.
vikkycirus
samim2000
Technical Scripter 2018
Python Programs
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Lodash _.unzip() Method

28 Aug, 2020
The _.unzip method is similar to _.zip (i.e.; it creates an array of grouped elements) except that it accepts an array of grouped elements and also creates an array regrouping the elements to their pre-zip configuration.
Syntax:
_.unzip(array)

Parameters: This method accepts a single parameters as mentioned above and described below:
array (Array): This parameter holds the array of grouped elements to process.
Return Value: This method is used to returns the new array of regrouped elements.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array var zipped = _.zip(['a', 'b'], [1, 2], [true,   false]);      // Use of _.zip() // methodlet gfg = _.zip(zipped);      // Printing the output console.log(gfg);
Output:
[ [['a', 1, true], ['b', 2, false]] ]

Example 2:
javascript
// Requiring the lodash library const _ = require("lodash");       // Original array var zipped = (['x', 'y'], [5, 6], [true, false]);      // Use of _.zip() // methodlet gfg = _.zip(zipped);      // Printing the output console.log(gfg);
Output:
[ [true, false] ]

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
java.time.Duration.of() Method Example

The java.time.Duration.of(long amount, TemporalUnit unit) method obtains a Duration representing an amount in the specified unit.
Following is the declaration for java.time.Duration.of(long amount, TemporalUnit unit) method.
public static Duration of(long amount, TemporalUnit unit)

amount − the amount of the duration, measured in terms of the unit, positive or negative.
amount − the amount of the duration, measured in terms of the unit, positive or negative.
unit − the unit that the duration is measured in, must have an exact duration, not null.
unit − the unit that the duration is measured in, must have an exact duration, not null.
a Duration, not null.
DateTimeException − if the period unit has an estimated duration.
DateTimeException − if the period unit has an estimated duration.
ArithmeticException − if numeric overflow occurs.
ArithmeticException − if numeric overflow occurs.
The following example shows the usage of java.time.Duration.of(long amount, TemporalUnit unit) method.
package com.tutorialspoint;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

public class DurationDemo {
   public static void main(String[] args) {

      Duration duration = Duration.of(5, ChronoUnit.SECONDS);
      System.out.println(duration.getSeconds());      
   }
}
Let us compile and run the above program, this will produce the following result −
5

 Print
 Add Notes
 Bookmark this page
C# Program to Count trailing zeroes in factorial of a number - GeeksforGeeks

02 Jan, 2019
Given an integer n, write a function that returns count of trailing zeroes in n!.
Examples :
Input: n = 5
Output: 1 
Factorial of 5 is 120 which has one trailing 0.

Input: n = 20
Output: 4
Factorial of 20 is 2432902008176640000 which has
4 trailing zeroes.

Input: n = 100
Output: 24

Trailing 0s in n! = Count of 5s in prime factors of n!
                  = floor(n/5) + floor(n/25) + floor(n/125) + ....

C#
// C# program to count// trailing 0s in n!using System;  class GFG {      // Function to return trailing    // 0s in factorial of n    static int findTrailingZeros(int n)    {        // Initialize result        int count = 0;          // Keep dividing n by powers        // of 5 and update count        for (int i = 5; n / i >= 1; i *= 5)            count += n / i;          return count;    }      // Driver Code    public static void Main()    {        int n = 100;        Console.WriteLine("Count of trailing 0s in "                 + n + "! is " + findTrailingZeros(n));    }}  // This code is contributed by vt_m
Count of trailing 0s in 100! is 24

Please refer complete article on Count trailing zeroes in factorial of a number for more details!
C# Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different Ways to Take Input and Print a Float Value in C#
How to Get a Total Number of Days in a Month using built in Functions in C#?
Program to Print a New Line in C#
C# Program to Convert a Binary String to an Integer
C# | Graphics.DrawLine() Method | Set – 2
How to Convert ASCII Char to Byte in C#?
Getting the Total Number of Days in a Month Using If-else and Switch Statements in C#
Program to swap numbers using XOR operator in C#
Program to Print Backslash () in C#
Program to define various types of constants in C#
turtle.addshape() function in Python - GeeksforGeeks

28 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This function is used to Adds a turtle shape to TurtleScreen’s shapelist.
Syntax :
turtle.addshape(name, shape=None)

Parameters:
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# import packageimport turtle  # print list of the all# shapes availableprint(turtle.getshapes())  # add shape to the shape listturtle.addshape(name="gfg.gif",shape=None)  # check the updated shape listprint(turtle.getshapes())
Output :
[‘arrow’, ‘blank’, ‘circle’, ‘classic’, ‘square’, ‘triangle’, ‘turtle’][‘arrow’, ‘blank’, ‘circle’, ‘classic’, ‘gfg.gif’, ‘square’, ‘triangle’, ‘turtle’]
Example 2 :
Python3
# import packageimport turtle  # add shape to the shape list as aboveturtle.addshape(name="gfg.gif",shape=None)  # set turtle with new shape# and new positionturtle.shape("gfg.gif")turtle.up()turtle.setpos(-10,10)turtle.down()  # loop for motionfor i in range(22):    turtle.fd(40+5*i)    turtle.right(90)
Output :
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists
How to set the absolute position of a view in Android?

This example demonstrates how do I set the absolute position of a view in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:id="@+id/relativeLayout"
   tools:context=".MainActivity">
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      RelativeLayout rl = findViewById(R.id.relativeLayout);
      ImageView iv = new ImageView(this);
      iv.setImageResource(R.drawable.image);
      RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(500, 400);
      params.leftMargin = 100;
      params.topMargin = 300;
      rl.addView(iv, params);
   }
}
Step 4 −Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.sample">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
What is Effective Isotropic Radiated Power (EIRP)?

A wireless link budget, in general, estimates the possible losses that will be encountered by the signal being transmitted and adjustments are made on the design parameters to combat the effects of such losses. EIRP is commonly used in wireless link budget calculations to specify the power level required for transmission.
As the name suggests, the EIRP takes power transmitted by an isotropic source as the reference. EIRP combines the power of the transmitting antenna and its gain. EIRP is expressed as the product of the power of the transmitting antenna and its gain.
EIRP=PtGt
Pt is the power of the transmitting antenna and Gt is the gain of the transmitting antenna.
In essence, the product of the power radiated and the gain of a realizable antenna is compared with the product of the power radiated and the gain of an isotropic source. Since an isotropic source radiates equally in all directions, its gain is unity (or 0 dB).
The figure shows the EIRP of an isotropic radiator and a realizable antenna. We can observe that the EIRP of a realizable antenna would usually be greater than the EIRP of an isotropic radiator.
EIRP of realizable antenna > EIRP of isotropic
The EIRP of an isotropic radiator and a realizable antenna is expressed as below −
EIRPISOTROPIC=PISOTROPIC×GISOTROPIC
EIRPSYSTEM=PANTENNA×GANTENNA
EIRP is expressed as an absolute value as well as logarithmic value in base 10 scale.
EIRPdBW=10log10(PtGt)
EIRPdBW=10log10(Pt)+10log10(Gt)=Pt(dB)+Gt(dB)
Since the gain of the antenna is essentially a unitless quantity in both the absolute and logarithmic scale, EIRP will take the unit of power and when expressed in the logarithmic scale, we use dBW which means decibel power with reference to 1 W. Here, 1 W is the reference power. The representation dBmW is also used where 1 mW is taken as the reference power.
These are representing powers in the logarithmic base 10 scale. We take the ratios of two quantities having the unit of power and map it on to the logarithmic scale. In this ratio, one of the power quantities is taken as the reference power.
PdBW=10log10(PW1W)
PdBmW=10log10(PW1mW)
If PdBW and PdBmW take negative values, it implies that, the measured power is less than the reference power.
If the specified power level is -20 dBm, this means that the measured or received power level is one-hundredth of the reference power.
−20dBm=10log10(P1mW)
log10(P1mW)=−2
(P1mW)=10−2;P=1100(1mW)=0.01mW
In a satellite communication, the transmitting antenna radiates a power of 20 W. The gain of the antenna is 15 dBi. Calculate the EIRP.
Soln. We convert the antenna gain back to the absolute scale.
15=10log10(X)
X=101.5=31.622
EIRP=Pt.Gt=(20W)(31.622)=632.44W=28.01dBW
How to catch StandardError Exception in Python?


There is the Exception class, which is the base class for StopIteration, StandardError and Warning. All the standard errors are derived from StandardError. Some standard errors like ArithmeticErrror, AttributeError, AssertionError are derived from base class StandardError.
When an attribute reference or assignment fails, AttributeError is raised. For example, when trying to reference an attribute that does not exist:
We rewrite the given code and catch the exception and know it type.
import sys
try:
class Foobar:
def __init__(self):
self.p = 0
f = Foobar()
print(f.p)
print(f.q)
except Exception as e:
print e
print sys.exc_type
print 'This is an example of StandardError exception'
0
Foobar instance has no attribute 'q'
<type 'exceptions.AttributeError'>
This is an example of StandardError exception
Exclude some ID records from a list and display rest in MySQL

To exclude records, use MySQL NOT IN(). Let us first create a table −
mysql> create table DemoTable
(
   Id int
);
Query OK, 0 rows affected (0.64 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(1);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(2);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(3);
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values(4);
Query OK, 1 row affected (0.41 sec)
mysql> insert into DemoTable values(5);
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable values(6);
Query OK, 1 row affected (0.12 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------+
| Id   |
+------+
| 1    |
| 2    |
| 3    |
| 4    |
| 5    |
| 6    |
+------+
6 rows in set (0.00 sec)
Following is the query to exclude records −
mysql> select *from DemoTable where Id NOT IN(1,4,6,3);
This will produce the following output −
+------+
| Id   |
+------+
| 2    |
| 5    |
+------+
2 rows in set (0.00 sec)
How to use ArrayBlockingQueue in android?

Before getting into example, we should know what arrayblockingqueue is, it travels FIFO manner and first element going to live longest period of time and last element of the queue going to live short period of the time.
This example demonstrate about How to use ArrayBlockingQueue in android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:gravity="center"
   android:layout_height="match_parent"
   tools:context=".MainActivity"
   android:orientation="vertical">
   <TextView
      android:id="@+id/actionEvent"
      android:textSize="40sp"
      android:layout_marginTop="30dp"
      android:layout_width="wrap_content"
      android:layout_height="match_parent" />
</LinearLayout>
In the above code, we have taken a text view to show ArrayBlockingQueue elements.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.util.concurrent.ArrayBlockingQueue;
public class MainActivityextends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      TextViewactionEvent = findViewById(R.id.actionEvent);
      ArrayBlockingQueuearrayBlockingQueue = new ArrayBlockingQueue<>(50);
      arrayBlockingQueue.add("sai");
      arrayBlockingQueue.add("ram");
      arrayBlockingQueue.add("krishna");
      arrayBlockingQueue.add("prasad");
      actionEvent.setText("" + arrayBlockingQueue);
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click  here  to download the project code
Java Examples - Display root directories

How to display root directories in the system ?
Following example shows how to find root directories in your system using listRoots() method of File class.
import java.io.*;

public class Main { 
   public static void main(String[] args) { 
      File[] roots = File.listRoots();
      System.out.println("Root directories in your system are:");
      
      for (int i = 0; i < roots.length; i++) {
         System.out.println(roots[i].toString());
      } 
   }
}
The above code sample will produce the following result. The result may vary depending on the system & operating system. If you are using Unix system you will get a single root '/'.
Root directories in your system are:
C:\
D:\
E:\
F:\
G:\
H:\

 Print
 Add Notes
 Bookmark this page
GATE-CS-2015 (Set 2) - GeeksforGeeks

10 Nov, 2021
Statements: 
  (I) One fourth of the weight of a pole is 5 kg
  (II) The total weight of these poles is 160 kg more
       than the total weight of two poles.
(I) is sufficient. We can determine total weight of 1o
   poles as 10 * 4 * 5 = 200 Kg

(II) is also sufficient, we can determine the weight.
  Let x be the weight of 1 pole.
  10*x - 2*x = 160 Kg
  x = 20 Kg
  10x = 200 Kg 
f(x) = 1 – |x|
f(0) = 1
f(1) = f(-1) = 0
f(0.5) = f(-0.5) = 0.5

Area of a Δ = 1/2 * ac sinB 
            = 1/2 * bc sinA 
            = 1/2 ab sinC

Here area (ΔPQR) = area (ΔPQS) + area (ΔPRS)

1/2 rq sin120 = 1/2 PS * r sin60 + 1/2 PS * q sin60

=> PS = rq/(r+q)
If p, q, r, s are distinct integers such that:
f(p, q, r, s) = max (p, q, r, s)
g(p, q, r, s) = min (p, q, r, s)
h(p, q, r, s) = remainder of (p × q) / (r × s)  if (p × q) > (r × s) OR 
                remainder of (r × s) / (p × q) if (r × s) > (p × q)
Also a function fgh (p, q, r, s) =
                f(p, q, r, s) × g(p, q, r, s) × h(p, q, r, s).
Also the same operation are valid with two variable functions 
of the form f(p, q).

What is the value of fg(h(2, 5, 7, 3), 4, 6, 8)? 
The question asks value of fg (h(2, 5, 7, 3), 4, 6, 8)

We need to first find value of h(2, 5, 7, 3) 

h is defined as 
h(p, q, r, s) = remainder of (p × q) / (r × s)  if (p × q) > (r × s)
                remainder of (r × s) / (r × q)  if (r × s) > (p × q)

h(2, 5, 7, 3) = remainder of (7 * 3) / (2 * 5)  since 7*3 > 2*5
              = 1

fg(1, 4, 6, 8) = f(1, 4, 6, 8) * g(1, 4, 6, 8)
               = max(1, 4, 6, 8) * min(1, 4, 6, 8)
               = 8 * 1
               = 8
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ...
Must Do Coding Questions for Product Based Companies
Git - Difference Between Git Fetch and Git Pull
SDE SHEET - A Complete Guide for SDE Preparation
How to Install and Use NVM on Windows?
DSA Sheet by Love Babbar
Download Image From URL in Android
Java Threads
Top 20 Puzzles Commonly Asked During SDE Interviews
Spring Boot - Architecture
How to create a rainbow using HTML5 ?

14 Dec, 2020
In this, we will be talking about how can we create a rainbow using HTML5. To create the rainbow we have to know how the SVG tag works and its attributes.
Approach:
Firstly, we have to use the width and height attribute of the SVG tag to create the base for the structure of the rainbow. 
Now we will use the circle element to create the structure of the rainbow and fill it with respective colors.
<!DOCTYPE html><html>  <body>    <!-- Here the background color is aqua -->    <!-- To make the circle 1/2 in order to         create the rainbow structure we need         to give a height that makes the         circle 1/2 -->    <svg width="800" height="400"         style="background-color: aqua;">          <!-- In order to create the rainbow         we have to use the circle element -->        <!-- Here we will use circle attribute         to properly align the half circle         with a radius at correct position -->        <!-- Here to make the color red we have         to use the attribute fill-->        <!-- stroke-width defines the thickness-->        <circle cx="400" cy="450" r="400" stroke="none"            stroke-width="2" fill="red" />          <!-- r defines the radius of the circle  -->        <circle cx="400" cy="450" r="300" stroke="none"             stroke-width="2" fill="yellow" />        <circle cx="400" cy="450" r="250" stroke="none"             stroke-width="2" fill="green" />        <circle cx="400" cy="450" r="200" stroke="none"             stroke-width="2" fill="blue" />        <circle cx="400" cy="450" r="150" stroke="none"             stroke-width="2" fill="indigo" />        <circle cx="400" cy="450" r="100" stroke="none"             stroke-width="2" fill="violet" />    </svg></body>  </html>
Output:
HTML-Misc
HTML-SVG
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Make a div horizontally scrollable using CSS
DOM (Document Object Model)
How to get values from html input array using JavaScript ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
REST API (Introduction)
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Select data and set value to boolean based on timestamp column in MySQL

For this, use IF(). Let us first see the current date −
mysql> select curdate();
+------------+
| curdate()  |
+------------+
| 2019-12-10 |
+------------+
1 row in set (0.00 sec)
Let us first create a table −
mysql> create table DemoTable1890
   (
   DueDate timestamp
   );
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1890 values('2017-12-10');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1890 values('2021-12-10');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1890 values('2018-04-24');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1890 values('2020-05-11');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement −
mysql> select * from DemoTable1890;
This will produce the following output −
+---------------------+
| DueDate             |
+---------------------+
| 2017-12-10 00:00:00 |
| 2021-12-10 00:00:00 |
| 2018-04-24 00:00:00 |
| 2020-05-11 00:00:00 |
+---------------------+
4 rows in set (0.00 sec)
Here is the query to select data and set value based on timestamp column −
mysql> select if(DueDate > curdate() - interval 2 year,false,true) as Status from DemoTable1890;
This will produce the following output −
+--------+
| Status |
+--------+
|      1 |
|      0 |
|      0 |
|      0 |
+--------+
4 rows in set (0.00 sec)
How to set horizontal header for a table?

Tables in HTML can have horizontal as well as the vertical header. For the horizontal header, you need to set all <th> inside a single <tr> tag i.e. row, that will be the topmost.
You can try to run the following code to set a horizontal header for a table
<!DOCTYPE html>
<html>
   <head>
      <style>
         table, th, td {
            border: 1px solid black;
            width: 100px;
            height: 50px;
         }
      </style>
   </head>

   <body>
      <h1>Employee Details</h1>
      <table>
         <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Technology</th>
         </tr>
         <tr>
            <td>Amit</td>
            <td>27</td>
            <td>Database</td>
         </tr>
         <tr>
            <td>Sachin</td>
            <td>34</td>
            <td>Marketing</td>
         </tr>
      </table>
   </body>
</html>
PHP | Check if a number is Perfect number

14 Oct, 2019
A perfect number is a number if it is equal to the sum of its factors,that is original number is equal to sum of all its factors excluding the number itself. We have already discuss how to check if a number is perfect or not in this article. In this article we will discuss about how to do the same in PHP.
Examples:
Input : 6
Output : Perfect Number
Explanation: factors of 6 are 1, 2, 3, 6
             sum of its factors (excluding the 
             number itself) = 1 + 2 + 3 = 6 

Input : 24
Output : Not Perfect Number
Explanation : factors of 24 are 1,2,3,4,6,8,12,24 
              sum of its factors(excluding the 
              number itself) = 1 + 2 + 3 + 4  
                                + 6 + 8 + 12 = 36

The idea to this is we will traverse through each number in the range [1,N) and check if it is a factor of the given number N. If it is a factor, we will add this number to a variable $sum. At the end is the variable $sum is equal to the original number then the given number is a Perfect Number.
Below is the implementation of above idea in PHP:
<?php// Function to check if a number is perfectfunction isPerfectNumber($N){    // To store the sum    $sum = 0;           // Traversing through each number    // In the range [1,N)    for ($i = 1; $i < $N; $i++)    {        if ($N % $i == 0)        {            $sum = $sum + $i;        }          }          // returns True is sum is equal    // to the original number.    return $sum == $N;}   // Driver's code$N = 6;  if (isPerfectNumber($N))    echo " Perfect Number";else    echo "Not  Perfect Number";?>
Output:
Perfect Number

Akanksha_Rai
PHP-basics
school-programming
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Shell Script to Convert a File Content to Lower Case or Upper Case

13 Jul, 2021
Here we are going to see how to convert a file to lower case or upper sase as specified by the user. We are going to write a  POSIX  compatible shell script which is going to give us the desired output after input of files such as sample.txt, a text file with a combination of lowercase, uppercase, digits and special character
Example:
File Content

this is lowercase

THIS IS UPPERCASE

$P3C14L C#4R4CT3R$

1234567890

OUTPUT

Uppercase

THIS IS LOWERCASE

THIS IS UPPERCASE

$P3C14L C#4R4CT3R$

1234567890

Lowercase

this is lowercase

this is uppercase

$p3c14l c#4r4ct3r$

1234567890
Ask User Choice if they want to convert from Uppercase to Lowercase or vice-versa
Read the choice
Get into the Switch case depending on the choice. while exiting if the choice is none of the above-mentioned.
Asking user for the filename
Checking if file exists, if not then exit with error code 1, otherwise continue
Translating the file content as per the previous selected user choice and printing the output by the use of tr command.
End of Script
#!/bin/sh
# shebang to specify that this is an shell script

# Function to get File
getFile(){
    # Reading txtFileName to convert it's content
    echo -n "Enter File Name:"
    read txtFileName
    # Checking if file exist
    if [ ! -f $txtFileName ]; then
        echo "File Name $txtFileName does not exists."
        exit 1
    fi
}

clear
  echo "1. Uppercase to Lowercase "
  echo "2. Lowercase to Uppercase"
  echo "3. Exit"
  echo -n "Enter your Choice(1-3):"
  read Ch

  case "$Ch" in
    1) 
      # Function Call to get File 
      getFile    
      # Converting to lower case if user chose 1     
      echo "Converting Upper-case to Lower-Case "
      tr '[A-Z]' '[a-z]' <$txtFileName
    ;;

    2)
      # Function Call to get File 
      getFile
      # Converting to upper case if user chose 2
      echo "Converting Lower-Case to Upper-Case "
      tr '[a-z]' '[A-Z]' <$txtFileName
    ;;
    

    *) # exiting for all other cases
        echo "Exiting..."
        exit
    ;;
  esac
Output:
Sample text file and making our script executable
Showcasing content of sample text file with cat command and modifying our script by making it executable with chmod command.
Converting file content from uppercase to lowercase
Converting file content from lowercase to uppercase
In the Case File does not exist
adnanirshad158
Picked
Shell Script
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2008 | Question 59

28 Jun, 2021
Let R (A, B, C, D) be a relational schema with the following functional dependencies:
A → B, B → C,
C → D and D → B. 

The decomposition of R into 
(A, B), (B, C), (B, D)

(A) gives a lossless join, and is dependency preserving(B) gives a lossless join, but is not dependency preserving(C) does not give a lossless join, but is dependency preserving(D) does not give a lossless join and is not dependency preservingAnswer: (A)Explanation: Background :
Lossless-Join Decomposition:Decomposition of R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies)    R1 ∩ R2 → R1
   OR
    R1 ∩ R2 → R2

Lossless-Join Decomposition:Decomposition of R into R1 and R2 is a lossless-join decomposition if at least one of the following functional dependencies are in F+ (Closure of functional dependencies)
    R1 ∩ R2 → R1
   OR
    R1 ∩ R2 → R2

Dependency Preserving Decomposition:Decomposition of R into R1 and R2 is a dependency preserving decomposition if closure of functional dependencies after decomposition is same as closure of of FDs before decomposition.A simple way is to just check whether we can derive all the original FDs from the FDs present after decomposition.
Question :Let R (A, B, C, D) be a relational schema with the following functional dependencies:
A -> B, B -> C,
C -> D and D -> B. 

The decomposition of R into 
(A, B), (B, C), (B, D)

Note that A, B, C and D are all key attributes. We can derive all attributes from every attribute.
Since Intersection of all relations is B and B derives all other attributes, relation is lossless.
The relation is dependency preserving as well as all functional dependencies are preserved directly or indirectly. Note that C -> D is also preserved with following two C -> B and B -> D.
Quiz of this Question
Gate IT 2008
GATE-Gate IT 2008
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2004 | Question 31
GATE | GATE-CS-2001 | Question 50
gunzip - Unix, Linux Command

gunzip, gzip - compress or expand files
gunzip [ -acfhlLnNrtvV ] [-S suffix] [ name ... ]
gzip [ -acdfhlLnNrtvV19 ] [-S suffix] [ name ... ]
gunzip takes a list of files on its command line and replaces each file whose name ends with .gz, -gz, .z, -z, _z or .Z and which begins with the correct magic number with an uncompressed file without the original extension. gunzip also recognizes the special extensions .tgz and .taz as shorthands for .tar.gz and .tar.Z respectively. When compressing, gzip uses the .tgz extension if necessary instead of truncating a file with a .tar extension.
gunzip can currently decompress files created by gzip, zip, compress, compress -H or pack. The detection of the input format is automatic. When using the first two formats, gunzip checks a 32 bit CRC. For pack, gunzip checks the uncompressed length. The standard compress format was not designed to allow consistency checks. However gunzip is sometimes able to detect a bad .Z file. If you get an error when uncompressing a .Z file, do not assume that the .Z file is correct simply because the standard uncompress does not complain. This generally means that the standard uncompress does not check its input, and happily generates garbage output. The SCO compress -H format (lzh compression method) does not include a CRC but also allows some consistency checks.
Files created by zip can be uncompressed by gzip only if they have a single member compressed with the 'deflation' method. This feature is only intended to help conversion of tar.zip files to the tar.gz format. To extract a zip file with a single member, use a command like gunzip <foo.zip or gunzip -S .zip foo.zip. To extract zip files with several members, use unzip instead of gunzip.
Example-1:
To Decompress A File Using The "gunzip" Command:
$ gunzip myfilename.gz
output:
$ lsmyfilename.gz
$ gunzip myfilename.gz
$ lsmyfilename
Example-2:
Force A File To Decompress:
$ gunzip -f myfilename.gz
output:
$ lsmyfilename.gz
$ gunzip myfilename.gz
$ lsmyfilename
Example-3:
To keep both the compressed and decompressed file:
$ gunzip -k myfile.gz
output:
$ lsmyfilename.gz
$ gunzip -k myfilename.gz
$ lsmyfilename  myfilename.gz
Example-4:
To display compressed output:
$ gunzip -l myfile.gz
output:
$ gunzip -l myfilename.gz         compressed        uncompressed  ratio uncompressed_name                 31                   0   0.0% myfilename
Example-5:
Decompressing Lots Of Files Recursively:
$ gunzip -r /tmp
output:
$ ls /tmp/myfilename1.gz  myfilename.gz
$ gunzip -r /tmp/
$ ls /tmp/myfilename  myfilename1
How to move all files from one directory to another using Python ?

08 Jul, 2022
In this article, we will see how to move all files from one directory to another directory using Python.  In our day-to-day computer usage we generally copy or move files from one folder to other, now let’s see how to move a file in Python:
Using os module.
Using shutil module.
Source and Destination Folder
 
Source Folders
Destination Folder – before
rename() method takes two arguments first one is the source path and the second one is the destination path, the rename function will move the file at the source path to the provided destination.
Firstly import the os module, store the path of the source directory and path of the destination directory, and make a list of all files in the source directory using listdir() method in the os module. Now move all the files from the list one by one using rename() method.
Code:
Python3
import os source = 'C:/Users/sai mohan pulamolu/Desktop/deleted/source/'destination = 'C:/Users/sai mohan pulamolu/Desktop/deleted/destination/' allfiles = os.listdir(source) for f in allfiles:    os.rename(source + f, destination + f)
The shutil.move() method takes two arguments first one is the source path and the second one is the destination path, the move function will move the file at the source path to the provided destination.
Firstly import shutil module, and store the path of the source directory and path of the destination directory. Make a list of all files in the source directory using listdir() method in the os module. Now move all the files from the list one by one using shutil.move() method.
Python3
import osimport shutil source = 'C:/Users/sai mohan pulamolu/Desktop/deleted/source/'destination = 'C:/Users/sai mohan pulamolu/Desktop/deleted/destination/' allfiles = os.listdir(source) for f in allfiles:    shutil.move(source + f, destination + f)
Outputs are the same:
Destination Folder – after
surajkumarguptaintern
Picked
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
Long longValue() Method in Java

13 Dec, 2021
The java.lang.Long.longValue() is an inbuilt method of the Long class in Java which returns the value of this Long object as a long after the conversion.Syntax: 
public long longValue()
Parameters: This method do not take any parameters.Return Value: This method will return the numeric value represented by this object after conversion to long type.Examples:  
Input: 5366623
Output: (Long) 5366623

Input: -6723887
Output: (Long) -6723887
Explanation:
When the number is passed in this object it will convert that 
to long and gives the value like,
Long lobject = new Long(5366623)
It will return 5366623 as long.
Below programs illustrate the working of java.lang.Long.longValue() method. Program 1: For a positive number.  
java
// Java program to illustrate the// java.lang.Long.longValue() method import java.lang.*; public class Geek {     public static void main(String[] args)    {         Long lobject = new Long(77387187);         // It will return the value of this Long as a long        long nl = lobject.longValue();        System.out.println("The Value of nl as long is = " + nl);         Long lobject2 = new Long(-6723887);         // It will return the value of this Long as a long        long nl2 = lobject2.longValue();        System.out.println("The Value of nl2 as long is = " + nl2);    }}
The Value of nl as long is = 77387187
The Value of nl2 as long is = -6723887
 
Program 2: For a very large no. // It will produce compile time error. 
java
// Java program to illustrate the// java.lang.Long.longValue() methodimport java.lang.*; public class Geek {     public static void main(String[] args)    {         Long lobject = new Long(97387717187);         // Very large number will produce compile errors        long nl = lobject.longValue();        System.out.println("The Value of nl as long is = " + nl);    }}
prog.java:9: error: integer number too large: 97387717187
    Long lobject = new Long(97387717187);
                            ^
1 error
 
Reference: https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html#longValue() 
akshaysingh98088
Java-Functions
Java-lang package
java-Long
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
sciPy stats.signaltonoise() function | Python

18 Feb, 2019
scipy.stats.signaltonoise(arr, axis=0, ddof=0) function computes the signal-to-noise ratio of the input data.
Its formula :
Parameters :arr : [array_like]Input array or object having the elements to calculate the signal-to-noise ratioaxis : Axis along which the mean is to be computed. By default axis = 0.ddof : Degree of freedom correction for Standard Deviation.
Results : mean to standard deviation ratio i.e. signal-to-noise ratio.
Code #1: Working
# stats.signaltonoise() method import numpy as npfrom scipy import stats      arr1 = [[20, 2, 7, 1, 34],        [50, 12, 12, 34, 4]]  arr2 = [50, 12, 12, 34, 4]  print ("\narr1 : ", arr1)print ("\narr2 : ", arr2)  print ("\nsignaltonoise ratio for arr1 : ",        stats.signaltonoise(arr1, axis = 0, ddof = 0))  print ("\nsignaltonoise ratio for arr1 : ",        stats.signaltonoise(arr1, axis = 1, ddof = 0))  print ("\nsignaltonoise ratio for arr1 : ",        stats.signaltonoise(arr2, axis = 0, ddof = 0)) 
Output :
arr1 : [[20, 2, 7, 1, 34], [50, 12, 12, 34, 4]]
arr2 : [50, 12, 12, 34, 4]
signaltonoise ratio for arr1 : [2.33333333 1.4 3.8 1.06060606 1.26666667]
signaltonoise ratio for arr1 : [1.01779811 1.31482934]
signaltonoise ratio for arr2 : 1.3148293369202024
 Code #2 : How to implement
def signaltonoise(a, axis, ddof):    a = np.asanyarray(a)    m = a.mean(axis)    sd = a.std(axis = axis, ddof = ddof)    return np.where(sd == 0, 0, m / sd)  print ("\nsignaltonoise ratio for arr1 : ",        signaltonoise(arr1, axis = 0, ddof = 0))  print ("\nsignaltonoise ratio for arr1 : ",        signaltonoise(arr1, axis = 1, ddof = 0))  print ("\nsignaltonoise ratio for arr2 : ",        signaltonoise(arr2, axis = 0, ddof = 0))
Output :
signaltonoise ratio for arr1 : [2.33333333 1.4 3.8 1.06060606 1.26666667]
signaltonoise ratio for arr1 : [1.01779811 1.31482934]
signaltonoise ratio for arr2 : 1.3148293369202024
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts