code-rag-bench/online-tutorials huggingface dataset:
Build a GUI Application to ping the host using Python - GeeksforGeeks

04 Dec, 2021
Prerequisite: Python GUI – Tkinter
In this article, we are going to see how to ping the host with a URL or IP using the python ping module in Python. This module provides a simple way to ping in python. And It checks the host is available or not and measures how long the response takes.
“Before” starting we need to install this module into your system.
pip install pythonping
The GUI would look like below:
Syntax: ping(‘URL or IP’)
Parameter:
verbose : enables the verbose mode, printing output to a stream
timeout : is the number of seconds you wish to wait for a response, before assuming the target is unreachable
payload : allows you to use a specific payload (bytes)
size : is an integer that allows you to specify the size of the ICMP payload you desire
Code:
Python3
# import modulefrom pythonping import ping # pinging the hostping('www.google.com', verbose=True)
 Output:
Reply from 142.250.71.4, 9 bytes in 61.09ms
Reply from 142.250.71.4, 9 bytes in 60.24ms
Reply from 142.250.71.4, 9 bytes in 60.22ms
Reply from 142.250.71.4, 9 bytes in 60.04ms
Reply from 142.250.71.4, 9 bytes in 61.09ms
Reply from 142.250.71.4, 9 bytes in 60.24ms
Reply from 142.250.71.4, 9 bytes in 60.22ms
Reply from 142.250.71.4, 9 bytes in 60.04ms

Round Trip Times min/avg/max is 60.04/60.4/61.09 ms
Implementation for GUI:
Pinging GUI Application with Tkinter
Python3
# import modulesfrom tkinter import *from pythonping import ping def get_ping():    result = ping(e.get(), verbose=True)    res.set(result) # object of tkinter# and background set for light greymaster = Tk()master.configure(bg='light grey') # Variable Classes in tkinterres = StringVar() # Creating label for each information# name using widget LabelLabel(master, text="Enter URL or IP :",      bg="light grey").grid(row=0, sticky=W)Label(master, text="Result :", bg="light grey").grid(row=1, sticky=W) # Creating label for class variable# name using widget EntryLabel(master, text="", textvariable=res, bg="light grey").grid(    row=1, column=1, sticky=W) e = Entry(master)e.grid(row=0, column=1) # creating a button using the widget# Button that will call the submit functionb = Button(master, text="Show", command=get_ping)b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) mainloop()
 Output:
abhigoya
avtarkumar719
Python Tkinter-exercises
Python-tkinter
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
How to verify action bar tittle is truncating or not in android?

This example demonstrates How to verify action bar tittle is truncating or not 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"?>
<LinearLayout xmlns: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">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to action bar tittle status.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @SuppressLint("RestrictedApi")
   @RequiresApi(api = Build.VERSION_CODES.N)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      getSupportActionBar().setTitle("Home");
      getSupportActionBar().setSubtitle("sairam");
      textView.setText(" "+getSupportActionBar().isTitleTruncated());
   }
   @Override
   public boolean onOptionsItemSelected(MenuItem menuItem) {
      if (menuItem.getItemId() = = android.R.id.home) {
         finish();
      }
      return super.onOptionsItemSelected(menuItem);
   }
}
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
Solve System of Equations in R

23 Aug, 2021
In this article, we will discuss how to solve a system of equations in R Programming Language. 
solve() function in R Language is used to solve the equation. Here equation is like a*x = b, where b is a vector or matrix and x is a variable whose value is going to be calculated.
Syntax: solve(a, b)
Parameters:
a: coefficients of the equation
b: vector or matrix of the equation
Given Equations:
x + 2y + 3z = 20  
2x + 2y + 3z = 100  
3x + 2y + 8z = 200

Matrix A and B for solution using coefficient of equations:
A->
1   2   3
2   2   3
3   2   8
B->
20
100
200
To solve this using two matrices in R we use the following code:
R
# create matrix A and B using given equationsA <- rbind(c(1, 2, 3),            c(2, 2, 3),            c(3, 2, 8))B <- c(20, 100, 200)  # Solve them using solve function in Rsolve(A, B)
Output:
80 -36 3.99999999999999
which means x=80, y=-36 and z=4 is the solution for linear equations.
To get solutions in form of fractions, we use library MASS in R Language and wrap solve function in fractions.
Given Equations:
19x + 32y + 31z = 1110  
22x + 28y + 13z = 1406  
31x + 12y + 81z = 3040
Matrix A and B for solution using coefficient of equations:
A->
19   32   31
22   28   13
31   12   81
B->
1110
1406
3040
To solve this using two matrices in R we use the following code:
R
# Load package MASSlibrary(MASS)  # create matrix A and B using given equationsA <- rbind(c(19, 32, 31),            c(22, 28, 31),            c(31, 12, 81))B <- c(1110, 1406, 3040)  # Solve them using solve# function wrapped in fractionsfractions(solve(A, B))
Output:
[1] 159950/2243 -92039/4486  29784/2243
which means x=159950/2243 , y=-92039/4486 and z=29784/2243 is the solution for the above given linear equation.
R
# create matrix A and B using given equationsA <- matrix(c(4, 7, 3, 6), ncol = 2)print(A)  print("Inverse matrix")  # Solve them using solve function in Rprint(solve(A))
Output:
     [,1] [,2]
[1,]    4    3
[2,]    7    6
[1] "Inverse matrix"
          [,1]      [,2]
[1,]  2.000000 -1.000000
[2,] -2.333333  1.333333
Picked
R Math-Function
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
HTML | DOM Input Checkbox defaultChecked Property

30 May, 2022
The Input Checkbox defaultChecked property in HTML is used to return the default value of checked attribute. It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.
Syntax: 
checkboxObject.defaultChecked
Return Values: It returns a Boolean value that returns true if the checkbox is checked by default otherwise returns false.
Example: This example illustrates the Input Checkbox defaultChecked property. 
HTML
<!DOCTYPE html><html>    <head>        <title>            DOM Input Checkbox defaultChecked Property        </title>    </head>         <body style="text-align:center;">             <h1 style="color:green;">            GeeksforGeeks        </h1>                 <h2>DOM Input Checkbox defaultChecked Property</h2>                 <form id="myGeeks">                     <!-- Below input elements have attribute                 checked -->            <input type="checkbox" name="check" id="GFG"                    value="1" Checked>Checked by default<br>                                 <input type="checkbox" name="check" value="2">                    Not checked by default<br>        </form><br>                 <button onclick="myGeeks()">            Submit        </button>                 <p id="sudo" style="color:green;font-size:25px;"></p>                   <!-- Script to return the Input Checkbox            defaultChecked Property -->        <script>            function myGeeks() {                var g = document.getElementById("GFG").defaultChecked;                document.getElementById("sudo").innerHTML = g;            }        </script>    </body></html>                            
Output: Before clicking on the Button:  
After clicking on the Button:  
Supported Browsers: The browser supported by DOM input Checkbox defaultchecked property are listed below: 
Google Chrome
Internet Explorer
Firefox
Opera
Safari
 
arorakashish0911
hritikbhatnagar2182
vinayedula
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Creating a simple machine learning model

13 Jun, 2018
Create a Linear Regression Model in Python using a randomly created data set.
Linear Regression ModelLinear regression geeks for geeks
Generating the Training Set
# python library to generate random numbersfrom random import randint  # the limit within which random numbers are generatedTRAIN_SET_LIMIT = 1000  # to create exactly 100 data itemsTRAIN_SET_COUNT = 100  # list that contains input and corresponding outputTRAIN_INPUT = list()TRAIN_OUTPUT = list()  # loop to create 100 data  items with three columns eachfor i in range(TRAIN_SET_COUNT):    a = randint(0, TRAIN_SET_LIMIT)    b = randint(0, TRAIN_SET_LIMIT)    c = randint(0, TRAIN_SET_LIMIT)  # creating the output for each data item    op = a + (2 * b) + (3 * c)    TRAIN_INPUT.append([a, b, c])  # adding each output to output list    TRAIN_OUTPUT.append(op)
Machine Learning Model – Linear Regression
The Model can be created in two steps:-1. Training the model with Training Data2. Testing the model with Test Data
Training the ModelThe data that was created using the above code is used to train the model
# Sk-Learn contains the linear regression modelfrom sklearn.linear_model import LinearRegression  # Initialize the linear regression modelpredictor = LinearRegression(n_jobs =-1)  # Fill the Model with the Datapredictor.fit(X = TRAIN_INPUT, y = TRAIN_OUTPUT)
Testing the DataThe testing is done Manually. Testing can be done using some random data and testing if the model gives the correct result for the input data.
# Random Test dataX_TEST = [[ 10, 20, 30 ]]  # Predict the result of X_TEST which holds testing dataoutcome = predictor.predict(X = X_TEST)  # Predict the coefficientscoefficients = predictor.coef_  # Print the result obtained for the test dataprint('Outcome : {}\nCoefficients : {}'.format(outcome, coefficients))
The Outcome of the above provided test-data should be, 10 + 20*2 + 30*3 = 140.Output
Outcome : [ 140.]
Coefficients : [ 1. 2. 3.]

Advanced Computer Subject
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
Docker - COPY Instruction
How to Run a Python Script using Docker?
ML | Underfitting and Overfitting
Clustering in Machine Learning
Agents in Artificial Intelligence
Search Algorithms in AI
Support Vector Machine Algorithm
Introduction to Recurrent Neural Network
ML | Underfitting and Overfitting
LEN() Function in SQL Server

27 Nov, 2020
LEN() function calculates the number of characters of an input string, excluding the trailing spaces.
Syntax :
LEN(input_string)
Parameter –This method accepts a single-parameter as mentioned above and described below :  
input_string –It is an expression that can be a constant, variable, or column of either character or binary data.
Returns :
It returns the number of characters of an input string, excluding the trailing spaces.
Example-1: Return the length of a string
SELECT LEN('Geeksforgeeks');
Output :
13
Example-2: Check LEN() Function count trailing spaces or not
SELECT LEN('GFG       ') 
As Length_with_trailing_spaces;
Output :
Example-3: Check LEN() Function count leading spaces or not
SELECT LEN('       GFG') 
As Length_with_leading_spaces;
Output:
Example-4: Using LEN() function with a column
Table — Player_Details
SELECT
    PlayerName,
    LEN(PlayerName) PlayerName_Length
FROM
    Player_Details
Output :
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL | Sub queries in From Clause
SQL using Python
RANK() Function in SQL Server
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
How to Write a SQL Query For a Specific Date Range and Date Time?
Angular Material 7 - Card

The <mat-card>, an Angular Directive, is used to create a card with material design styling and animation capabilities. It provides preset styles for the common card sections.
<mat-card-title> − Represents the section for title.
<mat-card-title> − Represents the section for title.
<mat-card-subtitle> − Represents the section for subtitle.
<mat-card-subtitle> − Represents the section for subtitle.
<mat-card-content> − Represents the section for content.
<mat-card-content> − Represents the section for content.
<mat-card-actions> − Represents the section for actions.
<mat-card-actions> − Represents the section for actions.
<mat-card-footer> − Represents the section for footer.
<mat-card-footer> − Represents the section for footer.
In this chapter, we will showcase the configuration required to draw a card control using Angular Material.
Follow the following steps to update the Angular application we created in Angular 6 - Project Setup chapter −
Following is the content of the modified module descriptor app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatCardModule, MatButtonModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatCardModule, MatButtonModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified CSS file app.component.css.
.tp-card {
   max-width: 400px;
}
.tp-header-image {
   background-image: url('https://www.tutorialspoint.com/materialize/src/html5-mini-logo.jpg');
   background-size: cover;
}
Following is the content of the modified HTML host file app.component.html.
<mat-card class = "tp-card">
   <mat-card-header>
      <div mat-card-avatar class = "tp-header-image"></div>
      <mat-card-title>HTML5</mat-card-title>
      <mat-card-subtitle>HTML Basics</mat-card-subtitle>
   </mat-card-header>
   <img mat-card-image src = "https://www.tutorialspoint.com/materialize/src/html5-mini-logo.jpg" alt = "Learn HTML5">
   <mat-card-content>
      <p>
         HTML5 is the next major revision of the HTML standard superseding
         HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for
         structuring and presenting content on the World Wide Web.
      </p>
   </mat-card-content>
   <mat-card-actions>
      <button mat-button>LIKE</button>
      <button mat-button>SHARE</button>
   </mat-card-actions>
</mat-card>
Verify the result.
Here, we've created a card using mat-card.
What is the use of scope resolution operator in C++?

The :: (scope resolution) operator is used to get hidden names due to variable scopes so that you can still use them. The scope resolution operator can be used as both unary and binary
You can use the single scope operator if a namespace scope or global scope name is hidden by a certain declaration of a similar name during a block or class. For example, if you have a global variable of name my_var and a local variable of name my_var, to access global my_var, you'll need to use the scope resolution operator. For example,
#include <iostream>  
using namespace std;  

int my_var = 0;
int main(void) {
   int my_var = 0;
   ::my_var = 1;  // set global my_var to 1
   my_var = 2;    // set local my_var to 2

   cout << ::my_var << ", " << my_var;
   return 0;
}
This will give the output −
1, 2
The declaration of my_var declared in the main function hides the integer named my_var declared in global namespace scope. The statement ::my_var = 1 accesses the variable named my_var declared in global namespace scope.
You can also use the scope resolution operator to use class names or class member names. If a class member name is hidden, you can use it by prefixing it with its class name and the class scope operator. For example,
#include <iostream>
using namespace std;

class X {
   public:
   static int count;
};

int X::count = 10;      // define static data member
int main () {
   int X = 0;          // hides class type X
   cout << X::count << endl;   // use static member of class X
}
This will give the output −
10
How to stop C++ console application from exiting immediately?

Sometimes we have noticed that the console is being closed immediately after displaying the result. So we cannot see the result properly. Here we will see how we can stop the console from closing.
The idea is very simple. We can use the getchar() function at the end. This will wait for one character. If one character is pressed, the console will exit.
 Live Demo
#include <iostream>
using namespace std;
int main() {
   cout << "Hello World" << endl;
   getchar();
}
Hello World
5
Here button 5 was pressed when it is waiting for a character.
Python 3 - Number tan() Method

The tan() method returns the tangent of x radians.
Following is the syntax for tan() method −
tan(x)

Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
This method returns a numeric value between -1 and 1, which represents the tangent of the parameter x.
The following example shows the usage of tan() method.
#!/usr/bin/python3
import math

print ("(tan(3) : ",  math.tan(3))
print ("tan(-3) : ",  math.tan(-3))
print ("tan(0) : ",  math.tan(0))
print ("tan(math.pi) : ",  math.tan(math.pi))
print ("tan(math.pi/2) : ",  math.tan(math.pi/2))
print ("tan(math.pi/4) : ",  math.tan(math.pi/4))
When we run the above program, it produces the following result −
(tan(3) :  -0.1425465430742778
tan(-3) :  0.1425465430742778
tan(0) :  0.0
tan(math.pi) :  -1.2246467991473532e-16
tan(math.pi/2) :  1.633123935319537e+16
tan(math.pi/4) :  0.9999999999999999


    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
How to initialize const member variable in a C++ class?

Here we will see how to initialize the const type member variable using constructor?
To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.
#include <iostream>
using namespace std;
class MyClass{
   private:
      const int x;
   public:
      MyClass(int a) : x(a){
      //constructor
   }
   void show_x(){
      cout << "Value of constant x: " << x ;
   }
};
int main() {
   MyClass ob1(40);
   ob1.show_x();
}
Value of constant x: 40
JavaScript algorithm for converting integers to roman numbers

Let’s say, we are required to write a function, say intToRoman(), which, as the name suggests,
returns a Roman equivalent of the number passed in it as an argument.
Let’s write the code for this function −
const intToRoman = (num) => {
   let result = "";
   while(num){
      if(num>=1000){
         result += "M";
         num -= 1000;
      }else if(num>=500){
         if(num>=900){
            result += "CM";
            num -= 900;
         }else{
            result += "D";
            num -= 500;
         }
         }else if(num>=100){
            if(num>=400){
               result += "CD";
               num -= 400;
            }else{
               result += "C";
               num -= 100;
            }
         }else if(num>=50){
            if(num>=90){
               result += "XC";
               num -= 90;
            }else{
               result += "L";
               num -= 50;
            }
         }else if(num>=10){
            if(num>=40){
               result += "XL";
               num -= 40;
            }else{
               result += "X";
               num -= 10;
            }
         }else if(num>=5){
            if(num>=9){
               result += "IX";
               num -= 9;
           }else{
               result += "V";
               num -= 5;
            }
         }else{
            if(num>=4){
               result += "IV";
               num -= 4;
         }else{
            result += "I";
            num -= 1;
         }
      }
   }
   return result;
};
console.log(intToRoman(178));
console.log(intToRoman(89));
console.log(intToRoman(55));
console.log(intToRoman(1555));
The output for this code in the console will be −
CLXXVIII
LXXXIX
LV
MDLV
Read file line by line using C++

This is a C++ program to read file line by line.
tpoint.txt is having initial content as
“Tutorials point.”
Tutorials point.
Begin
   Create an object newfile against the class fstream.
   Call open() method to open a file “tpoint.txt” to perform write operation using object newfile.
   If file is open then
      Input a string “Tutorials point" in the tpoint.txt file.
      Close the file object newfile using close() method.
   Call open() method to open a file “tpoint.txt” to perform read operation using object newfile.
   If file is open then
      Declare a string “tp”.
      Read all data of file object newfile using getline() method and put it into the string tp.
      Print the data of string tp.
Close the file object newfile using close() method.
End.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
   fstream newfile;
   newfile.open("tpoint.txt",ios::out);  // open a file to perform write operation using file object
   if(newfile.is_open()) //checking whether the file is open
   {
      newfile<<"Tutorials point \n";   //inserting text
      newfile.close();    //close the file object
   }
   newfile.open("tpoint.txt",ios::in); //open a file to perform read operation using file object
   if (newfile.is_open()){   //checking whether the file is open
      string tp;
      while(getline(newfile, tp)){ //read data from file object and put it into string.
         cout << tp << "\n"; //print the data of the string
      }
      newfile.close(); //close the file object.
   }
}
Tutorials point.
Program to determine color of a chessboard square using Python

Suppose we have a chessboard coordinate, that is a string that represents the coordinates of row and column of the chessboard. Below is a chessboard for your reference.
We have to check whether given cell is white or not, if white return true, otherwise return false.
So, if the input is like coordinate = "f5", then the output will be True (See the image)
To solve this, we will follow these steps −
if ASCII of coordinate[0] mod 2 is same coordinate[1]) mod 2, thenreturn False
if ASCII of coordinate[0] mod 2 is same coordinate[1]) mod 2, then
return False
return False
otherwise,return True
otherwise,
return True
return True
Let us see the following implementation to get better understanding −
 Live Demo
def solve(coordinate):
   if (ord(coordinate[0]))%2 == int(coordinate[1])%2:
      return False
   else:
      return True
coordinate = "f5"
print(solve(coordinate))
"f5"
True
How can we initialize a boolean array in Java?


The boolean array can be used to store boolean datatype values only and the default value of the boolean array is false. An array of booleans are initialized to false and arrays of reference types are initialized to null. In some cases, we need to initialize all values of the boolean array with true or false. We can use the Arrays.fill() method in such cases.
boolean[] booleanArray;
import java.util.Arrays;
public class BooleanArrayTest {
   public static void main(String[] args) {
      Boolean[] boolArray = new Boolean[5]; // initialize a boolean array
      for(int i = 0; i < boolArray.length; i++) {
         System.out.println(boolArray[i]);
      }
      Arrays.fill(boolArray, Boolean.FALSE);
      // all the values will be false
      for(int i = 0; i < boolArray.length; i++) {
         System.out.println(boolArray[i]);
      }
      Arrays.fill(boolArray, Boolean.TRUE);
      // all the values will be true
      for (int i = 0; i < boolArray.length; i++) {
         System.out.println(boolArray[i]);
      }
   }
}
null
null
null
null
null
false
false
false
false
false
true
true
true
true
true
SymPy - Derivative

The derivative of a function is its instantaneous rate of change with respect to one of its variables. This is equivalent to finding the slope of the tangent line to the function at a point.we can find the differentiation of mathematical expressions in the form of variables by using diff() function in SymPy package.
diff(expr, variable)
>>> from sympy import diff, sin, exp 
>>> from sympy.abc import x,y 
>>> expr=x*sin(x*x)+1 >>> expr

The above code snippet gives an output equivalent to the below expression −
xsin⁡(x2)+1
>>> diff(expr,x)

The above code snippet gives an output equivalent to the below expression −
2x2cos⁡(x2)+sin⁡(x2)
>>> diff(exp(x**2),x)

The above code snippet gives an output equivalent to the below expression −
2xex2
To take multiple derivatives, pass the variable as many times as you wish to differentiate, or pass a number after the variable.
>>> diff(x**4,x,3)

The above code snippet gives an output equivalent to the below expression −
24x
>>> for i in range(1,4): print (diff(x**4,x,i))

The above code snippet gives the below expression −
4*x**3
12*x**2
24*x
It is also possible to call diff() method of an expression. It works similarly as diff() function.
>>> expr=x*sin(x*x)+1 
>>> expr.diff(x)

The above code snippet gives an output equivalent to the below expression −
2x2cos⁡(x2)+sin⁡(x2)
An unevaluated derivative is created by using the Derivative class. It has the same syntax as diff() function. To evaluate an unevaluated derivative, use the doit method.
>>> from sympy import Derivative 
>>> d=Derivative(expr) 
>>> d

The above code snippet gives an output equivalent to the below expression −
ddx(xsin⁡(x2)+1)
>>> d.doit()

The above code snippet gives an output equivalent to the below expression −
2x2cos⁡(x2)+sin⁡(x2)
 Print
 Add Notes
 Bookmark this page
Working with Display Block in CSS

The CSS Display property with value block renders an element with parent’s full width available, it also forces a line break. An element with display as block renders as a <div> or <p> element.
Following is the syntax of CSS display block −
Selector {
   display: block;
}
Let’s see an example of CSS display block −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<title>CSS Display Block</title>
<style>
form {
   width:70%;
   margin: 0 auto;
   text-align: center;
}
* {
   padding: 2px;
   margin:5px;
}
input[type="button"] {
   border-radius: 10px;
}
em{
   background-color: #C303C3;
   color: #fff;
   display:block;
}
</style>
</head>
<body>
<form>
<fieldset>
<legend>CSS-Display-Block</legend>
<label for="textSelect">Formatter: </label>
<input id="textSelect" type="text" placeholder="John Doe">
<input type="button" onclick="convertItalic()" value="Check">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var textSelect = document.getElementById("textSelect");
function convertItalic() {
   for(i=0; i<2; i++){
      var italicObject = document.createElement("EM");
      var italicText = document.createTextNode(textSelect.value);
      italicObject.appendChild(italicText);
      divDisplay.appendChild(italicObject);
   }
}
</script>
</body>
</html>
This will produce the following output −
Before clicking ‘Check’ button −
After clicking ‘Check’ button −
Let’s see another example of CSS Display block −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#flex {
   display: flex;
}
#none {
   display: none;
}
.inline-block {
   display: inline-block;
   background-color: mintcream;
}
.grid {
   display: grid;
   background-color: cornflowerblue;
}
div {
   margin: 30px;
   padding: 5px;
   height: 10px;
   line-height: 5px;
   text-align: center;
   background-color: lightblue;
   border: 2px solid black;
}
div > div {
   background-color: lightpink;
   border: 2px solid green;
}
div > div > div {
   background-color: sandybrown;
   border: 2px solid darkred;
}
</style>
</head>
<body>
<div><span id="flex">heyyy</span>
<div><span id="none">heyyy</span>
<div>
<span class="inline-block">heyyy</span>
<span class="inline-block">heyyy</span>
<div>
<span class="grid">heyyy demo</span>
<span class="grid">heyyy demo</span>
</div>
</div>
</div>
</div>
</body>
</html>
This will produce the following output −
How to map keys to values for an individual field in a MySQL select query?

You can use CASE statement in MySQL to map keys to values for an individual field in select query. The syntax is as follows −
SELECT yourColumnName1,yourColumnName2,yourColumnName3,.........N
(
   CASE WHEN yourColumnName = 1 THEN 'ENABLED'
   ELSE 'DISABLED'
   END
) AS anyVariableName
FROM yourTableName;
You can use IF() function also for the same purpose. The syntax is as follows −
SELECT yourColumnName1,yourColumnName2,yourColumnName3,.........N
,IF(yourColumnName,'ENABLED','DISABLED') as anyVariableName FROM yourTableName;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table MapKeys
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> Name varchar(20),
   -> isActive boolean,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into MapKeys(Name,isActive) values('Larry',true);
Query OK, 1 row affected (0.13 sec)

mysql> insert into MapKeys(Name,isActive) values('David',false);
Query OK, 1 row affected (0.16 sec)

mysql> insert into MapKeys(Name,isActive) values('Mike',true);
Query OK, 1 row affected (0.14 sec)

mysql> insert into MapKeys(Name,isActive) values('Carol',false);
Query OK, 1 row affected (0.17 sec)

mysql> insert into MapKeys(Name,isActive) values('Sam',false);
Query OK, 1 row affected (0.15 sec)

mysql> insert into MapKeys(Name,isActive) values('Bob',true);
Query OK, 1 row affected (0.19 sec)
Display all records from the table using select statement. The query is as follows:
mysql> select *from MapKeys;
The following is the output −
+----+-------+----------+
| Id | Name  | isActive |
+----+-------+----------+
|  1 | Larry |        1 |
|  2 | David |        0 |
|  3 | Mike  |        1 |
|  4 | Carol |        0 |
|  5 | Sam   |        0 |
|  6 | Bob   |        1 |
+----+-------+----------+
6 rows in set (0.00 sec)
Let us now map key using case statement. The query is as follows −
mysql> select Id,Name,
   -> (
   -> CASE WHEN isActive = 1 THEN 'ENABLED'
   -> ELSE 'DISABLED'
   -> END
   -> ) AS Status
   -> from MapKeys;
The following is the output −
+----+-------+----------+
| Id | Name  | Status   |
+----+-------+----------+
|  1 | Larry | ENABLED  |
|  2 | David | DISABLED |
|  3 | Mike  | ENABLED  |
|  4 | Carol | DISABLED |
| 5  | Sam   | DISABLED |
| 6  | Bob   | ENABLED  |
+----+-------+----------+
6 rows in set (0.00 sec)
You can achieve the same with the help of IF() function −
mysql> select Id,Name,if(isActive,'ENABLED','DISABLED') as Status from MapKeys;
The following is the output −
+----+-------+----------+
| Id | Name  | Status   |
+----+-------+----------+
| 1 | Larry | ENABLED   |
| 2 | David | DISABLED |
| 3 | Mike   | ENABLED |
| 4 | Carol | DISABLED |
| 5 | Sam   | DISABLED |
| 6 | Bob   | ENABLED  |
+----+-------+----------+
6 rows in set (0.00 sec)
Why the t.test returns a smallest p-value of 2.2e – 16 in R?

When we perform a t test in R and the difference between two groups is very large then the p-value of the test is printed as 2.2e – 16 which is a printing behaviour of R for hypothesis testing procedures. The actual p-value can be extracted by using the t test function as t.test(“Var1”,”Var2”,var.equal=FALSE)$p.value. This p-value is not likely to be the same as 2.2e – 16.
 Live Demo
> x1<-1:100
> y1<-100001:110000
> t.test(x1,y1,var.equal=FALSE)
   Welch Two Sample t-test
data: x1 and y1
t = -3617.2, df = 10098, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-105006.9 -104893.1
sample estimates:
mean of x mean of y
   50.5 105000.5
> t.test(x1,y1,var.equal=FALSE)$p.value
[1] 0
 Live Demo
> x2<-sample(1:10,50,replace=TRUE)
> y2<-sample(500:510,replace=TRUE)
> t.test(x2,y2,var.equal=FALSE)
   Welch Two Sample t-test
data: x2 and y2
t = -427.61, df = 12.789, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-500.4179 -495.3785
sample estimates:
mean of x mean of y
   5.9200 503.8182
> t.test(x2,y2,var.equal=FALSE)$p.value
[1] 5.881324e-28
 Live Demo
> x3<-sample(101:110,50,replace=TRUE)
> y3<-sample(1001:1010,50,replace=TRUE)
> t.test(x3,y3,var.equal=FALSE)
   Welch Two Sample t-test
data: x3 and y3
t = -1730.7, df = 97.907, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-901.4725 -899.4075
sample estimates:
mean of x mean of y
   105.38 1005.82
> t.test(x3,y3,var.equal=FALSE)$p.value
[1] 2.07048e-221
 Live Demo
> x4<-sample(1001:1010,50,replace=TRUE)
> y4<-sample(100001:1000010,50)
> t.test(x4,y4,var.equal=FALSE)
   Welch Two Sample t-test
data: x4 and y4
t = -14.798, df = 49, p-value < 2.2e-16
alternative hypothesis: true difference in means is not equal to 0
95 percent confidence interval:
-620129.5 -471835.6
sample estimates:
mean of x mean of y
   1005.6 546988.1
> t.test(x4,y4,var.equal=FALSE)$p.value
[1] 1.043251e-19
SQL - WHERE Clause

The SQL WHERE clause is used to specify a condition while fetching the data from a single table or by joining with multiple tables. If the given condition is satisfied, then only it returns a specific value from the table. You should use the WHERE clause to filter the records and fetching only the necessary records.
The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.
The basic syntax of the SELECT statement with the WHERE clause is as shown below.
SELECT column1, column2, columnN 
FROM table_name
WHERE [condition]

You can specify a condition using the comparison or logical operators like >, <, =, LIKE, NOT, etc. The following examples would make this concept clear.
Consider the CUSTOMERS table having the following records −
+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+
The following code is an example which would fetch the ID, Name and Salary fields from the CUSTOMERS table, where the salary is greater than 2000 −
SQL> SELECT ID, NAME, SALARY 
FROM CUSTOMERS
WHERE SALARY > 2000;
This would produce the following result −
+----+----------+----------+
| ID | NAME     | SALARY   |
+----+----------+----------+
|  4 | Chaitali |  6500.00 |
|  5 | Hardik   |  8500.00 |
|  6 | Komal    |  4500.00 |
|  7 | Muffy    | 10000.00 |
+----+----------+----------+

The following query is an example, which would fetch the ID, Name and Salary fields from the CUSTOMERS table for a customer with the name Hardik.
SQL> SELECT ID, NAME, SALARY 
FROM CUSTOMERS
WHERE NAME = 'Hardik';
This would produce the following result −
+----+----------+----------+
| ID | NAME     | SALARY   |
+----+----------+----------+
|  5 | Hardik   |  8500.00 |
Lex program to check whether given string is Palindrome or Not

01 May, 2019
Problem: Write a Lex program to check whether given string is Palindrome or Not.
Explanation:Lex is a computer program that generates lexical analyzers and was written by Mike Lesk and Eric Schmidt. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
Description: A string is said to be palindrome if reverse of the string is same as string. For example, “abba” is palindrome, but “abbc” is not palindrome.
Examples:
Input: Enter a string : naman 
Output: Given string is Palindrome

Input: Enter a string : geeksforgeeks
Output: Given string is not Palindrome 
Implementation:
/* Lex program to check whether      - given string is Palindrome or Not */  % {    int i, j, flag;    % }  /* Rule Section */% %    [a - z A - z 0 - 9]*{    for (i = 0, j = yyleng - 1; i <= j; i++, j--) {        if (yytext[i] == yytext[j]) {            flag = 1;        }        else {            flag = 0;            break;        }    }    if (flag == 1)        printf("Given string is Palindrome");    else        printf("Given string is not Palindrome");}% %      // driver code    int main(){    printf("Enter a string :");    yylex();    return 0;}  int yywrap(){    return 1;}
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Data flow analysis in Compiler
S - attributed and L - attributed SDTs in Syntax directed translation
Runtime Environments in Compiler Design
Compiler construction tools
Basic Blocks in Compiler Design
Token, Patterns, and Lexems
Compiler Design - Variants of Syntax Tree
Loop Optimization in Compiler Design
Perl | Data Types

22 Jun, 2022
Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself. 
There are 3 data types in Perl as follows: 
ScalarsArraysHashes(Associative Arrays)
Scalars
Arrays
Hashes(Associative Arrays)
It is a single unit of data that can be an integer number, floating-point, a character, a string, a paragraph, or an entire web page. To know more about scalars please refer to Scalars in Perl. 
Example:
Perl
# Perl Program to demonstrate the# Scalars data types # An integer assignment$age = 1;             # A string$name = "ABC"; # A floating point  $salary = 21.5;     # displaying resultprint "Age = $age\n";print "Name = $name\n";print "Salary = $salary\n";
Output: 
Age = 1
Name = ABC
Salary = 21.5
Scalar Operations: There are many operations that can be performed on the scalar data types like addition, subtraction, multiplication, etc.
Example:
Perl
# Perl Program to demonstrate# the Scalars operations #!/usr/bin/perl # Concatenates strings$str = "GFG" . " is the best"; # adds two numbers    $num = 1 + 0; # multiplies two numbers            $mul = 4 * 9; # concatenates string and number            $mix = $str . $num;             # displaying resultprint "str = $str\n";print "num = $num\n";print "mul = $mul\n";print "mix = $mix\n";
Output: 
str = GFG is the best
num = 1
mul = 36
mix = GFG is the best1
An array is a variable that stores the value of the same data type in the form of a list. To declare an array in Perl, we use ‘@’ sign in front of the variable name. 
@age=(10, 20, 30)
It will create an array of integers that contains the values 10, 20, and 30. To access a single element of an array, we use the ‘$’ sign. 
$age[0]
It will produce an output of 10. To know more about arrays please refer to Arrays in Perl
Example:
Perl
# Perl Program to demonstrate# the Arrays data type #!/usr/bin/perl # creation of arrays@ages = (33, 31, 27);            @names = ("Geeks", "for", "Geeks"); # displaying resultprint "\$ages[0] = $ages[0]\n";print "\$ages[1] = $ages[1]\n";print "\$ages[2] = $ages[2]\n";print "\$names[0] = $names[0]\n";print "\$names[1] = $names[1]\n";print "\$names[2] = $names[2]\n";
Output: 
$ages[0] = 33
$ages[1] = 31
$ages[2] = 27
$names[0] = Geeks
$names[1] = for
$names[2] = Geeks
It is a set of key-value pair. It is also termed the Associative Arrays. To declare a hash in Perl, we use the ‘%’ sign. To access the particular value, we use the ‘$’ symbol which is followed by the key in braces.
Example:
Perl
# Perl Program to demonstrate the# Hashes data type # Hashes%data = ('GFG', 7, 'for', 4, 'Geeks', 11); #displaying resultprint "\$data{'GFG'} = $data{'GFG'}\n";print "\$data{'for'} = $data{'for'}\n";print "\$data{'Geeks'} = $data{'Geeks'}\n";
Output: 
$data{'GFG'} = 7
$data{'for'} = 4
$data{'Geeks'} = 11
lakshmansingh5016
deepakbethi416
perl-basics
perl-data-types
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
reflect.Indirect() Function in Golang with Examples

28 Apr, 2020
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Indirect() Function in Golang is used to get the value that v points to, i.e., If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v. To access this function, one needs to imports the reflect package in the program.
Syntax:
func Indirect(v Value) Value

Parameters: This function takes the following parameters:
v: This parameter is the value to be passed.
Return Value: This function returns the value that v points to.
Below examples illustrate the use of the above method in Golang:
Example 1:
// Golang program to illustrate// reflect.Indirect() Function  package main  import (    "fmt"    "reflect")  // Main functionfunc main() {     val1:= []int  {1, 2, 3, 4}                    var val2 reflect.Value = reflect.ValueOf(&val1)     fmt.Println("&val2 type : ", val2.Kind())           // using the function     indirectI := reflect.Indirect(val2)     fmt.Println("indirectI  type : ", indirectI.Kind())     fmt.Println("indirectI  value : ", indirectI)  }
Output:
&val2 type :  ptr
indirectI  type :  slice
indirectI  value :  [1 2 3 4]

Example 2:
// Golang program to illustrate// reflect.Indirect() Function  package main  import (    "fmt"    "reflect")  // Main functionfunc main() {     var val1 []int                    var val2 [3]string             var val3 = make(map[int]string)        var val4 reflect.Value = reflect.ValueOf(&val1)     indirectI := reflect.Indirect(val4)     fmt.Println("val1: ", indirectI.Kind())         var val5 reflect.Value = reflect.ValueOf(&val2)     indirectStr := reflect.Indirect(val5)     fmt.Println("val2 type : ", indirectStr.Kind())       var val6 reflect.Value = reflect.ValueOf(&val3)     fmt.Println("&val3 type : ", val6.Kind())       indirectM := reflect.Indirect(val6)     fmt.Println("val3 type : ", indirectM.Kind())  }
Output:
val1:  slice
val2 type :  array
&val3 type :  ptr
val3 type :  map

Golang-reflect
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
TreeMap entrySet() Method in Java

09 Jul, 2018
The java.util.TreeMap.entrySet() method in Java is used to create a set out of the same elements contained in the treemap. It basically returns a set view of the treemap or we can create a new set and store the map elements into them.
Syntax:
tree_map.entrySet()
Parameters: The method does not take any parameter.
Return Value: The method returns a set having same elements as the treemap.
Below programs are used to illustrate the working of java.util.TreeMap.entrySet() Method:Program 1: Mapping String Values to Integer Keys.
// Java code to illustrate the entrySet() methodimport java.util.*;  public class Tree_Map_Demo {    public static void main(String[] args)    {          // Creating an empty TreeMap        TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>();          // Mapping string values to int keys        tree_map.put(10, "Geeks");        tree_map.put(15, "4");        tree_map.put(20, "Geeks");        tree_map.put(25, "Welcomes");        tree_map.put(30, "You");          // Displaying the TreeMap        System.out.println("Initial Mappings are: " + tree_map);          // Using entrySet() to get the set view        System.out.println("The set is: " + tree_map.entrySet());    }}
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
The set is: [10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You]

Program 2: Mapping Integer Values to String Keys.
// Java code to illustrate the entrySet() methodimport java.util.*;  public class Tree_Map_Demo {    public static void main(String[] args)    {          // Creating an empty TreeMap        TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>();          // Mapping int values to string keys        tree_map.put("Geeks", 10);        tree_map.put("4", 15);        tree_map.put("Geeks", 20);        tree_map.put("Welcomes", 25);        tree_map.put("You", 30);          // Displaying the TreeMap        System.out.println("Initial Mappings are: " + tree_map);          // Using entrySet() to get the set view        System.out.println("The set is: " + tree_map.entrySet());    }}
Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}
The set is: [4=15, Geeks=20, Welcomes=25, You=30]

Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
Java-Collections
java-TreeMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.