code-rag-bench/online-tutorials huggingface dataset:
How to print console without trailing newline in Node.js ? - GeeksforGeeks

26 Feb, 2020
In Node.js, console.log() method is used to display the message on the console. By default, the console.log() method prints on console with trailing newline.
Example 1:
// Node.js program to demonstrate the   // console.log() Method  console.log("Welcome to GeeksforGeeks! ");console.log("A computer science portal for geeks");
Output:
Welcome to GeeksforGeeks!
A computer science portal for geeks
In the above example, Welcome to GeeksforGeeks! printed on first line and A computer science portal for geeks printed on second line.But sometimes we may need to print the console without trailing newline. In that case, we can use process.stdout.write() method to print to console without trailing newline.
Example 2:
// Node.js program to demonstrate the   // process.stdout.write() Method  process.stdout.write("Welcome to GeeksforGeeks! ");process.stdout.write("A computer science portal for geeks");
Output:
Welcome to GeeksforGeeks! A computer science portal for geeks
Note: The process object is global so it can be used without using require() method.
Node.js-Misc
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Node.js fs.readFile() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to read and write Excel file in Node.js ?
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
Changing the color of a single X-axis tick label in Matplotlib

To change the color of a single X-axis tick label in matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement.
Create x and y data points using numpy.
Plot x and y data points using plot() method.
To set the color of X-axis tick label in matplotlib, we can use tick_params() method with axis='x' and color='red'.
To display the figure, use show() method.
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

fig = plt.figure()
ax = fig.add_subplot(111)

x = np.linspace(-10, 10, 100)
y = np.sin(x)

plt.plot(x, y)

ax.tick_params(axis='x', colors='red')

plt.show()
How to Create Blinking Text using CSS ? - GeeksforGeeks

