code-rag-bench/online-tutorials huggingface dataset:
SciPy - ODR

ODR stands for Orthogonal Distance Regression, which is used in the regression studies. Basic linear regression is often used to estimate the relationship between the two variables y and x by drawing the line of best fit on the graph.
The mathematical method that is used for this is known as Least Squares, and aims to minimize the sum of the squared error for each point. The key question here is how do you calculate the error (also known as the residual) for each point?
In a standard linear regression, the aim is to predict the Y value from the X value – so the sensible thing to do is to calculate the error in the Y values (shown as the gray lines in the following image). However, sometimes it is more sensible to take into account the error in both X and Y (as shown by the dotted red lines in the following image).
For example − When you know your measurements of X are uncertain, or when you do not want to focus on the errors of one variable over another.
Orthogonal Distance Regression (ODR) is a method that can do this (orthogonal in this context means perpendicular – so it calculates errors perpendicular to the line, rather than just ‘vertically’).
The following example demonstrates scipy.odr implementation for univariate regression.
import numpy as np
import matplotlib.pyplot as plt
from scipy.odr import *
import random

# Initiate some data, giving some randomness using random.random().
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([i**2 + random.random() for i in x])

# Define a function (quadratic in our case) to fit the data with.
def linear_func(p, x):
   m, c = p
   return m*x + c

# Create a model for fitting.
linear_model = Model(linear_func)

# Create a RealData object using our initiated data from above.
data = RealData(x, y)

# Set up ODR with the model and data.
odr = ODR(data, linear_model, beta0=[0., 1.])

# Run the regression.
out = odr.run()

# Use the in-built pprint method to give us results.
out.pprint()
The above program will generate the following output.
Beta: [ 5.51846098 -4.25744878]
Beta Std Error: [ 0.7786442 2.33126407]

Beta Covariance: [
   [ 1.93150969 -4.82877433]
   [ -4.82877433 17.31417201
]]

Residual Variance: 0.313892697582
Inverse Condition #: 0.146618499389
Reason(s) for Halting:
   Sum of squares convergence

 Print
 Add Notes
 Bookmark this page
How to use the IndexOf(,) method of array class in C#?

The IndexOf() method of array class in C# searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.
We have set the array.
int[] arr = new int[10];
arr[0] = 100;
arr[1] = 200;
arr[2] = 300;
arr[3] = 400;
arr[4] = 500;
arr[5] = 600;
arr[6] = 700;
arr[7] = 800;
arr[8] = 900;
arr[9] = 1000;
Now use the IndexOf() method and set the element for which you want the index, for example, I have set it for element 800.
int a = Array.IndexOf(arr, 800);
The following is the example showing the usage of IndexOf(,) method in C#.
 Live Demo
using System;
class Program {
   static void Main() {
      int[] arr = new int[10];
      arr[0] = 100;
      arr[1] = 200;
      arr[2] = 300;
      arr[3] = 400;
      arr[4] = 500;
      arr[5] = 600;
      arr[6] = 700;
      arr[7] = 800;
      arr[8] = 900;
      arr[9] = 1000;
      int a = Array.IndexOf(arr, 800);
      Console.WriteLine(a);
   }
}
7
What is the difference between append() and appendTo() in jQuery?

The append (content) method appends content to the inside of every matched element, whereas the appendTo (selector) method appends all of the matched elements to another, specified, set of elements.
jQuery append() function
The append (content) method appends content to the inside of every matched element.
Here is the description of all the parameters used by this method −
content − Content to insert after each target. This could be HTML or Text content
You can try to run the following code to learn how to work with append() function in jQuery:
Live Demo
<html>

   <head>
      <title>jQuery append() method</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).append('<div class = "div"></div>' );
            });
         });
      </script>
       
      <style>
         .div{
            margin:10px;
            padding:12px;
            border:2px solid #666;
            width:60px;
         }
      </style>
   </head>
   
   <body>
   
      <p>Click on any square below to see the result:</p>
       
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
</html>
jQuery appendTo() function
The appendTo (selector) method appends all of the matched elements to another, specified, set of elements. Here is the description of all the parameters used by this method −
selector − This is the target to which the content will be appended.
You can try to run the following code to learn how to work with appendTo() function in jQuery:
Live Demo
<html>
   <head>
      <title>jQuery appendTo()</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("div").click(function () {
               $(this).appendTo("#result");
            });
         });
      </script>
       
      <style>
         .div{
             margin:10px;
             padding:12px;
             border:2px solid #666;
             width:60px;
         }
      </style>
   </head>
   
   <body>
      <p>Click on any square below to see the result:</p>
      <p id = "result"> THIS IS TEST </p>
      <hr />
       
      <div class = "div" style = "background-color:blue;"></div>
      <div class = "div" style = "background-color:green;"></div>
      <div class = "div" style = "background-color:red;"></div>
       
   </body>
</html>
Demonstrate static variables, methods and blocks in Java

The static variable is a class level variable and it is common to all the class objects i.e. a single copy of the static variable is shared among all the class objects.
A static method manipulates the static variables in a class. It belongs to the class instead of the class objects and can be invoked without using a class object.
The static initialization blocks can only initialize the static instance variables. These blocks are only executed once when the class is loaded.
A program that demonstrates this is given as follows:
 Live Demo
public class Demo {
   static int x = 10;
   static int y;
   static void func(int z) {
      System.out.println("x = " + x);
      System.out.println("y = " + y);
      System.out.println("z = " + z);
   }
   static {
      System.out.println("Running static initialization block.");
      y = x + 5;
   }
   public static void main(String args[]) {
      func(8);
   }
}
Running static initialization block.
x = 10
y = 15
z = 8
Now let us understand the above program.
The class Demo contains static variables x and y. The static method func() prints the values of x, y and z. A code snippet which demonstrates this is as follows:
static int x = 10;
static int y;
static void func(int z) {
   System.out.println("x = " + x);
   System.out.println("y = " + y);
   System.out.println("z = " + z);
}
The static initialization block initializes the static variable y. In the main() method, the func() method is called. A code snippet which demonstrates this is as follows:
static {
   System.out.println("Running static initialization block.");
   y = x + 5;
}
public static void main(String args[]) {
   func(8);
}
How to convert String to Number in JavaScript?

You can try to run the following to learn how to convert String to Number in JavaScript −
Live Demo
<!DOCTYPE html>
<html>
   <body>
      <p>Convert String to Number</p>
      <script>
         var myString = "Amit";
         document.write("Number : " + Number(myString));
      </script>
   </body>
</html>
Caret Bootstrap class

Use carets to indicate dropdown functionality and direction. To get this functionality use the class caret with a <span> element.
You can try to run the following code to implement caret Bootstrap class
Live Demo
<!DOCTYPE html>
<html>
   <head>
      <title>Bootstrap Example</title>
      <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
      <script src = "/scripts/jquery.min.js"></script>
      <script src = "/bootstrap/js/bootstrap.min.js"></script>
   </head>
   <body>
      <p>Caret Example<span class = "caret"></span></p>
   </body>
</html>
In CSS using Images as List Markers

The CSS list-style-image property is used to set an image as a marker for the list item.
The syntax of CSS list-style-image property is as follows −
Selector {
   list-style-image: /*value*/
}
The following examples illustrate CSS list-style-image property −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul {
   width: 150px;
   list-style-image: url("https://www.tutorialspoint.com/images/Servlets.png");
   background: goldenrod;
}
li {
   text-align: center;
   background: lavenderblush;
   margin: 5px 30px;
}
</style>
</head>
<body>
<h2>Servlets</h2>
<ul>
<li>Client Request</li>
<li>Server Response</li>
<li>Cookies Handling</li>
<li>Session Tracking</li>
</ul>
</body>
</html>
This gives the following output −
 Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
ul {
   margin-left: 20px;
   list-style-image: url("https://www.tutorialspoint.com/images/hibernate.png");
}
li {
   font-size: 1.3em;
   text-align: center;
   background: burlywood;
   margin: 3px;
}
</style>
</head>
<body>
<h2>Hibernate Tutorial</h2>
<ul>
<li>Sessions</li>
<li>Persistent Class</li>
<li>Mapping Files</li>
<li>Mapping Types</li>
<li>Annotations</li>
</ul>
</body>
</html>
This gives the following output −
Infinity or exception in Java when divide by 0?

Consider the following code snippet where we divide a number by 0.
 Live Demo
public class Tester{
   public static void main(String[] args) {
      double d = 100;
      System.out.println(d/0);
   }
}
Infinity
Now consider the following code snippet.
 Live Demo
public class Tester{
   public static void main(String[] args) {
      int d = 100;
      System.out.println(d/0);
   }
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Tester.main(Tester.java:5)
As you've noted, the Infinity vs ArithmeticException, a different result for similar divide by zero program. The difference lies in floating point arithmetic used in first program and integer arithmetic used in second program.
Batch Script - How to Modifying an Array - GeeksforGeeks

04 Jan, 2022
In this article, we are going to learn how we can modify any array using Batch Script.
We can modify any array in two ways. We can add elements in any array or we can replace elements of any array.
Modify an array by adding an element.
Code :
@echo off 
set arr[0]=Geeks
set arr[1]=for
set arr[2]=Geeks
::adding an element at the end of array.
set arr[3]=GFG
echo The last element of the array is %arr[3]%
pause
Explanation:
We are creating an array with name ‘array’.
By using ‘set’ we are creating an array, by specifying the index of every element.
set arr[0]=Geeks
set arr[1]=for
set arr[2]=Geeks
Now we will add an element at the end of ‘array’ by using last index of array.
In above code our last index will be ‘3’. So we will use below expression.
set arr[3]=GFG
Above command will add ‘GFG’ at the end of array ‘arr’.
At last we are printing last element of array by using ‘%arr[3]%’ , which will print ‘GFG’ as output as it is last element of our array now.
Output:
Output of above code
Modify an array by replacing its Element :
Code :
@echo off 
set arr[0]=Geeks
set arr[1]=and
set arr[2]=Geeks
::replacing an element in any array.
set arr[1]=for
echo The new element at 1 index is %arr[1]%
pause
Explanation:
Now we are creating an array ‘arr’.
We want to replace ‘and’ by ‘for’ . So now we will use below expression to replace ‘and’ with ‘for’.
set arr[1]=for
We are using index of  ‘and’ in given array for replacing it by ‘for’.
Then we are printing element at index 1, just to check whether its replaced or not.
At last ‘pause’ is used to hold the screen, so that we can see our output.
Output :
Replacing element of any array
Batch-script
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
nohup Command in Linux with Examples
scp command in Linux with Examples
Thread functions in C/C++
mv command in Linux with examples
chown command in Linux with Examples
SED command in Linux | Set 2
Docker - COPY Instruction
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
nslookup command in Linux with Examples
Lambda expression in Python to rearrange positive and negative numbers

In this article, we will learn about using lambda expressions that will take an input array of positive and negative integers. We compute two separate arrays one containing negative numbers and other containing positive numbers.
Here we define a Rearrange() function that accepts only one argument i.e. array of integers. The function returns both arrays merged together with each type on different sides of the array.
Now let’s see the code to understand it better.
def Rearrange(arr):
# First lambda expression returns a list of negative numbers in arr.
# Second lambda expression returns a list of positive numbers in arr.
arr_neg=[x for x in arr if x < 0]
arr_pos=[x for x in arr if x >= 0]
return arr_neg+ arr_pos

# Driver function
if __name__ == "__main__":
   arr = [19,-56,3,-1,-45,-23,45,89,90]
   print (Rearrange(arr))
[-56, -1, -45, -23, 19, 3, 45, 89, 90]
In this article, we learned how to implement lambda expressions to rearrange positive and negative integers in the input array.
MySQL Tryit Editor v1.0

SELECT OrderID, Quantity,
CASE WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;
​
        
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, and Opera.
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.
JavaScript - Get href value

Let’s say we have the following anchor tag with URL −
<a class="demo" title="get the url" href="./mainPage.jsp/1245">href value at console</a>
We need to get only the URL value i.e. the href attribute value. For this, use attr() −
attr('href')
Following is the code −
 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>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
   <ul class="getURLDemo">
      <li>
         <a class="demo" title="get the url" href="./mainPage.jsp/1245">href value at console</a>
      </li>
   </ul>
</body>
<script>
   var hrefValue = $('ul.getURLDemo li a.demo').attr('href');
   console.log(hrefValue);
</script> 
</html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VSCode editor −
This will produce the following output on console −
The output in console −
Get the union of two sets in Java

To get the union of two sets, use the addAll() method.
The first set −
HashSet <String> set1 = new HashSet <String>();
set1.add("Mat");
set1.add("Sat");
set1.add("Cat");
The second set −
HashSet <String> set2 = new HashSet <String>();
set2.add("Mat");
set2.add("Cat");
set2.add("Fat");
set2.add("Hat");
Get the union −
set1.addAll(set2);
The following is an example −
 Live Demo
import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashSet <String> set1 = new HashSet <String>();
      HashSet <String> set2 = new HashSet <String>();
      set1.add("Mat");
      set1.add("Sat");
      set1.add("Cat");
      System.out.println("Set1 = "+ set1);
      set2.add("Mat");
      set2.add("Cat");
      set2.add("Fat");
      set2.add("Hat");
      System.out.println("Set2 = "+ set2);
      set1.addAll(set2);
      System.out.println("Union = "+ set1);
   }
}
Set1 = [Mat, Sat, Cat]
Set2 = [Mat, Cat, Fat, Hat]
Union = [Mat, Sat, Cat, Fat, Hat]
What is 'void' Operator in JavaScript?

The void is an important keyword in JavaScript, which can be used as a unary operator that appears before its single operand, which may be of any type. This operator specifies an expression to be evaluated without returning a value.
The syntax of void can be either of the following two −
<head>
   <script>
      <!--
         void func()
         javascript:void func()
         or:
         void(func())
         javascript:void(func())
      //-->
   </script>
</head>
The most common use of this operator is in a client-side javascript: URL, where it allows you to evaluate an expression for its side-effects without the browser displaying the value of the evaluated expression.
Here the expression alert ('Warning!!!') is evaluated but it is not loaded back into the current document.
<html>
   <head>
      <script>
         <!--
         //-->
      </script>
   </head>

   <body>
      <p>Clickthe following, This won't react at all...</p>
      <ahref = "javascript:void(alert('Warning!!!'))">Clickme!</a>
   </body>
</html>
DoubleFunction Interface in Java with Examples

08 Oct, 2018
The DoubleFunction Interface is a part of the java.util.function package which has been introduced since Java 8, to implement functional programming in Java. It represents a function which takes in a double-valued argument and produces a result of type R.
This functional interface takes in only one generic, namely:-
R: denotes the type of the output of this function
The lambda expression assigned to an object of DoubleFunction type is used to define its apply() which eventually applies the given operation on its only argument. It is similar to using an object of type Function<Double, R>.
The DoubleFunction interface has only one function:
This method accepts a double-valued argument and gives a result of type R.
Syntax:
R apply(double value)
Parameters: This method takes in one parameter value which is a double-valued argument.
Returns: This method returns a value of type R.
Below is the code to illustrate apply() method:
Program
import java.util.function.DoubleFunction;  public class Main {    public static void main(String args[])    {        DoubleFunction<Integer> ob = a -> (int)(a * 10);          // Using apply() method        System.out.println(ob.apply(3.2));    }}
32

Java - util package
Java 8
java-basics
java-interfaces
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Scala | reduce() Function

01 Jun, 2021
The reduce() method is a higher-order function that takes all the elements in a collection (Array, List, etc) and combines them using a binary operation to produce a single value. It is necessary to make sure that operations are commutative and associative. Anonymous functions are passed as parameter to the reduce function. Syntax:  
val l = List(2, 5, 3, 6, 4, 7)
// returns the largest number from the collection
l.reduce((x, y) => x max y)
The order in which numbers are selected for operation by the reduce method is random. This is the reason why non-commutative and non-associative operations are not preferred. Example :  
scala
// Scala program to// print maximum value// using reduce() // Creating objectobject GfG{     // Main methoddef main(args:Array[String]){    // source collection    val collection = List(1, 3, 2, 5, 4, 7, 6)     // finding the maximum valued element    val res = collection.reduce((x, y) => x max y)     println(res)}}
Output :  
7
In the above program, the reduce method selects random pairs and finds out the maximum value in a particular pair. These values are again compared with each other until a single maximum valued element is obtained. We generally make use of the reduce() method along with the map() method while working with Resilient Distributed Datasets in Spark. The map() method helps us to transform a collection to another collection while the reduce() method allows us to perform some action.Finding average using map() and reduce(): Example :  
scala
// Scala program to// print average// using map() and reduce() //Creating objectobject GfG{     // Main methoddef main(args:Array[String]){    // source collection    val collection = List(1, 5, 7, 8)     // converting every element to a pair of the form (x,1)    // 1 is initial frequency of all elements    val new_collection = collection.map(x => (x,1))     /*    List((1, 1), (5, 1), (7, 1), (8, 1))    */     // adding elements at corresponding positions    val res = new_collection.reduce( (a,b) => ( a._1 + b._1,                                            a._2 + b._2 ) )    /*    (21, 4)    */     println(res)    println("Average="+ res._1/res._2.toFloat)}}
Output:  
(21, 4)
Average= 5.25
In the above program, all elements of the collection are transformed into tuples with two elements. First element of the tuple is the number itself and the second element is the counter. Initially all counters are set to 1. The output itself is a tuple with two elements: first value is the sum and the second value is the number of elements. Note: Type of output given by reduce() method is same as the type of elements of the collection. 
simmytarika5
Scala
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the difference between printf, sprintf and fprintf?

13 Dec, 2018
printf:printf function is used to print character stream of data on stdout console.
Syntax :
 int printf(const char* str, ...); 
Example :
// simple print on stdout #include<stdio.h>int main(){   printf("hello geeksquiz");   return 0;}
Output :
 hello geeksquiz
sprintf:Syntax:
int sprintf(char *str, const char *string,...); 
String print function instead of printing on console store it on char buffer which are specified in sprintf
Example :
// Example program to demonstrate sprintf()#include<stdio.h>int main(){    char buffer[50];    int a = 10, b = 20, c;    c = a + b;    sprintf(buffer, "Sum of %d and %d is %d", a, b, c);      // The string "sum of 10 and 20 is 30" is stored     // into buffer instead of printing on stdout    printf("%s", buffer);      return 0;}
Output :
Sum of 10 and 20 is 30
fprintf:fprintf is used to print the string content in file but not on stdout console.
int fprintf(FILE *fptr, const char *str, ...);
Example :
#include<stdio.h>int main(){    int i, n=2;    char str[50];      //open file sample.txt in write mode    FILE *fptr = fopen("sample.txt", "w");    if (fptr == NULL)    {        printf("Could not open file");        return 0;    }      for (i=0; i<n; i++)    {        puts("Enter a name");        gets(str);        fprintf(fptr,"%d.%s\n", i, str);    }    fclose(fptr);      return 0;}
Input: GeeksforGeeks
       GeeksQuiz
Output :  sample.txt file now having output as 
0. GeeksforGeeks
1. GeeksQuiz
Thank you for reading, i will soon update with scanf, fscanf, sscanf keep tuned.
This article is contributed by Vankayala Karunakar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
mikerua
C-Input and Output Quiz
c-input-output
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Functions that cannot be overloaded in C++
Exception Handling in C++
Function Pointer in C
Command line arguments in C/C++
Different Methods to Reverse a String in C++
Structures in C
Switch Statement in C/C++
std::string class in C++
Functions in C/C++
MatSnackBar in Angular Material

23 Feb, 2021
Angular Material is a UI component library developed by Angular team to build design components for desktop and mobile web applications. In order to install it, we need to have angular installed in our project, once you have done it you can enter the below command and can download it. MatSnackBar is used to display information or text from bottom of the screen when performing any action.
Installation syntax:
ng add @angular/material
Approach:
First, install the angular material using the above-mentioned command.
After completing the installation, Import ‘MatSnackBarModule’ from ‘@angular/material/snack-bar’ in the app.module.ts file.
First we need to create an instance for ‘MatSnackBar’. Then we need to invoke a function on button click.
Using this instance we get access to open() function which is in-built.
Now we need to mention the duration of the message.
Once done with the above steps then serve or start the project.
Code Implementation:
app.module.ts
import { NgModule } from '@angular/core';  import { BrowserModule } from '@angular/platform-browser';  import { FormsModule } from '@angular/forms';          import { AppComponent } from './app.component';  import { BrowserAnimationsModule } from      '@angular/platform-browser/animations'; import {MatSnackBarModule} from '@angular/material/snack-bar';import { MatButtonModule } from '@angular/material/button';      @NgModule({      imports: [          BrowserModule,          FormsModule,          MatButtonModule,         MatSnackBarModule,         BrowserAnimationsModule     ],      declarations: [ AppComponent ],      bootstrap: [ AppComponent ]  })  export class AppModule { }
app.component.ts
import { Component } from '@angular/core';import {MatSnackBar} from '@angular/material/snack-bar';    @Component({  selector: 'my-app',  templateUrl: './app.component.html',  styleUrls: [ './app.component.css' ]})export class AppComponent  {    constructor(private _snackBar: MatSnackBar) {}    openSnackBar(message: string, action: string) {    this._snackBar.open(message, action, {      duration: 2000,    });  }}
app.component.html:
HTML
<button mat-stroked-button (click)=    "openSnackBar('GAME ONE','HURRAH !!!!!')">    Show snack-bar Message</button>  <p>    By Clicking on above button we can invoke     the function and it will, render the     message of snack-bar</p>
Output:
 
Angular-material
Picked
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Python | Rearrange Positive and Negative Elements

05 Sep, 2019
Sometimes, while working with Python lists, we can have a problem in which we need to perform a sort in list. There are many variations of sorting that might be required to perform. Once such variation can be to sort elements of list, but keeping in mind, positive elements appear before negative elements. Let’s discuss a way in which this task can be performed.
Method : Using sorted() + lambdaThis task can be performed using combination of above functions. In this, the logic we apply is computing inverse and negative of each number and then perform the sort using sorted(). The inversion makes sure that larger magnitude elements occur at middle and smaller at ends ( hill arrangement ) and negative takes care of making positives occur before negatives.
# Python3 code to demonstrate working of# Sort while keeping Positive elements before negatives# using sorted() + lambda  # initialize listtest_list = [4, -8, -6, 3, -5, 8, 10, 5, -19]  # printing original listprint("The original list is : " + str(test_list))  # Sort while keeping Positive elements before negatives# using sorted() + lambdares = sorted(test_list, key = lambda i: 0 if i == 0 else -1 / i)  # printing resultprint("Result after performing sort operation : " + str(res))
The original list is : [4, -8, -6, 3, -5, 8, 10, 5, -19]
Result after performing sort operation : [3, 4, 5, 8, 10, -19, -8, -6, -5]

Python list-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Replace an element at a specified index of the Vector in Java

An element in a Vector can be replaced at a specified index using the java.util.Vector.set() method. This method has two parameters i.e the index at which the Vector element is to be replaced and the element that it should be replaced with. Vector.set() method returns the element that was at the position specified at the index previously.
A program that demonstrates this is given as follows:
 Live Demo
import java.util.Vector;
public class Demo {
   public static void main(String args[]) {
      Vector vec = new Vector(5);
      vec.add(7);
      vec.add(3);
      vec.add(9);
      vec.add(1);
      vec.add(5);
      System.out.println("The Vector elements are: " + vec);
      vec.set(1, 6);
      System.out.println("The Vector elements are: " + vec);
   }
}
The output of the above program is as follows:
The Vector elements are: [7, 3, 9, 1, 5]
The Vector elements are: [7, 6, 9, 1, 5]
Now let us understand the above program.
The Vector is created. Then Vector.add() is used to add the elements to the Vector. Then Vector.set() is used to replace the element 3 with element 6 at index 1. Then the Vector is displayed. A code snippet which demonstrates this is as follows:
Vector vec = new Vector(5);
vec.add(7);
vec.add(3);
vec.add(9);
vec.add(1);
vec.add(5);
System.out.println("The Vector elements are: " + vec);
vec.set(1, 6);
System.out.println("The Vector elements are: " + vec);
Returning an Array from a Method in Java

A method may also return an array. For example, the following method returns an array that is the reversal of another array -
public static int[] reverse(int[] list) {
   int[] result = new int[list.length];
   for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
      result[j] = list[i];
   }
   return result;
}
Firebase - Filtering Data

Firebase offers several ways to filter data.
Let us understand what limit to first and last is.
limitToFirst method returns the specified number of items beginning from the first one.
limitToFirst method returns the specified number of items beginning from the first one.
limitToLast method returns a specified number of items beginning from the last one.
limitToLast method returns a specified number of items beginning from the last one.
Our example is showing how this works. Since we only have two players in database, we will limit queries to one player.
Let us consider the following example.
var firstPlayerRef = firebase.database().ref("players/").limitToFirst(1);

var lastPlayerRef = firebase.database().ref('players/').limitToLast(1);

firstPlayerRef.on("value", function(data) {
   console.log(data.val());
}, function (error) {
   console.log("Error: " + error.code);
});

lastPlayerRef.on("value", function(data) {
   console.log(data.val());
}, function (error) {
   console.log("Error: " + error.code);
});
Our console will log the first player from the first query, and the last player from the second query.
We can also use other Firebase filtering methods. The startAt(), endAt() and the equalTo() can be combined with ordering methods. In our example, we will combine it with the orderByChild() method.
Let us consider the following example.
var playersRef = firebase.database().ref("players/");

playersRef.orderByChild("name").startAt("Amanda").on("child_added", function(data) {
   console.log("Start at filter: " + data.val().name);
});

playersRef.orderByChild("name").endAt("Amanda").on("child_added", function(data) {
   console.log("End at filter: " + data.val().name);
});

playersRef.orderByChild("name").equalTo("John").on("child_added", function(data) {
   console.log("Equal to filter: " + data.val().name);
});

playersRef.orderByChild("age").startAt(20).on("child_added", function(data) {
   console.log("Age filter: " + data.val().name);
});
The first query will order elements by name and filter from the player with the name Amanda. The console will log both players. The second query will log "Amanda" since we are ending query with this name. The third one will log "John" since we are searching for a player with that name.
The fourth example is showing how we can combine filters with "age" value. Instead of string, we are passing the number inside the startAt() method since age is represented by a number value.

    60 Lectures 
     5 hours 

 University Code

    28 Lectures 
     2.5 hours 

 Appeteria

    85 Lectures 
     14.5 hours 

 Appeteria

    46 Lectures 
     2.5 hours 

 Gautham Vijayan

    13 Lectures 
     1.5 hours 

 Nishant Kumar

    85 Lectures 
     16.5 hours 

 Rahul Agarwal
 Print
 Add Notes
 Bookmark this page
Python Program Exit handlers (atexit)

The atexit module in the standard distribution of Python has two functions – register() and unregister(). Both functions take some existing function as an argument. Registered functions are executed automatically when the interpreter session is terminated normally.
If more than one functions are registered, their execution is in the reverse order of registration. It means, functions f1(), f2() and f3() are registered one after other, their order of execution will be f3(), f2() and f1().
The unregister() function removes the specified function from list of functions to be automatically invoked.
Following code shows how a function is registered for automatic execution upon termination of code. (Note: This code has to be executed from a command line and not through IDLE). The program asks a user to input numbers successively and adds them. When the loop is over, the registered function savetotal() is called automatically to save the addition to a file.
import atexit
sum = 0
def savetotal():
fo = open("atexit.txt","w")
fo.write(str(sum))
print ("sum written to file")
fo.close()
atexit.register(savetotal)
while True:
n = int(input("enter a number. -1 to exit"))
if n == -1:
break
sum = sum + n
print (sum)
Save above code as atexit-example.py and run from command line. Successive numbers input are added and the total is written to atexit.txt at the end.
C:\python36>python atexit-example.py
enter a number. -1 to exit4
enter a number. -1 to exit6
enter a number. -1 to exit3
enter a number. -1 to exit5
enter a number. -1 to exit2
enter a number. -1 to exit-1
20
sum written to file
The atexit.txt file will be created in current directory and it will store the total (20 in this case).
It is also possible to register a function with different arguments. In that case, function with each argument will be registered independently and will be executed in reverse order of registration.
import atexit
names = ['Ashok', 'Radha', 'Abdul', 'John']
def hello(name):
print ("Hello",name)
for name in names:
atexit.register(hello,name)
Output
C:\python36>python atexit-example2.py
Hello John
Hello Abdul
Hello Radha
Hello Ashok
atexit.unregister(hello) will remove all copies of hello() with various parameters from the list of functions.
A convenient alternative to register a function is to use register() function as a decorator.
import atexit
@atexit.register
def hello():
print('Hello World!')
print('Say Hello')
C:\python36>python atexit-example3.py
Say Hello
Hello World!
The registered functions will not be invoked automatically if program terminates abruptly or os.exit() function is called.
The atexit module is useful in automatically performing clean operations like closing databases and files, freeing up resources etc.
MySQL - Multiplication Operator (*)

This operator is used to multiply two numbers in MySQL.
Following is an example of the "*" operator −
mysql> SELECT 4156456*56445;
+---------------+
| 4156456*56445 |
+---------------+
| 234611158920  |
+---------------+
1 row in set (0.00 sec)
Let us see another example −
mysql> SELECT 547.5478*657.3547*5475;
+------------------------+
| 547.5478*657.3547*5475 |
+------------------------+
| 1970633830.93051350    |
+------------------------+
1 row in set (0.00 sec)
You can also have negative values as operands for this operator −
mysql> SELECT 4445*-533;
+-----------+
| 4445*-533 |
+-----------+
| -2369185  |
+-----------+
1 row in set (0.00 sec)
Assume we have created a table in MySQL using the following quires −
CREATE TABLE student (Name VARCHAR(100), Math INT, English INT, Science INT, History INT);
INSERT INTO student values('Raman', 95, 89, 85, 81);
INSERT INTO student values('Rahul' , 90, 87, 86, 81);
INSERT INTO student values('Mohit', 90, 85, 86, 81);
Following query calculates displays the percentage of each student −
mysql> SELECT name, (Math + English + Science + History)/400*100 as Percentage FROM student;
+-------+------------+
| name  | Percentage |
+-------+------------+
| Raman | 87.5000    |
| Rahul | 86.0000    |
| Mohit | 85.5000    |
+-------+------------+
3 rows in set (0.00 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
VBA - Join Function

A Function, which returns a string that contains a specified number of substrings in an array. This is an exact opposite function of Split Method.
Join(List[,delimiter]) 

List − A required parameter. An array that contains the substrings that are to be joined.
List − A required parameter. An array that contains the substrings that are to be joined.
Delimiter − An optional parameter. The character, which used as a delimiter while returning the string. The default delimiter is Space.
Delimiter − An optional parameter. The character, which used as a delimiter while returning the string. The default delimiter is Space.
Add a button and add the following function.
Private Sub Constant_demo_Click()
   ' Join using spaces
   a = array("Red","Blue","Yellow")
   b = join(a)
   msgbox("The value of b " & " is :"  & b)
  
   ' Join using $
   b = join(a,"$")
   msgbox("The Join result after using delimiter is : " & b)
End Sub
When you execute the above function, it produces the following output.
The value of b is :Red Blue Yellow
The Join result after using delimiter is : Red$Blue$Yellow


    101 Lectures 
     6 hours 

 Pavan Lalwani

    41 Lectures 
     3 hours 

 Arnold Higuit

    80 Lectures 
     5.5 hours 

 Prashant Panchal

    25 Lectures 
     2 hours 

 Prashant Panchal

    26 Lectures 
     2 hours 

 Arnold Higuit

    92 Lectures 
     10.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Java break Keyword

❮ Java Keywords

End the loop when i is equal to 4:
for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  System.out.println(i);
}


Try it Yourself »

The break keyword is used to break out a
for loop, a while 
loop or a switch block.
Break out of a while loop:
int i = 0;while (i < 10) {
  System.out.println(i);
  i++;
  if (i == 4) {
    break;
  }
}


Try it Yourself »

Use the continue 
keyword to end the current iteration in a loop, but continue with the next.
Read more about for loops in our Java For Loops Tutorial.
Read more about while loops in our Java While Loops Tutorial.
Read more about break and continue in our Java Break Tutorial.

❮ Java Keywords

We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
How to create histogram with relative frequency in R?

The relative frequency histogram can be created for the column of an R data frame or a vector that contains discrete data. For this purpose, we can use PlotRelativeFrequency function of HistogramTools package along with hist function to generate histogram. For example, if we have a vector x for which we want to create a histogram with relative frequencies then it can be done as PlotRelativeFrequency(hist(x)).
Consider the below vector −
 Live Demo
x<-sample(1:5,20,replace=TRUE)
x
[1] 2 1 1 4 3 5 5 4 1 3 5 1 4 1 3 4 4 1 1 1
Loading HistogramTools package and creating histogram of x with relative frequency −
library("HistogramTools")
PlotRelativeFrequency(hist(x))
 Live Demo
y<-sample(1:10,100,replace=TRUE)
y
[1] 7 6 8 9 5 1 2 9 6 7 2 1 3 3 6 7 7 4 9 5 10 5 10 6 6
[26] 4 10 9 5 1 9 7 9 9 2 7 8 8 10 10 8 5 9 8 3 6 9 8 9 10
[51] 6 6 6 4 8 8 6 10 2 7 6 5 1 8 7 9 2 6 2 9 2 5 8 3 2
[76] 3 2 4 5 9 5 5 9 4 2 6 3 10 3 2 7 9 4 8 10 6 5 8 8 2
PlotRelativeFrequency(hist(y))
How to change the local user account password using PowerShell?

To change the local user account password using PowerShell, we can use the Set-LocalUser command with the Password parameter. This password parameter should be in the secure string. So we need to ask the user to input the password as a secure string or need to explicitly convert the plain text password to the secure string. For example,
$localuser = Read-Host "Enter Local UserName"
$password = Read-Host "Enter local user account password "
-AsSecureString
Set-LocalUser -Name $localuser -Password $password -Verbose
If you need to set the password without asking the user prompt then you need to convert the plain text password to the secure string forcefully as shown below.
$password = "Admin123" | ConvertTo-SecureString
-AsPlainText -Force
Set-LocalUser -Name TestUser -Password $password -Verbose
To set the local user password on the remote computer, use Invoke-Command.
Invoke-Command -ComputerName Computer1, Computer2 -ScriptBlock{
   $password = "Admin123" | ConvertTo-SecureString -AsPlainText -Force
   Set-LocalUser -Name 'TestUser' -Password $password -Verbose
}
The above command will set the local user account password on the remote servers computer1 and Computer2.
Program to find sum of digits until it is one digit number in Python

Suppose we have a positive number n, we will add all of its digits to get a new number. Now
repeat this operation until it is less than 10.
So, if the input is like 9625, then the output will be 4.
To solve this, we will follow these steps −
Define a method solve(), this will take n
if n < 10, thenreturn n
return n
s := 0
l := the floor of (log(n) base 10 + 1)
while l > 0, dos := s + (n mod 10)n := quotient of n / 10l := l - 1
s := s + (n mod 10)
n := quotient of n / 10
l := l - 1
return solve(s)
Let us see the following implementation to get better understanding −
 Live Demo
import math
class Solution:
   def solve(self, n):
      if n < 10:
         return n
      s = 0
      l = math.floor(math.log(n, 10) + 1)
      while l > 0:
         s += n % 10
         n //= 10
         l -= 1
      return self.solve(s)
ob = Solution()
print(ob.solve(9625))
9625
4
Draw an ellipse on an image using OpenCV

In this program, we will draw an ellipse on an image in using the OpenCV library. We will use the OpenCV function ellipse() for the same.
Step 1: Import cv2.
Step 2: Read the image using imread().
Step 3: Set the center coordinates.
Step 4: Set the axes length.
Step 5: Set the angle.
Step 6: Set start and end angle.
Step 6: Set the color.
Step 7: Set the thickness.
Step 8: Draw the ellipse by passing the above parameters in the cv2.ellipse function along with the original image.
Step 9: Display the final output.
import cv2
image = cv2.imread('testimage.jpg')
center_coordinates = (120, 100)

axesLength = (100, 50)
angle = 0
startAngle = 0
endAngle = 360
color = (0, 0, 255)
thickness = 5
image = cv2.ellipse(image, center_coordinates, axesLength, angle, startAngle, endAngle, color, thickness)

cv2.imshow('Ellipse', image)
Online Code Practice - Tutorials Point

Support Class File
Util Class File
Extra Class File
C library function - signal()

The C library function void (*signal(int sig, void (*func)(int)))(int) sets a function to handle signal i.e. a signal handler with signal number sig.
Following is the declaration for signal() function.
void (*signal(int sig, void (*func)(int)))(int)
sig − This is the signal number to which a handling function is set. The following are few important standard signal numbers −
sig − This is the signal number to which a handling function is set. The following are few important standard signal numbers −
SIGABRT
(Signal Abort) Abnormal termination, such as is initiated by the function.
SIGFPE
(Signal Floating-Point Exception) Erroneous arithmetic operation, such as zero divide or an operation resulting in overflow (not necessarily with a floating-point operation).
SIGILL
(Signal Illegal Instruction) Invalid function image, such as an illegal instruction. This is generally due to a corruption in the code or to an attempt to execute data.
SIGINT
(Signal Interrupt) Interactive attention signal. Generally generated by the application user.
SIGSEGV
(Signal Segmentation Violation) Invalid access to storage − When a program tries to read or write outside the memory it is allocated for it.
SIGTERM
(Signal Terminate) Termination request sent to program.
func − This is a pointer to a function. This can be a function defined by the programmer or one of the following predefined functions −
func − This is a pointer to a function. This can be a function defined by the programmer or one of the following predefined functions −
SIG_DFL
Default handling − The signal is handled by the default action for that particular signal.
SIG_IGN
Ignore Signal − The signal is ignored.
This function returns the previous value of the signal handler, or SIG_ERR on error.
The following example shows the usage of signal() function.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

void sighandler(int);

int main () {
   signal(SIGINT, sighandler);

   while(1) {
      printf("Going to sleep for a second...\n");
      sleep(1); 
   }
   return(0);
}

void sighandler(int signum) {
   printf("Caught signal %d, coming out...\n", signum);
   exit(1);
}
Let us compile and run the above program that will produce the following result and program will go in infinite loop. To come out of the program we used CTRL + C keys.
Going to sleep for a second...
Going to sleep for a second...
Going to sleep for a second...
Going to sleep for a second...
Going to sleep for a second...
Caught signal 2, coming out...


    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