code-rag-bench/online-tutorials huggingface dataset:
Tuple Division in Python - GeeksforGeeks

26 Nov, 2019
Sometimes, while working with records, we can have a problem in which we may need to perform mathematical division operation across tuples. This problem can occur in day-day programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using zip() + generator expressionThe combination of above functions can be used to perform this task. In this, we perform the task of division using generator expression and mapping index of each tuple is done by zip().
# Python3 code to demonstrate working of # Tuple division# using zip() + generator expression   # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3)   # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))   # Tuple division # using zip() + generator expression res = tuple(ele1 // ele2 for ele1, ele2 in zip(test_tup1, test_tup2))   # printing result print("The divided tuple : " + str(res)) 
The original tuple 1 : (10, 4, 6, 9)
The original tuple 2 : (5, 2, 3, 3)
The divided tuple : (2, 2, 2, 3)

 
Method #2 : Using map() + floordivThe combination of above functionalities can also perform this task. In this, we perform the task of extending logic of division using floordiv and mapping is done by map().
# Python3 code to demonstrate working of # Tuple division # using map() + floordiv from operator import floordiv  # initialize tuples test_tup1 = (10, 4, 6, 9) test_tup2 = (5, 2, 3, 3)   # printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2))   # Tuple division# using map() + floordiv res = tuple(map(floordiv, test_tup1, test_tup2))   # printing result print("The divided tuple : " + str(res))
The original tuple 1 : (10, 4, 6, 9)
The original tuple 2 : (5, 2, 3, 3)
The divided tuple : (2, 2, 2, 3)

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
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?
Tryit Editor v3.7

Tryit: The video element
TensorFlow - TFLearn And Its Installation

TFLearn can be defined as a modular and transparent deep learning aspect used in TensorFlow framework. The main motive of TFLearn is to provide a higher level API to TensorFlow for facilitating and showing up new experiments.
Consider the following important features of TFLearn −
TFLearn is easy to use and understand.
TFLearn is easy to use and understand.
It includes easy concepts to build highly modular network layers, optimizers and various metrics embedded within them.
It includes easy concepts to build highly modular network layers, optimizers and various metrics embedded within them.
It includes full transparency with TensorFlow work system.
It includes full transparency with TensorFlow work system.
It includes powerful helper functions to train the built in tensors which accept multiple inputs, outputs and optimizers.
It includes powerful helper functions to train the built in tensors which accept multiple inputs, outputs and optimizers.
It includes easy and beautiful graph visualization.
It includes easy and beautiful graph visualization.
The graph visualization includes various details of weights, gradients and activations.
The graph visualization includes various details of weights, gradients and activations.
Install TFLearn by executing the following command −
pip install tflearn

Upon execution of the above code, the following output will be generated −
The following illustration shows the implementation of TFLearn with Random Forest classifier −
from __future__ import division, print_function, absolute_import

#TFLearn module implementation
import tflearn
from tflearn.estimators import RandomForestClassifier

# Data loading and pre-processing with respect to dataset
import tflearn.datasets.mnist as mnist
X, Y, testX, testY = mnist.load_data(one_hot = False)

m = RandomForestClassifier(n_estimators = 100, max_nodes = 1000)
m.fit(X, Y, batch_size = 10000, display_step = 10)

print("Compute the accuracy on train data:")
print(m.evaluate(X, Y, tflearn.accuracy_op))

print("Compute the accuracy on test set:")
print(m.evaluate(testX, testY, tflearn.accuracy_op))

print("Digits for test images id 0 to 5:")
print(m.predict(testX[:5]))

print("True digits:")
print(testY[:5])

    61 Lectures 
     9 hours 

 Abhishek And Pukhraj

    57 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     7 hours 

 Abhishek And Pukhraj

    52 Lectures 
     6 hours 

 Abhishek And Pukhraj

    29 Lectures 
     3.5 hours 

 Mohammad Nauman

    82 Lectures 
     4 hours 

 Anis Koubaa
 Print
 Add Notes
 Bookmark this page
Difference between Thread.start() and Thread.run() in Java.

As we know that start() and run() are the two important methods of multithreading and one is used to create a new thread while other is used to start executing that thread.
Following are the important differences between Thread.start() and Thread.run().
JavaTester.java
 Live Demo
public class JavaTester extends Thread{
   public void run(){
      System.out.println("Thread is running...");
   }
   public static void main(String args[]){
      JavaTester t1=new JavaTester();
      // this will call run() method
      t1.start();
   }
}
Thread is running...
JavaTester.java
 Live Demo
public class JavaTester implements Runnable{
   public void run(){
      System.out.println("Thread is running...");
   }
   public static void main(String args[]){
      JavaTester m1=new JavaTester();
      Thread t1 =new Thread(m1);
      // this will call run() method
      t1.start();
   }
}
Thread is running...
Creating an Excel-like data grid in React JS

In this article, we will see how to create an Excel-like data grid in React JS frontend. We will use a third-party package for this, which is called react-data-grid. This is a useful package if you are working with data and want to make a dashboard application.
First create a react project −
npx create-react-app tutorialpurpose
Go to the project directory −
cd tutorialpurpose
Download and install the react-data-grid package −
npm i --save react-data-grid
We can use this package to add default styled grid tables or you can
say data grids which are premade.
Add the following lines of code in App.js −
import DataGrid from "react-data-grid";

const columns = [
   { key: "id", name: "ID" },
   { key: "title", name: "Title" },
];

const rows = [
   { id: 0, title: "Example" },
   { id: 1, title: "Demo" },
   { id: 2, title: "React JS" },
   { id: 3, title: "Tutorialspoint" },
   { id: 4, title: "Ath Tripathi" },
   { id: 5, title: "Kiran Kumar Panigrahi" },
];

export default function App() {
   return <DataGrid columns={columns} rows={rows} />;
}
The concept is simple. We first make a column variable to indicate how the columns should be arranged. It will be a list of JSON objects and one column should have two keys: “key” which will be used for reference when creating a row and “name” which will be used for showing the column name.
The row variable will be same as the column variable. Keys of row’s JSON will be the “key” of column variable, and the value will be the data to show under that column.
On execution, it will produce the following output −
Checking SAP HANA Schema owner name

To check schema owner, you need access on “SYS” schema. Open SAP HANA SQL console and run the following SQL query −
SELECT * FROM "SYS"."SCHEMAS";
fc-list command in Linux with examples - GeeksforGeeks

15 May, 2019
fc-list command is a part of the fontconfig system. It is used to list the available fonts and font styles. Using the format option, the list of all fonts can be filtered and sorted out. Moreover, multiple parameters can be passed to it after a colon symbol (:) to restrict the information that is being displayed on the screen.
Syntax:
fc-list [-vqVh] [-f FORMAT] [–verbose] [–format=FORMAT] [–quiet] [–version] [–help] [pattern] {element ...} List fonts matching [pattern]
Example: It will print all the file locations of the font files present in the system, with their font name, spacing and style type.
fc-list
Options:
-v, –verbose: It is used to show the entire font pattern verbosely.
-f, –format=FORMAT: To use the given output format.
-q, –quiet: It will suppress all normal output, exit 1 if no fonts matched.
-V, –version: It will show font config version and exit.
-h, –help: Used to show the help message and exit.
Some More Examples:
fc-list with font-family: It will print only the names of the font families, without displaying the other aforementioned details.fc-list : family 
fc-list : family 
fc-list with font family + Language selector: It will print only the names of the font families which support the selected language code, without displaying the other aforementioned details.Note: The language code used here is “ta”, which stands for the language Tamil.fc-list : family lang=ta Note: The language code used here is “hi”, which stands for the language Hindi.fc-list : family lang=hi
Note: The language code used here is “ta”, which stands for the language Tamil.
fc-list : family lang=ta 
Note: The language code used here is “hi”, which stands for the language Hindi.
fc-list : family lang=hi
fc-list with other selectors: Similar to the family selector, we can also select the file location, spacing or/and style of the required fonts to be displayed onscreen.fc-list : family style Note: Sorting and unique can also be incorporated along with this commandfc-list : family spacing | sort | uniq
fc-list : family style 
Note: Sorting and unique can also be incorporated along with this command
fc-list : family spacing | sort | uniq
fc-list with format option: This option is used to format the output text to the required pattern given by the user. In this example, the format option is used to get the family names of all the fonts, sorted and unique.fc-list --format="%{family[0]}\n" | sort | uniq
fc-list --format="%{family[0]}\n" | sort | uniq
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Named Pipe or FIFO with example C program
Thread functions in C/C++
SED command in Linux | Set 2
Array Basics in Shell Scripting | Set 1
Introduction to Linux Shell and Shell Scripting
Linux system call in Detail
chown command in Linux with Examples
Looping Statements | Shell Script
mv command in Linux with examples
PING Command in Linux with examples
filter() in python - GeeksforGeeks

22 Apr, 2020
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not.
syntax:
filter(function, sequence)
Parameters:
function: function that tests if each element of a 
sequence true or not.
sequence: sequence which needs to be filtered, it can 
be sets, lists, tuples, or containers of any iterators.
Returns:
returns an iterator that is already filtered.

# function that filters vowelsdef fun(variable):    letters = ['a', 'e', 'i', 'o', 'u']    if (variable in letters):        return True    else:        return False    # sequencesequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']  # using filter functionfiltered = filter(fun, sequence)  print('The filtered letters are:')for s in filtered:    print(s)
Output:
The filtered letters are:
e
e

Application:It is normally used with Lambda functions to separate list, tuple, or sets.
# a list contains both even and odd numbers. seq = [0, 1, 2, 3, 5, 8, 13]  # result contains odd numbers of the listresult = filter(lambda x: x % 2 != 0, seq)print(list(result))  # result contains even numbers of the listresult = filter(lambda x: x % 2 == 0, seq)print(list(result))
Output:
[1, 3, 5, 13]
[0, 2, 8]

Please refer Python Lambda functions for more details.
kailashc_j
nidhi_biet
erpriyarana
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
How to drop one or multiple columns in Pandas Dataframe
*args and **kwargs in Python
Graph Plotting in Python | Set 1
Print lists in Python (4 Different Ways)
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Convert integer to string in Python
Python program to create a list of tuples from given list having number and its cube in each tuple - GeeksforGeeks

21 Nov, 2018
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number.
Example:
Input: list = [1, 2, 3]
Output: [(1, 1), (2, 8), (3, 27)]

Input: list = [9, 5, 6]
Output: [(9, 729), (5, 125), (6, 216)]
We can use list comprehension to create a list of tuples. The first element will be simply an element and second element will be cube of that number.
Below is the Python implementation:
# Python program to create a list of tuples# from given list having number and# its cube in each tuple  # creating a listlist1 = [1, 2, 5, 6]  # using list comprehension to iterate each# values in list and create a tuple as specifiedres = [(val, pow(val, 3)) for val in list1]  # print the resultprint(res)
Output:
[(1, 1), (2, 8), (5, 125), (6, 216)]
Python list-programs
Python tuple-programs
python-list
python-tuple
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Button in wxPython - Python - GeeksforGeeks

10 May, 2020
In this article we are going to learn how can we add buttons to a frame in wxPython. This can be done by using using the Button() constructor of wx.Button class.
Following styles are supported in this class:
wx.BU_LEFT: Left-justifies the label. Windows and GTK+ only.
wx.BU_TOP: Aligns the label to the top of the button. Windows and GTK+ only.
wx.BU_RIGHT: Right-justifies the bitmap label. Windows and GTK+ only.
wx.BU_BOTTOM: Aligns the label to the bottom of the button. Windows and GTK+ only.
wx.BU_EXACTFIT: By default, all buttons are made of at least the standard button size, even if their contents is small enough to fit into a smaller size. This is done for consistency as most platforms use buttons of the same size in the native dialogs, but can be overridden by specifying this flag. If it is given, the button will be made just big enough for its contents. Notice that under MSW the button will still have at least the standard height, even with this style, if it has a non-empty label.
wx.BU_NOTEXT: Disables the display of the text label in the button even if it has one or its id is one of the standard stock ids with an associated label: without using this style a button which is only supposed to show a bitmap but uses a standard id would display a label too.
wx.BORDER_NONE: Creates a button without border. This is currently implemented in MSW, GTK2 and OSX/Cocoa.
Syntax :
wx.StaticText(self, parent, id=ID_ANY, label=””, 
              pos=DefaultPosition, size=DefaultSize, 
                 style=0, validator= DefaultVadator, 
                            name=StaticTextNameStr)

Parameters :
Example #1:
# import wxPythondef onButton(event):    print( "Button pressed.")  app = wx.App()frame = wx.Frame(None, -1, 'win.py')frame.SetDimensions(200, 0, 200, 50)  panel = wx.Panel(frame, wx.ID_ANY)button = wx.Button(panel, wx.ID_ANY, 'Test', (10, 10))button.Bind(wx.EVT_BUTTON, onButton)  frame.Show()app.MainLoop()
Output :
Python-gui
Python-wxPython
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Print different star patterns in SQL - GeeksforGeeks

21 Mar, 2018
Let’s see how we can print the pattern of various type using SQL.
Syntax :

Declare @variable_name DATATYPE     -- first declare all the
                                    -- variables with datatype
                                    -- like (int)

select @variable = WITH_ANY_VALUE   -- select the variable and 
                                    -- initialize with value

while CONDITION                     -- condition like @variable > 0 

begin                               -- begin