18 Jun, 2020
Blinking text effect also be known as the flashing text effect can be easily created using HTML and CSS @keyframes rule and the opacity property.
HTML Code: In this section, we will create a basic div element which will have some text inside it.
<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content=    "width=device-width, initial-scale=1.0">  <title>Blinking Text</title></head><body>  <div>    <h2>Blink</h2>  </div></body></html>
CSS Code: In this section, the designing of the text with the desired effect by using CSS @keyframes rule is implemented. The opacity property is set as shown below.
<style>  body{  margin: 0;  padding: 0;}  div{  position: absolute;  top: 50%;  left: 50%;  transform: translate(-50%, -50%);}    h2{   font-size: 5em;   font-family: serif;   color:#008000;   text-align: center;   animation: animate 1.5s linear infinite; }    @keyframes animate{   0%{     opacity: 0;   }   50%{     opacity: 0.7;   }   100%{     opacity: 0;   } }</style>
Final Code: It is the combination of the above two code sections.
<!DOCTYPE html><html lang="en">  <head>    <meta charset="UTF-8">    <meta name="viewport" content=        "width=device-width, initial-scale=1.0">      <title>Blinking Text</title>      <style>        body {            margin: 0;            padding: 0;        }          div {            position: absolute;            top: 50%;            left: 50%;            transform: translate(-50%, -50%);        }          h2 {            font-size: 5em;            font-family: serif;            color: #008000;            text-align: center;            animation: animate                 1.5s linear infinite;        }          @keyframes animate {            0% {                opacity: 0;            }              50% {                opacity: 0.7;            }              100% {                opacity: 0;            }        }    </style></head>  <body>    <div>        <h2>Blink</h2>    </div></body>  </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
How to set space between the flexbox ?
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
unordered_map begin() in C++ - GeeksforGeeks

03 Dec, 2021
The unordered_map::begin() is a built-in function in C++ STL which returns an iterator pointing to the first element in the unordered_map container or in any of its bucket. 
Syntax for first element in unordered_map container: 
unordered_map.begin()
Parameters: This function does not accepts any parameters. Return Value: The function returns an iterator pointing to the first element in the unordered_map container. Note: In an unordered map, there is no specific element which is considered as the first element. Below program illustrate the above function. 
CPP
// CPP program to demonstrate the// unordered_map::begin() function// when first element of the container// is to be returned as iterator#include <bits/stdc++.h>using namespace std; int main(){     // Declaration    unordered_map<std::string, std::string> mymap;     // Initialisation    mymap = { { "Australia", "Canberra" },              { "U.S.", "Washington" },              { "France", "Paris" } };     // Iterator pointing to the first element    // in the unordered map    auto it = mymap.begin();     // Prints the elements of the first element in map    cout << it->first << " " << it->second;     return 0;}
France Paris
 
Syntax for first element in unordered_map bucket: 
unordered_map.begin( n )
Parameters: The function accepts one mandatory parameter n which specifies the bucket number whose first element’s iterator is to be returned. Return Value: The function returns an iterator pointing to the first element in the n-th bucket. Below program illustrate the above function. 
CPP
// CPP program to demonstrate the// unordered_map::begin() function// when first element of n-th container// is to be returned as iterator#include <bits/stdc++.h>using namespace std; int main(){     // Declaration    unordered_map<std::string, std::string> mymap;     // Initialisation    mymap = { { "Australia", "Canberra" },            { "U.S.", "Washington" }, { "France", "Paris" } };     // Iterator pointing to the first element    // in the n-th bucket    auto it = mymap.begin(0);     // Prints the elements of the n-th bucket    cout << it->first << " " << it->second;     return 0;}
U.S. Washington
 
gabaa406
sweetyty
CPP-Functions
cpp-unordered_map
cpp-unordered_map-functions
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
Inline Functions in C++
Pair in C++ Standard Template Library (STL)
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Pure Virtual Functions and Abstract Classes in C++
How to use Popper Component in ReactJS ? - GeeksforGeeks

22 Feb, 2021
A Popper is used to show the part of the content on top of another. It’s an alternative feature for react-popper. Material UI for React has this component available for us, and it is simple and very easy to integrate. For perfect positioning, it uses 3rd party library which is Popper.js. We can use the Popper Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
Project Structure: 
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. 
App.js
import React from 'react';import Popper from '@material-ui/core/Popper';  export default function App() {    const [anchorEl, setAnchorEl] = React.useState(null);  const open = Boolean(anchorEl);    return (    <div style={{ display: 'block', padding: 30 }}>      <h4>How to use Popper Component in ReactJS?</h4>      <button type="button" onClick={(event) => {        setAnchorEl(anchorEl ? null : event.currentTarget);      }}>        Click Me to Toggle Popper      </button>      <Popper        id={open ? 'simple-popper' : undefined}        open={open}        anchorEl={anchorEl}>        <div style={{          padding: 2,          border: '1px solid',          backgroundColor: 'gray',        }}>Greetings from GeeksforGeeks</div>      </Popper>    </div>  );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/popper/
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set background images in ReactJS ?
How to create a table in ReactJS ?
ReactJS useNavigate() Hook
How to navigate on path by button click in react router ?
React-Router Hooks
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to use replace () in Android textview?

This example demonstrate about How to use replace () in Android textview.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:gravity="center"
   tools:context=".MainActivity">
   <EditText
      android:id="@+id/name"
      android:layout_width="match_parent"
      android:hint="Enter name"
      android:layout_height="wrap_content" />
   <Button
      android:id="@+id/click"
      android:text="Click"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
   <TextView
      android:id="@+id/textview"
      android:layout_width="wrap_content"
      android:textSize="25sp"
      android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken name as Edit text, when user click on button it will take data and replace all a values with
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
   EditText name;
   Button button;
   TextView text;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      name = findViewById(R.id.name);
      button = findViewById(R.id.click);
      text = findViewById(R.id.textview);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            if (!name.getText().toString().isEmpty()) {
               if (name.getText().toString().length() >= 0) {
                  String replace = name.getText().toString().replace("a","-");
                  text.setText(String.valueOf(replace));
               }
            } else {
               name.setError("Plz enter name");
            }
         }
      });
   }
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, enter the string as “Krishna sai sai” . It replaced all a values with −
Click here to download the project code
How we can bundle multiple python modules?

Assuming you are using Python 2.6 or later, you could package the scripts into a zip file, add a __main__.py and run the zip file directly. For example, if you zip all files in a file called my_app.zip and place your main script in __main__.py, you can run this zip using python:
$ python my_app.zip
If you want to use a third party script, you can have a look at stickytape module. It can be used to convert a Python script and any Python modules it depends into a single-file Python script. To install stickytape, open your terminal and enter:
$ pip install stickytape
Assuming all your scripts and dependencies reside in the script/sample folder, you can use stickytape in the following way:
$ stickytape scripts/sample --add-python-path . > ./sample-standalone
You can also use the --output-file parameter to give it a file argument:
$ stickytape scripts/sample --add-python-path . --output-file ./sample-standalone
Styling html pages in Node.js

In html files we can simply add style in head section −
<html>
   <head>
      <style>
         //add css code
      </style>
   </head>
<body>
</body>
</html>
We can add inline css styles as well in html directly.
Generally css is separated from the html code. Third option add css is to include a css file .
How to serve static files in Node.js?
Generally css files are added with below tag −
<head>
   <link rel=”stylesheet” href=”path-to-css-file”>
</head>
Express js provides a middleware to seve static file. This middleware gives read access to given folder.
app.use(express.static(path.join(__dirname, ‘public’)));
path: its our core module in node.js
__dirname: Actual path to root folder of project
Public: Folder name which has read access fom node server
Css files will be stored in public folder.
Example usage of css file −
App.js
const http = require('http');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false})); app.use(express.static(path.join(__dirname, 'public')));
app.use('/test',route);
app.use((req, res,next)=>{
   res.status(404).send('<h1> Page not found </h1>');
});
const server = http.createServer(app);
server.listen(3000);
create a public folder in main project folder and store a main.css file under css folder in it.
Main.css
input {
   width:200px;
   height:20px;
}
route.js
const path = require('path');
const express = require('express');
const router = express.Router();
router.get('/add-username', (req, res,next)=>{
   // res.send('<form action="/test/post-username" method="POST"> <input type="text" name="username">    <button type="submit"> Send </button> </form>');
   res.sendFile(path.join(__dirname, 'views', 'add-user.html'));
});
router.post('/post-username', (req, res, next)=>{
   console.log('data: ', req.body.username);
   res.send('<h1>'+req.body.username+'</h1>');
});
module.exports = router;
add-user.html
<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
      <link rel="stylesheet" href="/css/main.css">
   </head>
<body>
   <form action="/test/post-username" method="POST"> <input type="text" name="username"> <button          type="submit"> Send </button> </form>
</body>
</html>
Run : npm start
Browse: localhost:3000/test/add-username and we will updated css for input field from css file.
How to stop par(mfrow) to create multiple plots in one plot window and create only one plot in R?

When we use par(mfrow), we define the number of plots we want to draw on the plot window and when we draw all the necessary plots then starts again with the first plot. For example, if we set par(mfrow) to (2,2) then we will have four plots on the plot window but if we want to create one plot on the plot window then it does not work, it will show a small plot on the upper left side. To deal with the problem, we can set par(mfrow) to (1,1).
par(mfrow=c(2,2))
x<-rnorm(100)
y<-rnorm(100,0.5)
z<-rnorm(100,1)
a<-rnorm(100,1.5)
hist(x)
hist(y)
hist(z)
hist(a)
Creating fifth plot which we want to fit the whole plot window −
b<-rpois(10000,2)
hist(b)
Changing par(mfrow) to make the fifth plot on the whole plot window −
par(mfrow=c(1,1))
hist(b)
STARTOFMONTH function

Returns the first date of the month in the current context for the specified column of dates.
STARTOFMONTH (<dates>) 

dates
A column that contains dates.
A table containing a single column and single row with a date value.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
= STARTOFMONTH (Sales[Date]) 

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
DAX Text - EXACT function

Compares two text strings and returns TRUE if they are exactly the same, FALSE otherwise.
EXACT is case sensitive, but ignores formatting differences.
EXACT (<text1>, <text2>) 

text1
The first text string or column that contains text.
text2
The second text string or column that contains text.
TRUE or FALSE.
You can use EXACT function to test the text being entered into a document.
= EXACT(Results[Sport], [Sport])  
returns TRUE, if the value in Sport column in Results table match with the value in Sport column.

    53 Lectures 
     5.5 hours 

 Abhay Gadiya

    24 Lectures 
     2 hours 

 Randy Minder

    26 Lectures 
     4.5 hours 

 Randy Minder
 Print
 Add Notes
 Bookmark this page
BitSet toString() Method in Java with Examples - GeeksforGeeks

27 Dec, 2018
The java.util.BitSet.toString() is an inbuilt method of BitSet class that is used to get a string representation of the bits of the sets in the form of a set of entries separated by “, “. So basically the toString() method is used to convert all the elements of BitSet into String. In addition to this for every index of the bits in the set state, the decimal representation of that index is also included in the result.
Syntax:
Bit_Set.toString()
Parameter: The method does not take any parameters.
Return value: The method returns the set consisting of the string representation of the elements of the given BitSet.
Below programs illustrate the working of java.util.BitSet.toString() method:Program 1:
// Java code to illustrate toString()import java.util.*;  public class BitSet_Demo {    public static void main(String args[])    {        // Creating an empty BitSet        BitSet init_bitset = new BitSet();          // Use set() method to add elements into the Set        init_bitset.set(40);        init_bitset.set(25);        init_bitset.set(31);        init_bitset.set(100);        init_bitset.set(53);          // Displaying the BitSet        System.out.println("BitSet: " + init_bitset);          // Displaying the toString() working        System.out.println("The String representation: "                           + init_bitset.toString());    }}
BitSet: {25, 31, 40, 53, 100}
The String representation: {25, 31, 40, 53, 100}

Program 2:
// Java code to illustrate toString()import java.util.*;  public class BitSet_Demo {    public static void main(String args[])    {        // Creating an empty BitSet        BitSet init_bitset = new BitSet();          // Use set() method to add elements into the Set        init_bitset.set(10);        init_bitset.set(20);        init_bitset.set(30);        init_bitset.set(40);        init_bitset.set(50);          // Displaying the BitSet        System.out.println("BitSet: " + init_bitset);          // Displaying the toString() working        System.out.println("The String representation: "                           + init_bitset.toString());    }}
BitSet: {10, 20, 30, 40, 50}
The String representation: {10, 20, 30, 40, 50}

Java - util package
Java-BitSet
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Multidimensional Arrays in Java
Stack Class in Java
Stream In Java
Singleton Class in Java
Overriding in Java
Determine which Button was pressed in Tkinter

Buttons are very useful in many applications where user interaction is required. Let us suppose that we want to know which button is pressed in a given application. In order to get the information about the Button, we can use the callback function in the Button configuration. In the Callback function, we will use the print(test) function to print the button that is clicked.
#Import the required libraries
from tkinter import *
from tkinter import ttk

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry
win.geometry("700x250")

# Define function to get the information about the Button
def get_button(t):
   print(t)

#Create Button Object
b1= ttk.Button(win, text= "Button-1", command= lambda t= "Button-1 Clicked": get_button(t))
b1.place(relx= .46, rely= .5, anchor= CENTER)
b2= ttk.Button(win, text= "Button-2", command= lambda t= "Button-2 Clicked": get_button(t))
b2.place(relx= .58, rely= .5, anchor= CENTER)

win.mainloop()
Running the above code will display a window with two buttons.
If you click "Button-1", it will print the following on the console.
Button-1 Clicked
How to Create a Virus to Open Multiple CMD Windows Automatically ? - GeeksforGeeks

21 Apr, 2021
The virus that we are going to create in this article will automatically open up multiple CMD windows in the victim’s Windows PC.
This is an annoying type of Virus because as per the heading this is capable of opening multiple CMD window screen in front of the user without allowing the user to open any other file that he/she wants to work after the activation of this virus file, and also freeze the PC.
Now to create the virus follow the below steps:
Step 1: Press the Window + R Button from the Keyboard. This will open the Run Dialog book will Open in front of us. 
Step 2: Type Notepad in the Dialog Box and press Enter. This will open the notepad for us.
 
Step 3: Type in the below-mentioned code in the Notepad:
:A
START
goto A
Step 4: After typing in all the code save the file with the name of your choice. But remember to save the file with .bat extension.
The Virus has been Successfully Created by you but this will only work when it is opened by the user once.
To Resolve this problem the user must restart the PC. 
Disclaimer: GeeksforGeeks does not support the spread of ransomware/viruses and if you intend to use this information for malicious purposes, we are in no way responsible. This information is intended to be used for educational purposes only.
How To
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install FFmpeg on Windows?
How to Add External JAR File to an IntelliJ IDEA Project?
How to Set Git Username and Password in GitBash?
How to create a nested RecyclerView in Android
How to Create and Setup Spring Boot Project in Eclipse IDE?
Docker - COPY Instruction
Top Programming Languages for Android App Development
How to Run a Python Script using Docker?
Setting up the environment in Java
How to Add External JAR File to an IntelliJ IDEA Project?
Python | N consecutive Odd or Even Numbers - GeeksforGeeks

29 Apr, 2019
The problem focused in this article is quite specific and may be less useful in different domains. But the way this is going to solve may open doors to solve potentially like problems, hence making it worth a read. This article solves the problem of testing if a list contains series of odd or even elements. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using sum() + list comprehension + zip() + any()
This problem can be solved using the combination of above functions. This method solves problem in 2 steps. In 1st step, we compute all the possible pairs of N using list comprehension and zip function and in the second step we use sum and any function to test for N divisible result, if we find any one of it, we return positive.
# Python3 code to demonstrate# N consecutive Odd or Even Numbers# using sum() + zip() + any() + list comprehension  # initializing listtest_list = [1, 5, 6, 4, 8]  # printing original listprint("The original list : " + str(test_list))  # initializing N N = 3  # using sum() + zip() + any() + list comprehension# N consecutive Odd or Even Numberstemp = ( test_list[i : i + N] for i in range(len(test_list) - N + 1) )res = any( sum(ele % 2 for ele in temps) % N == 0 for temps in temp )  # print resultprint("Does list contain the desired consecution : " + str(res))
The original list : [1, 5, 6, 4, 8]
Does list contain the desired consecution : True

 
Method #2 : Using groupby() + any()
The whole logic of doing the 1st step in the above method can be managed using the groupby function in which we perform the grouping and any function can be used later for checking the consecution.
# Python3 code to demonstrate# N consecutive Odd or Even Numbers# using groupby() + any()from itertools import groupby  # initializing listtest_list = [1, 5, 6, 4, 8]  # printing original listprint("The original list : " + str(test_list))  # initializing N N = 3  # using groupby() + any()# N consecutive Odd or Even Numbersres = any(len(list(sub)) == N for idx, sub in     groupby([sub % 2 for sub in test_list]))  # print resultprint("Does list contain the desired consecution : " + str(res))
The original list : [1, 5, 6, 4, 8]
Does list contain the desired consecution : True

Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
Working with RxJS & Angular

In this chapter, we will see how to use RxJs with Angular. We will not get into the installation process for Angular here, to know about Angular Installation refer this link −https://www.tutorialspoint.com/angular7/angular7_environment_setup.htm
We will directly work on an example, where will use Ajax from RxJS to load data.
import { Component } from '@angular/core';
import { environment } from './../environments/environment';
import { ajax } from 'rxjs/ajax';
import { map } from 'rxjs/operators'

@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = '';
   data;
   constructor() {
      this.data = "";
      this.title = "Using RxJs with Angular";
      let a = this.getData();
   }
   getData() {
      const response =
      ajax('https://jsonplaceholder.typicode.com/users')
         .pipe(map(e => e.response));
      response.subscribe(res => {
         console.log(res);
         this.data = res;
      });
   }
}
<div>
   <h3>{{title}}</h3>
   <ul *ngFor="let i of data">
      <li>{{i.id}}: {{i.name}}</li>
   </ul>
</div>

<router-outlet></router-outlet>
We have used ajax from RxJS that will load data from this url − https://jsonplaceholder.typicode.com/users.
When you compile the display is as shown below −
scipy stats.beta() | Python

20 Mar, 2019
scipy.stats.beta() is an beta continuous random variable that is defined with a standard format and some shape parameters to complete its specification.
Parameters :q : lower and upper tail probabilitya, b : shape parametersx : quantilesloc : [optional] location parameter. Default = 0scale : [optional] scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’).
Results : beta continuous random variable
Code #1 : Creating beta continuous random variable
# importing scipyfrom scipy.stats import beta  numargs = beta.numargs[a, b] = [0.6, ] * numargsrv = beta(a, b)  print ("RV : \n", rv)
Output :
RV : 
 <scipy.stats._distn_infrastructure.rv_frozen object at 0x0000029482FCC438>

Code #2 : beta random variates and probability distribution function.
import numpy as npquantile = np.arange (0.01, 1, 0.1)   # Random VariatesR = beta.rvs(a, b, scale = 2,  size = 10)print ("Random Variates : \n", R)  # PDFR = beta.pdf(quantile, a, b, loc = 0, scale = 1)print ("\nProbability Distribution : \n", R)
Output :
Random Variates : 
 [1.47189604 1.47284574 1.84692416 1.0686604  0.32709236 1.96857076
 0.00639731 1.97093898 1.34811881 0.34269426]

Probability Distribution : 
 [2.62281037 1.04883674 0.84934164 0.76724957 0.73040985 0.72096547
 0.73529768 0.77903762 0.8752367  1.1264383 ]
Code #3 : Graphical Representation.
import numpy as npimport matplotlib.pyplot as plt  distribution = np.linspace(0, np.maximum(rv.dist.b, 5))plot = plt.plot(distribution, rv.pdf(distribution))
Output :
Code #4 : Varying Positional Arguments
from scipy.stats import arcsineimport matplotlib.pyplot as pltimport numpy as np  x = np.linspace(0, 1.0, 100)  # Varying positional argumentsy1 = beta.pdf(x, 2.75, 2.75)y2 = beta.pdf(x, 3.25, 3.25)plt.plot(x, y1, "*", x, y2, "r--")
Output :
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
How to remove legend title in R with ggplot2 ?

21 Jul, 2021
At times, the legend keys are enough to display what they are supposed to describe. Thus, in such cases, the legend title can be dropped. In this article, we will discuss how the legend title can be removed using ggplot2 in the R programming language.
Let us first draw a regular plot with a legend title:
R
library("ggplot2")  function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)}  df=data.frame(x=-2:2,              values=c(function1(-2:2),                       function2(-2:2),                       function3(-2:2),                       function4(-2:2)),              fun=rep(c("function1","function2",                        "function3","function4")))  ggplot(df, aes(x, values, col = fun)) + geom_line()
Output:
scale_color_discrete() function deals with legend aesthetics. To remove the title, its name attribute is set to nothing or left black, which makes it not appear in the final plot. 
Syntax: scale_color_discrete(name)
Example: Remove legend title using scale_color_discrete().
R
library("ggplot2")  function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)}  df=data.frame(x=-2:2,              values=c(function1(-2:2),                       function2(-2:2),                       function3(-2:2),                       function4(-2:2)),              fun=rep(c("function1","function2",                        "function3","function4")))  ggplot(df,aes(x,values,col=fun))+geom_line()+scale_color_discrete(name="")
Output:
theme() function is a powerful way to customize the non-data components of your plots: i.e. titles, labels, fonts, background, gridlines, and legends. To remove legend title, its legend.title attribute is set to element_blank().
Syntax: theme(legend.title= element_blank())
Example: Removing legend title with theme().
R
library("ggplot2")  function1<- function(x){x**2}function2<-function(x){x**3}function3<-function(x){x/2}function4<-function(x){2*(x**3)+(x**2)-(x/2)}  df=data.frame(x=-2:2,              values=c(function1(-2:2),                       function2(-2:2),                       function3(-2:2),                       function4(-2:2)),              fun=rep(c("function1","function2",                        "function3","function4")))  ggplot(df,aes(x,values,col=fun))+geom_line()+  theme(legend.title=element_blank())
Output:
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
R - if statement
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
How to write Pandas DataFrame as TSV using Python?

05 Nov, 2021
In this article, we will discuss how to write pandas dataframe as TSV using Python.
Let’s start by creating a data frame. It can be done by importing an existing file, but for simplicity, we will create our own.
Python3
# importing the moduleimport pandas as pd  # creating some sample datasample = {'name': ['a', 'b', 'c', 'd'],         'age': [24, 65, 39, 18]}  # creating the DataFramedf = pd.DataFrame(sample)  # displaying the DataFrameprint(df)
Output:
  name  age
0    a   24
1    b   65
2    c   39
3    d   18
Now, let’s export this as a TSV file. We can use to_csv method from pandas for this.
Syntax: df.to_csv(” file.tsv”, sep = “”)
Example:
Python3
# saving as tsv filedf.to_csv('example.tsv', sep="\t")
Output:
Here, sep defines what is the separator which separates the data entries in the file. In this case, we define it as a tabspace (‘\t’).  It will create a .csv file by default if the separator is not defined.
Picked
Python pandas-io
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Performing Analysis of a Factor in R Programming – factanal() Function

01 Jun, 2020
Factor Analysis also known as Exploratory Factor Analysis is a statistical technique used in R programming to identify the inactive relational structure and further, narrowing down a pool of variables to few variables. The main motive to use this technique is to find out which factor is most responsible for influence in the categorization of weights.
Syntax: factanal(x, factors)
Parameters:x: represents datasetfactors: specifies number of factors to be fitted
Example:Let us suppose, there are number of food available in the dataset with their food texture data points such as Oil, Density, Crispy, Fracture, and Hardness.
# Reading csv file of food texturesfood_textures <- read.csv("https://userpage.fu-berlin.de/soga/300/30100_data_sets/food-texture.csv")  food_textures <- food_textures[, 2:6]  factor_analysis <- factanal(food_textures, factors = 2)  print(factor_analysis)  # Output to be present as PNG file png(file = "factorAnalysisGFG.png")  # Plot factor 1 by factor 2load <- factor_analysis$loadings[, 1:2]  # Plot graphplot(load, type = "n")text(load, labels = names(food_textures), cex = .9)  # Saving the filedev.off()
Output:
Call:
factanal(x = food_textures, factors = 2)

Uniquenesses:
     Oil  Density   Crispy Fracture Hardness 
   0.334    0.156    0.042    0.256    0.407 

Loadings:
         Factor1 Factor2
Oil      -0.816         
Density   0.919         
Crispy   -0.745   0.635 
Fracture  0.645  -0.573 
Hardness          0.764 

               Factor1 Factor2
SS loadings      2.490   1.316
Proportion Var   0.498   0.263
Cumulative Var   0.498   0.761

Test of the hypothesis that 2 factors are sufficient.
The chi-square statistic is 0.27 on 1 degree of freedom.
The p-value is 0.603
R Factor-Function
R-Factors
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
How to filter R DataFrame by values in a column?
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming
How to combine Two Lists in R

23 Aug, 2021
In this article , we are going to merge two lists in R programming language.
This function is used to append the list to another list.
Syntax:
append(list1,list)
where
list1 is the first list
list 2 is the second list
Example: R program to create first list with strings and a second list with integers and append them
R
# create a list of stringslist1 =list("sravan","bobby","ojaswi",            "satwik","rohith","gnanesh")  # create a list of numberslist2=list(1,2,3,4,5)  # merge the two lists by using append() # functionlist3=append(list1,list2)  list3
Output:
[[1]]
[1] "sravan"
[[2]]
[1] "bobby"
[[3]]
[1] "ojaswi"
[[4]]
[1] "satwik"
[[5]]
[1] "rohith"
[[6]]
[1] "gnanesh"
[[7]]
[1] 1
[[8]]
[1] 2
[[9]]
[1] 3
[[10]]
[1] 4
[[11]]
[1] 5
This is used to combine two lists
Syntax:
c(list1,list2)
where,
list1 is the first list
list2 is the second list
Example: R program to create a list1 with strings and list2 with a list of integers and merge using c() function
R
# create a list of stringslist1 =list("sravan","bobby","ojaswi",            "satwik","rohith","gnanesh")  # create a list of numberslist2=list(1,2,3,4,5)  # merge the two lists by using c()# functionlist3=c(list1,list2)  list3
Output:
[[1]]
[1] "sravan"
[[2]]
[1] "bobby"
[[3]]
[1] "ojaswi"
[[4]]
[1] "satwik"
[[5]]
[1] "rohith"
[[6]]
[1] "gnanesh"
[[7]]
[1] 1
[[8]]
[1] 2
[[9]]
[1] 3
[[10]]
[1] 4
[[11]]
[1] 5
Picked
R List-Programs
R-List
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
Extract specific column from a DataFrame using column name in R
String strip() in JavaScript

08 Jun, 2020
The task here is to remove all leading and trailing spaces and tabs from the string. We will use some methods to reach the goal.
Method 1: Here, we will be using trim() method. We can strip a string using trim() method and can remove unnecessary trailing and leading spaces and tabs from the string.
Example:
HTML
<!DOCTYPE html><html><head>    <title>String strip() for JavaScript</title></head><body>    <script>        var string="    GeeksforGeeks     ";        console.log("Before string:'"+string+"'");                  console.log("After string :'"+string.trim()+"'");    </script></body></html>
Output:
Method 2: Here we will be making a user-defined function. We will be writing a JavaScript to strip the string and to remove unnecessary spaces.
Example:
HTML
<!DOCTYPE html><html>   <head>      <title>String strip() for JavaScript</title>   </head>   <body>       <script>          function strip(string) {              return string.replace(/^\s+|\s+$/g, '');        }                  var string="    GeeksforGeeks     ";        console.log("Before string:'"+string+"'");                   console.log("After string :'"+strip(string)+"'");      </script>  </body></html>
javascript-functions
javascript-string
Picked
JavaScript
Web Technologies
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
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
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 ?
A Puzzle using C Program

Here we will see one C puzzle question. Suppose we have two numbers 48 and 96. We have to add the first number after the second one. So final result will be like 9648. But we cannot use any logical, arithmetic, string related operations, also cannot use any pre-defined functions. So how can we do that?
This is easy. We can do by using Token Pasting operator(##) in C. The Token Pasting operator is a preprocessor operator. It sends commands to compiler to add or concatenate two tokens into one string. We use this operator at the macro definition.
#include<stdio.h>
#define MERGE(x, y) y##x
main() {
   printf("%d", MERGE(48, 96));
}
9648
PHP - Function set_error_handler()

mixed set_error_handler ( callback $error_handler [, int $error_types] );
This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions.
error_handler(Required)
It specifies the function to be run at errors. Syntax of error_handler is given below.
error_types(Optional)
It specifies on which errors report levels the user-defined error will be shown. Default is "E_ALL". See "PHP Error and Logging Constants:" for possible error report levels.
error_function(error_level,error_message, error_file,error_line,error_context);

Here are the paramenter's description −
errno − The first parameter, errno, contains the level of the error raised, as an integer.
errno − The first parameter, errno, contains the level of the error raised, as an integer.
errstr − The second parameter, errstr, contains the error message, as a string.
errstr − The second parameter, errstr, contains the error message, as a string.
errfile − The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.
errfile − The third parameter is optional, errfile, which contains the filename that the error was raised in, as a string.
errline − The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.
errline − The fourth parameter is optional, errline, which contains the line number the error was raised at, as an integer.
errcontext − The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred.
errcontext − The fifth parameter is optional, errcontext, which is an array that points to the active symbol table at the point the error occurred.
Returns a string containing the previously defined error handler (if any), or NULL on error.
Following is the usage of this function −
<?php
   function customError($errno, $errstr, $errfile, $errline) {
      echo "Custom error: [$errno] $errstr\n";
      echo "Error on line $errline in $errfile\n";
      echo "Ending Script";
      
      die();
   }
   
   //set error handler
   set_error_handler("customError");
   $test = 0;
   
   //trigger error
   if ($test >  -1) {
      trigger_error("A custom error has been triggered");
   }
?> 
This will produce the following result −
Custom error: [1024] A custom error has been triggered Error on line 16 
in /home/cg/root/1531703/main.php 
Ending Script


    45 Lectures 
     9 hours 

 Malhar Lathkar

    34 Lectures 
     4 hours 

 Syed Raza

    84 Lectures 
     5.5 hours 

 Frahaan Hussain

    17 Lectures 
     1 hours 

 Nivedita Jain

    100 Lectures 
     34 hours 

 Azaz Patel

    43 Lectures 
     5.5 hours 

 Vijay Kumar Parvatha Reddy
 Print
 Add Notes
 Bookmark this page
Difference between default and static interface method in Java 8.

According to Oracle's Javadocs −
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.
Static method in interface are part of the interface class can’t implement or override it whereas class can override the default method.
public interface DefaultStaticExampleInterface {
   default void show() {
      System.out.println("In Java 8- default method - DefaultStaticExampleInterface");
   }
   static void display() {
      System.out.println("In DefaultStaticExampleInterface I");
   }
}
public class DefaultStaticExampleClass implements DefaultStaticExampleInterface {
}
public class Main {
   static void main(String args[]) {
      // Call interface static method on Interface
      DefaultStaticExampleInterface.display();
      DefaultStaticExampleClass defaultStaticExampleClass = new DefaultStaticExampleClass();
     
      // Call default method on Class
      defaultStaticExampleClass.show();
   }
}