code-rag-bench/online-tutorials huggingface dataset:
C library function - fwrite()

The C library function size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) writes data from the array pointed to, by ptr to the given stream.
Following is the declaration for fwrite() function.
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
ptr − This is the pointer to the array of elements to be written.
ptr − This is the pointer to the array of elements to be written.
size − This is the size in bytes of each element to be written.
size − This is the size in bytes of each element to be written.
nmemb − This is the number of elements, each one with a size of size bytes.
nmemb − This is the number of elements, each one with a size of size bytes.
stream − This is the pointer to a FILE object that specifies an output stream.
stream − This is the pointer to a FILE object that specifies an output stream.
This function returns the total number of elements successfully returned as a size_t object, which is an integral data type. If this number differs from the nmemb parameter, it will show an error.
The following example shows the usage of fwrite() function.
#include<stdio.h>

int main () {
   FILE *fp;
   char str[] = "This is tutorialspoint.com";

   fp = fopen( "file.txt" , "w" );
   fwrite(str , 1 , sizeof(str) , fp );

   fclose(fp);
  
   return(0);
}
Let us compile and run the above program that will create a file file.txt which will have following content −
This is tutorialspoint.com

Now let's see the content of the above file using the following program −
#include <stdio.h>

int main () {
   FILE *fp;
   int c;

   fp = fopen("file.txt","r");
   while(1) {
      c = fgetc(fp);
      if( feof(fp) ) {
         break ;
      }
      printf("%c", c);
   }
   fclose(fp);
   return(0);
}
Let us compile and run the above program to produce the following result −
This is tutorialspoint.com


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
Self-Balancing-Binary-Search-Trees (Comparisons) - GeeksforGeeks

19 Jul, 2021
Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keeps height as small as possible when insertion and deletion operations are performed on tree. The height is typically maintained in order of Log n so that all operations take O(Log n) time on average. 
Examples : Red Black Tree  
AVL Tree:  
Language Implementations : set and map in C++ STL. TreeSet and TreeMap in Java. Most of the library implementations use Red Black Tree. Python standard library does not support Self Balancing BST. In Python, we can use bisect module to keep a set of sorted data. We can also use PyPi modules like rbtree (implementation of red black tree) and pyavl (implementation of AVL tree). 
How do Self-Balancing-Tree maintain height? A typical operation done by trees is rotation. Following are two basic operations that can be performed to re-balance a BST without violating the BST property (keys(left) < key(root) < keys(right)). 1) Left Rotation 2) Right Rotation 
 
T1, T2 and T3 are subtrees of the tree 
rooted with y (on the left side) or x (on 
the right side)           
     y                               x
    / \     Right Rotation          /  \
   x   T3   - - - - - - - >        T1   y 
  / \       < - - - - - - -            / \
 T1  T2     Left Rotation            T2  T3
Keys in both of the above trees follow the 
following order 
 keys(T1) < key(x) < keys(T2) < key(y) < keys(T3)
So BST property is not violated anywhere.
We have already discussed AVL tree, Red Black Tree and Splay Tree. In this acrticle, we will compare the efficiency of these trees:  
 
ssaksham
AVL-Tree
Advanced Data Structure
Binary Search Tree
Binary Search Tree
AVL-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ordered Set and GNU C++ PBDS
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Suffix Array | Set 1 (Introduction)
Difference between Backtracking and Branch-N-Bound technique
Binary Search Tree | Set 1 (Search and Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Construct BST from given preorder traversal | Set 1
Sorted Array to Balanced BST
Python | Imputation using the KNNimputer() - GeeksforGeeks

05 Sep, 2020
KNNimputer is a scikit-learn class used to fill out or predict the missing values in a dataset. It is a more useful method which works on the basic approach of the KNN algorithm rather than the naive approach of filling all the values with mean or the median. In this approach, we specify a distance from the missing values which is also known as the K parameter. The missing value will be predicted in reference to the mean of the neighbours.
It is implemented by the KNNimputer() method which contains the following arguments:
n_neighbors: number of data points to include closer to the missing value.metric: the distance metric to be used for searching.values – {nan_euclidean. callable} by default – nan_euclideanweights: to determine on what basis should the neighboring values be treatedvalues -{uniform , distance, callable} by default- uniform.
Code: Python code to illustrate KNNimputor class
# import necessary librariesimport numpy as npimport pandas as pd  # import the KNNimputer classfrom sklearn.impute import KNNImputer    # create dataset for marks of a studentdict = {'Maths':[80, 90, np.nan, 95],         'Chemistry': [60, 65, 56, np.nan],         'Physics':[np.nan, 57, 80, 78],       'Biology' : [78,83,67,np.nan]}  # creating a data frame from the list Before_imputation = pd.DataFrame(dict)#print dataset before imputaionprint("Data Before performing imputation\n",Before_imputation)  # create an object for KNNImputerimputer = KNNImputer(n_neighbors=2)After_imputation = imputer.fit_transform(Before_imputation)# print dataset after performing the operationprint("\n\nAfter performing imputation\n",After_imputation)
Output:
Data Before performing imputation
    Maths  Chemistry  Physics  Biology
0   80.0       60.0      NaN     78.0
1   90.0       65.0     57.0     83.0
2    NaN       56.0     80.0     67.0
3   95.0        NaN     78.0      NaN


After performing imputation
 [[80.  60.  68.5 78. ]
 [90.  65.  57.  83. ]
 [87.5 56.  80.  67. ]
 [95.  58.  78.  72.5]]

Note: After transforming the data becomes a numpy array.
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Decision Tree
Reinforcement learning
Decision Tree Introduction with example
Python | Decision tree implementation
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Taking input in Python
Can I define more than one public class in a Java package?

No, while defining multiple classes in a single Java file you need to make sure that only one class among them is public. If you have more than one public classes a single file a compile-time error will be generated.
In the following example we have two classes Student and AccessData we are having both of them in the same class and declared both public.
 Live Demo
import java.util.Scanner;
public class Student {
   private String name;
   private int age;
   Student(){
      this.name = "Rama";
      this.age = 29;
   }
   Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void display() {
      System.out.println("name: "+this.name);
      System.out.println("age: "+this.age);
   }
}
public class AccessData{
   public static void main(String args[]) {
      //Reading values from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      System.out.println("Enter the age of the student: ");
      int age = sc.nextInt();
      Student obj1 = new Student(name, age);
      obj1.display();
      Student obj2 = new Student();
      obj2.display();
   }
}
On compiling, the above program generates the following compile-time error.
AccessData.java:2: error: class Student is public, should be declared in a file named Student.java
public class Student {
       ^
1 error
To resolve this either you need to shift one of the classes into a separate file or,
Remove the public declaration before the class that doesn’t contain a public static void main(String args) method.
Remove the public declaration before the class that doesn’t contain a public static void main(String args) method.
Name the file with the class name that contains main method.
Name the file with the class name that contains main method.
In this case, remove the public before the Student class. Name the file as “AccessData.java”.
The match Function in Python

This function attempts to match RE pattern to string with optional flags.
Here is the syntax for this function −
re.match(pattern, string, flags=0)
Here is the description of the parameters −
The re.match function returns a match object on success, None on failure. We usegroup(num) or groups() function of match object to get matched expression.
 Live Demo
#!/usr/bin/python
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
   print "matchObj.group() : ", matchObj.group()
   print "matchObj.group(1) : ", matchObj.group(1)
   print "matchObj.group(2) : ", matchObj.group(2)
else:
   print "No match!!"
When the above code is executed, it produces the following result −
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
Swap two variables in one line in using Python?

In this section, we are going to swap two variable in one line using python. The standard way to swap two variables in python is very simple and easy−
>>> a = 20;b=30
>>> a
20
>>> b
30
>>> #Swap two variable in one line
>>> a, b = b, a
>>> a
30
>>> b
20
Above code generate swapped values of a and b.
Python evaluates expression from left to right. However, while evaluating an assignment, the right-hand side is evaluated before the left-hand side.
That means the following for the expression a, b = b, a
The right-hand side ‘b, a’ is evaluated, that is to say a tuple of two elements is created in the memory. The two element are the objects designated by the identifiers b and a, that were existing before the instruction is encountered during an execution of program.
The right-hand side ‘b, a’ is evaluated, that is to say a tuple of two elements is created in the memory. The two element are the objects designated by the identifiers b and a, that were existing before the instruction is encountered during an execution of program.
Once the tuple is created, but no assignment of this tuple object is made yet, but that’s not a issue, as python internally knows where it is.
Once the tuple is created, but no assignment of this tuple object is made yet, but that’s not a issue, as python internally knows where it is.
Then the left-hand side is evaluated, that is- the tuple which is stored in memory is assigned to the left-hand side as the left-hand side is composed of two identifiers a and b. the tuple is unpacked in order that the first identifier a(left-side) is assigned by the first element of the tuple (.i.e. b) and the second identifier b is assigned by the second element of the tuple (.i.e. a).
Then the left-hand side is evaluated, that is- the tuple which is stored in memory is assigned to the left-hand side as the left-hand side is composed of two identifiers a and b. the tuple is unpacked in order that the first identifier a(left-side) is assigned by the first element of the tuple (.i.e. b) and the second identifier b is assigned by the second element of the tuple (.i.e. a).
In short, the expression: “ a, b = b, a”, first right gets assigned to first left and second right get assigned to second left at the same time therefore swap values of a and b.
Formatted Strings Using Template Strings in JavaScript

Following is the code for formatted strings using template strings in Javascript −
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,
   .sample {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
   .sample {
      color: red;
   }
</style>
</head>
<body>
<h1>Formatted Strings Using Template Strings JavaScript</h1>
<div class="sample">
`The person name is ${personObj.name}. His age and rollno are
${personObj.age} and ${personObj.rollno} respectively`
</div>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to see the template string formatted with the
personObj values</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let personObj = { name: "Rohan Sharma", age: 12, rollno: 22 };
   let arr = [22, 55, 11, 19, 55];
   BtnEle.addEventListener("click", (event) => {
      resEle.innerHTML = `The person name is ${personObj.name}. His age and rollno are
      ${personObj.age} and ${personObj.rollno} respectively`;
   });
</script>
</body>
</html>
On clicking the ‘CLICK HERE’ button −
How to open a file in read and write mode with Python?

To open files in read/write mode, specify 'w+' as the mode. For example,
f = open('my_file.txt', 'w+')
file_content = f.read()
f.write('Hello World')
f.close()
 Above code opens my_file.txt in write mode, stores the file content in file_content variable and rewrites the file to contain "Hello World". You can also use r+ mode as it doesn't truncate the file.
TypeScript - Number toPrecision()

This method returns a string representing the number object to the specified precision.
number.toPrecision( [ precision ] )

precision − An integer specifying the number of significant digits.
Returns a string representing a Number object in fixed-point or exponential notation rounded to precision significant digits.
var num = new Number(7.123456); 
console.log(num.toPrecision()); 
console.log(num.toPrecision(1)); 
console.log(num.toPrecision(2));

On compiling, it will generate the same code in JavaScript.
The code will produce the following output −
7.123456 
7 
7.1


    45 Lectures 
     4 hours 

 Antonio Papa

    41 Lectures 
     7 hours 

 Haider Malik

    60 Lectures 
     2.5 hours 

 Skillbakerystudios

    77 Lectures 
     8 hours 

 Sean Bradley

    77 Lectures 
     3.5 hours 

 TELCOMA Global

    19 Lectures 
     3 hours 

 Christopher Frewin
 Print
 Add Notes
 Bookmark this page
Java Program to Find Sum of the Series 1/1! + 2/2! + 3/3! + ......1/N! - GeeksforGeeks

13 Jan, 2022
Factorial of a number simply returns out the multiplication of that number with all numbers lesser than the number up to 1 over which factorial is applied. Now the question arises whether the series is convergent or divergent. According to concepts of  Infinite series and factorial in mathematics, the series may not converge but it can contain a convergent subsequence.
Illustration:
n! = n * (n-1) × (n-2) × (n-3) × (n-4) × ...... × 4 × 3 × 2 × 1
Input      : n = 5
Processing : 1/1! + 2/2! + 3/3! + 4/4! + 5/5!
             1    + 2/2  + 3/6  + 4/24 + 5/120
Output     : 2.708333333333333            
Approach : 
Enter the number of terms N.
Create a function to calculate the sum of series, say, calculateSum.
In calculateSum function(), create a variable sum which stores the total sum of the series.
Run a loop N times.
Call factorial function() to calculate the factorial of a given number.
Return sum.
Implementation:
Java
// Java Program to Find Sum of the Series// 1/1! + 2/2! + 3/3! + ......1/N! // Importing java generic librariesimport java.io.*; class GFG {       // Function(recursive) to calculate factorial    public static double factorial(int i)    {        // Step1: Base case        if (i == 1) {            return 1;        }        // Step2&3: Recursion execution & call statements        return i * factorial(i - 1);    }     // Function to calculate sum of series    public static double calculateSum(int N)    {        // Store total_sum in sum        double sum = 0;         // Iteration by running a loop N times        for (int i = 1; i <= N; i++) {            sum = sum + ((double)i / factorial(i));        }         // Return calculated final sum        return sum;    }     // Main driver method    public static void main(String[] args)    {        /* No of terms in series           taken inn order to show output */        int N = 5;         // Print sum of series by        // calling function calculating sum of series        System.out.println("The sum of series upto " + N                           + " terms is : "                           + calculateSum(N));    }}
The sum of series upto 5 terms is : 2.708333333333333
Time Complexity: O(n)
kalrap615
clintra
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Generics in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
How to create a JSON object in JavaScript? Explain with an example.

Following is the code to create a JSON object in JavaScript.
 Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JSON object in JavaScript</h1>
<div class="sample"></div>
<div style="color: green;" class="result">JSON OBJECT <br></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to create a JSON object and display it
</h3>
<script>
   let resEle = document.querySelector(".result");
   let obj = {
      firstName:'Rohan',
      lastName: 'Sharma',
      Age:14,
   }
   document.querySelector(".Btn").addEventListener("click", () => {
      for(i in obj){
         resEle.innerHTML += 'key = '+i+' value = ' + obj[i] + '<br>';
      }
   });
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘CLICK HERE’ button −
HTML5 Canvas - Drawing Paths

We require the following methods to draw paths on the canvas −
beginPath()
This method resets the current path.
moveTo(x, y)
This method creates a new subpath with the given point.
closePath()
This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.
fill()
This method fills the subpaths with the current fill style.
stroke()
This method strokes the subpaths with the current stroke style.
arc(x, y, radius, startAngle, endAngle, anticlockwise)
Adds points to the subpath such that the arc described by the circumference of the circle described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction, is added to the path, connected to the previous point by a straight line.
Following is a simple example which makes use of above mentioned methods to draw a shape.
<!DOCTYPE HTML>

<html>
   <head>
   
      <style>
         #test {
            width: 100px;
            height:100px;
            margin: 0px auto;
         }
      </style>
      
      <script type = "text/javascript">
         function drawShape() {
            
            // get the canvas element using the DOM
            var canvas = document.getElementById('mycanvas');

            // Make sure we don't execute when canvas isn't supported
            if (canvas.getContext) {
               
               // use getContext to use the canvas for drawing
               var ctx = canvas.getContext('2d');

               // Draw shapes
               ctx.beginPath();
               ctx.arc(75,75,50,0,Math.PI*2,true);  // Outer circle
               
               ctx.moveTo(110,75);
               ctx.arc(75,75,35,0,Math.PI,false);   // Mouth
               
               ctx.moveTo(65,65);
               ctx.arc(60,65,5,0,Math.PI*2,true);  // Left eye
               
               ctx.moveTo(95,65);
               ctx.arc(90,65,5,0,Math.PI*2,true);  // Right eye
               ctx.stroke();
            } else {
               alert('You need Safari or Firefox 1.5+ to see this demo.');
            }
         }
      </script>
   </head>
	
   <body id = "test" onload = "drawShape();">
      <canvas id = "mycanvas"></canvas>
   </body>
	
</html>
It will produce the following output −

    19 Lectures 
     2 hours 

 Anadi Sharma

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    18 Lectures 
     1.5 hours 

 Frahaan Hussain

    57 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)

    54 Lectures 
     6 hours 

 DigiFisk (Programming Is Fun)

    45 Lectures 
     5.5 hours 

 DigiFisk (Programming Is Fun)
 Print
 Add Notes
 Bookmark this page
Kotlin Regex Patterns

07 Feb, 2022
Regular expression is used to search for text and more advanced text manipulation. Regular Expressions are a fundamental part of almost every programming language and Kotlin is no exception to it. In Kotlin, the support for regular expression is provided through Regex class. An object of this class represents a regular expression, that can be used for string matching purposes.We can easily find use of regular expressions in different kind of software, from simplest to incredibly complex applications.Kotlin regular expression In Kotlin, we build regular expressions with the Regex.  
Regex("pen")
"pen".toRegex()
Regex.fromLiteral("pen")
A pattern defines the text we need to search for or manipulate. It consists of text literals and metacharacters. Metacharacters are special characters that control the evaluation of the regular expression. For example, with \s we search for white spaces.In Kotlin, some of the regex patterns are given in the table below. 
Note :- First we have create a pattern, then we can use one of the functions to apply to the pattern on a text string. The functions include find(), findall(), replace(), and split(). 
It returns the first match of a regular expression in the input, starting at the specified start index. In Kotlin, the default start index is 0.Kotlin program of using find method –  
Kotlin
fun main(args : Array<String>) {     val company = "GeeksforGeeks : A computer science portal for students"     val pattern = "science".toRegex()     val found = pattern.find(company)     val m = found?.value    val index = found?.range     println("$m found at indexes: $index") }
Output:  
science found at indexes: 27..33
 
It returns a sequence of all the occurrences of a regular expression within the given input string.Kotlin program of using findAll method –  
Kotlin
fun main(args : Array<String>) {     val company = "GeeksforGeeks"     val pattern = "Geeks".toRegex()     val patt = pattern.findAll(company)     patt.forEach { f ->        val m = f.value        val index = f.range        println("$m indexes are: $index")     }}
Output:  
Geeks indexes are: 0..4
Geeks indexes are: 8..1
 
The dot (.) metacharacter denotes any of the single characters in the text. Kotlin program –  
Kotlin
fun main(args : Array<String>) {     val names = listOf("GeeksforGeeks", "GeekyAnts", "McGeek")     val pattern = "..Geek".toRegex()     names.forEach { name ->        if (pattern.containsMatchIn(name)) {            println("$name matches")         }    }}
Output:  
GeeksforGeeks matches
McGeek matches
 
nidhi_biet
ayushpandey3july
Kotlin Regex
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android RecyclerView in Kotlin
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
Suspend Function In Kotlin Coroutines
How to Change the Color of Status Bar in an Android App?
Kotlin when expression
variable === undefined vs. typeof variable === “undefined” in JavaScript

28 Oct, 2021
Undefined comes into a picture when any variable is defined already but not has been assigned any value. Undefined is not a keyword. A function can also be undefined when it doesn’t have the value returned. There are two ways to determine if a variable is not defined, Value and type.  
javascript
var geeks;alert ( geeks === undefined)
It’s so clear that you assigned a variable that was not defined but the variable exists. Here you are comparing geeks variable with the global variable “undefined” which is undefined also. Syntax:  
Check by Value (Strict equality Operator): Here you will get that variable is assigned a value or not if the variable is not assigned a value it will display undefined.Check the type (Typeof operator): Here you will get what type of variable was that if there is no variable was assigned then it will display “undefined”.
Check by Value (Strict equality Operator): Here you will get that variable is assigned a value or not if the variable is not assigned a value it will display undefined.
Check the type (Typeof operator): Here you will get what type of variable was that if there is no variable was assigned then it will display “undefined”.
Note The strict equality operator (===) doesn’t check whether the variable is null or not.The type of operator does not throw an error if the variable has not been declared.Example: Here we assign two variable one is undefined and the other one is defined “null”, here null is not undefined when you put console.log it will show “null” if you check typeof then it will display object, below program will illustrate the approach more clearly. Program:  
javascript
var firstName;var lastName = null; // Print: undefined       console.log(firstName);// Print: nullconsole.log(lastName);          // Print: undefinedconsole.log(typeof firstName);// Print: objectconsole.log(typeof lastName);          // Print: falseconsole.log(null === undefined)         if(firstName === undefined) {        console.log('LastName is undefined');     } else if(firstName === null){        console.log('FirstName is null');     }
Output:  
undefined
null

undefined
object

false
variable === undefined VS typeof variable === “undefined”  
 
ruhelaa48
JavaScript-Misc
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Roadmap to Learn JavaScript For Beginners
How to get character array from string in JavaScript?
How do you run JavaScript script through the Terminal?
JavaScript | console.log() with Examples
Node.js | fs.writeFileSync() Method
Kotlin - Interface

In this chapter, we will learn about the interface in Kotlin. In Kotlin, the interface works exactly similar to Java 8, which means they can contain method implementation as well as abstract methods declaration. An interface can be implemented by a class in order to use its defined functionality. We have already introduced an example with an interface in Chapter 6 - section “anonymous inner class”. In this chapter, we will learn more about it. The keyword “interface” is used to define an interface in Kotlin as shown in the following piece of code.
interface ExampleInterface {
   var myVar: String     // abstract property
   fun absMethod()       // abstract method
   fun sayHello() = "Hello there" // method with default implementation
}
In the above example, we have created one interface named as “ExampleInterface” and inside that we have a couple of abstract properties and methods all together. Look at the function named “sayHello()”, which is an implemented method.
In the following example, we will be implementing the above interface in a class.
interface ExampleInterface  {
   var myVar: Int            // abstract property
   fun absMethod():String    // abstract method
   
   fun hello() {
      println("Hello there, Welcome to TutorialsPoint.Com!")
   }
}
class InterfaceImp : ExampleInterface {
   override var myVar: Int = 25
   override fun absMethod() = "Happy Learning "
}
fun main(args: Array<String>) {
   val obj = InterfaceImp()
   println("My Variable Value is = ${obj.myVar}")
   print("Calling hello(): ")
   obj.hello()
   
   print("Message from the Website-- ")
   println(obj.absMethod())
}
The above piece of code will yield the following output in the browser.
My Variable Value is = 25
Calling hello(): Hello there, Welcome to TutorialsPoint.Com!
Message from the Website-- Happy Learning 

As mentioned earlier, Kotlin doesn’t support multiple inheritances, however, the same thing can be achieved by implementing more than two interfaces at a time.
In the following example, we will create two interfaces and later we will implement both the interfaces into a class.
interface A {
   fun printMe() {
      println(" method of interface A")
   }
}
interface B  {
   fun printMeToo() {
      println("I am another Method from interface B")
   }
}

// implements two interfaces A and B
class multipleInterfaceExample: A, B

fun main(args: Array<String>) {
   val obj = multipleInterfaceExample()
   obj.printMe()
   obj.printMeToo()
}
In the above example, we have created two sample interfaces A, B and in the class named “multipleInterfaceExample” we have implemented two interfaces declared earlier. The above piece of code will yield the following output in the browser.
method of interface A
I am another Method from interface B


    68 Lectures 
     4.5 hours 

 Arnab Chakraborty

    71 Lectures 
     5.5 hours 

 Frahaan Hussain

    18 Lectures 
     1.5 hours 

 Mahmoud Ramadan

    49 Lectures 
     6 hours 

 Catalin Stefan

    49 Lectures 
     2.5 hours 

 Skillbakerystudios

    22 Lectures 
     1 hours 

 CLEMENT OCHIENG
 Print
 Add Notes
 Bookmark this page
Java Program to add integers and check for overflow

To check for Integer overflow, we need to check the Integer.MAX_VALUE with the added integers result, Here, Integer.MAX_VALUE is the maximum value of an integer in Java.
Let us see an example wherein integers are added and if the sum is more than the Integer.MAX_VALUE, then an exception is thrown.
 Live Demo
public class Demo {
   public static void main(String[] args) {
      int a = 9897988;
      int b = 8798798;
      System.out.println("Value1: "+a);
      System.out.println("Value2: "+b);
      long sum = (long)a + (long)b;
      if (sum > Integer.MAX_VALUE) {
         throw new ArithmeticException("Integer Overflow!");
      }
      // displaying sum
      System.out.println("Sum: "+(int)sum);
   }
}
Value1: 9897988
Value2: 8798798
Sum: 18696786
In the above example, we have taken the following two integers.
int val1 = 9897988;
int val2 = 8798798;
Now we will cast and add them to a long.
long sum = (long)val1 + (long)val2;
If the result is more than the maximum value, then an exception is thrown.
If (sum > Integer.MAX_VALUE) {
   throw new ArithmeticException("Overflow!");
}
SQL Tryit Editor v1.6

ALTER TABLE Employees
ALTER COLUMN BirthDate year;
​
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
How to iterate the values of an enum using a for loop in Java?

Enumerations in Java represents a group of named constants, you can create an enumeration using the following syntax −
enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
You can retrieve the contents of an enum using the values() method. This method returns an array containing all the values. Once you obtain the array you can iterate it using the for loop.
public class IterateEnum{
   public static void main(String args[]) {
      Days days[] = Days.values();
      System.out.println("Contents of the enum are: ");      
      //Iterating enum using the for loop
      for(Days day: days) {
         System.out.println(day);
      }
   }   
}
Contents of the enum are:
SUNDAY
MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
Live Demo
enum Vehicles {
   //Declaring the constants of the enum
   ACTIVA125, ACTIVA5G, ACCESS125, VESPA, TVSJUPITER;
   int i; //Instance variable
   Vehicles() { //constructor
   }   
   public void enumMethod() { //method
      System.out.println("Current value: "+Vehicles.this);
   }
}
public class Sam{
   public static void main(String args[]) {
      Vehicles vehicles[] = Vehicles.values();
      for(Vehicles veh: vehicles) {
         System.out.println(veh);
      }
      vehicles[3].enumMethod();      
   }   
}
ACTIVA125
ACTIVA5G
ACCESS125
VESPA
TVSJUPITER
Current value: VESPA
Ionic - Footer

Ionic footer is placed at the bottom of the app screen. Working with footers is almost the same as working with headers.
The main class for Ionic footers is bar (the same as header). When you want to add footer to your screens, you need to add bar-footer class to your element after the main bar class. Since we want to use our footer on every screen in the app, we will add it to the body of the index.html file. We will also add title for our footer.
<div class = "bar bar-footer">
   <h1 class = "title">Footer</h1>
</div>

The above code will produce the following screen −
If you want to style your footer, you just need to add the appropriate color class to it. When you style your elements, you need to add your main element class as a prefix to your color class. Since we are styling a footer bar, the prefix class will be a bar and the color class that we want to use in this example is assertive (red).
<div class = "bar bar-footer bar-assertive">
   <h1 class = "title">Footer</h1>
</div>

The above code will produce the following screen −
You can use any of the following nine classes to give a color of your choice to your app footer −
Footers can contain elements inside it. Most of the time you will need to add buttons with icons inside a footer.
The first button added will always be in the left corner. The last one will be placed on the right. The buttons in between will be grouped next to the first one on the left side of your footer. In following example, you can also notice that we use the icon class to add icons on top of the buttons.
<div class = "bar bar-footer bar-assertive">
   <button class = "button icon ion-navicon"></button>
   <button class = "button icon ion-home"></button>
   <button class = "button icon ion-star"></button>
   <button class = "button icon ion-checkmark-round"></button>
</div>
The above code will produce the following screen −
If you want to move your button to the right you can add pull-right class.
<div class = "bar bar-footer bar-assertive">
   <button class = "button icon ion-navicon pull-right"></button>
</div>
The above code will produce the following screen −

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    185 Lectures 
     46.5 hours 

 Nikhil Agarwal
 Print
 Add Notes
 Bookmark this page
Python Pandas DataFrame Join, Merge, and Concatenate | by Jiahui Wang | Towards Data Science

When using sql, we have join operation. In Python, pandas.DataFrame also provides the similar table operations. However, pandas.DataFrame has join, merge, and concat. What’s the difference among them? In this post, I will summarize the code and illustration of these operations.
Among the three DataFrame operations, join allows the lowest level of control. It will combine all the columns from the two tables, with the common columns renamed with the defined lsuffix and rsuffix. The way that rows from the two tables are combined is defined by how.
DataFrame.join(self, other, on=None, how='left', lsuffix='', rsuffix='', sort=False)
Similar to join, merge also combines all the columns from the two tables, with the common columns renamed with the defined suffixes. However, merge provides three ways of flexible control over row-wise alignment. The first way is to use on = COLUMN NAME, here the given column must be the common column in both tables. The second way is to use left_on = COLUMN NAME and right_on = COLUMN NAME , and it allows to align the two tables using two different columns. The third way is to use left_index = True and right_index = True, and the two tables are aligned based on their index.
DataFrame.merge(self, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)
Different from join and merge, which by default operate on columns, concat can define whether to operate on columns or rows.
pandas.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=None, copy=True)
For pandas.DataFrame, both join and merge operates on columns and rename the common columns using the given suffix. In terms of row-wise alignment, merge provides more flexible control.
Different from join and merge, concat can operate on columns or rows, depending on the given axis, and no renaming is performed. In addition, concat allows defining hierachy structures by passing in keys and names.
C++ Program to Implement Affine Cipher

In the Affine cipher, each letter in an alphabet is mapped to its numeric equivalent, is a type of monoalphabetic substitution cipher. Encryption is done using a simple mathematical function and converted back to a letter.
The letters of an alphabet of size m are first mapped to the integers in the range 0 ... m-1, in the Affine cipher,
The ‘key’ for the Affine cipher consists of 2 numbers, a and b. a should be chosen to be relatively prime to m.
To transform the integer, it uses modular arithmetic that each plaintext letter corresponds to into another integer that correspond to a cipher text letter. The encryption function for a single letter is
E ( x ) = ( a x + b ) mod m
modulus m: size of the alphabet
a and b: key of the cipher.
In decryption, convert each of the cipher text letters into their integer values. The decryption function is
D ( x ) = a^-1 ( x - b ) mod m
a^-1 : modular multiplicative inverse of a modulo m. i.e., it satisfies the equation
1 = a^-1 mod m.
Here is a C++ program to implement this process.
Begin
Function encryption(string m)
   for i = 0 to m.length()-1
      if(m[i]!=' ')
         c = c + (char) ((((a * (m[i]-'A') ) + b) % 26) + 'A')
      else
         c += m[i]
   return c
End
Begin
Function decryption(string c)
   Initialize a_inverse = 0
   Initialize flag = 0
   For i = 0 to 25
      flag = (a * i) % 26
      if (flag == 1)
         a_inverse = i
      done
   done
   For i = 0 to c.length() - 1
      if(c[i]!=' ')
         m = m + (char) (((a_inverse * ((c[i]+'A' - b)) % 26)) + 'A')
      else
         m = m+ c[i]
   done
End
#include<bits/stdc++.h>
using namespace std;
static int a = 7;
static int b = 6;
string encryption(string m) {
   //Cipher Text initially empty
   string c = "";
   for (int i = 0; i < m.length(); i++) {
      // Avoid space to be encrypted
      if(m[i]!=' ')
         // added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
         c = c + (char) ((((a * (m[i]-'A') ) + b) % 26) + 'A');
      else
         //else append space character
         c += m[i];
   }
   return c;
}
string decryption(string c) {
   string m = "";
   int a_inverse = 0;
   int flag = 0;
   //Find a^-1 (the multiplicative inverse of a
   //in the group of integers modulo m.)
   for (int i = 0; i < 26; i++) {
      flag = (a * i) % 26;
      //Check if (a * i) % 26 == 1,
      //then i will be the multiplicative inverse of a
      if (flag == 1) {
         a_inverse = i;
      }
   }
   for (int i = 0; i < c.length(); i++) {
      if(c[i] != ' ')
         // added 'A' to bring it in range of ASCII alphabet [ 65-90 | A-Z ]
         m = m + (char) (((a_inverse * ((c[i]+'A' - b)) % 26)) + 'A');
      else
         //else append space character
         m += c[i];
   }
   return m;
}
int main(void) {
   string msg = "TUTORIALSPOINT";
   string c = encryption(msg);
   cout << "Encrypted Message is : " << c<<endl;
   cout << "Decrypted Message is: " << decryption(c);
   return 0;
}
Encrypted Message is : JQJAVKGFCHAKTJ
Decrypted Message is: TUTORIALSPOINT
MySQL - LOOP Statement

Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog. These procedures contain IN and OUT parameters, or both. They may return result sets in case you use SELECT statements; they can return multiple result-sets. You can also create functions in MYSQL.
Similar to other programming languages MySQL provides support for the flow control statements such as IF, CASE, ITERATE, LEAVE LOOP, WHILE, and REPEAT. You can use these statements in the stored programs (procedures), and RETURN in stored functions. You can use one Flow Control Statement with in another.
The LOOP is a compound MySQL statement which is used to execute a single or set of statements repeatedly.
Following is the syntax of the loop statement is MySQL −
begin_label: LOOP
statement_list
END LOOP end_label

Where, statement_list is a single or set of statements that are to be repeated. begin_label and end_label are the optional labels of the LOOP statement.
The statement(s) in the LOOP are executed repeatedly till the loop is terminated. You can terminate the LOOP using the LEAVE statement.
When used in a function the LOOP can also be terminated using the RETURN statement. Each statement in the LOOP ends with a semi colon (or. the current delimiter).
Following query demonstrates the usage of the LOOP statement with a procedure −
mysql> Delimiter //
mysql> CREATE procedure loopDemo()
   label:BEGIN
      DECLARE val INT ;
      DECLARE result VARCHAR(255);
      SET val =1;
      SET result = '';
         loop_label: LOOP
         IF val > 10 THEN 
            LEAVE loop_label;
         END IF;
         SET result = CONCAT(result,val,',');
         SET val = val + 1;
         ITERATE loop_label;
      END LOOP;
      SELECT result;
      END//
You can call the above procedure as follows −
mysql> call loopDemo;//
+-----------------------+
| result                |
+-----------------------+
| 1,2,3,4,5,6,7,8,9,10, |
+-----------------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.07 sec)
Following query demonstrates how to use the LOOP statement with in a function.
DELIMITER //
CREATE FUNCTION Sample (bonus INT)
   RETURNS INT
   BEGIN
      DECLARE income INT;
      SET income = 0;
      myLabel: LOOP
         SET income = income + bonus;
         IF income < 10000 THEN
            ITERATE myLabel;
         END IF;
         LEAVE myLabel;
      END LOOP myLabel;
   RETURN income;
END; //
Query OK, 0 rows affected (0.41 sec)
mysql> DELIMITER ;
You can call the above created function as shown below −
mysql> SELECT Sample(1000);
+--------------+
| Sample(1000) |
+--------------+
| 10000        |
+--------------+
1 row in set (0.15 sec)

    31 Lectures 
     6 hours 

 Eduonix Learning Solutions

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    6 Lectures 
     3.5 hours 

 DATAhill Solutions Srinivas Reddy

    60 Lectures 
     10 hours 

 Vijay Kumar Parvatha Reddy

    10 Lectures 
     1 hours 

 Harshit Srivastava

    25 Lectures 
     4 hours 

 Trevoir Williams
 Print
 Add Notes
 Bookmark this page
Add alpha to an existing Matplotlib colormap

To add apha to an existing matplotlib colormap, we can take the following steps −
Create data with a 4×4 dimension array using numpy.
Create data with a 4×4 dimension array using numpy.
Get the colormap using plt.cm.RdBU.
Get the colormap using plt.cm.RdBU.
Create a new colormap using numpy.
Create a new colormap using numpy.
Set alpha value to the new colormap.
Set alpha value to the new colormap.
Generate a colormap object using the list of colors.
Generate a colormap object using the list of colors.
Create a new figure or activate an existing figure using figure() method.
Create a new figure or activate an existing figure using figure() method.
Add a subplot to the current figure, nrows=1, ncols=2 at index=1.
Add a subplot to the current figure, nrows=1, ncols=2 at index=1.
Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method.
Create a pseudocolor plot with a non-regular rectangular grid using pcolormesh() method.
Create a colorbar for scalar mappable instance.
Create a colorbar for scalar mappable instance.
Repeat steps 7 to 9, at index 2.
Repeat steps 7 to 9, at index 2.
Use tight_layout() to adjust the padding between and around the subplots.
Use tight_layout() to adjust the padding between and around the subplots.
To display the figure, use show() method.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
data1 = np.random.random((4, 4))
cmap = plt.cm.RdBu
my_cmap = cmap(np.arange(cmap.N))
my_cmap[:, -1] = np.linspace(0, 1, cmap.N)
my_cmap = ListedColormap(my_cmap)
plt.figure()
plt.subplot(121)
plt.pcolormesh(data1, cmap=plt.cm.RdBu)
plt.colorbar()
plt.subplot(122)
plt.pcolormesh(data1, cmap=my_cmap)
plt.colorbar()
plt.tight_layout()
plt.show()
How can we capitalize only first letter of a string with the help of MySQL function/s?

Actually, there is no single function in MySQL to capitalize only first letter of the string. We need to use nesting of functions and for this case, we can use UPPER() and LOWER() with SUBSTRING() functions. To understand it, we are using data, given as below, from ‘emp_tbl’.
mysql> Select * from emp_tbl;
+----+----------------+
| Id | Name           |
+----+----------------+
| 1  | rahul singh    |
| 2  | gaurav kumar   |
| 3  | yashpal sharma |
| 4  | krishan kumar  |
| 5  | kuldeep rai    |
| 6  | munish nayak   |
+----+----------------+
6 rows in set (0.00 sec)
We can see from the above result set that the first character of name string is in small letters. The following query will capitalize the first letter of string −
mysql> Select CONCAT(UPPER(SUBSTRING(name,1,1)),LOWER(SUBSTRING(name,2))) AS Name from emp_tbl;
+----------------+
| Name           |
+----------------+
| Rahul singh    |
| Gaurav kumar   |
| Yashpal sharma |
| Krishan kumar  |
| Kuldeep rai    |
| Munish nayak   |
+----------------+
6 rows in set (0.00 sec)