print replicate('*', @variable)     -- replicate insert the *
                                    -- character in variable times

set increment/decrement             -- in increment/decrement
                                    -- @variable= @variable+1
END                                 -- end while loop


DECLARE @var int               -- DeclareSELECT @var = 5                -- InitializationWHILE @var > 0                 -- conditionBEGIN                          -- BeginPRINT replicate('* ', @var)    -- PrintSET @var = @var - 1            -- decrementEND                            -- END
Output :
* * * * *
* * * * 
* * * 
* * 
*

Second Pattern :
DECLARE @var int                  -- Declare SELECT @var = 1                   -- initialization WHILE @var <= 5                   -- ConditionBEGIN                             -- BeginPRINT replicate('* ', @var)       -- PrintSET @var = @var + 1               -- SetEND                               -- end
Output :
*
* *
* * *
* * * *
* * * * *

Third Pattern :
DECLARE @var int, @x int                 -- declare two variableSELECT @var = 4,@x = 1                   -- initializationWHILE @x <=5                             -- conditionBEGINPRINT space(@var) + replicate('*', @x)   -- here space for                                          -- create spaces SET @var = @var - 1                      -- setset @x = @x + 1                          -- setEND                                      -- End
Output :
    *
   **
  ***
 ****
*****

Fourth Pattern :
DECLARE @var int, @x int                 -- declare two variableSELECT @var = 0,@x = 5                   -- initializationWHILE @x > 0                             -- conditionBEGINPRINT space(@var) + replicate('*', @x)   -- here space for                                         -- create spaces SET @var = @var + 1                      -- setset @x = @x - 1                          -- setEND                                      -- End
Output :
*****
 ****
  ***
   **
    *

pattern-printing
SQL-PL/SQL
SQL
pattern-printing
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
ReactJS componentWillUnmount() Method - GeeksforGeeks

18 Jan, 2021
The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e before the component gets unmounted.
All the cleanups such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount() should be coded in the componentWillUnmount() method block.
Tip: Never call setState() in componentWillUnmount() method.
Syntax:
componentWillUnmount()
Creating React Application:
Step 1: Create a React application using the following command:
npx create-react-app functiondemo
Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:
cd functiondemo
Project Structure: It will look like the following.
Project Structure
Example: In this example, we are going to build a name color application that changes the color of the text when the component is rendered in the DOM tree.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';class ComponentOne extends React.Component {   // Defining the componentWillUnmount method  componentWillUnmount() {    alert('The component is going to be unmounted');  }   render() {    return <h1>Hello Geeks!</h1>;  }} class App extends React.Component {  state = { display: true };  delete = () => {    this.setState({ display: false });  };   render() {    let comp;    if (this.state.display) {      comp = <ComponentOne />;    }    return (      <div>        {comp}        <button onClick={this.delete}>          Delete the component        </button>      </div>    );  }} export default App;
  Note: You can define your own styling in the App.css file.
Step to Run Application: Run the application using the following command from the root directory of the project: 
npm start
Output: 
 
 
Reference: https://reactjs.org/docs/react-component.html#componentwillunmount
 
rbbansal
react-js
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
How to apply style to parent if it has child with CSS?
How to convert array to string in PHP ?
What is web socket and how it is different from the HTTP?
How to set space between the flexbox ?
Design a web page using HTML and CSS
How to install the previous version of node.js and npm ?
How to get selected value in dropdown list using JavaScript ?
How to Fix a 401 Unauthorized Error?
How to change selected value of a drop-down list using jQuery?
Matplotlib.figure.Figure.text() in Python - GeeksforGeeks

03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The text() method figure module of matplotlib library is used to Add text to figure.
Syntax: text(self, x, y, s, fontdict=None, withdash=, **kwargs)
Parameters: This method accept the following parameters that are discussed below:
x: This parameter is the x position to place the text.
y: This parameter is the y position to place the text.
s: This parameter is the text string.
fontdict : This parameter is the dictionary to override the default text properties.
withdash : This parameter is used to create a TextWithDash instance instead of a Text instance.
Returns: This method returns the Text.
Below examples illustrate the matplotlib.figure.Figure.text() function in matplotlib.figure:
Example 1:
#Implementation of matplotlib functionimport matplotlib.pyplot as plt          fig, ax = plt.subplots()   fig.text(0.28, 0.5,          'GeeksforGeeks',          style = 'italic',         fontsize = 30,         color = "green")   ax.set(xlim = (0, 8),       ylim = (0, 8))   fig.suptitle("""matplotlib.figure.Figure.text()function Example\n\n""",fontweight="bold")  fig.show()
Output:
Example 2:
# Implementation of matplotlib functionimport matplotlib.pyplot as plt   fig, ax = plt.subplots()ax.set_xlabel('xlabel')ax.set_ylabel('ylabel')   fig.text(0.3, 0.7,         'GeeksforGeeks',         style = 'italic',         fontsize = 30,         bbox ={'facecolor':'green',                'alpha':0.6,                'pad':10})   fig.text(0.35, 0.6,          'Python matplotlib Module',         fontsize = 15)   fig.text(0.35, 0.3,         'Figure Class - Text Function')   fig.text(0, 0, 'by-Shubham Singh',        verticalalignment ='bottom',         horizontalalignment ='left',        transform = ax.transAxes,        color ='green',        fontsize = 5)         ax.set(xlim =(0, 10), ylim =(0, 10))  fig.suptitle("""matplotlib.figure.Figure.text()function Example\n\n""", fontweight ="bold")  fig.show()
Output:
Matplotlib figure-class
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Output of C Programs | Set 12

27 Dec, 2016
Predict the output of below programs.
Question 1
int fun(char *str1){  char *str2 = str1;  while(*++str1);  return (str1-str2);}      int main(){  char *str = "geeksforgeeks";  printf("%d", fun(str));  getchar();  return 0;}
Output: 13Inside fun(), pointer str2 is initialized as str1 and str1 is moved till ‘\0’ is reached (note ; after while loop). So str1 will be incremented by 13 (assuming that char takes 1 byte).
Question 2
void fun(int *p){  static int q = 10;  p = &q;}      int main(){  int r = 20;  int *p = &r;  fun(p);  printf("%d", *p);  getchar();  return 0;}
Output: 20Inside fun(), q is a copy of the pointer p. So if we change q to point something else then p remains unaffected.
Question 3
void fun(int **p){  static int q = 10;  *p = &q;}      int main(){  int r = 20;  int *p = &r;  fun(&p);  printf("%d", *p);  getchar();  return 0;}
Output 10
Note that we are passing address of p to fun(). p in fun() is actually a pointer to p in main() and we are changing value at p in fun(). So p of main is changed to point q of fun(). To understand it better, let us rename p in fun() to p_ref or ptr_to_p
void fun(int **ptr_to_p){  static int q = 10;  *ptr_to_p = &q;  /*Now p of main is pointing to q*/}
Also, note that the program won’t cause any problem because q is a static variable. Static variables exist in memory even after functions return. For an auto variable, we might have seen some weird output because auto variable may not exist in memory after functions return.
Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.
C-Output
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Condition To Print “HelloWorld”

21 Feb, 2022
What should be the “condition” so that the following code snippet prints both HelloWorld!
 
      if  "condition"
          printf ("Hello");
      else
          printf("World"); 
Method 1:  
c
#include<stdio.h>int main(){    if(!printf("Hello"))        printf("Hello");    else        printf("World");    getchar();}       
Explanation: Printf returns the number of character it has printed successfully. So, following solutions will also workif (printf(“Hello”) < 0) or if (printf(“Hello”) < 1) etc Method 2: Using fork()  
c
#include<stdio.h>#include<unistd.h>int main(){    if(fork())        printf("Hello");    else        printf("World");    getchar();}       
This method is contributed by Aravind Alapati.Please comment if you find more solutions of this. 
sagar0719kumar
c-puzzle
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Program to format a number with thousands separator in C/C++

31 Oct, 2020
Given an integer N, the task is to print output of the given integer in international place value format and put commas at the appropriate place, from the right.
Examples
Input: N = 47634Output: 47, 634
Input: N = 1000000Output : 1, 000, 000
Approach: Follow the steps below to solve the problem:
Convert the given integer N to its equivalent string.Iterate over the characters of the given string from the right to the left.After traversing every 3 characters, insert a ‘,’ separator.
Convert the given integer N to its equivalent string.
Iterate over the characters of the given string from the right to the left.
After traversing every 3 characters, insert a ‘,’ separator.
Below is the implementation of the above approach:
C++
// C++ program to implement the// above approach  #include <bits/stdc++.h>using namespace std;  // Function to put thousands// separators in the given integerstring thousandSeparator(int n){    string ans = "";      // Convert the given integer    // to equivalent string    string num = to_string(n);      // Initialise count    int count = 0;      // Traverse the string in reverse    for (int i = num.size() - 1;         i >= 0; i--) {        count++;        ans.push_back(num[i]);          // If three characters        // are traversed        if (count == 3) {            ans.push_back(',');            count = 0;        }    }      // Reverse the string to get    // the desired output    reverse(ans.begin(), ans.end());      // If the given string is    // less than 1000    if (ans.size() % 4 == 0) {          // Remove ','        ans.erase(ans.begin());    }      return ans;}  // Driver Codeint main(){    int N = 47634;    string s = thousandSeparator(N);    cout << s << endl;}
47,634

Time Complexity: O(log10N)Auxiliary Space: O(1)
Mathematical
School Programming
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Merge two sorted arrays with O(1) extra space
Program to print prime numbers from 1 to N.
Find next greater number with same set of digits
Segment Tree | Set 1 (Sum of given range)
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Playing with Destructors in C++

29 May, 2017
Predict the output of the below code snippet.
#include <iostream>using namespace std;  int i;  class A{public:    ~A()    {        i=10;    }};  int foo(){    i=3;    A ob;    return i;}  int main(){    cout << "i = " << foo() << endl;    return 0;}
Output of the above program is “i = 3”.Why the output is i= 3 and not 10?While returning from a function, destructor is the last method to be executed. The destructor for the object “ob” is called after the value of i is copied to the return value of the function. So, before destructor could change the value of i to 10, the current value of i gets copied & hence the output is i = 3.
How to make the program to output “i = 10” ?Following are two ways of returning updated value:
1) Return by Reference:Since reference gives the l-value of the variable,by using return by reference the program will output “i = 10”.
#include <iostream>using namespace std;  int i;  class A{public:    ~A()    {        i = 10;    }};  int& foo(){    i = 3;    A ob;    return i;}  int main(){    cout << "i = " << foo() << endl;    return 0;}
The function foo() returns the l-value of the variable i. So, the address of i will be copied in the return value. Since, the references are automatically dereferened. It will output “i = 10”.
2. Create the object ob in a block scope
#include <iostream>using namespace std;  int i;  class A{public:    ~A()    {        i = 10;    }};  int foo(){    i = 3;    {        A ob;    }    return i;}  int main(){    cout << "i = " << foo() << endl;    return 0;}
Since the object ob is created in the block scope, the destructor of the object will be called after the block ends, thereby changing the value of i to 10. Finally 10 will copied to the return value.
This article is compiled by Aashish Barnwal and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
cpp-destructor
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Python | Pandas Series.set_axis()

03 Sep, 2021
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index.
Pandas Series.set_axis() function is used to assign desired index to given axis. Indexes for column or row labels can be changed by assigning a list-like or Index.
Syntax: Series.set_axis(labels, axis=0, inplace=None)Parameter : labels : The values for the new index. axis : The axis to update. The value 0 identifies the rows, and 1 identifies the columns. inplace : Whether to return a new %(klass)s instance.Returns : renamed : series 
Example #1: Use Series.set_axis() function to reset the axis of the given Series object. 
Python3
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series(['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio', 'Moscow']) # Create the Indexindex_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5', 'City 6'] # set the indexsr.index = index_ # Print the seriesprint(sr)
Output : 
Now we will use Series.set_axis() function to reset the index of the given series object 
Python3
# Create the Indexdidx = pd.DatetimeIndex(start ='2014-08-01 10:00', freq ='W',                     periods = 6, tz = 'Europe/Berlin')  # reset the indexsr.set_axis(didx, inplace = True) # Print the seriesprint(sr)
Output : 
As we can see in the output, the Series.set_axis() function has successfully reset the index of the given Series object.
Example #2: Use Series.set_axis() function to reset the axis of the given Series object. 
Python3
# importing pandas as pdimport pandas as pd # Creating the Seriessr = pd.Series([100, 25, 32, 118, 24, 65]) # Print the seriesprint(sr)
Output : 
Now we will use Series.set_axis() function to reset the index of the given series object 
Python3
# Assign the new indexsr.set_axis(['A', 'B', 'C', 'D', 'E', 'F'], inplace = True) # print the seriesprint(sr)
Output : 
As we can see in the output, the Series.set_axis() function has successfully reset the index of the given Series object. 
anikakapoor
Python pandas-series
Python pandas-series-methods
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
scipy stats.moment() function | Python

11 Feb, 2019
scipy.stats.moment(array, axis=0) function calculates the nth moment about the mean for a sample i.e. array elements along the specified axis of the array (list in python).
Its formula –
Parameters :array : Input array or object having the elements to calculate the moment.axis : Axis along which the moment is to be computed. By default axis = 0.moment : Order of central moment that is returned.
Returns : n-th central moment of the array elements based on the set parameters.
Code #1:
# Momentfrom scipy import statsimport numpy as np   arr1 = np.array([[1, 31, 27, 13, 21, 9],                [8, 12, 8, 4, 7, 10]])      print("Oth moment : \n", stats.moment(arr1, moment = 0)) 
Output :
Oth moment : 
 [1. 1. 1. 1. 1. 1.]
 Code #2: With multi-dimensional data
# Moment from scipy import statsimport numpy as np   arr1 = [[1, 3, 27],         [3, 4, 6],         [7, 6, 3],         [3, 6, 8]]    print("Oth moment : \n", stats.moment(arr1, moment = 0))  print("\n6th moment : \n", stats.moment(arr1, moment = 6))  print("\n9th moment : \n", stats.moment(arr1, moment = 9, axis = None))  print("\n12th moment : \n", stats.moment(arr1, moment = 12, axis = 1))  print("\n10th moment : \n", stats.moment(arr1, moment = 10, axis = 1))
Output :
Oth moment : 
 [1. 1. 1.]

6th moment : 
 [5.20609375e+02 9.13256836e+00 4.26392850e+06]

9th moment : 
 55265909588.26437

12th moment : 
 [1.53284936e+14 1.63654317e+02 8.83474172e+03 5.17842143e+04]

10th moment : 
 [5.53094361e+11 6.10464868e+01 1.64971407e+03 7.65588508e+03]
Python scipy-stats-functions
Python-scipy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Row Echelon Form

22 Jan, 2021
A matrix is in Row Echelon form if it has the following properties:
Any row consisting entirely of zeros occurs at the bottom of the matrix.
For each row that does not contain entirely zeros, the first non-zero entry is 1 (called a leading 1).
For two successive (non-zero) rows, the leading 1 in the higher row is further left than the leading one in the lower row.
For reduced row echelon form, the leading 1 of every row contains 0 below and above its in that column.
Below is an example of row-echelon form: 
and reduced row-echelon form:
Any matrix can be transformed to reduced row echelon form, using a technique called Gaussian elimination. This is particularly useful for solving systems of linear equations.
Gaussian Elimination is a way of converting a matrix into the reduced row echelon form. It can also be used as a way of finding a solution to a solution to the system of linear equations. The idea behind this is that we perform some mathematical operations on the row and continue until only one variable is left.
Below are some operations which we can perform:
Interchange any two rows
Add two rows together.
Multiply one row by a non-zero constant (i.e. 1/3, -1/5, 2).
Given the following linear equation:
and the augmented matrix above 
Now, we need to convert this into the row-echelon form. To convert this into row-echelon form, we need to perform Gaussian Elimination.
First, we need to subtract 2*r1 from the r2 and 4*r1 from the r3 to get the 0 in the first place of r2 and r3.
Next, we will interchange the rows, r2 and r3 and after that subtract 5*r2 from r3 to get the second 0 in the third row.
Now, we can deduce the value z from r3, i.e 10 z =0 ⇾ z=0. With the help of the value of z =0, we can put it to r2, y = 2. Similarly, we can put the value of y and z in r1 and we get a value of x=3
The rank of the matrix is the number of non-zero rows in the row echelon form. To find the rank, we need to perform the following steps:
Find the row-echelon form of the given matrix
Count the number of non-zero rows.
Let’s take an example matrix:
Now, we reduce the above matrix to row-echelon form
Here, only one row contains non-zero elements. Hence, the rank of the matrix is 2.
To convert a matrix into reduced row-echelon form, we used the Sympy package in python, first, we need to install it.
# install sympy! pip install sympy  # import sympyimport sympy  # find the reduced row echelon formsympy.Matrix([[4,0,1],[2,0,2],[3,0,3]]).rref()  # find the rank of matrixprint("Rank of matrix :",sympy.Matrix([[4,0,1],[2,0,2],[3,0,3]]).rank())
Output:
(Matrix([
 [1, 0, 0],
 [0, 0, 1],
 [0, 0, 0]]), (0, 2))
 
 Rank of matrix : 2
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
DBSCAN Clustering in ML | Density based clustering
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
Python Dictionary
How to get column names in Pandas dataframe
GATE | GATE IT 2005 | Question 71

28 Jun, 2021
A network with CSMA/CD protocol in the MAC layer is running at 1 Gbps over a 1 km cable with no repeaters. The signal speed in the cable is 2 x 108 m/sec. The minimum frame size for this network should be
 (A) 10000 bits(B) 10000 bytes(C) 5000 bits(D) 5000 bytesAnswer: (A)Explanation:
Frame Size S >= 2BL/P

Where,

Cable Length L = 1KM = 1000M 
Propogation Speed P = 2 x 10^8 m/sec
Bandwidth = 1 Gbps = 10^9 bps

See this for details of above formula.

S >= (2 *  10^9 * 1000) / (2 x 10^8)
  >= 10000 bits

Quiz of this Question
adnanirshad158
Gate IT 2005
GATE-Gate IT 2005
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33
GATE | GATE CS 2008 | Question 46
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE-CS-2014-(Set-1) | Question 51
GATE | GATE CS 1996 | Question 63
GATE | GATE-CS-2015 (Set 2) | Question 55
GATE | GATE-CS-2001 | Question 50
GATE | GATE-CS-2004 | Question 31
Open computer drives like C, D or E using Python

29 Dec, 2020
Have you ever wondered that you can open your drives by just typing C, D or E and then that drives are open.This can be possible by using Python. So, for performing this task this we are using os.startfile() method of OS library. This Method start a file with its associated program.
Syntax: os.startfile(file_name)
Return: None.
Now let’s see the code:
Python3
# import libraryimport os  # take Input from the user query = input("Which drive you have to open ? C , D or E: \n")  # Check the condition for # opening the C driveif "C" in query or "c" in query:  os.startfile("C:")    # Check the condition for # opening the D driveelif "D" in query or "d" in query:  os.startfile("D:")  # Check the condition for # opening the D driveelif "E" in query or "e" in query:  os.startfile("E:")  else:    print("Wrong Input")
Output:
Python os-module-programs
python-os-module
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
TreeSet iterator() Method in Java

26 Nov, 2018
The Java.util.TreeSet.iterator() method is used to return an iterator of the same elements as that of the TreeSet. The elements are returned in random order from what was present in the Tree set.
Syntax:
Iterator iterate_value = Tree_Set.iterator();

Parameters: The function does not take any parameter.
Return Value: The method iterates over the elements of the Tree set and returns the values(iterators).
Below program illustrates the use of Java.util.TreeSet.iterator() method:
// Java code to illustrate iterator()import java.util.*;import java.util.TreeSet;  public class TreeSetDemo {    public static void main(String args[])    {        // Creating an empty TreeSet        TreeSet<String> set = new TreeSet<String>();          // Use add() method to add elements into the Set        set.add("Welcome");        set.add("To");        set.add("Geeks");        set.add("4");        set.add("Geeks");          // Displaying the TreeSet        System.out.println("TreeSet: " + set);          // Creating an iterator        Iterator value = set.iterator();          // Displaying the values after iterating through the set        System.out.println("The iterator values are: ");        while (value.hasNext()) {            System.out.println(value.next());        }    }}
TreeSet: [4, Geeks, To, Welcome]
The iterator values are: 
4
Geeks
To
Welcome

Java - util package
Java-Collections
Java-Functions
java-treeset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
Python | How to get unique elements in nested tuple

21 Nov, 2019
Sometimes, while working with tuples, we can have a problem in which we have nested tuples and we need to extract elements that occur singly, i.e are elementary. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this problem can be solved.
Method #1 : Using nested loop + set()The above 2 functionalities can be used to solve this particular problem. In this, we iterate each nested tuple and add to set if element has occurred for first time and check for each element before adding.
# Python3 code to demonstrate working of# Unique elements in nested tuple# Using nested loop + set()  # initialize listtest_list = [(3, 4, 5), (4, 5, 7), (1, 4)]  # printing original list print("The original list : " + str(test_list))  # Unique elements in nested tuple# Using nested loop + set()res = []temp = set()for inner in test_list:        for ele in inner:            if not ele in temp:                temp.add(ele)                res.append(ele)  # printing resultprint("Unique elements in nested tuples are : " + str(res))
The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Unique elements in nested tuples are : [3, 4, 5, 7, 1]

 
Method #2 : Using set() + from_iterable()The combo of above functionalities can be used to solve this. This is done is 2 steps, first, we flatten the nested list and then find distincts using set().
# Python3 code to demonstrate working of# Unique elements in nested tuple# Using from_iterable() + set()from itertools import chain  # initialize listtest_list = [(3, 4, 5), (4, 5, 7), (1, 4)]  # printing original list print("The original list : " + str(test_list))  # Unique elements in nested tuple# Using from_iterable() + set()res = list(set(chain.from_iterable(test_list)))  # printing resultprint("Unique elements in nested tuples are : " + str(res))
The original list : [(3, 4, 5), (4, 5, 7), (1, 4)]
Unique elements in nested tuples are : [1, 3, 4, 5, 7]

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary