code-rag-bench/online-tutorials huggingface dataset:
Create a blue button (primary) with Bootstrap

Use the .btn-primary class in Bootstrap to create a primary button in Bootstrap that is blue in color −
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>Click below if you want to know the result:</p>
      <button type = "button" class = "btn btn-primary">Result</button>
   </body>
</html>
How to open new pseudo-terminal pair using Python?

You can use the os.openpty() to open a new pseudo-terminal pair using Python. This method gives a pair of file descriptors (master, slave), for the master and the slave end, respectively.
You can use it in the following way:
import os
# master for pty, slave for tty
m,s = os.openpty()
print m
print s
# showing terminal name
s = os.ttyname(s)
print m
print s
You will get the output:
3
4
3
/dev/pty0
How to change the color of a single bar if a condition is true (Matplotlib)?

To change the color of a single bar if a condition is true, we can make a set of values and a list of colors with red until the value is 2; else add yellow color in the list.
Set the figure size and adjust the padding between and around the subplots.
Initialize a variable width of a bar.
Make two lists of values and colors.
Use bar() method to plot bars.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.arange(5)
width = 0.5
vals = [1, 2, 1, 5, 3]
colors = ["red" if i != 2 else "yellow" for i in vals]
plt.bar(data, vals, width, color=colors)
plt.show()
PHP program to split a given comma delimited string into an array of values

To split a given comma delimited string into an array of values, the PHP code is as follows −
 Live Demo
<?php
$my_string = "456,789,23, 4, 019";
$my_str_arr = preg_split ("/,/", $my_string);
print_r("The array is ");
print_r($my_str_arr);
$my_string = "00, 876, 5432, 1234, 0";
$my_str_arr = explode (",", $my_string);
print_r("The array is ");
print_r($my_str_arr);
?>
The array is Array
(
   [0] => 456
   [1] => 789
   [2] => 23
   [3] => 4
   [4] => 019
)
The array is Array
(
   [0] => 00
   [1] => 876
   [2] => 5432
   [3] => 1234
   [4] => 0
)
A string of numbers is defined and the ‘preg_split’ function is used to separate the numbers based on the occurance of ‘/’ or ‘.’. The split array is now printed. Another method to split the given number in the form of a string is to use the explode function. It splits the array based on the occurance of a comma.
Get Operating System temporary directory / folder in Java

To get the temporary directory in Java, use the System.getProperty() method. Use the
It’s syntax is −
String getProperty(String key)
Above, the key is the name of the system property. Since, we want the Java Home Directory name, therefore we will add the key as −
java.io.tmpdir
The following is an example −
 Live Demo
public class Demo {
   public static void main(String []args){
      String strTmp = System.getProperty("java.io.tmpdir");
      System.out.println("OS current temporary directory: " + strTmp);
      System.out.println("OS Name: " + System.getProperty("os.name"));
      System.out.println("OS Version: " + System.getProperty("os.version"));
   }
}
OS current temporary directory: /tmp
OS Name: Linux
OS Version: 3.10.0-862.9.1.el7.x86_64
What are the essential tags for an HTML Document?

HTML has various tags to format content, heading, align content, add sections, etc to a website. Some of the essential tags for an HTML document are doctype, <html>, <head>, <title> and <body>.
doctypedoctype is the doctype declaration type. It is used for specifying which version of HTML the document is using.
<!DOCTYPE html>
<html>The HTML <html> tag is the container for all other HTML elements except for the <!DOCTYPE html> tag, which is located before the opening <html> tag. All other HTML elements are nested between the <html> and </html> tags.<head>The HTML <head> tag is used for indicating the head section of the HTML document. Tags included inside head tags are not displayed on browser window.<title>The <title>...</title> tag goes inside the <html>...</html>. The title text gets added on the web browser tab. It is visible on the web browsers title bar.
<head>
   <title>HTML Document</title>
</head>
<body>
The HTML <body> tag shows the main content section of the HTML document. The <p> tag for formatting, <strong> tag for bold text, <ul> tag for ordered list, etc gets added inside the HTML <body>...</body> tag.
How can I convert Python strings into tuple?

Python’s built-in function tuple() converts any sequence object to tuple. If it is a string, each character is treated as a string and inserted in tuple separated by commas.
>>> string="Tutorialspoint"
>>> tuple(string)
('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'p', 'o', 'i', 'n', 't')
Any non-sequence object as argument results in TypeError.
What is dependency injection in PHP?


Dependency injection is a procedure where one object supplies the dependencies of another object. Dependency Injection is a software design approach that allows avoiding hard-coding dependencies and makes it possible to change the dependencies both at runtime and compile time.
There are numerous approaches to inject objects, here are couple generally known −
In this approach, we can inject an object through the class constructor.
 Live Demo
<?php
   class Programmer {
      private $skills;
      public function __construct($skills){
         $this->skills = $skills;
      }
      public function totalSkills(){
         return count($this->skills);
      }
   }
   $createskills = array("PHP", "JQUERY", "AJAX");
   $p = new Programmer($createskills);
   echo $p->totalSkills();
?>
3
where you inject the object to your class through a setter function.
<?php
   class Profile {
      private $language;
      public function setLanguage($language){
         $this->language = $language;
      }
   }
   $profile = new Profile();
   $language = array["Hindi","English","French"];
   $profile->setLanguage($language);
?>
Adding a new dependency is as easy as adding a new setter method, which does not interfere with the existing code.
Statistical - BAHTTEXT Function

The BAHTTEXT function converts a number to Thai text and adds a suffix of "Baht."
BAHTTEXT (number)

You can change the Baht format to a different style in the Excel desktop application by using Regional and Language Options in Control Panel of Windows.
You can change the Baht format to a different style in the Excel desktop application by using Regional and Language Options in Control Panel of Windows.
If number is not recognized as a numeric value, BAHTTEXT returns #VALUE! Error value.
If number is not recognized as a numeric value, BAHTTEXT returns #VALUE! Error value.
Excel 2007, Excel 2010, Excel 2013, Excel 2016

    296 Lectures 
     146 hours 

 Arun Motoori

    56 Lectures 
     5.5 hours 

 Pavan Lalwani

    120 Lectures 
     6.5 hours 

 Inf Sid

    134 Lectures 
     8.5 hours 

 Yoda Learning

    46 Lectures 
     7.5 hours 

 William Fiset

    25 Lectures 
     1.5 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
ML | ADAM (Adaptive Moment Estimation) Optimization - GeeksforGeeks

08 Sep, 2021
Prerequisite: Optimization techniques in Gradient Descent
Gradient Descent is applicable in the scenarios where the function is easily differentiable with respect to the parameters used in the network. It is easy to minimize continuous functions than minimizing discrete functions. The weight update is performed after one epoch, where one epoch represents running through an entire dataset. This technique produces satisfactory results but it deteriorates if the training dataset size becomes large and does not converge well. It also may not lead to a global minimum in case of the existence of multiple local minima.
Stochastic gradient descent overcomes this drawback by randomly selecting data samples and updating the parameters based on the cost function. Additionally, it converges faster than regular gradient descent and saves memory by not accumulating the intermediate weights.Adaptive Moment Estimation (ADAM) facilitates the computation of learning rates for each parameter using the first and second moment of the gradient.
Being computationally efficient, ADAM requires less memory and outperforms on large datasets. It require p2, q2, t to be initialized to 0, where p0 corresponds to 1st moment vector i.e. mean, q0 corresponds to 2nd moment vector i.e. uncentered variance and t represents timestep.While considering ƒ(w) to be the stochastic objective function with parameters w, proposed values of parameters in ADAM, are as follows:
α = 0.001, m1=0.9, m2=0.999,  ε = 10-8. 
Another major advantage discussed in the study of ADAM is that the updation of the parameter is completely invariant to gradient rescaling, the algorithm will converge even if the objective function changes with time. The drawback of this particular technique is that it requires the computation of second-order derivatives which results in increased cost.
The algorithm of ADAM has been briefly mentioned below –
Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
ML | Stochastic Gradient Descent (SGD)
Support Vector Machine Algorithm
CNN | Introduction to Pooling Layer
Difference between Informed and Uninformed Search in AI
Singular Value Decomposition (SVD)
ML | Logistic Regression using Python
Principal Component Analysis with Python
ML | Linear Discriminant Analysis
Difference between ANN, CNN and RNN
Normalization vs Standardization
Python | Pandas Period.to_timestamp

06 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Period.to_timestamp() function return the Timestamp representation of the Period at the target frequency at the specified end (how) of the Period.
Syntax : Period.to_timestamp()
Parameters :freq : Target frequency. Default is ‘D’ if self.freq is week or longer and ‘S’ otherwisehow : ‘S’, ‘E’. Can be aliased as case insensitive ‘Start’, ‘Finish’, ‘Begin’, ‘End’
Return : Timestamp
Example #1: Use Period.to_timestamp() function to return the given period object as a Timestamp object in the specified frequency.
# importing pandas as pdimport pandas as pd  # Create the Period objectprd = pd.Period(freq ='S', year = 2000, month = 2, day = 22,                         hour = 8, minute = 21, second = 24)  # Print the Period objectprint(prd)
Output :
Now we will use the Period.to_timestamp() function to return the given period object as a timestamp object.
# return as a timestamp in the specified frequency.# 'M' represents monthly frequencyprd.to_timestamp(freq ='M')
Output :
As we can see in the output, the Period.to_timestamp() function has returned the given period object as a timestamp in the specified frequency. Example #2: Use Period.to_timestamp() function to return the given period object as a Timestamp object in the specified frequency.
# importing pandas as pdimport pandas as pd  # Create the Period objectprd = pd.Period(freq ='S', year = 2006, month = 10,               hour = 15, minute = 49, second = 17)  # Print the objectprint(prd)
Output :
Now we will use the Period.to_timestamp() function to return the given period object as a timestamp object.
# return as a timestamp in the specified frequency.# 'T' represents minutely frequencyprd.to_timestamp(freq ='T')
Output :
As we can see in the output, the Period.to_timestamp() function has returned the given period object as a timestamp in the specified frequency.
Pandas scalar-period
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
numpy.trapz() function | Python

26 Mar, 2020
numpy.trapz() function integrate along the given axis using the composite trapezoidal rule.
Syntax : numpy.trapz(y, x = None, dx = 1.0, axis = -1)
Parameters :y : [array_like] Input array to integrate.x : [array_like, optional] The sample points corresponding to the y values. If x is None, the sample points are assumed to be evenly spaced dx apart. The default is None.dx : [scalar, optional] The spacing between sample points when x is None. The default is 1.axis : [int, optional] The axis along which to integrate.
Return :trapz: [float] Definite integral as approximated by trapezoidal rule.
Code #1 :
# Python program explaining# numpy.trapz() function  # importing numpy as geek  import numpy as geek  y = [1, 2, 3, 4]  gfg = geek.trapz( y )  print (gfg)
Output :
7.5

 Code #2 :
# Python program explaining# numpy.trapz() function  # importing numpy as geek  import numpy as geek  y = [1, 2, 3, 4]x = [5, 6, 7, 8]  gfg = geek.trapz(y, x)  print (gfg)
Output :
7.5

 Code #3 :
# Python program explaining# numpy.trapz() function  # importing numpy as geek  import numpy as geek  y = [1, 2, 3, 4]    gfg = geek.trapz(y, dx = 2)  print (gfg)
Output :
15.0

Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Change the Name of a Pygame window?

01 Oct, 2021
PyGame window is a simple window that displays our game on the window screen. By default, pygame uses “Pygame window” as its title and pygame icon as its logo for pygame window. We can use set_caption() function to change the name and set_icon() to set icon of our window.
To change the name of pygame window:
Syntax: pygame.display.set_caption('Title of window')
To change the icon of pygame window:
Syntax: pygame.display.set_icon(Icon_name)
Step 1: First we import and initialize all imported modules. We use import pygame to import all modules and .init() function to initialize those modules.
import pygame
pygame.init() 
Step 2: Initialize a window to display. We use .set_mode() function to create a window. We pass the width and height of our window as parameters to set_mode() function.
pygame.display.set_mode((width_of_window,height_of_window))
Step 3: To change default title and icon of pygame window we use .set_caption() and .set_icon() functions. To change icon first we load icon image using pygame.image.load(“image_path”) function, and then we use .set_icon() to change default image.
pygame.display.set_caption('GeeksforGeeks')


Icon = pygame.image.load('gfglogo.png')


pygame.display.set_icon(Icon)
Step 4: Keep that window running until the user presses the exit button. We use a variable that is true unless the user presses the quit button. To keep the game running we use a while loop and check our variable if it is true or not.
running  = True

while running:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
           running = False
Complete Code:
Python3
# import pygame moduleimport pygame # initializing imported modulepygame.init() # Displaying a window of height# 500 and width 400pygame.display.set_mode((400, 500)) # Here we set name or title of our# pygame windowpygame.display.set_caption('GeeksforGeeks') # Here we load the image we want to# useIcon = pygame.image.load('gfglogo.png') # We use set_icon to set new iconpygame.display.set_icon(Icon) # Creating a bool value which checks if# game is runningrunning = True # Keep game running till running is truewhile running:         # Check for event if user has pushed    # any event in queue    for event in pygame.event.get():                 # If event is of type quit then set        # running bool to false        if event.type == pygame.QUIT:            running = False
Output:
sumitgumber28
anikaseth98
Picked
Python-PyGame
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
Flood fill algorithm using C graphics

30 Jun, 2021
Given a rectangle, your task to fill this rectangle using flood fill algorithm. Examples:  
Input : rectangle(left = 50, top = 50, right= 100, bottom = 100)
        flood( x = 55, y = 55, new_color = 12, old_color = 0)
Output : 
Input : rectangle(left = 50, top = 50, right= 200, bottom = 400)
        flood( x = 51, y = 51, new_color = 6, old_color = 0)
Output :
 
Flood fill algorithm fills new color until the old color match.Flood fill algorithm:-  
// A recursive function to replace previous
// color 'oldcolor' at  '(x, y)' and all 
// surrounding pixels of (x, y) with new 
// color 'newcolor' and
floodfill(x, y, newcolor, oldcolor)
1) If x or y is outside the screen, then
   return.
2) If color of getpixel(x, y) is same as
   oldcolor, then 
3) Recur for top, bottom, right and left.
    floodFill(x+1, y, newcolor, oldcolor);
    floodFill(x-1, y, newcolor, oldcolor);
    floodFill(x, y+1, newcolor, oldcolor);
    floodFill(x, y-1, newcolor, oldcolor); 
 
CPP
// program to fill polygon using floodfill// algorithm#include <graphics.h>#include <stdio.h> // flood fill algorithmvoid flood(int x, int y, int new_col, int old_col){    // check current pixel is old_color or not    if (getpixel(x, y) == old_col) {         // put new pixel with new color        putpixel(x, y, new_col);         // recursive call for bottom pixel fill        flood(x + 1, y, new_col, old_col);         // recursive call for top pixel fill        flood(x - 1, y, new_col, old_col);         // recursive call for right pixel fill        flood(x, y + 1, new_col, old_col);         // recursive call for left pixel fill        flood(x, y - 1, new_col, old_col);    }} int main(){    int gd, gm = DETECT;     // initialize graph    initgraph(&gd, &gm, "");     // rectangle coordinate    int top, left, bottom, right;     top = left = 50;    bottom = right = 300;     // rectangle for print rectangle    rectangle(left, top, right, bottom);     // filling start coordinate    int x = 51;    int y = 51;     // new color to fill    int newcolor = 12;     // new color which you want to fill    int oldcolor = 0;     // call for fill rectangle    flood(x, y, newcolor, oldcolor);    getch();     return 0;}
Output:-  
 
as5853535
c-graphics
computer-graphics
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
C Program to Swap two Numbers
How to Append a Character to a String in C
Program to find Prime Numbers Between given Interval
C program to sort an array in ascending order
Set, Clear and Toggle a given bit of a number in C
Synchronous and Asynchronous in JavaScript

09 Jul, 2020
Synchronous JavaScript: As the name suggests synchronous means to be in a sequence, i.e. every statement of the code gets executed one by one. So, basically a statement has to wait for the earlier statement to get executed.Let us understand this with the help of an example.
Example:
<script>    document.write("Hi"); // First    document.write("<br>");      document.write("Mayukh") ;// Second    document.write("<br>");          document.write("How are you"); // Third</script>
Output:
In the above code snippet, the first line of the code Hi will be logged first then the second line Mayukh will be logged and then after its completion, the third line would be logged How are you.So as we can see the codes work in a sequence. Every line of code waits for its previous one to get executed first and then it gets executed.
Asynchronous JavaScript: Asynchronous code allows the program to be executed immediately where the synchronous code will block further execution of the remaining code until it finishes the current one. This may not look like a big problem but when you see it in a bigger picture you realize that it may lead to delaying the User Interface.
Let us see the example how Asynchronous JavaScript runs.
<script>    document.write("Hi");    document.write("<br>");      setTimeout(() => {        document.write("Let us see what happens");    }, 2000);      document.write("<br>");    document.write("End");    document.write("<br>");</script>
Output:
So, what the code does is first it logs in Hi then rather than executing the setTimeout function it logs in End and then it runs the setTimeout function.
At first, as usual, the Hi statement got logged in. As we use browsers to run JavaScript, there are the web APIs that handle these things for users. So, what JavaScript does is, it passes the setTimeout function in such web API and then we keep on running our code as usual. So it does not block the rest of the code from executing and after all the code its execution, it gets pushed to the call stack and then finally gets executed. This is what happens in asynchronous JavaScript.
javascript-basics
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tryit Editor v3.7

Tryit: Using w3css
WebSockets - Opening Connections

Once a connection has been established between the client and the server, the open event is fired from Web Socket instance. It is called as the initial handshake between client and server.
The event, which is raised once the connection is established, is called the onopen. Creating Web Socket connections is really simple. All you have to do is call the WebSocket constructor and pass in the URL of your server.
The following code is used to create a Web Socket connection −
// Create a new WebSocket.
var socket = new WebSocket('ws://echo.websocket.org');
Once the connection has been established, the open event will be fired on your Web Socket instance.
onopen refers to the initial handshake between client and the server which has lead to the first deal and the web application is ready to transmit the data.
The following code snippet describes opening the connection of Web Socket protocol −
socket.onopen = function(event) {
   console.log(“Connection established”);
   // Display user friendly messages for the successful establishment of connection
   var.label = document.getElementById(“status”);
   label.innerHTML = ”Connection established”;
}
It is a good practice to provide appropriate feedback to the users waiting for the Web Socket connection to be established. However, it is always noted that Web Socket connections are comparatively fast.
The demo of the Web Socket connection established is documented in the given URL − https://www.websocket.org/echo.html
A snapshot of the connection establishment and response to the user is shown below −
Establishing an open state allows full duplex communication and transfer of messages until the connection is terminated.
Building up the client-HTML5 file.
<!DOCTYPE html>
<html>
   <meta charset = "utf-8" />
   <title>WebSocket Test</title>

   <script language = "javascript" type = "text/javascript">
      var wsUri = "ws://echo.websocket.org/";
      var output;
	
      function init() {
         output = document.getElementById("output");
         testWebSocket();
      }
	
      function testWebSocket() {
         websocket = new WebSocket(wsUri);
			
         websocket.onopen = function(evt) {
            onOpen(evt)
         };
      }
	
      function onOpen(evt) {
         writeToScreen("CONNECTED");
      }
	
      window.addEventListener("load", init, false);
   
   </script>

   <h2>WebSocket Test</h2>
   <div id = "output"></div>

</html>
The output will be as follows −
The above HTML5 and JavaScript file shows the implementation of two events of Web Socket, namely −
onLoad which helps in creation of JavaScript object and initialization of connection.
onLoad which helps in creation of JavaScript object and initialization of connection.
onOpen establishes connection with the server and also sends the status.
onOpen establishes connection with the server and also sends the status.
 Print
 Add Notes
 Bookmark this page
Java Examples - Write Data into Excel Sheet

How to write data into excel sheet using Java.
Following is the program to write data into excel sheet using Java.
import java.io.File;
import java.io.FileOutputStream;

import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteDataToExcel {
   public static void main(String[] args) throws Exception {

      //Create blank workbook
      XSSFWorkbook workbook = new XSSFWorkbook();
      
      //Create a blank sheet
      XSSFSheet spreadsheet = workbook.createSheet( " Employee Info ");

      //Create row object
      XSSFRow row;

      //This data needs to be written (Object[])
      Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();
      empinfo.put( "1", new Object[] {
         "EMP ID", "EMP NAME", "DESIGNATION" });
      
      empinfo.put( "2", new Object[] {
         "tp01", "Gopal", "Technical Manager" });
      
      empinfo.put( "3", new Object[] {
         "tp02", "Manisha", "Proof Reader" });
      
      empinfo.put( "4", new Object[] {
         "tp03", "Masthan", "Technical Writer" });
      
      empinfo.put( "5", new Object[] {
         "tp04", "Satish", "Technical Writer" });
      
      empinfo.put( "6", new Object[] {
         "tp05", "Krishna", "Technical Writer" });

      //Iterate over data and write to sheet
      Set < String > keyid = empinfo.keySet();
      int rowid = 0;
      
      for (String key : keyid) {
         row = spreadsheet.createRow(rowid++);
         Object [] objectArr = empinfo.get(key);
         int cellid = 0;
         
         for (Object obj : objectArr){
            Cell cell = row.createCell(cellid++);
            cell.setCellValue((String)obj);
         }
      }
      //Write the workbook in file system
      FileOutputStream out = new FileOutputStream(
         new File("C:/poiexcel/Writesheet.xlsx"));
      
      workbook.write(out);
      out.close();
      System.out.println("Writesheet.xlsx written successfully");
   }
}
 Print
 Add Notes
 Bookmark this page
Combining Conditional Statements in Golang - GeeksforGeeks

08 Jun, 2020
Go is a open-source programming language developed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. Go is similar to C syntactically but with CSP style concurrency and many features of other robust programming language. Often refereed to as Golang because of the domain name, this language also has the If/else conditions. Usually the If/else/else if condition when written with one condition makes the program lengthy and increases the complexity thus we can combine two conditions. The conditions can be combined in the following ways :-
Using &&(AND) Operator
The And (&&) is a way of combining conditional statement has the following syntax:
if (condition1) && (condition2) {
......
}

Here, condition1 represents the first condition and condition2 represents the second condition. The && statement combines the conditions and gives the results in the following way:
If condition1 is True and condition2 is also True, the result is True.If condition1 is True and condition2 is  False, the result is False.If condition1 is False and condition2 is  True, the result is False.If condition1 is False and condition2 is also False, the result is False. 
If condition1 is True and condition2 is also True, the result is True.
If condition1 is True and condition2 is  False, the result is False.
If condition1 is False and condition2 is  True, the result is False.
If condition1 is False and condition2 is also False, the result is False. 
Go
package main  import "fmt"  // AND Conditionfunc main() {    time := 18    if time > 10 && time < 18 {        fmt.Println("Time for work")    }}
Using OR operator
The OR way of combining conditional statement has the following syntax:
if (condition1) || (condition2) {
.......
}

Here, condition1 represents the first condition and condition2 represents the second condition. The || statement combines the conditions and gives the results in the following way:
If condition1 is True and condition2 is also True, the result is True.If condition1 is True and condition2 is  False, the result is True.If condition1 is False and condition2 is  True, the result is True.If condition1 is False and condition2 is also False, the result is False. 
If condition1 is True and condition2 is also True, the result is True.
If condition1 is True and condition2 is  False, the result is True.
If condition1 is False and condition2 is  True, the result is True.
If condition1 is False and condition2 is also False, the result is False. 
Go
package main  import "fmt"  // OR Conditionfunc main() {    time := 14    if time > 10 || time < 12 {        fmt.Println("Hello geeks")    }}
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Parse JSON in Golang?
Defer Keyword in Golang
Time Durations in Golang
Loops in Go Language
time.Parse() Function in Golang With Examples
Anonymous function in Go Language
Strings in Golang
Class and Object in Golang
How to iterate over an Array using for loop in Golang?
Structures in Golang
What are class variables, instance variables and local variables in Java?

A variable provides us with named storage that our programs can manipulate. Java provides three types of variables.
Class variables − Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
Class variables − Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block. There would only be one copy of each class variable per class, regardless of how many objects are created from it.
Instance variables − Instance variables are declared in a class, but outside a method. When space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
Instance variables − Instance variables are declared in a class, but outside a method. When space is allocated for an object in the heap, a slot for each instance variable value is created. Instance variables hold values that must be referenced by more than one method, constructor or block, or essential parts of an object's state that must be present throughout the class.
Local variables − Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
Local variables − Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
 Live Demo
public class VariableExample{
   int myVariable;
   static int data = 30;
   
   public static void main(String args[]){
      int a = 100;
      VariableExample obj = new VariableExample();
      
      System.out.println("Value of instance variable myVariable: "+obj.myVariable);
      System.out.println("Value of static variable data: "+VariableExample.data);
      System.out.println("Value of local variable a: "+a);
   }
}
Value of instance variable myVariable: 0
Value of static variable data: 30
Value of local variable a: 100
Python time time() Method

Pythom time method time() returns the time as a floating point number expressed in seconds since the epoch, in UTC.
Note − Even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.
Following is the syntax for time() method −
time.time()

NA
NA
This method returns the time as a floating point number expressed in seconds since the epoch, in UTC.
The following example shows the usage of time() method.
#!/usr/bin/python
import time

print "time.time(): %f " %  time.time()
print time.localtime( time.time() )
print time.asctime( time.localtime(time.time()) )
When we run above program, it produces following result −
time.time(): 1234892919.655932
(2009, 2, 17, 10, 48, 39, 1, 48, 0)
Tue Feb 17 10:48:39 2009


    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
What is variable shadowing in java?

In Java you can declare three types of variables namely, instance variables, static variables and, local variables.
Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
Class (static) variables − Class variables are variables declared within a class, outside any method, with the static keyword.
If the instance variable and local variable have same name whenever you print (access) it in the method. The value of the local variable will be printed (shadowing the instance variable).
In the following Java example, the class FieldShadowingExample has two instance variables (name, age) and a method (display()).
In the method there are two variables same as the instance variables (name and type).
When you invoke print (access) them in the method, the local variable values will be printed shadowing the instance ones.
 Live Demo
public class FieldShadowingExample{
   String name = "Krishna";
   int age = 25;
   public void display(){
      String name = "Vishnu";
      int age = 22;
      System.out.println("Name: "+name);
      System.out.println("age: "+age);
   }
   public static void main(String args[]){
      new FieldShadowingExample().display();
   }
}
Name: Vishnu
age: 22
If you still, need to access the values of instance variables in a method (in this case) you need to access them using this keyword (or object) as shown below −
 Live Demo
public class FieldShadowingExample{
   String name = "Krishna";
   int age = 25;
   public void display(){
      String name = "Vishnu";
      int age = 22;
      System.out.println("Name: "+name);
      System.out.println("age: "+age);
      System.out.println("Name: "+this.name);
      System.out.println("age: "+this.age);
   }
   public static void main(String args[]){
      new FieldShadowingExample().display();
   }
}
Name: Vishnu
age: 22
Name: Krishna
age: 25
Redis - Commands

Redis commands are used to perform some operations on Redis server.
To run commands on Redis server, you need a Redis client. Redis client is available in Redis package, which we have installed earlier.
Following is the basic syntax of Redis client.
$redis-cli 

Following example explains how we can start Redis client.
To start Redis client, open the terminal and type the command redis-cli. This will connect to your local server and now you can run any command.
$redis-cli 
redis 127.0.0.1:6379> 
redis 127.0.0.1:6379> PING  
PONG

In the above example, we connect to Redis server running on the local machine and execute a command PING, that checks whether the server is running or not.
To run commands on Redis remote server, you need to connect to the server by the same client redis-cli
$ redis-cli -h host -p port -a password

Following example shows how to connect to Redis remote server, running on host 127.0.0.1, port 6379 and has password mypass.
$redis-cli -h 127.0.0.1 -p 6379 -a "mypass" 
redis 127.0.0.1:6379> 
redis 127.0.0.1:6379> PING  
PONG


    22 Lectures 
     40 mins

 Skillbakerystudios
 Print
 Add Notes
 Bookmark this page
Pairs of Songs With Total Durations Divisible by 60 in Python

Suppose we have a list of songs, the i-th song has a duration of time[i] seconds. We have to find the number of pairs of songs for which their total time in seconds is divisible by 60.
So if the time array is like [30, 20, 150, 100, 40], then the answer will be 3. Three pairs will be (3, 150), (20, 100), (20, 40) for all cases the total duration is divisible by 60.
To solve this, we will follow these steps −
Take a map rem to store remainders. Set ans := 0
for all elements i in time −if i is divisible by 0 and 0 in rem, then ans := ans + rem[0]o otherwise when 60 – (i mod 60) in rem, then ans := ans + rem[60 – (i mod 60)]if i mod 60 in rem, then rem[i mod 60] := rem[i mod 60] + 1otherwise rem[i mod 60] := 1
if i is divisible by 0 and 0 in rem, then ans := ans + rem[0]
o otherwise when 60 – (i mod 60) in rem, then ans := ans + rem[60 – (i mod 60)]
if i mod 60 in rem, then rem[i mod 60] := rem[i mod 60] + 1
otherwise rem[i mod 60] := 1
return the ans
Let us see the following implementation to get better understanding −
 Live Demo
class Solution(object):
   def numPairsDivisibleBy60(self, time):
      ans = 0
      remainder = {}
      for i in time:
         if i % 60 == 0 and 0 in remainder:
            ans += remainder[0]
         elif 60 - (i%60) in remainder:
            ans += remainder[60 - (i%60)]
         if i % 60 in remainder:
            remainder[i%60]+=1
         else:
            remainder[i%60]=1
      return ans
ob1 = Solution()
print(ob1.numPairsDivisibleBy60([30,20,150,100,40]))
[30,20,150,100,40]
3
Shell Script How to write logs in a Separate File | Shell Script Log Message

PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
This is a very common scenario to log the application messages into a separate file; Here, we will see a Shell script how to write logs in a separate file.
To make this use-case simple and more reusable, I am writing two different script files one is to write the messages to the log file, and another one is for generating the logs.
Create log_functions.sh file which will be responsible for logging the different types of log messages like INFO, WARN and ERROR into application.log file.
#!/bin/bash

VAR_LOG_DIR="/home/"
VAR_LOG_FILE="application.log"

logWarn(){
     echo "--[`date "+%Y/%m/%d %H:%M:%S"`] -- WARN -- $@" >> ${VAR_LOG_DIR}/${VAR_LOG_FILE};
}

logInfo(){
     echo "--[`date "+%Y/%m/%d %H:%M:%S"`] -- INFO -- $@" >> ${VAR_LOG_DIR}/${VAR_LOG_FILE};
}

logError(){
     echo "--[`date "+%Y/%m/%d %H:%M:%S"`] -- ERROR -- $@" >> ${VAR_LOG_DIR}/${VAR_LOG_FILE};
     exit 1;
}

Create a simple shell script to write some messages into application.log file.
#!/bin/bash

#Getting current directory
readonly CURRENT_DIR=$(cd `dirname $0`; pwd -P)
source ${CURRENT_DIR}/log_functions.sh

logInfo "I am information"
logWarn " I am a Warning message"
logError "I am an Error"
Make both files as executable.
$chmod 777 log_functions.sh
$chmod 777 log_messages.sh
Run log_messages.sh file and see the application.log file.
$./log_messages.sh
check the application.log file
$ more application.log
--[2020/04/16 15:41:07] -- INFO -- I am information
--[2020/04/16 15:41:07] -- WARN --  I am a Warning message
--[2020/04/16 15:41:07] -- ERROR -- I am an Error

Happy Learning 🙂

Date yyyymmdd format in Shell Script
How add files to S3 Bucket using Shell Script
How to write (PHP fwrite) a file in PHP
PHP File Handling fopen fread and fclose  Example
Writing data to a file in Java
Python – How to create Zip File in Python ?
Java How to create Jar File ?
Java 8 Read File Line By Line Example
How to Search a file in a Directory using Java
Modes of Python Program
How to Convert Python List Of Objects to CSV File
php readfile Example Tutorials
JDBC Connection with Properties file
How to Copy Local Files to AWS EC2 instance Manually ?
How to Export MySQL Tables to a file from command line

Date yyyymmdd format in Shell Script
How add files to S3 Bucket using Shell Script
How to write (PHP fwrite) a file in PHP
PHP File Handling fopen fread and fclose  Example
Writing data to a file in Java
Python – How to create Zip File in Python ?
Java How to create Jar File ?
Java 8 Read File Line By Line Example
How to Search a file in a Directory using Java
Modes of Python Program
How to Convert Python List Of Objects to CSV File
php readfile Example Tutorials
JDBC Connection with Properties file
How to Copy Local Files to AWS EC2 instance Manually ?
How to Export MySQL Tables to a file from command line
Java program to find Largest, Smallest, Second Largest, Second Smallest in an array

To find largest, smallest, second largest, second smallest in an array, the code is as follows -
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String []args){
      int arr[] = {55, 10, 8, 90, 43, 87, 95, 25, 50, 12};
      System.out.println("Array = "+Arrays.toString(arr));
      Arrays.sort(arr);
      System.out.println("Sorted Array = "+Arrays.toString(arr));
      System.out.println("Smallest element = "+arr[0]);
      System.out.println("2nd Smallest element = "+arr[0]);
      System.out.println("Largest element = "+arr[9]);
      System.out.println("2nd Largest element = "+arr[8]);
   }
}
Array = [55, 10, 8, 90, 43, 87, 95, 25, 50, 12]
Sorted Array = [8, 10, 12, 25, 43, 50, 55, 87, 90, 95]
Smallest element = 8
2nd Smallest element = 8
Largest element = 95
2nd Largest element = 90
Let us now see another example:
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String []args){
      int a;
      int arr[] = {55, 10, 8, 90, 43, 87, 95, 25, 50, 12};
      System.out.println("Array = "+Arrays.toString(arr));
      int count = arr.length;
      for (int i = 0; i < count; i++) {
         for (int j = i + 1; j < count; j++) {
            if (arr[i] > arr[j]) {
               a = arr[i];
               arr[i] = arr[j];
               arr[j] = a;
            }
         }
      }
      System.out.println("Smallest: "+arr[0]);
      System.out.println("Largest: "+arr[count-1]);
      System.out.println("Second Smallest: "+arr[1]);
      System.out.println("Second Largest: "+arr[count-2]);
   }
}
Array = [55, 10, 8, 90, 43, 87, 95, 25, 50, 12]
Smallest: 8
Largest: 95
Second Smallest: 10
Second Largest: 90
Concatenation of strings in Lua programming

Concatenation of strings is the process in which we combine two or more strings with each other, and in most of the programming languages this can be done by making use of the assignment operator.
In Lua, the assignment operator concatenation doesn’t work.
Consider the example shown below −
 Live Demo
str1 = "tutorials"
str2 = "point"
will throw an error
s = str1 + str2
print(s)
input:7: attempt to add a 'string' with a 'string'
Hence, the most straightforward way is to make use of the concatenation keyword which is denoted by .. (two dots)
Let’s consider a few examples of the concatenation keyword in Lua.
Consider the example shown below −
 Live Demo
str1 = "tutorials"
str2 = "point"
s = str1 .. str2
print(s)
tutorialspoint
Consider the example shown below −
 Live Demo
message = "Hello, " .. "world!"
print(message)
Hello, world!
It should be noted that Lua doesn’t allow augmented concatenation.
Consider the example shown below −
 Live Demo
str1 = "tutorials"
str2 = "point"
str1 ..= str2
print(str1)
input:5: syntax error near '..'
It should also be noted that whenever we make use of the concatenation operator, a new string gets created internally and the concatenation is done on that string, and this approach has performance issues when we want to concatenate multiple strings in one string.
Alternate approach is to make use of the table.concat function.
Consider the example shown below −
 Live Demo
numbers = {}
for i=1,10 do
numbers[i] = i
end
message = table.concat(numbers)
print(message)
12345678910
<mat-checkbox> in Angular Material - GeeksforGeeks

31 Mar, 2021
Angular Material is a UI component library that is developed by the Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have it you can enter the below command and can download it. <mat-checkbox> is used to check or select whenever we have multiple options to select.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatCheckboxModule’ from ‘@angular/material/checkbox’ in the app.module.ts file.
Then we need to use the <mat-checkbox> tag for displaying the checkbox.
We can also disable the checkbox by using the disabled input property.
If we want to change the theme then we can change it by using the color property. In angular we have 3 themes, they are primary, accent, and warn.
Once done with the above steps then serve or start the project.
Project Structure: It will look like the following:
app.module.ts
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms';   import { MatCheckboxModule } from '@angular/material/checkbox';import { AppComponent } from './app.component'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations';  @NgModule({   imports:   [     BrowserModule,     FormsModule,     MatCheckboxModule,    BrowserAnimationsModule  ],   declarations: [ AppComponent ],   bootstrap: [ AppComponent ] })   export class AppModule { }
app.component.html
<mat-checkbox color="primary">   Primary theme checkbox</mat-checkbox>  <br><br>  <mat-checkbox color="accent">   Accent theme checkbox</mat-checkbox>  <br><br>  <mat-checkbox color="warn">   Warn theme checkbox</mat-checkbox>  <br><br>  <mat-checkbox color="warn" disabled>   Disabled  checkbox</mat-checkbox>  <br><br>  <mat-checkbox color="primary" indeterminate="true">   Indeterminate  checkbox</mat-checkbox>
Output:
Angular-material
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Angular Libraries For Web Developers
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills