code-rag-bench/online-tutorials huggingface dataset:
Backward iteration in Python

04 Jul, 2022
The iteration of numbers is done by looping techniques in Python. There are many techniques in Python which facilitate looping. Sometimes we require to perform the looping backward and having shorthands to do so can be quite useful. Let’s discuss certain ways in which this can be done.
Method #1 : Using reversed() The simplest way to perform this is to use the reversed function for the for loop and the iteration will start occurring from the rear side than the conventional counting. 
Python3
# Python3 code to demonstrate# backward iteration# using reversed() # Initializing number from which# iteration beginsN = 6 # using reversed() to perform the back iterationprint ("The reversed numbers are : ", end = "")for num in reversed(range(N + 1)) :    print(num, end = " ")
The reversed numbers are : 6 5 4 3 2 1 0 
 Method #2 : Using range(N, -1, -1) This particular task can also be performed using the conventional range function which, if provided with the third argument performs the skip and second argument is used to start from backwards. 
Python3
# Python3 code to demonstrate# backward iteration# using range(N, -1, -1) # Initializing number from which# iteration beginsN = 6 # using reversed() to perform the back iterationprint ("The reversed numbers are : ", end = "")for num in range(N, -1, -1) :    print(num, end = " ")
The reversed numbers are : 6 5 4 3 2 1 0 
Method#3: Using slice syntax This particular task can also be performed using the slice syntax which, is used for reversing the list. We used it for reversing the range class in the for loop then we perform the backward iteration.
Python3
# # Python3 code to demonstrate# # backward iteration# # using slice syntax # # Initializing number from which# # iteration beginsN = 6  # Using slice syntax perform the backward iterationk = range(N+1)[::-1]print("The reversed numbers are : ",end='')for i in k:    print(i, end=' ')
The reversed numbers are : 6 5 4 3 2 1 0 
satyam00so
shabankhn002
Python loop-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
Python String | replace()
How to Install PIP on Windows ?
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
GATE | GATE-CS-2003 | Question 21 - GeeksforGeeks

15 Nov, 2018
Consider the following graph,
Among the following sequences:
(I) a b e g h f 
(II) a b f e h g
(III) a b f h g e 
(IV) a f g h b e  
Which are depth first traversals of the above graph?(A) I, II and IV only(B) I and IV only(C) II, III and IV only(D) I, III and IV onlyAnswer: (D)Explanation: DFS of a graph
1) Visits a node. 
2) Do following for every unvisited adjacent.
   a) Completely explores all vertices through current 
      adjacent using recursive call to DFS.

There can be any DFS possible as we may pick different vertices as starting points and we may pick adjacents in different orders.
(i) a b e g h f [Visit a, explore all adjacents through b, and so on..]. In this b’s adjacent e is picked first(iii) a b f h g e [Visit a, explore all adjacents through b, and so on..]. In this b’s adjacent f is picked first(iv) a f g h b e [Visit a, explore all adjacents through f, and so on..]. In this f’s adjacent g is picked first
(ii) a b f e h g can not be an answer as e is visited after f [e is not an adjacent of f and all adjcents of f are not explored yet]Quiz of this Question
clintra
GATE-CS-2003
GATE-GATE-CS-2003
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
Create a Bar chart using Recharts in ReactJS - GeeksforGeeks

27 Jul, 2021

Introduction: Rechart JS is a library that is used for creating charts for React JS. This library is used for building Line charts, Bar charts, Pie charts, etc, with the help of React and D3 (Data-Driven Documents).  
To create Bar Chart using Recharts, we create a dataset with x and y coordinate details. Then we define the bars using bar element with dataKey property which will have the data of the dataset created and then we create a cartesian grid and both axes using data coordinates.
Creating React Application And Installing Module:

Step 1: Create a React application using the following command.
npx create-react-app foldername

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 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 required modules using the following command.
npm install --save recharts

Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save recharts
Project Structure: It will look like the following.
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 { BarChart, Bar, CartesianGrid, XAxis, YAxis } from 'recharts'; 
  
  
const App = () => { 
  
// Sample data 
const data = [ 
  {name: 'Geeksforgeeks', students: 400}, 
  {name: 'Technical scripter', students: 700}, 
  {name: 'Geek-i-knack', students: 200}, 
  {name: 'Geek-o-mania', students: 1000} 
]; 
  
  
return ( 
<BarChart width={600} height={600} data={data}> 
    <Bar dataKey="students" fill="green" /> 
    <CartesianGrid stroke="#ccc" /> 
    <XAxis dataKey="name" /> 
    <YAxis /> 
  </BarChart> 
); 
} 
  
export default App; 






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:
Output

React-Questions


Recharts


JavaScript


ReactJS


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
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
How to Use the JavaScript Fetch API to Get Data?
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
How to pass data from child component to its parent in ReactJS ?
Create a Responsive Navbar using ReactJS
How to pass data from one component to other component in ReactJS ?
Fibonacci Iterative Program in C

RecursionDemo.c
#include <stdio.h>

int factorial(int n) {
   //base case
   if(n == 0) {
      return 1;
   } else {
      return n * factorial(n-1);
   }
}

int fibbonacci(int n) {
   if(n == 0) {
      return 0;
   } else if(n == 1) {
      return 1;
   } else {
      return (fibbonacci(n-1) + fibbonacci(n-2));
   }
}

int main() {
   int n = 5;
   int i;
	
   printf("Factorial of %d: %d\n" , n , factorial(n));
   printf("Fibbonacci of %d: " , n);
	
   for(i = 0;i < n;i++) {
      printf("%d ",fibbonacci(i));
   }
}
If we compile and run the above program, it will produce the following result −
Factorial of 5: 120
Fibbonacci of 5: 0 1 1 2 3


    42 Lectures 
     1.5 hours 

 Ravi Kiran

    141 Lectures 
     13 hours 

 Arnab Chakraborty

    26 Lectures 
     8.5 hours 

 Parth Panjabi

    65 Lectures 
     6 hours 

 Arnab Chakraborty

    75 Lectures 
     13 hours 

 Eduonix Learning Solutions

    64 Lectures 
     10.5 hours 

 Eduonix Learning Solutions
 Print
 Add Notes
 Bookmark this page
iOS - Labels

Labels are used for displaying static content, which consists of a single line or multiple lines.
textAlignment
textColor
text
numberOflines
lineBreakMode
-(void)addLabel {
   UILabel *aLabel = [[UILabel alloc]initWithFrame:
   CGRectMake(20, 200, 280, 80)];
   aLabel.numberOfLines = 0;
   aLabel.textColor = [UIColor blueColor];
   aLabel.backgroundColor = [UIColor clearColor];
   aLabel.textAlignment = UITextAlignmentCenter;
   aLabel.text = @"This is a sample text\n of multiple lines.
   here number of lines is not limited.";
   [self.view addSubview:aLabel];
}
Update viewDidLoad in ViewController.m as follows −
- (void)viewDidLoad {
   [super viewDidLoad];
   
   //The custom method to create our label is called
   [self addLabel];
   // Do any additional setup after loading the view, typically from a nib.
}
When we run the application we'll get the following output −

    23 Lectures 
     1.5 hours 

 Ashish Sharma

    9 Lectures 
     1 hours 

 Abhilash Nelson

    14 Lectures 
     1.5 hours 

 Abhilash Nelson

    15 Lectures 
     1.5 hours 

 Abhilash Nelson

    10 Lectures 
     1 hours 

 Abhilash Nelson

    69 Lectures 
     4 hours 

 Frahaan Hussain
 Print
 Add Notes
 Bookmark this page
What is Memory Leak? How can we avoid? - GeeksforGeeks

01 Aug, 2021
Memory leak occurs when programmers create a memory in heap and forget to delete it. 
The consequences of memory leak is that it reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down vastly .
Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate. 
c
/* Function with memory leak */#include <stdlib.h> void f(){   int *ptr = (int *) malloc(sizeof(int));    /* Do some work */    return; /* Return without freeing ptr*/}
To avoid memory leaks, memory allocated on heap should always be freed when no longer needed. 
c
/* Function without memory leak */#include <stdlib.h>; void f(){   int *ptr = (int *) malloc(sizeof(int));    /* Do some work */    free(ptr);   return;}
arora_hritik
C-Dynamic Memory Allocation
Articles
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
Mutex vs Semaphore
Time Complexity and Space Complexity
SQL | GROUP BY
SQL | Views
Arrays in C/C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++
Swapping two numbers using template function in C++ - GeeksforGeeks

27 Dec, 2021
A significant benefit of object-oriented programming is the reusability of code which eliminates redundant coding. An important feature of C++ is called templates. Templates support generic programming, which allows to development of reusable software components such as functions, classes, etc., supporting different data types in a single framework.
A template is a simple and yet very powerful tool in C++. The simple idea is to pass data type as a parameter so that we don’t need to write the same code for different data types. For example, a software company may need sort() for different data types. Rather than writing and maintaining the multiple codes, we can write one sort() and pass data type as a parameter. The templates declared for functions are called function templates and those declared for classes are called class templates.
This article focuses on discussing how to use a function template to swap two numbers in C++.
Function Templates
There are several functions of considerable importance which have to be used frequently with different data types. The limitation of such functions is that they operate only on a particular data type. It can be overcome by defining that function as a function template or a generic function. A function template specifies how an individual function can be constructed.
Syntax:
template <class T, ...... >returntype FuncName (arguments){    // body of template function    ...........         ............}
Below is the C++ program to implement the function templates to swap two numbers.
C++
// C++ program to implement// function templates#include <iostream>using namespace std;  // Function template to swap// two numberstemplate <class T>int swap_numbers(T& x, T& y){    T t;    t = x;    x = y;    y = t;    return 0;}  // Driver codeint main(){    int a, b;    a = 10, b = 20;      // Invoking the swap()    swap_numbers(a, b);    cout << a << " " << b << endl;    return 0;}
20 10
CPP-Functions
Swap-Program
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
Iterative Letter Combinations of a Phone Number
Return by reference in C++ with Examples
How to sort an Array in descending order using STL in C++?
Setting up Sublime Text for C++ Competitive Programming Environment
Why it is important to write "using namespace std" in C++ program?
How to get the second-to-last element of a list in Python?

Python sequence, including list object allows indexing. Any element in list can be accessed using zero based index. If index is a negative number, count of index starts from end.  As we want second to last element in list, use -2 as index.
>>> L1=[1,2,3,4,5]
>>> print (L1[-2])
4
exp() function C++

The C / C++ library function double exp(double x) returns the value of e raised to the
xth power. Following is the declaration for exp() function.
double exp(double x)
The parameter is a floating point value. And this function returns the exponential
value of x.
 Live Demo
#include <iostream>
#include <cmath>
using namespace std;
int main () {
   double x = 0;
   cout << "The exponential value of " << x << " is " << exp(x) << endl;
   cout << "The exponential value of " << x+1 << " is " << exp(x+1) <<
   endl;
      cout << "The exponential value of " << x+2 << " is " << exp(x+2) <<
   endl;
   return(0);
}
The exponential value of 0 is 1
The exponential value of 1 is 2.71828
The exponential value of 2 is 7.38906
MomentJS - Subtract

Just like the add method, subtract allows to subtract days, months, hours, minutes, seconds etc., from a given date.
moment().subtract(Number, String);
moment().subtract(Duration);
moment().subtract(Object);

Observe the following example that shows how to use the subtract method −
<html>
   <head>
      <title>MomentJS - Subtract Method</title>
      <script type="text/JavaScript"    src="https://MomentJS.com/downloads/moment.js"></script>
      <style>
         div {
            border: solid 1px #ccc;
            padding:10px;
            font-family: "Segoe UI",Arial,sans-serif;
            width: 75%;
         }
      </style>
   </head>
   <body>
      <h1>MomentJS - Subtract Method</h1>
      <div style="font-size:25px" id="currentdate"></div>
      <br/>
      <br/>
      <div style="font-size:25px" id="changeddate"></div>
      <br/>
      <br/>
      <div style="font-size:25px" id="changeddate1"></div>
      <br/>
      <br/>
      <div style="font-size:25px" id="changeddate2"v</div>
      <script type="text/JavaScript">
         var day = moment();
         document.getElementById("currentdate").innerHTML = "Current Date: " + day._d;
         var changeddate = moment().subtract(5, 'days').subtract(2, 'months');
         document.getElementById("changeddate").innerHTML = "Subtracting 5 days and 2 month using chaining method: " + changeddate._d;
         var changeddate1 = moment().subtract({ days: 5, months: 2 });
         document.getElementById("changeddate1").innerHTML = "Subtracting 5 days and 2 month using object method: " + changeddate1._d;
         var duration = moment.duration({ 'days': 10 });
         var changeddate2 = moment([2017, 10, 15]).subtract(duration);
         document.getElementById("changeddate2").innerHTML = "Subtracting 10 days from given date using duration method: " + changeddate2._d;
      </script>
   </body>
</html>
To subtract days, months from the date we have done following −
//chaining subtract method
var changeddate = moment().subtract(5, 'days').subtract(2, 'months');

// subtract object method
var changeddate1 = moment().subtract({ days: 5, months: 2 });

//using duration in subract method
var duration = moment.duration({ 'days': 10 });
var changeddate2 = moment([2017, 10, 15]).subtract(duration);
The output for the same in shown in the above example.
 Print
 Add Notes
 Bookmark this page
C | Structure & Union | Question 10 - GeeksforGeeks

28 Jun, 2021
Predict the output of following C program
#include<stdio.h>struct Point{  int x, y, z;};  int main(){  struct Point p1 = {.y = 0, .z = 1, .x = 2};  printf("%d %d %d", p1.x, p1.y, p1.z);  return 0;}
(A) Compiler Error(B) 2 0 1(C) 0 1 2(D) 2 1 0Answer: (B)Explanation: Refer designated Initialization discussed here.Quiz of this Question
C-Structure & Union
Structure & Union
C Language
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
fork() in C
Function Pointer in C
TCP Server-Client implementation in C
Enumeration (or enum) in C
Data Types in C
Compiling a C program:- Behind the Scenes
Operator Precedence and Associativity in C
Output of C programs | Set 64 (Pointers)
C | Structure & Union | Question 10
C | File Handling | Question 1
Powershell - Brackets

Powershell supports three types of brackets.
Parenthesis brackets. − () 

Parenthesis brackets. − () 
Braces brackets. − {} 

Braces brackets. − {} 
Square brackets. − [] 

Square brackets. − [] 
This type of brackets is used to
pass arguments
pass arguments
enclose multiple set of instructions
enclose multiple set of instructions
resolve ambiguity
resolve ambiguity
create array
create array
> $array = @("item1", "item2", "item3")
 
> foreach ($element in $array) { $element }
item1
item2
item3
This type of brackets is used to
enclose statements
enclose statements
block commands
block commands
$x = 10

if($x -le 20){
   write-host("This is if statement")
}
This will produce the following result −
This is if statement.

This type of brackets is used to
access to array
access to array
access to hashtables
access to hashtables
filter using regular expression
filter using regular expression
> $array = @("item1", "item2", "item3")
 
> for($i = 0; $i -lt $array.length; $i++){ $array[$i] }
item1
item2
item3
 
>Get-Process [r-s]*
 Handles    NPM(K)     PM(K)    WS(K)   VM(M)   CPU(s)     Id    ProcessName
-------    ------     -----     -----   -----   ------     --    -----------  
    320        72     27300     33764    227     3.95    4028    SCNotification 
   2298        77     57792     48712    308             2884    SearchIndexer
Program for n-th even number

25 Oct, 2018
Given a number n, print the nth even number. The 1st even number is 2, 2nd is 4 and so on.
Examples:
Input : 3
Output : 6
First three even numbers are 2, 4, 6, ..

Input : 5
Output : 10
First five even numbers are 2, 4, 6, 8, 19..

The nth even number is given by the formula 2*n.
C++
Java
Python3
C#
PHP
// CPP program to find the nth even number#include <bits/stdc++.h>using namespace std;  // Function to find the nth even numberint nthEven(int n){    return (2 * n);}  // Driver codeint main(){    int n = 10;    cout << nthEven(n);    return 0;}
// JAVA program to find the nth EVEN number  class GFG{    // Function to find the nth odd number    static int nthEven(int n)    {        return (2 * n);    }          // Driver code    public static void main(String [] args)    {        int n = 10;        System.out.println(nthEven(n));              }}  // This code is contributed// by ihritik
# Python 3 program to find the # nth odd number  #  Function to find the nth Even numberdef nthEven(n):      return (2 * n)      # Driver codeif __name__=='__main__':    n = 10    print(nthEven(n))  # This code is contributed# by ihritik
// C# program to find the // nth EVEN numberusing System;  class GFG{// Function to find the// nth odd numberstatic int nthEven(int n){    return (2 * n);}  // Driver codepublic static void Main(){    int n = 10;    Console.WriteLine(nthEven(n));}}  // This code is contributed// by anuj_67
<?php// PHP program to find the// nth even number  // Function to find the// nth even numberfunction nthEven($n){    return (2 * $n);}  // Driver code$n = 10;echo nthEven($n);  // This code is contributed// by anuj_67?>
Output:
20
ihritik
vt_m
series
C++
C++ Programs
Mathematical
School Programming
Mathematical
series
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL
Substring in C++
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
Ruby | Time now() function

07 Jan, 2020
The now() is an inbuilt method in Ruby returns the current time.
Syntax: time.now()
Parameters: The function accepts no parameter
Return Value: It returns the current time
Example 1:
# Ruby code for now() method  # Include Timerequire 'time'  # Declaring time a = Time.now()  # Prints current time puts a
Output:
2019-08-27 08:26:42 +0000

Example 2:
# Ruby code for now() method  # Include Timerequire 'time'  # Declaring time a = Time.now()  # Prints current time puts a
Output:
2019-08-27 08:26:42 +0000

Ruby Time-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | unless Statement and unless Modifier
Ruby | Data Types
Python | Converting all strings in list to integers

29 Nov, 2018
Interconversion between data types is facilitated by python libraries quite easily. But the problem of converting the entire list of string to integers is quite common in development domain. Let’s discuss few ways to solve this particular problem.
Method #1 : Naive Method
This is most generic method that strikes any programmer while performing this kind of operation. Just looping over whole list and convert each of the string of list to int by type casting.
# Python3 code to demonstrate # converting list of strings to int# using naive method   # initializing list test_list = ['1', '4', '3', '6', '7']  # Printing original listprint ("Original list is : " + str(test_list))  # using naive method to# perform conversionfor i in range(0, len(test_list)):    test_list[i] = int(test_list[i])        # Printing modified list print ("Modified list is : " + str(test_list))
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

 Method #2 : Using list comprehension
This is just a kind of replica of the above method, just implemented using list comprehension, kind of shorthand that a developer looks for always. It saves time and complexity of coding a solution.
# Python3 code to demonstrate # converting list of strings to int# using list comprehension  # initializing list test_list = ['1', '4', '3', '6', '7']  # Printing original listprint ("Original list is : " + str(test_list))  # using list comprehension to# perform conversiontest_list = [int(i) for i in test_list]        # Printing modified list print ("Modified list is : " + str(test_list))
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

 Method #3 : Using map()
This is the most elegant, pythonic and recommended method to perform this particular task. This function is exclusively made for this kind of task and should be used to perform them.
# Python3 code to demonstrate # converting list of strings to int# using map()  # initializing list test_list = ['1', '4', '3', '6', '7']  # Printing original listprint ("Original list is : " + str(test_list))  # using map() to# perform conversiontest_list = list(map(int, test_list))        # Printing modified list print ("Modified list is : " + str(test_list))
Original list is : ['1', '4', '3', '6', '7']
Modified list is : [1, 4, 3, 6, 7]

Python list-programs
python-list
Python
python-list
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
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
numpy.invert() in Python

29 Nov, 2018
numpy.invert() function is used to Compute the bit-wise Inversion of an array element-wise. It computes the bit-wise NOT of the underlying binary representation of the integers in the input arrays.
For signed integer inputs, the two’s complement is returned. In a two’s-complement system negative numbers are represented by the two’s complement of the absolute value.
Syntax : numpy.invert(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, ufunc ‘invert’)
Parameters :x : [array_like] Input array.out : [ndarray, optional] A location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.**kwargs : Allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function.where : [array_like, optional] True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone.
Return : [ndarray or scalar] Result. This is a scalar if x is scalar.
Code #1 : Working
# Python program explaining# invert() function  import numpy as geekin_num = 10print ("Input  number : ", in_num)    out_num = geek.invert(in_num) print ("inversion of 10 : ", out_num) 
Output :
Input  number :  10
inversion of 10 :  -11

 Code #2 :
# Python program explaining# invert() function  import numpy as geek  in_arr = [2, 0, 25]print ("Input array : ", in_arr)    out_arr = geek.invert(in_arr) print ("Output array after inversion: ", out_arr) 
Output :
Input array :  [2, 0, 25]
Output array after inversion:  [ -3  -1 -26]

 Code #3 :
# Python program explaining# invert() function  import numpy as geek  in_arr = [True, False]print("Input array : ", in_arr)       out_arr = geek.invert(in_arr) print ("Output array after inversion: ", out_arr) 
Output :
Input array :  [True, False]
Output array after inversion:  [False  True]

Python numpy-Binary Operation
Python-numpy
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
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python
Draw Spiraling Star using Turtle in Python

01 Aug, 2020
Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle and methods defined in the turtle module and by using some logical loops. To draw something on the screen(cardboard) just move the turtle(pen).To move turtle(pen) there are some functions i.e forward(), backward(), etcApproach to draw a Spiraling Star of size n: 
import turtle and create a turtle instance.
Using for loop(i=0 to i<n) and repeat below stepturtle.forward(i*10)turtle.right(144)
turtle.forward(i*10)
turtle.right(144)
close the turtle instance. 
Python3
# importing turtle moduleimport turtle  # number of sidesn = 10  # creating instance of turtlepen = turtle.Turtle()  # loop to draw a sidefor i in range(n):    # drawing side of     # length i*10    pen.forward(i * 10)      # changing direction of pen     # by 144 degree in clockwise    pen.right(144)  # closing the instanceturtle.done()
Output:  
 
Python-projects
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Convert integer to string in Python
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Create a Pandas DataFrame from Lists
Check if element exists in list in Python
Python | Pandas Series.round()

12 Jun, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.When doing mathematical operations on series, many times the returned series is having decimal values and decimal values could go to upto many places. Pandas Series.round() method is used in such cases only to round of decimal values in series. 
Syntax: Series.round(decimals=0, *args, **kwargs) Parameters: decimals: Int value, specifies upto what number of decimal places the value should be rounded of, default is 0.Return type: Series with updated values
To download the data set used in following example, click here. In the following examples, the data frame used contains data of some NBA players. The image of data frame before any operations is attached below.  
Example: Since in the dataframe, there isn’t any series with decimal values more than 1 place. Hence the Salary column is divided by the Weight column first to get a series with decimal values. Since the returned series is having values with decimal upto 6 places. First a new series created by using round() method and another series new2 is created by passing a parameter of 2 to round() method to see working of this method. Before doing any operations, null rows were removed using dropna() method. 
Python3
# importing pandas moduleimport pandas as pd # making data framedata = pd.read_csv("https://media.geeksforgeeks.org/wp-content/uploads/nba.csv")   # removing null values to avoid errorsdata.dropna(inplace = True) # creating new column with divided valuesdata["New_Salary"]= data["Salary"].div(data['Weight']) # rounding of values and storing in new columndata['New']= data['New_Salary'].round() # variable for max decimal placesdec_places = 2 # rounding of values and storing in new columndata['New2']= data['New_Salary'].round(dec_places) # displaydata.head(10)
Output: As shown in the Output image, the new series is completely rounded of with no decimal values and new2 series contains decimals upto 2 places after that only.  
 
arorakashish0911
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.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python | os.path.join() method
Python OOPs Concepts
Create a Pandas DataFrame from Lists
Creating custom modules in Node.js

The node.js modules are a kind of package that contains certain functions or methods to be used by those who imports them. Some modules are present on the web to be used by developers such as fs, fs-extra, crypto, stream, etc. You can also make a package of your own and use it in your code.
exports.function_name = function(arg1, arg2, ....argN) {
   // Put your function body here...
};
Create two file with name – calc.js and index.js and copy the below code snippet.
The calc.js is the custom node module which will hold the node functions.
The index.js will import calc.js and use it in the node process.
calc.js
//Creating a custom node module
// And making different functions
exports.add = function (a, b) {
   return a + b; // Adding the numbers
};

exports.sub = function (a, b) {
   return a - b; // Subtracting the numbers
};

exports.mul = function (a, b) {
   return a * b; // Multiplying the numbers
};

exports.div = function (a, b) {
   return a / b; // Dividing the numbers
};
index.js
// Importing the custom node module with the below statement
var calculator = require('./calc');

var a = 21 , b = 67

console.log("Addition of " + a + " and " + b + " is " + calculator.add(a, b));

console.log("Subtraction of " + a + " and " + b + " is " + calculator.sub(a, b));

console.log("Multiplication of " + a + " and " + b + " is " + calculator.mul(a, b));

console.log("Division of " + a + " and " + b + " is " + calculator.div(a, b));
C:\home\node>> node index.js
Addition of 21 and 67 is 88
Subtraction of 21 and 67 is -46
Multiplication of 21 and 67 is 1407
Division of 21 and 67 is 0.31343283582089554
How to read integers from a file using BufferedReader in Java?

The BufferedReader class of Java is used to read the stream of characters from the specified source (character-input stream). The constructor of this class accepts an InputStream object as a parameter.
This class provides a method known as readLine() which reads and returns the next line from the source and returns it in String format.
The BufferedReader class doesn’t provide any direct method to read an integer from the user you need to rely on the readLine() method to read integers too. i.e. Initially you need to read the integers in string format.
The parseInt() method of the Integer class accepts a String value, parses it as a signed decimal integer and returns it.
Using this convert the read Sting value into integer and use. In short, to read integer value-form user using BufferedReader class −
Instantiate an InputStreamReader class bypassing your InputStream object as a parameter.
Instantiate an InputStreamReader class bypassing your InputStream object as a parameter.
Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a parameter.
Then, create a BufferedReader, bypassing the above obtained InputStreamReader object as a parameter.
Now, read integer value from the current reader as String using the readLine() method.
Now, read integer value from the current reader as String using the readLine() method.
Then parse the read String into an integer using the parseInt() method of the Integer class.
Then parse the read String into an integer using the parseInt() method of the Integer class.
The following Java program demonstrates how to read integer data from the user using the BufferedReader class.
 Live Demo
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class Employee{
   String name;
   int id;
   int age;
   Employee(String name, int age, int id){
      this.name = name;
      this.age = age;
      this.id = id;
   }
   public void displayDetails(){
      System.out.println("Name: "+this.name);
      System.out.println("Age: "+this.age);
      System.out.println("Id: "+this.id);
   }
}
public class ReadData {
   public static void main(String args[]) throws IOException {
      BufferedReader reader =new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter your name: ");
      String name = reader.readLine();
      System.out.println("Enter your age: ");
      int age = Integer.parseInt(reader.readLine());
      System.out.println("Enter your Id: ");
      int id = Integer.parseInt(reader.readLine());
      Employee std = new Employee(name, age, id);
      std.displayDetails();
   }
}
Enter your name:
Krishna
Enter your age:
25
Enter your Id:
1233
Name: Krishna
Age: 25
Id: 1233
How can I display an image using Pillow in Tkinter?

Python provides Pillow Package (PIL) to process and load the images in the application. An image can be loaded using the inbuilt Image.open("image location") method. Further, we can use a Label widget to display the Image in the window.
#Import tkinter library
from tkinter import *
from PIL import Image,ImageTk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("750x550")
#Load the image
img= Image.open("tutorialspoint.jpg")
#Convert To photoimage
tkimage= ImageTk.PhotoImage(img)
#Display the Image
label=Label(win,image=tkimage)
label.pack()
win.mainloop()
Running the above code will display an image in the window.
Before executing the code, make sure you have the image in the same project directory, or provide the absolute path of the image location.
How to get first day of week in PHP?

To get the first day of the week in PHP, the code is as follows −
 Live Demo
<?php
   $res = date('l - d/m/Y', strtotime("this week"));
   echo "First day = ", $res;
?>
This will produce the following output −
First day = Monday - 09/12/2019
Let us now see another example −
 Live Demo
<?php
   echo "Displaying Sunday as first day of a week...\n";
   $res = date('l - d/m/Y', strtotime("sunday 0 week"));
   echo "First day (next week) = ", $res;
?>
This will produce the following output −
Displaying Sunday as first day of a week...
First day (next week) = Sunday - 15/12/2019
C library function - getc()

The C library function int getc(FILE *stream) gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream.
Following is the declaration for getc() function.
int getc(FILE *stream)
stream − This is the pointer to a FILE object that identifies the stream on which the operation is to be performed.
stream − This is the pointer to a FILE object that identifies the stream on which the operation is to be performed.
This function returns the character read as an unsigned char cast to an int or EOF on end of file or error.
The following example shows the usage of getc() function.
#include<stdio.h>

int main () {
   char c;

   printf("Enter character: ");
   c = getc(stdin);
   printf("Character entered: ");
   putc(c, stdout);
   
   return(0);
}
Let us compile and run the above program that will produce the following result −
Enter character: a
Character entered: a


    12 Lectures 
     2 hours 

 Nishant Malik

    12 Lectures 
     2.5 hours 

 Nishant Malik

    48 Lectures 
     6.5 hours 

 Asif Hussain

    12 Lectures 
     2 hours 

 Richa Maheshwari

    20 Lectures 
     3.5 hours 

 Vandana Annavaram

    44 Lectures 
     1 hours 

 Amit Diwan
 Print
 Add Notes
 Bookmark this page
What are Python coding standards/best practices?

You can use the PEP8 guide as a holy grail. Almost all python world uses this guide to write clean understandable and standard python code. This is available as an extension as a linter for all modern text editors. You can check it out at  http://www.python.org/dev/peps/pep-0008/
Properly Structure your folders. All projects need proper structuring. This helps organize code better. Python has an opinionated folder structure that you should use.
README.rst
LICENSE
setup.py
requirements.txt
sample/__init__.py
sample/core.py
sample/helpers.py
docs/conf.py
docs/index.rst
tests/test_basic.py
tests/test_advanced.py
Use doctests. The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown. This is one of the best and most useful peices of the language and you should use it to the max. This allows doing TDD.
Use PyPi to get all your modules. PyPi is a central repository of python modules. Instead of building your own packages, use pip to install modules off of Pypi.
Write Pythonic code by adhering to python idioms. This takes some getting used to but can help you go a long way. You can read more about idiomatic python onhttp://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html
Type Inference in C++ (auto and decltype)

In this tutorial, we will be discussing a program to understand Type interference in C++ (auto and decltype).
In case of auto keyword, the type of the variable is defined from the type of its initializer. Further with decltype, it lets you extract the type of variable from the called element.
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
   auto x = 4;
   auto y = 3.37;
   auto ptr = &x;
   cout << typeid(x).name() << endl
      << typeid(y).name() << endl
      << typeid(ptr).name() << endl;
   return 0;
}
i
d
Pi
 Live Demo
#include <bits/stdc++.h>
using namespace std;
int fun1() { return 10; }
char fun2() { return 'g'; }
int main(){
   decltype(fun1()) x;
   decltype(fun2()) y;
   cout << typeid(x).name() << endl;
   cout << typeid(y).name() << endl;
   return 0;
}
i
c
Scala - Functions Call-by-Name

Typically, parameters to functions are by-value parameters; that is, the value of the parameter is determined before it is passed to the function. But what if we need to write a function that accepts as a parameter an expression that we don't want evaluated until it's called within our function? For this circumstance, Scala offers call-by-name parameters.
A call-by-name mechanism passes a code block to the call and each time the call accesses the parameter, the code block is executed and the value is calculated. Here, delayed prints a message demonstrating that the method has been entered. Next, delayed prints a message with its value. Finally, delayed returns ‘t’.
The following program shows how to implement call–by–name.
object Demo {
   def main(args: Array[String]) {
        delayed(time());
   }

   def time() = {
      println("Getting time in nano seconds")
      System.nanoTime
   }
   def delayed( t: => Long ) = {
      println("In delayed method")
      println("Param: " + t)
   }
}
Save the above program in Demo.scala. The following commands are used to compile and execute this program.
\>scalac Demo.scala
\>scala Demo

In delayed method                                                             
Getting time in nano seconds                                                  
Param: 2027245119786400 


    82 Lectures 
     7 hours 

 Arnab Chakraborty

    23 Lectures 
     1.5 hours 

 Mukund Kumar Mishra

    52 Lectures 
     1.5 hours 

 Bigdata Engineer

    76 Lectures 
     5.5 hours 

 Bigdata Engineer

    69 Lectures 
     7.5 hours 

 Bigdata Engineer

    46 Lectures 
     4.5 hours 

 Stone River ELearning
 Print
 Add Notes
 Bookmark this page
Statistical - TRIMMEAN Function

The TRIMMEAN function returns the mean of the interior of a data set. TRIMMEAN calculates the mean taken by excluding a percentage of data points from the top and bottom tails of a data set. You can use this function when you wish to exclude outlying data from your analysis.
TRIMMEAN (array, percent)

TRIMMEAN rounds the number of excluded data points down to the nearest multiple of 2. If percent = 0.1, 10 percent of 30 data points equals 3 points. For symmetry, TRIMMEAN excludes a single value from the top and bottom of the data set.
TRIMMEAN rounds the number of excluded data points down to the nearest multiple of 2. If percent = 0.1, 10 percent of 30 data points equals 3 points. For symmetry, TRIMMEAN excludes a single value from the top and bottom of the data set.
If percent < 0 or percent > 1, TRIMMEAN returns the #NUM! error value.
If percent < 0 or percent > 1, TRIMMEAN returns the #NUM! error value.
If the supplied array is empty, TRIMMEAN returns the #NUM! error value.
If the supplied array is empty, TRIMMEAN returns the #NUM! error value.
If the percent is non-numeric, TRIMMEAN returns the #VALUE! error value.
If the percent is non-numeric, TRIMMEAN returns the #VALUE! error value.
Excel 2007, Excel 2010, Excel 2013, Excel 2016

    296 Lectures 
     146 hours 

 Arun Motoori

    56 Lectures 
     5.5 hours 

 Pavan Lalwani

    120 Lectures 
     6.5 hours 

 Inf Sid

    134 Lectures 
     8.5 hours 

 Yoda Learning

    46 Lectures 
     7.5 hours 

 William Fiset

    25 Lectures 
     1.5 hours 

 Sasha Miller
 Print
 Add Notes
 Bookmark this page
Why do we use import statement in Java? Where it should be included in the class?

The import statement can be used to import an entire package or sometimes import certain classes and interfaces inside the package. The import statement is written before the class definition and after the package statement(if there is any). Also, the import statement is optional.
A program that demonstrates this in Java is given as follows:
 Live Demo
import java.util.LinkedList;

public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Apple");
      l.add("Mango");
      l.add("Cherry");
      l.add("Orange");
      l.add("Pear");
      System.out.println("The LinkedList is: " + l);
   }
}
The LinkedList is: [Apple, Mango, Cherry, Orange, Pear]
Now let us understand the above program.
The LinkedList class is available in the java.util package. The import statement is used to import it. Then LinkedList l is created. LinkedList.add() is used to add a elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows:
LinkedList<String> l = new LinkedList<String>();
l.add("Apple");
l.add("Mango");
l.add("Cherry");
l.add("Orange");
l.add("Pear");
System.out.println("The LinkedList is: " + l);
How to find the inner height and inner width of a browser window in JavaScript?

Javascript window object simply represents the browser window. This method is supported by all browsers. To get the inner height and inner width this method has provided some properties such as window.innerHeight and window.innerwidth respectively. Using these properties, it is easy to find the height and width of a browser window. Let's discuss them individually.
In the following example, using the property window.innerWidth, the inner width of the browser window is found out and the result is displayed in the output. It gives the result in pixels.
Live Demo
<html>
<body>
<p id="width"></p>
<script>
   var w = window.innerWidth
   var x = document.getElementById("width");
   x.innerHTML = "Browser inner window width: " + w ;
</script>
</body>
</html>
Browser inner window width: 598
In the following example, using the property window.innerheight, the inner height of the browser window is found out and the result is displayed in the output. It gives the result in pixels.
 Live Demo
<html>
<body>
<p id="height"></p>
<script>
   var h = window.innerHeight
   var x = document.getElementById("height");
   x.innerHTML = "Browser inner window height: " + h ;
</script>
</body>
</html>
Browser inner window height: 477;