code-rag-bench/online-tutorials huggingface dataset:
Python | time.time() method

28 Aug, 2019
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules.
time.time() method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent.
Note: The epoch is the point where the time starts, and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use time.gmtime(0).
Syntax: time.time()
Parameter: No parameter is required
Return type: This method returns a float value which represents the time in seconds since the epoch.
Code #1: Use of time.time() method
# Python program to explain time.time() method  # importing time moduleimport time  # Get the epochobj = time.gmtime(0)epoch = time.asctime(obj)print("epoch is:", epoch)  # Get the time in seconds# since the epochtime_sec = time.time()  # Print the time print("Time in seconds since the epoch:", time_sec)
epoch is: Thu Jan  1 00:00:00 1970
Time in seconds since the epoch: 1566454995.8361387

Code #2: Calculate seconds between two date
# Python program to explain time.time() method  # importing time moduleimport time  # Date 1date1 = "1 Jan 2000 00:00:00"  # Date 2# Current datedate2 = "22 Aug 2019 00:00:00"  # Parse the date strings# and convert it in # time.struct_time object using# time.strptime() methodobj1 = time.strptime(date1, "% d % b % Y % H:% M:% S")obj2 = time.strptime(date2, "% d % b % Y % H:% M:% S")  # Get the time in seconds# since the epoch# for both time.struct_time objectstime1 = time.mktime(obj1)time2 = time.mktime(obj2)  print("Date 1:", time.asctime(obj1))print("Date 2:", time.asctime(obj2))    # Seconds between Date 1 and date 2seconds = time2 - time1print("Seconds between date 1 and date 2 is % f seconds" % seconds)
Date 1: Sat Jan  1 00:00:00 2000
Date 2: Thu Aug 22 00:00:00 2019
Seconds between date 1 and date 2 is 619747200.000000 seconds

Reference: https://docs.python.org/3/library/time.html#time.time
python-utility
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
GATE | GATE CS 2019 | Question 61

19 Feb, 2019
A relational database contains two tables Student and Performance as shown below:The primary key of the Student table is Roll_no. For the Performance table, the columns Roll_no. and Subject_code together from the primary key. Consider the SQL query given below:
SELECT S.Student_name, sum(P.Marks)
FROM Student S, Performance P
WHERE  P.Marks  >  84
GROUP BY S.Student_name;
The number of rows returned by the above SQL query is _________ .
Note: This was Numerical Type question.(A) 5(B) 4(C) 3(D) None of these.Answer: (A)Explanation: In where condition no condition over Roll_no so query produces all groups.
Total 5 different student names all 5 group records in result. See: http://sqlfiddle.com/#!9/8a79d3/1/0Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | Gate IT 2005 | Question 11
GATE | GATE MOCK 2017 | Question 45
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2000 | Question 2
GATE | GATE CS 2013 | Question 50
GATE | GATE CS 2012 | Question 65
GATE | GATE-CS-2003 | Question 64
GATE | GATE-CS-2004 | Question 90
GATE | GATE-CS-2015 (Set 1) | Question 30
Why start + (end – start)/2 is preferable method for calculating middle of an array over (start + end)/2 ?

27 Jul, 2021
I am very sure that everyone is able to find middle index of array once you know start index and end index of array, but there are certain benefits of using start + (end – start)/2 over (start + end)/2, which are described below :
The very first way of finding middle index is 
mid = (start + end)/2
But there is problem with this approach, what if value of start or end or both is INT_MAX, it will cause integer overflow.The better way of calculating mid index is : 
mid = start + (end - start)/2
Let’s try these both methods in C program :  
C
// program for calculating mid of array#include <stdio.h>#include <limits.h>int main(){    int start = INT_MAX, end = INT_MAX;    printf("start = %dn", start);    printf("end = %dn", end);     // method 1    int mid1 = (start + end) / 2;    printf("mid using (start + end)/2 = %dn", mid1);     // method 2    int mid2 = start + (end - start) / 2;    printf("mid using start + (end - start)/2 = %dn", mid2);    return 0;}
Output: 
start = 2147483647
end = 2147483647
mid using (start + end)/2 = -1
mid using start + (end - start)/2 = 2147483647
Note : (end – start) may overflow if end < 0 or start < 0If you see the output, by using second method you get correct output and first method fails to calculate mid and if you use this index (-1 in this case), it can cause segmentation fault because of invalid index of array.
start + (end – start)/2 also works even if you are using pointers : 
Example : Method 1  
C
int s = 2, e = 3;int* start = &s;int* end = &e;int* mid = (start + end) / 2;
Output : 
error: invalid operands of types ‘int*’ and ‘int*’ to binary ‘operator+’
     int *mid = (start + end)/2;
Method 2  
C
int s = 2, e = 3;int* start = &s;int* end = &e;int* mid = start + (end - start) / 2;
Output : 
It will compile and give expected results
Explanation: pointer addition is not supported in C while pointer subtraction is supported, the reason being the result of subtraction is the difference (in array elements) between the operands. The subtraction expression yields a signed integral result of type ptrdiff_t (defined in the standard include file STDDEF.H)(in short subtraction gives memory distance), but addition of two pointers in not meaningful, that’s why not supported
References : 1) Additive Operators: + and – 2) why-prefer-start-end-start-2-over-start-end-2-when-calculating-the 3) pointer-addition-vs-subtraction
This article is contributed by Mandeep Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
msdeep14
sagar0719kumar
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular Material 7 - Form Field

The <mat-form-field>, an Angular Directive, is used to create a wrapper over angular components and is used to apply text styles like underline, bold, hints etc. 
Following angular component can be used within <mat-form-field>.
<input matNativeControl>
<input matNativeControl>
<textarea matNativeControl>
<textarea matNativeControl>
<select matNativeControl>
<select matNativeControl>
<mat-select>
<mat-select>
<mat-chip-list>
<mat-chip-list>
In this chapter, we will showcase the configuration required to use a mat-form-field control in 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 {MatInputModule,MatOptionModule, MatSelectModule, MatIconModule} from '@angular/material'
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatInputModule,MatOptionModule, MatSelectModule, MatIconModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }
Following is the content of the modified CSS file app.component.css.
.tp-container {
   display: flex;
   flex-direction: column;
}
.tp-container > * {
   width: 100%;
}
Following is the content of the modified HTML host file app.component.html.
<div class = "tp-container">
   <mat-form-field appearance = "standard">
      <input matInput placeholder = "Input">
      <mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
      <mat-hint>Sample Hint</mat-hint>
   </mat-form-field>
   <mat-form-field appearance = "fill">
      <textarea matInput placeholder = "Textarea"></textarea>
   </mat-form-field>
   <mat-form-field appearance = "outline">
      <mat-select placeholder = "Select">
         <mat-option value = "A">A</mat-option>
         <mat-option value = "B">B</mat-option>
         <mat-option value = "C">C</mat-option>      
      </mat-select>
   </mat-form-field>
</div>
Verify the result.
As first, we've created an form field using mat-form-field wrapper. We've changed the appearance of form field using appearance attribute.
As first, we've created an form field using mat-form-field wrapper. We've changed the appearance of form field using appearance attribute.
Then, a form control is added to the form field.
Then, a form control is added to the form field.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
Python break statement

It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C.
The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.
The syntax for a break statement in Python is as follows −
break

#!/usr/bin/python

for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print 'Current Letter :', letter
  
var = 10                    # Second Example
while var > 0:              
   print 'Current variable value :', var
   var = var -1
   if var == 5:
      break

print "Good bye!"
When the above code is executed, it produces the following result −
Current Letter : P
Current Letter : y
Current Letter : t
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!


    187 Lectures 
     17.5 hours 

 Malhar Lathkar

    55 Lectures 
     8 hours 

 Arnab Chakraborty

    136 Lectures 
     11 hours 

 In28Minutes Official

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    70 Lectures 
     8.5 hours 

 Lets Kode It

    63 Lectures 
     6 hours 

 Abhilash Nelson
 Print
 Add Notes
 Bookmark this page
How to apply a 3×3 convolution matrix using imageconvolution() in PHP?

imageconvolution() is an inbuilt function in PHP that is used to apply a 3×3 convolution matrix, using the coefficient and offset in the image.
bool imageconvolution ( $image, $matrix, $div, $offset)
imageconvolution() takes four parameters: $image, $matrix, $div, and $offset.
$image − This parameter is used to create the size of the image by using an image creation function such as imagecreatetruecolor().
$image − This parameter is used to create the size of the image by using an image creation function such as imagecreatetruecolor().
$matrix − This parameter contains an array of 3×3 matrix of floats.
$matrix − This parameter contains an array of 3×3 matrix of floats.
$div − It is used for normalization.
$div − It is used for normalization.
$offset − This parameter is used to set the color offset.
$offset − This parameter is used to set the color offset.
imageconvolution() returns True on success and False on failure.
<?php
   // load the PNG image by using imagecreatefrompng function.
   $image = imagecreatefrompng('C:\xampp\htdocs\Images\img59.png');
   
   // Applied the 3X3 array matrix
   $matrix = array(
      array(2, 0, 0),
      array(0, -1, 0),
      array(0, 0, -1)
   );
   // imageconvolution function to modify image elements
   imageconvolution($image, $matrix, 1, 127);

   // show the output image in the browser
   header('Content-Type: image/png');
   imagepng($image, null, 9);
?>
Input PNG image before using imageconvolution() function
Output PNG image after using imageconvolution() function
<?php
   $image = imagecreatetruecolor(700, 300);
   
   // Writes the text and apply a gaussian blur on the image
   imagestring($image, 50, 25, 8, 'Gaussian Blur Text image', 0x00ff00);
   $gaussian = array(
      array(1.0, 2.0, 1.0),
      array(2.0, 4.0, 2.0),
      array(1.0, 2.0, 1.0)
   );
   imageconvolution($image, $gaussian, 16, 0);

   // Rewrites the text for comparison
   imagestring($image, 15, 20, 18, 'Gaussian Blur Text image', 0x00ff00);
   header('Content-Type: image/png');
   imagepng($image, null, 9);
?>
SymPy - Symbolic Computation

Symbolic computation refers to development of algorithms for manipulating mathematical expressions and other mathematical objects. Symbolic computation integrates mathematics with computer science to solve mathematical expressions using mathematical symbols. A Computer Algebra System (CAS) such as SymPy evaluates algebraic expressions exactly (not approximately) using the same symbols that are used in traditional manual method. For example, we calculate square root of a number using Python's math module as given below −
>>> import math 
>>> print (math.sqrt(25), math.sqrt(7))

The output for the above code snippet is as follows −
5.0 2.6457513110645907
As you can see, square root of 7 is calculated approximately. But in SymPy square roots of numbers that are not perfect squares are left unevaluated by default as given below −
>>> import sympy 
>>> print (sympy.sqrt(7))

The output for the above code snippet is as follows −
sqrt(7)
It is possible to simplify and show result of expression symbolically with the code snippet below −
>>> import math
>>> print (math.sqrt(12))

The output for the above code snippet is as follows −
3.4641016151377544
You need to use the below code snippet to execute the same using sympy −
##sympy output 
>>> print (sympy.sqrt(12))

And the output for that is as follows −
2*sqrt(3)
SymPy code, when run in Jupyter notebook, makes use of MathJax library to render mathematical symbols in LatEx form. It is shown in the below code snippet −
>>> from sympy import * 
>>> x=Symbol ('x') 
>>> expr = integrate(x**x, x) 
>>> expr

On executing the above command in python shell, following output will be generated −
Integral(x**x, x)

Which is equivalent to
∫xxdx
The square root of a non-perfect square can be represented by Latex as follows using traditional symbol −
>>> from sympy import * 
>>> x=7 
>>> sqrt(x)

The output for the above code snippet is as follows −
7
A symbolic computation system such as SymPy does all sorts of computations (such as derivatives, integrals, and limits, solve equations, work with matrices) symbolically. SymPy package has different modules that support plotting, printing (like LATEX), physics, statistics, combinatorics, number theory, geometry, logic, etc.
 Print
 Add Notes
 Bookmark this page
PYGLET – Accessing Label Text Color Property - GeeksforGeeks

16 Jan, 2022
In this article we will see how we can access the label text color property in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a “heavyweight” object occupying operating system resources. Windows may appear as floating regions or can be set to fill an entire screen (fullscreen). In order to show text or message we use html label object. A label is a graphical control element which displays text on a form. It is usually a static control; having no interactivity. By default the text color of the label is of white color although we can change this any time by accessing the color property.We can create a window and label with the help of commands given below  
# creating window
window = pyglet.window.Window(width, height, title)

# creating a label
label = pyglet.text.Label(text, font_name, font_size, x, y)
 
In order to create window we use color attribute with the label objectSyntax : label.colorArgument : It takes no argumentReturn : It returns tuple of having four values varying from 0-255  
Below is the implementation  
Python3
# importing pyglet moduleimport pygletimport pyglet.window.key # width of windowwidth = 500 # height of windowheight = 500 # caption i.e title of the windowtitle = "Geeksforgeeks" # creating a windowwindow = pyglet.window.Window(width, height, title) # texttext = "Welcome to GeeksforGeeks" # creating a label with font = times roman# font size = 36# aligning it to the centrelabel = pyglet.text.Label(text,                          font_name ='Times New Roman',                          font_size = 28,                          x = 20, y = window.height//2, ) # accessing color property of the label# setting new colorlabel.color = (100, 255, 100, 255) # on draw event@window.eventdef on_draw():             # clearing the window    window.clear()         # drawing the label on the window    label.draw()      # key press event   @window.eventdef on_key_press(symbol, modifier):     # key "C" get press    if symbol == pyglet.window.key.C:                 # closing the window        window.close()      # image for iconimg = image = pyglet.resource.image("logo.png") # setting image as iconwindow.set_icon(img)                 # start running the applicationpyglet.app.run()
Output :  
 
adnanirshad158
Python-gui
Python-Pyglet
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Accessing Grandparent’s member in Java using super - GeeksforGeeks

05 Feb, 2021
Directly accessing Grandparent’s member in Java:
Predict the output of the following Java program.
Java
// filename Main.javaclass Grandparent {    public void Print()    {        System.out.println("Grandparent's Print()");    }} class Parent extends Grandparent {    public void Print()    {        System.out.println("Parent's Print()");    }} class Child extends Parent {    public void Print()    {        // Trying to access Grandparent's Print()        super.super.Print();        System.out.println("Child's Print()");    }} public class Main {    public static void main(String[] args)    {        Child c = new Child();        c.Print();    }}
Output:
prog.java:20: error: <identifier> expected
        super.super.Print();
              ^
prog.java:20: error: not a statement
        super.super.Print(); 
There is an error at the line “super.super.print();”. In Java, a class cannot directly access the grandparent’s members. It is allowed in C++ though. In C++, we can use scope resolution operator (::) to access any ancestor’s member in the inheritance hierarchy. In Java, we can access grandparent’s members only through the parent class. 
For example, the following program compiles and runs fine. 
Java
// filename Main.javaclass Grandparent {    public void Print()    {        System.out.println("Grandparent's Print()");    }} class Parent extends Grandparent {    public void Print()    {        super.Print();        System.out.println("Parent's Print()");    }} class Child extends Parent {    public void Print()    {        super.Print();        System.out.println("Child's Print()");    }} public class Main {    public static void main(String[] args)    {        Child c = new Child();        c.Print();    }}
Grandparent's Print()
Parent's Print()
Child's Print()

 
Why doesn’t java allow accessing grandparent’s methods? 
It violates encapsulation. You shouldn’t be able to bypass the parent class’s behavior. It makes sense to sometimes be able to bypass your own class’s behavior (particularly from within the same method) but not your parent’s. 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
guruism056
java-inheritance
Java-Object Oriented
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Scala Map filterKeys() method with example - GeeksforGeeks

13 Aug, 2019
The filterKeys() method is utilized to find all the pairs where the keys satisfies the given predicate.
Method Definition: def filterKeys(p: (A) => Boolean): Map[A, B]
Return Type: It returns all the “key-value” pairs of the map where, the keys satisfies the given predicate.
Example #1:
// Scala program of filterKeys()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map(5 -> "geeks", 4 -> "for", 2 -> "cs")                  // Applying filterKeys method        val result = m1.filterKeys(_ > 2)                  // Displays output        println(result)          }}
Map(5 -> geeks, 4 -> for)

Here, only two key-value pairs are returned as their keys are greater than two as per the stated predicate.Example #2:
// Scala program of filterKeys()// method  // Creating objectobject GfG{       // Main method    def main(args:Array[String])    {              // Creating map        val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs")                  // Applying filterKeys method        val result = m1.filterKeys(_ > 3)                  // Displays output        println(result)          }}
Map()

Here, no pair is returned as none of the keys satisfies the stated predicate.
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Type Casting in Scala
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Inheritance in Scala
Operators in Scala
Scala Constructors
Scala | Arrays
Scala String substring() method with example
Lambda Expression in Scala
Python Program for Cycle Sort - GeeksforGeeks

20 Apr, 2022
Cycle sort is an in-place sorting Algorithm, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array.
It is optimal in terms of number of memory writes. It minimizes the number of memory writes to sort (Each value is either written zero times, if it’s already in its correct position, or written one time to its correct position.)
It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visualized as a graph. We have n nodes and an edge directed from node i to node j if the element at i-th index must be present at j-th index in the sorted array.Cycle in arr[] = {4, 5, 2, 1, 5}Cycle in arr[] = {4, 3, 2, 1}
Cycle in arr[] = {4, 3, 2, 1}
We one by one consider all cycles. We first consider the cycle that includes first element. We find correct position of first element, place it at its correct position, say j. We consider old value of arr[j] and find its correct position, we keep doing this till all elements of current cycle are placed at correct position, i.e., we don\’t come back to cycle starting point.
# Python program to implement cycle sort  def cycleSort(array):  writes = 0      # Loop through the array to find cycles to rotate.  for cycleStart in range(0, len(array) - 1):    item = array[cycleStart]          # Find where to put the item.    pos = cycleStart    for i in range(cycleStart + 1, len(array)):      if array[i] < item:        pos += 1          # If the item is already there, this is not a cycle.    if pos == cycleStart:      continue          # Otherwise, put the item there or right after any duplicates.    while item == array[pos]:      pos += 1    array[pos], item = item, array[pos]    writes += 1          # Rotate the rest of the cycle.    while pos != cycleStart:              # Find where to put the item.      pos = cycleStart      for i in range(cycleStart + 1, len(array)):        if array[i] < item:          pos += 1              # Put the item there or right after any duplicates.      while item == array[pos]:        pos += 1      array[pos], item = item, array[pos]      writes += 1      return writes    #  driver code arr = [1, 8, 3, 9, 10, 10, 2, 4 ]n = len(arr) cycleSort(arr)  print("After sort : ")for i in range(0, n) :     print(arr[i], end = \' \')  # Code Contributed by Mohit Gupta_OMG <(0_o)>
Output:
After sort : 
1 2 3 4 8 9 10 10 

Please refer complete article on Cycle Sort for more details!
simmytarika5
python sorting-exercises
Python Programs
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Python | Get the first key in dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
Remove Objects from Memory in R Programming - rm() Function - GeeksforGeeks

19 Jun, 2020
rm() function in R Language is used to delete objects from the memory. It can be used with ls() function to delete all objects. remove() function is also similar to rm() function.
Syntax: rm(x)
Parameters:x: Object name
Example 1:
# R Program to remove # objects from Memory  # Creating a vectorvec <- c(1, 2, 3, 4)vec  # Creating a listlist1 = list("Number" = c(1, 2, 3),             "Characters" = c("a", "b", "c"))list1  # Creating a matrixmat <- matrix(c(1:9), 3, 3)mat  # Calling rm() Functionrm(list1)  # Calling ls() to check object listls()
Output:
[1] 1 2 3 4
$Number
[1] 1 2 3

$Characters
[1] "a" "b" "c"

     [, 1] [, 2] [, 3]
[1, ]    1    4    7
[2, ]    2    5    8
[3, ]    3    6    9
[1] "mat" "vec"

Example 2:
# R Program to remove # objects from Memory  # Creating a vectorvec <- c(1, 2, 3, 4)  # Creating a listlist1 = list("Number" = c(1, 2, 3),             "Characters" = c("a", "b", "c"))  # Creating a matrixmat <- matrix(c(1:9), 3, 3)  # Calling rm() Function# to remove all objectsrm(list = ls())  # Calling ls() to check object listls()
Output:
character(0)

R Object-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
R Programming Language - Introduction
K-Means Clustering in R Programming
ReactJS getDerivedStateFromError() Method - GeeksforGeeks

16 Oct, 2021
The getDerivedStateFromError() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the render phase, so side-effects are not permitted in this method. For side-effects, use componentDidCatch() instead. 
Syntax:
static getDerivedStateFromError(error)
Parameters: It accepts the error that was thrown as a parameter.
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. folder name, move to it using the following command:
cd foldername
Example: Program to demonstrate the use of getDerivedStateFromError() method.
Project Structure: It will look like the following.  
 
Filename: App.js
Javascript
import React, { Component } from 'react'; export default class App extends Component {   // Initializing the state  state = {    error: false  };   static getDerivedStateFromError(error) {    // Changing the state to true if some error occurs    return {      error: true,    };  }   render() {    return (      <React.StrictMode>        <div>          {this.state.error ? <div>Some error</div> : <GFGComponent />}        </div>      </React.StrictMode>    );  }} class GFGComponent extends Component {   // GFGComponent throws error as state of GFGCompnonent is not defined  render() {    return <h1>{this.state.heading}</h1>;  }}
  
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
 
Reference: https://reactjs.org/docs/react-component.html#static-getderivedstatefromerror
ruhelaa48
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to apply style to parent if it has child with CSS?
How to execute PHP code using command line ?
Difference Between PUT and PATCH Request
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
How to merge lists in Scala - GeeksforGeeks

13 Jul, 2021
A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Lists are immutable and represents a linked list.Syntax of List:  
val variable_name: List[type] = List(item1, item2, item3)
or
val variable_name = List(item1, item2, item3)
Below are three different way to merge lists:  
using the ++
Using :::
Using concat
Following are the various ways to merge two lists in Scala: 
Example:  
Scala
// Scala program to merge lists // Creating objectobject GFG{    // Main method    def main(args:Array[String])    {        // Creating Lists        val a = List("geeks", "for", "geeks")        val b = List("is", "a", "computer science", "portal")        val c = List("for", "geeks")                 // Merging Lists        val d = a ++ b ++ c        println("After merging lists ")        println(d)    }}        
After merging lists 
List(geeks, for, geeks, is, a, computer science, portal, for, geeks)
 
In above example we are using ++ method to concatenate lists. This method is used consistently across immutable collections   
If we using the List class frequently, we may prefer using ::: method.Example:  
Scala
// Scala program to merging two lists // Creating objectobject GFG{    // Main method    def main(args:Array[String])    {        // Creating a List.        val a = List("Languages", "are")        val b = List("C++", "Java", "C#", "Python", "Scala")                 // Merging two lists        val c = a ::: b                 println("After merging lists")        println(c)    }}        
   
Example: 
Scala
// Scala program merging two lists // Creating objectobject GFG{    // Main method    def main(args:Array[String])    {        // Creating a List.        val a = List(1, 2, 3)        val b = List(4, 5, 6)                 // concatenate two lists        val c = List.concat(a, b)        println("After merging lists")        println(c)    }}    
After merging lists
List(1, 2, 3, 4, 5, 6)
 
gabaa406
Scala list-program
Scala-list
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Scala Lists
Scala Tutorial – Learn Scala with Step By Step Guide
Operators in Scala
Inheritance in Scala
Scala Constructors
Scala | Arrays
Lambda Expression in Scala
How to get the first element of List in Scala
Break statement in Scala
Counting number of elements in an array in Julia - count() Method - GeeksforGeeks

26 Mar, 2020
The count() is an inbuilt function in julia which is used to count the number of elements in the specified array for which the given predicate p returns true and if p is omitted, counts the number of true elements in the given collection of boolean values.
Syntax:count(p, itr)orcount(itr)
Parameters:
p: Specified set of instructions.
itr: Specified collection of boolean values.
Returns: It returns the count of the number of elements in the specified array for which the given predicate p returns true and if p is omitted, counts the number of true elements in the given collection of boolean values.
Example 1:
# Julia program to illustrate # the use of count() method  # Getting the count of the number# of elements in the specified array# for which the given predicate p # returns true.println(count(i->(i<= 3), [1, 2, 3, 4, 5]))println(count(i->(i>3), [1, 2, 3, 4, 5]))println(count(i->(2<= i<= 5), [1, 2, 3, 4, 5]))println(count(i->(i>= 0), [1, 2, 3]))
Output:
3
2
4
3

Example 2:
# Julia program to illustrate # the use of count() method  # Getting the counts of number of true elements# in the given collection of boolean values.println(count([false, false, false]))println(count([true, false, true]))println(count([true, true, true]))
Output:
0
2
3

Julia
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vectors in Julia
Getting rounded value of a number in Julia - round() Method
Storing Output on a File in Julia
Manipulating matrices in Julia
Reshaping array dimensions in Julia | Array reshape() Method
Comments in Julia
while loop in Julia
Tuples in Julia
Searching in Array for a given element in Julia
Get array dimensions and size of a dimension in Julia - size() Method
Java Math cos() method with Examples - GeeksforGeeks

06 Apr, 2018
The java.lang.Math.cos() returns the trigonometric cosine of an angle. If the argument is NaN or an infinity, then the result returned is NaN. The returned value will be in range [-1, 1].
Syntax :
public static double cos(double angle)
Parameters:
The function has one mandatory parameter angle which is in radians. 

Returns :The function returns the trigonometric cosine of an angle.
Example 1 : To show working of java.lang.Math.cos() method.
// Java program to demonstrate working// of java.lang.Math.cos() methodimport java.lang.Math;  class Gfg {      // driver code    public static void main(String args[])    {        double a = 30;                  // converting values to radians        double b = Math.toRadians(a);          System.out.println(Math.cos(b));          a = 45;                  // converting values to radians        b = Math.toRadians(a);          System.out.println(Math.cos(b));          a = 60;                  // converting values to radians        b = Math.toRadians(a);          System.out.println(Math.cos(b));          a = 0;                  // converting values to radians        b = Math.toRadians(a);          System.out.println(Math.cos(b));    }}
0.8660254037844387
0.7071067811865476
0.5000000000000001
1.0

Example 2 : To show working of java.lang.Math.cos() method when argument is NAN or infinity.
// Java program to demonstrate working// of java.lang.Math.cos() method infinity caseimport java.lang.Math; // importing java.lang package  public class GFG {    public static void main(String[] args)    {          double positiveInfinity =                Double.POSITIVE_INFINITY;        double negativeInfinity =                Double.NEGATIVE_INFINITY;        double nan = Double.NaN;        double result;          // Here argument is negative infinity,         // output will be NaN        result = Math.cos(negativeInfinity);        System.out.println(result);          // Here argument is positive infinity,         // output will also be NaN        result = Math.cos(positiveInfinity);        System.out.println(result);          // Here argument is NaN, output will be NaN        result = Math.cos(nan);        System.out.println(result);    }}
NaN
NaN
NaN

Java-lang package
Java-Library
java-math
Java
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java
LinkedList in Java
AIML - <random> Tag

<random> Tag is used to get random responses. This tag enables AIML to respond differently for the same input. <random> tag is used along with <li> tags. <li> tags carry different responses that are to be delivered to the user on a random basis.
<random>
   <li> pattern1 </li>
   <li> pattern2 </li>
   ...
   <li> patternN </li>
</random>
For example, consider the following conversation.
Human: Hi
Robot: Hello!
Human: Hi
Robot: Hi! Nice to meet you!

Create random.aiml inside C > ab > bots > test > aiml and random.aiml.csv inside C > ab > bots > test > aimlif directories.
<?xml version = "1.0" encoding = "UTF-8"?>
<aiml version = "1.0.1" encoding ="UTF-8"?>
   <category>
      <pattern>HI</pattern>
      
      <template>
         <random>
            <li> Hello! </li>
            <li> Hi! Nice to meet you! </li>
         </random>
      </template>
      
   <category>      
</aiml>
0,HI,*,*, <random><li> Hello! </li><li> Hi! Nice to meet you! </li></random>,random.aiml
Open the command prompt. Go to C > ab > and type the following command −
java -cp lib/Ab.jar Main bot = test action = chat trace = false

You will see the following output −
Human: Hi
Robot: Hi! Nice to meet you!
Human: Hi
Robot: Hello!

Here, the response may vary considering random responses.
 Print
 Add Notes
 Bookmark this page
How to prevent Reflection to break a Singleton Class Pattern?

A Singleton pattern states that a class can have a single instance and multiple instances are not permitted to be created. For this purpose, we make the constructor of the class a private and return a instance via a static method. But using reflection, we can still create multiple instance of a class by modifying the constructor scope. See the example below −
 Live Demo
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Tester {
   public static void main(String[] args) throws
   InstantiationException, IllegalAccessException,

   IllegalArgumentException, InvocationTargetException{
      A a = A.getInstance();
      A b = null;

      Constructor<?>[] constructors = A.class.getDeclaredConstructors();

      for (Constructor constructor : constructors) {
         //make the private constructor as public
         constructor.setAccessible(true);
         b = (A) constructor.newInstance();
         break;
      }
      System.out.println(a.hashCode());
      System.out.println(b.hashCode());
   }
}

class A implements Serializable {
   private static A a;
   private A(){}

   public static A getInstance(){
      if(a == null){
         a = new A();
      }
      return a;
   }
}
705927765
366712642
Here you can see, we've created another object of a Singleton class. Let's see how to prevent such a situation −
Create A using Enum instead of Class.
 Live Demo
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;

public class Tester {
   public static void main(String[] args) throws
   InstantiationException, IllegalAccessException,
   IllegalArgumentException, InvocationTargetException{

      A a = A.INSTANCE;
      A b = A.INSTANCE;

      System.out.println(a.hashCode());
      System.out.println(b.hashCode());
   }
}
enum A implements Serializable {
   INSTANCE;
}
705927765
705927765
Java program to merge two or more files alternatively into third file

Assume we have three files as −
output1.txt
Hello how are you
output2.txt
Welcome to Tutorialspoint
output3.txt
We provide simply easy learning
Following Java example merges the contents of the above three files alternatively into a single file −
import java.util.Scanner;
public class MergingFiles {
   public static void main(String args[]) throws IOException {
      Scanner sc1 = new Scanner(new File("D://input1.txt"));
      Scanner sc2 = new Scanner(new File("D://input2.txt"));
      Scanner sc3 = new Scanner(new File("D://input3.txt"));
      FileWriter writer = new FileWriter("D://result.txt");
      String str[] = new String[3];
      while (sc1.hasNextLine()||sc2.hasNextLine()||sc3.hasNextLine()) {
         str[0] = sc1.nextLine();
         str[1] = sc2.nextLine();
         str[2] = sc3.nextLine();
      }
      writer.append(str[0]+"\n");
      writer.append(str[1]+"\n");
      writer.append(str[2]+"\n");
      writer.flush();
      System.out.println("Contents added ");
   }
}
Contents added
If the above three files are in the same directly you can rewrite the sample program as −
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class MergingFiles {
   public static void main(String args[]) throws IOException {
      //Creating a File object for directory
      File directoryPath = new File("D:\\example");
      //List of all files and directories
      File filesList[] = directoryPath.listFiles();
      Scanner sc = null;
      FileWriter writer = new FileWriter("D://output.txt");
      for(File file : filesList) {
         sc = new Scanner(file);
         String input;
         StringBuffer sb = new StringBuffer();
         while (sc.hasNextLine()) {
            input = sc.nextLine();
            writer.append(input+"\n");
         }
         writer.flush();
      }
      System.out.println("Contents added ");
   }
}
Contents added
Build Python Packages Without Publishing | by Max Reynolds | Towards Data Science

Packages in Python allow for seamless distribution of python modules. When we use pip install, we are often downloading a publicly available package from PyPI. Local packages can also be useful for code organization and re-use, allowing you to simply import a module without having to navigate to its directory or re-write code. In this demonstration, we will be building and accessing a basic Python package.
Let’s create two simple modules and package them. We will then use this package to write a simple app that prompts a user to select a .jpg image from their computer to be gray-scaled.
ui.py
#ui.pyfrom tkinter import filedialogfrom tkinter import Tkdef get_image_file():    Tk().withdraw()    filename =  filedialog.askopenfilename(title = "Select file",filetypes = [("jpeg files","*.jpg")])    return filename
image_edits.py
#image_edits.pyfrom cv2 import imread, COLOR_RGB2GRAY, cvtColor, imwriteimport osdef write_grayscale_image(filepath):    original_image = imread(filepath)    grayed_image = cvtColor(original_image, COLOR_RGB2GRAY)    grayed_filename=os.path.join(os.path.split(filepath)[0],'grayed_'+os.path.split(filepath)[1])    print(grayed_filename)    imwrite(grayed_filename, grayed_image) #export grayscaled image    return grayed_filename
Create a blank __init__.py file, which will be used by Python to recognize this as a package.
$ touch __init__.py
At this point, our file structure should look like this:
dir/    image_pkg/              ui.py              image_edits.py              __init__.py
Next, create a setup.py file outside of your package directory
setup.py
import setuptoolssetuptools.setup(name='examplepackage',version='0.1',description='An example package',url='#',author='max',install_requires=['opencv-python'],author_email='',packages=setuptools.find_packages(),zip_safe=False)
Note that packages not included in the python standard library should be included in install_requires. Our file structure should now look like:
dir/    image_pkg/              ui.py              image_edits.py              __init__.py    setup.py
If you are using virtual environments (generally good practice for Python development), create and activate your environment.
$ python3 -m venv myenv$ source myenv/bin/activate
Install wheel.
$ pip install wheel
Install the package into your environment.
$ pip install .
Our package has been created, and we can now use it from anywhere. Let’s create a simple app which incorporates our package contents.
main.py
#main.pyfrom image_pkg.ui import get_image_filefrom image_pkg.image_edits import write_grayscale_imagewrite_grayscale_image(get_image_file())
We have now built and implemented a basic python package! More information regarding package distribution, licensing, and installation can be found in the documentation.
towardsdatascience.com
towardsdatascience.co
Registering for Medium supports my work.
How to install Scala on Windows? - GeeksforGeeks

05 Oct, 2021
Prerequisite: Introduction to Scala Before, we start with the process of Installing Scala on our System, we must have first-hand knowledge of What the Scala Language is and what it actually does? Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides the support to the functional programming approach. There is no concept of primitive data as everything is an object in Scala. It is designed to express the general programming patterns in a refined, succinct, and type-safe way. Scala programs can convert to bytecodes and can run on the JVM(Java Virtual Machine). Scala stands for Scalable language. It also provides the Javascript runtimes. Scala is highly influenced by Java and some other programming langauges like Lisp, Haskell, Pizza etc.Scala is a very compatible language and thus can very easily be installed into the Windows. The most basic requirement is that we must have Java 1.8 or a greater version installed on our computer.
Verifying Java Packages:The first thing we need to have is a Java Software Development Kit(SDK) installed on the computer. We need to verify this SDK packages and if not installed then install them. Just go to the Command line(For Windows, search for cmd in the Run dialog( + R).Now run the following command:
java -version 
Once this command is executed the output will show the java version and the output will be as follows:In case we are not having the SDK installed then download the latest version according to the computer requirements from oracle.com and just proceed with the installation.
Downloading Scala:Before starting with the installation process, you need to download it. For that, all versions of Scala for Windows are available on scala-lang.orgDownload the Scala and follow the further instructions for the installation of Scala.
Beginning with the Installation:
Getting Started:
Getting done with the User’s License Agreement:
Move on to Installing
Installation Process:
Finished Installation:
After completing the installation process, any IDE or text editor can be used to write Scala Codes and Run them on the IDE or the Command prompt with the use of command:
scalac file_name.Scala
scala class_name
Here’s a sample Program to begin with the use of Scala Programming:Let’s consider a simple Hello World Program.
// Scala program to print Hello World!  object Geeks  {     // Main Method      def main(args: Array[String])      {         // prints Hello World         println("Hello World!")      } } 
how-to-install
Scala-Basics
How To
Installation Guide
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Align Text in HTML?
How to filter object array based on attributes?
How to Install FFmpeg on Windows?
How to integrate Git Bash with Visual Studio Code?
How to Install Anaconda on Windows?
Installation of Node.js on Linux
How to Install FFmpeg on Windows?
How to Install Anaconda on Windows?
How to Install Pygame on Windows ?
How to Add External JAR File to an IntelliJ IDEA Project?