code-rag-bench/online-tutorials huggingface dataset:
How to get the indices of the sorted array using NumPy in Python? - GeeksforGeeks

05 Sep, 2020
We can get the indices of the sorted elements of a given array with the help of argsort() method. This function is used to perform an indirect sort along the given axis using the algorithm specified by the kind keyword. It returns an array of indices of the same shape as arr that that would sort the array.
Syntax:
numpy.argsort(arr, axis=-1, kind=’quicksort’, order=None)
Example 1:
Python3
import numpy as np    # Original arrayarray = np.array([10, 52, 62, 16, 16, 54, 453])print(array)  # Indices of the sorted elements of a # given arrayindices = np.argsort(array)print(indices)
Output:
[ 10  52  62  16  16  54 453]
[0 3 4 1 5 2 6]

Example 2:
Python3
import numpy as np    # Original arrayarray = np.array([1, 2, 3, 4, 5])print(array)  # Indices of the sorted elements of # a given arrayindices = np.argsort(array)print(indices)
Output:
[1 2 3 4 5]
[0 1 2 3 4]

Example 3:
Python3
import numpy as np     # input 2d array in_arr = np.array([[ 2, 0, 1], [ 5, 4, 3]]) print ("Input array :\n", in_arr)      # output sorted array indices out_arr1 = np.argsort(in_arr, kind ='mergesort', axis = 0) print ("\nOutput sorteded array indices along axis 0:\n", out_arr1)   out_arr2 = np.argsort(in_arr, kind ='heapsort', axis = 1) print ("\nOutput sorteded array indices along axis 1:\n", out_arr2) 
Output:
Input array :
 [[2 0 1]
 [5 4 3]]

Output sorteded array indices along axis 0:
 [[0 0 0]
 [1 1 1]]

Output sorteded array indices along axis 1:
 [[1 2 0]
 [2 1 0]]

Python numpy-Sorting Searching
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 ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
C Quiz - 101 - GeeksforGeeks

28 Sep, 2015
int fun(int n);

int main()
{
    // ptr is a pointer to function fun()
    int (*ptr)(int ) = fun;

    // fun() called using pointer 
    (*ptr)(3);
    return 0;
}

int fun(int n)
{
  for(;n > 0; n--)
    printf("GeeksQuiz ");
}

First and foremost, continue can be used in any of the 3 loops in C. In case of “for” loop, when continue is hit, the next expression to be executed would be i++ followed by controlling expression (i.e. i < 10). In case of “while” loop, when continue is hit, the next expression to be executed would be controlling expression (i.e. i < 10). In case of “do-while” loop, when continue is hit, the next expression to be executed would be controlling expression (i.e. i < 10). That’s why “while” and “do-while” loops would behave exactly same but not the “for” loop. Just to re-iterate, i++ would be executed in “for” loop when continue is hit.
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Comments
Old Comments
Must Do Coding Questions for Product Based Companies
How to set background images in ReactJS ?
BigInt (BIG INTEGERS) in C++ with Example
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
SQLAlchemy Core - Creating Table
How to Alter Multiple Columns at Once in SQL Server?
How to Replace Values in Column Based on Condition in Pandas?
How to Fix: SyntaxError: positional argument follows keyword argument in Python
C Program to read contents of Whole File
How to import a class from another file in Python ? - GeeksforGeeks

30 Apr, 2021

In this article, we will see How to import a class from another file in Python.
Import in Python is analogous to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is that the commonest way of invoking the import machinery, but it’s not the sole way. The import statement consists of the import keyword alongside the name of the module.
Here we have created a class named GFG which has two methods: add() and sub(). Apart from that an explicit function is created named method() in the same python file. This file will act as a module for the main python file.
Python
 

 
 










class GFG: 
      
    # methods 
    def add(self, a, b): 
        return a + b 
    def sub(self, a, b): 
        return a - b 
  
# explicit function       
def method(): 
    print("GFG")






Let the name of the above python file be module.py.
It’s now time to import the module and start trying out our new class and functions. Here, we will import a module named module and create the object of the class named GFG inside that module. Now, we can use its methods and variables.
Python
 

 
 










import module 
   
# Created a class object 
object = module.GFG() 
   
# Calling and printing class methods 
print(object.add(15,5)) 
print(object.sub(15,5)) 
   
# Calling the function 
module.method()






Output:
20
10
GFG
Importing the module as we mentioned earlier will automatically bring over every single class and performance within the module into the namespace. If you’re only getting to use one function, you’ll prevent the namespace from being cluttered by only importing that function as demonstrated in the program below:
Python
 

 
 










# import module 
from module import method 
   
# call method from that module   
method()






Output:
GFG
In this way, we can use class to import from another file.

Picked


python-modules


Python

Writing code in comment? 
                                    Please use ide.geeksforgeeks.org, 
                                    generate link and share the link here.
                                
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
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
Defaultdict in Python
Python OOPs Concepts
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Python | Convert Tuple to integer - GeeksforGeeks

25 Nov, 2019
Sometimes, while working with records, we can have a problem in which we need to convert the data records to integer by joining them. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using reduce() + lambdaThe combination of above functions can be used to perform this task. In this, we use lambda function to perform logic of conversion and reduce performs task of iteration and combining result.
# Python3 code to demonstrate working of# Convert Tuple to integer# Using reduce() + lambdaimport functools  # initialize tupletest_tuple = (1, 4, 5)  # printing original tuple print("The original tuple : " + str(test_tuple))  # Convert Tuple to integer# Using reduce() + lambdares = functools.reduce(lambda sub, ele: sub * 10 + ele, test_tuple)  # printing resultprint("Tuple to integer conversion : " + str(res))
The original tuple : (1, 4, 5)
Tuple to integer conversion : 145

 
Method #2 : Using int() + join() + map()The combination of these functions can also be used to perform this task. In this, we convert each element to string using join() and iterate using map(). At last we perform integer conversion.
# Python3 code to demonstrate working of# Convert Tuple to integer# Using int() + join() + map()  # initialize tupletest_tuple = (1, 4, 5)  # printing original tuple print("The original tuple : " + str(test_tuple))  # Convert Tuple to integer# Using int() + join() + map()res = int(''.join(map(str, test_tuple)))  # printing resultprint("Tuple to integer conversion : " + str(res))
The original tuple : (1, 4, 5)
Tuple to integer conversion : 145

Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert string dictionary to dictionary
What is PHP Output Buffering?

Output Buffering is a method to tell the PHP engine to hold the output data before sending it to the browser. As we know PHP sent the output data to the browser in pieces, but if we utilize the output buffering mechanism, the output data is stored in a variable and sent to the browser as one piece at the end of the script.
Let's demonstrate with a simple example.
 Live Demo
<?php
   ob_start();
   echo "Hello";
   $ob1 = ob_get_contents();
   echo "Tutorials Point";
   $ob2 = ob_get_contents();
   ob_end_clean();
   var_dump($ob1, $ob2);
 ?>
string(5) "Hello"
string(20) "HelloTutorials Point"
In the above example ob_get_contents() grabs all of the data gathered since we called ob_start, i.e. everything in the buffer. After that send the output data at once.
Turning on output buffering alone decreases the amount of time it takes to download and render our HTML in the browser. Hence it decreases the execution time of PHP script.
If you've ever faced messages like "Warning: Cannot modify header information - headers already sent by (output)" while setting cookies, you can solve it by Output Buffering.
jQuery | :first-child Selector

08 Sep, 2021
It is a jQuery Selector used to select every element that is the first child of its parent.Syntax:  
$(":first-child")
Return Value: It selects and returns the first child element of its parent.Example-1:  
html
<!DOCTYPE html><html><h1>  <center>    Geeks   </center>  </h1>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  </script>    <script>        $(document).ready(function() {            $("p:first-child").css(              "background-color", "green");        });    </script></head>  <body><div>      <p>Geeks for Geeks</p>        <p>jQuery</p>        <p>First Child Selector</p>  </div></body>  </html>
Output:  
Example-2:  
html
<!DOCTYPE html><html><h1>  <center>    Geeks   </center>  </h1>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">  </script>      <script>        $(document).ready(function() {            $("p:first-child").css(              "background-color", "green");        });    </script></head>  <body>    <div style="border:1px solid;">          <p>Geeks for Geeks</p>            <p>jQuery</p>      </div>    <br>      <div style="border:1px solid;">          <p>Geeks for Geeks</p>            <p>jQuery</p>            <p>First Child Selector</p>      </div>      <div>jQuery:First Child Selector</div>  </body>  </html>
Output:  
Supported Browsers:
Google Chrome 90.0+
Internet Explorer 9.0
Firefox 3.6
Safari 4.0
Opera 10.5
deepak2403
ysachin2314
jQuery-Selectors
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
JQuery | Set the value of an input text field
How to Dynamically Add/Remove Table Rows using jQuery ?
How to change selected value of a drop-down list using jQuery?
How to change the background color after clicking the button in JavaScript ?
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Node.js fs.readFileSync() Method
How to set input type date in dd-mm-yyyy format using HTML ?
Group objects by property in JavaScript

Suppose, we have an array of objects that contains data about some fruits and vegetables like this −
const arr = [
   {food: 'apple', type: 'fruit'},
   {food: 'potato', type: 'vegetable'},
   {food: 'banana', type: 'fruit'},
];
We are required to write a JavaScript function that takes in one such array.
Our function should then group the array objects based on the "type" property of the objects.
It means that all the "fruit" type objects are grouped together and the "vegetable' type grouped together separately.
The code for this will be −
const arr = [
   {food: 'apple', type: 'fruit'},
   {food: 'potato', type: 'vegetable'},
   {food: 'banana', type: 'fruit'},
];
const transformArray = (arr = []) => {
   const res = [];
   const map = {};
   let i, j, curr;
   for (i = 0, j = arr.length; i < j; i++) {
      curr = arr[i];
      if (!(curr.type in map)) {
         map[curr.type] = {type: curr.type, foods: []};
         res.push(map[curr.type]);
      };
      map[curr.type].foods.push(curr.food);
   };
   return res;
};
console.log(transformArray(arr));
And the output in the console will be −
[
   { type: 'fruit', foods: [ 'apple', 'banana' ] },
   { type: 'vegetable', foods: [ 'potato' ] }
]
Run python script from anywhere in linux

03 Nov, 2019
In Linux, there is a way to execute python files from anywhere. This can be done by typing several commands in the terminal.
Basic Shell Commands in Linux
Basics of python
At first, open the terminal and go to the home directory. To go the home directory type the following command.cd ~
cd ~
Create a folder and a python script inside that folder. Let the name of the folder be “check” and name of the script be “file1”. Type the following command to perform the above operations.mkdir check
cd check
touch file1.py

mkdir check
cd check
touch file1.py

Then type this script in the file1.pyimport osi = 1  # Write the path where to create the directoriespath ="/home / dev / test/"try:    while i<5:        os.mkdir(path+"file"+str(i))        i+= 1except OSError:    print("File creation failed !!")This script will create 4 directories in the specified path.
import osi = 1  # Write the path where to create the directoriespath ="/home / dev / test/"try:    while i<5:        os.mkdir(path+"file"+str(i))        i+= 1except OSError:    print("File creation failed !!")
This script will create 4 directories in the specified path.
Then to find where the python is installed in the system type the below commands.For python 2.7which pythonFor python 3which python3
which python
For python 3
which python3
Copy the output and add this in the starting of the script e.g if output is /usr/bin/python3 then write the below command in the starting of the script.#!/usr/bin/python3So the python script would look like#! usr / bin / python3import osi = 1# Write the path where to create the directoriespath ="/home / dev / test/"try:    while i<5:        os.mkdir(path+"file"+str(i))        i+= 1except OSError:    print("File creation failed !!")
#!/usr/bin/python3
So the python script would look like
#! usr / bin / python3import osi = 1# Write the path where to create the directoriespath ="/home / dev / test/"try:    while i<5:        os.mkdir(path+"file"+str(i))        i+= 1except OSError:    print("File creation failed !!")
Type the following command to get the path of the working directory, starting from the root.pwdLet it be /home/usr/check
pwd
Let it be /home/usr/check
Add this path in $PATH variable. For this type in terminalsudo nano .bashrcBefore this command make sure that you are in the home directory.Then add this line in the fileexport PATH=$PATH:/home/dev/checkThis will get added to the path variable. Then type source ~/.bashrc
sudo nano .bashrc
Before this command make sure that you are in the home directory.Then add this line in the file
export PATH=$PATH:/home/dev/check
This will get added to the path variable. Then type
 source ~/.bashrc
Close the terminal and open again. Now we can run the python file directly from anywhere in the terminal by typing the file namefile1.py
file1.py
This will create the four directories in the check folder. Now any python file placed in the check directory we can be executed from anywhere in the terminal by typing the file name.
Python-Miscellaneous
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is the use of %n in printf()?

In C language, %n is a special format specifier. It cause printf() to load the variable pointed by corresponding argument. The loading is done with a value which is equal to the number of characters printed by printf() before the occurrence of %n.
Note − It does not print anything. Another printf() function is used to print the statement.
Here is an example of %n in C language,
 Live Demo
#include<stdio.h>
int main() {
   int s;
   printf("The value of %ns : ", &s);
   printf("%d", s);
   getchar();
   return 0;
}
The value of s : 13
Even if we give the value to the identifier, it will not consider the value given by us. It counts the characters used before the use of %n in the statement. It will not count %n as a character.
Here is an example if we pass the value,
 Live Demo
#include<stdio.h>
int main() {
   int s;
   int m = 28;
   int val;
   printf("The value of %ns and %nm %nval : ", &s, &m, &val);
   printf("%d\t%d\t%d", s, m, val);
   return 0;
}
The value of s and m val : 131921
Contents list – Python Beautifulsoup

25 Oct, 2020
The contents list is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The content is a list that contains the tag’s children.
Syntax: 
 tag.contents 

Below given examples explain the concept of contents in Beautiful Soup. Example 1: In this example, we are going to get the contents of the element.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Create the documentdoc = "<body><b> Hello world </b><body>"  # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser")  # Get the whole content from the body tagcontents = soup.body.contents  # Print the contentsprint(contents)
Output: 
[<b> Hello world </b>, <body></body>]

Example 2: In this example, we are going to see the type of contents.
Python3
# Import Beautiful Soupfrom bs4 import BeautifulSoup  # Create the documentdoc = "<body><b> Hello world </b><body>"  # Initialize the object with the documentsoup = BeautifulSoup(doc, "html.parser")  # Get the whole content from the body tagcontents = soup.body.contents  # Print the type of contentsprint(type(contents))
Output: 
<type 'list'>

Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Queue in Python
Defaultdict in Python
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
reduce() in Python
Python | Get unique values from a list
Python – tensorflow.gather()

10 Jul, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks. 
gather() is used to slice the input tensor based on the indices provided.
Syntax: tensorflow.gather( params, indices, validate_indices, axis, batch_dims, name)
Parameters: 
params: It is a Tensor with rank greater than or equal to axis+1.
indices: It is a Tensor of dtype int32 or int64. It’s value should be in range [0, params.shape[axis]).
axis: It is a Tensor of dtype int32 or int64. It defines the axis from which indices should be gathered. Default value is 0 and it must be greater than of equal to batch_dims.
batch_dims: It is an integer representing the number o batch dimension. It must be less than or equal to rank(indices).
name: It defines the name for the operation.
Returns:
It returns a Tensor having same dtype as param.
Example 1:
Python3
# Importing the libraryimport tensorflow as tf  # Initializing the inputdata = tf.constant([1, 2, 3, 4, 5, 6])indices = tf.constant([0, 1, 2, 1])  # Printing the inputprint('data: ',data)print('indices: ',indices)  # Calculating resultres = tf.gather(data, indices)  # Printing the resultprint('res: ',res)
Output:
data:  tf.Tensor([1 2 3 4 5 6], shape=(6,), dtype=int32)
indices:  tf.Tensor([0 1 2 1], shape=(4,), dtype=int32)
res:  tf.Tensor([1 2 3 2], shape=(4,), dtype=int32)


Example 2:
Python3
# Importing the libraryimport tensorflow as tf  # Initializing the inputdata = tf.constant([[1, 2], [3, 4], [5, 6]])indices = tf.constant([2, 0, 1])  # Printing the inputprint('data: ',data)print('indices: ',indices)  # Calculating resultres = tf.gather(data, indices)  # Printing the resultprint('res: ',res)
Output:
data:  tf.Tensor(
[[1 2]
 [3 4]
 [5 6]], shape=(3, 2), dtype=int32)
indices:  tf.Tensor([2 0 1], shape=(3,), dtype=int32)
res:  tf.Tensor(
[[5 6]
 [1 2]
 [3 4]], shape=(3, 2), dtype=int32)



Python Tensorflow-math-functions
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# - Type Conversion

Type conversion is converting one type of data to another type. It is also known as Type Casting. In C#, type casting has two forms −
Implicit type conversion − These conversions are performed by C# in a type-safe manner. For example, are conversions from smaller to larger integral types and conversions from derived classes to base classes.
Implicit type conversion − These conversions are performed by C# in a type-safe manner. For example, are conversions from smaller to larger integral types and conversions from derived classes to base classes.
Explicit type conversion − These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.
Explicit type conversion − These conversions are done explicitly by users using the pre-defined functions. Explicit conversions require a cast operator.
The following example shows an explicit type conversion −
using System;

namespace TypeConversionApplication {
   class ExplicitConversion {
      static void Main(string[] args) {
         double d = 5673.74; 
         int i;
         
         // cast double to int.
         i = (int)d;
         Console.WriteLine(i);
         Console.ReadKey();
      }
   }
}
When the above code is compiled and executed, it produces the following result −
5673

C# provides the following built-in type conversion methods −
ToBoolean
Converts a type to a Boolean value, where possible.
ToByte
Converts a type to a byte.
ToChar
Converts a type to a single Unicode character, where possible.
ToDateTime
Converts a type (integer or string type) to date-time structures.
ToDecimal
Converts a floating point or integer type to a decimal type.
ToDouble
Converts a type to a double type.
ToInt16
Converts a type to a 16-bit integer.
ToInt32
Converts a type to a 32-bit integer.
ToInt64
Converts a type to a 64-bit integer.
ToSbyte
Converts a type to a signed byte type.
ToSingle
Converts a type to a small floating point number.
ToString
Converts a type to a string.
ToType
Converts a type to a specified type.
ToUInt16
Converts a type to an unsigned int type.
ToUInt32
Converts a type to an unsigned long type.
ToUInt64
Converts a type to an unsigned big integer.
The following example converts various value types to string type −
using System;

namespace TypeConversionApplication {
   class StringConversion {
      static void Main(string[] args) {
         int i = 75;
         float f = 53.005f;
         double d = 2345.7652;
         bool b = true;

         Console.WriteLine(i.ToString());
         Console.WriteLine(f.ToString());
         Console.WriteLine(d.ToString());
         Console.WriteLine(b.ToString());
         Console.ReadKey();
            
      }
   }
}
When the above code is compiled and executed, it produces the following result −
75
53.005
2345.7652
True


    119 Lectures 
     23.5 hours 

 Raja Biswas

    37 Lectures 
     13 hours 

 Trevoir Williams

    16 Lectures 
     1 hours 

 Peter Jepson

    159 Lectures 
     21.5 hours 

 Ebenezer Ogbu

    193 Lectures 
     17 hours 

 Arnold Higuit

    24 Lectures 
     2.5 hours 

 Eric Frick
 Print
 Add Notes
 Bookmark this page
Python - Create a Pipeline in Pandas

To create a pipeline in Pandas, we need to use the pipe() method. At first, import the required pandas library with an alias −
import pandas as pd
Now, create a DataFrame −
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)


Create a pipeline and call the upperFunc() custom function to convert column names to uppercase −
pipeline = dataFrame.pipe(upperFunc)
Following is the upperFun() to convert column names to uppercase −
def upperFunc(dataframe):
# Converting to upppercase
   dataframe.columns = dataframe.columns.str.upper()
   return dataframe
Following is the complete code −
import pandas as pd

# function to convert column names to uppercase
def upperFunc(dataframe):
   # Converting to upppercase
   dataframe.columns = dataframe.columns.str.upper()
   return dataframe

# Create DataFrame
dataFrame = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Mustang', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"DataFrame ...\n",dataFrame

# creating pipeline using pipe()
pipeline = dataFrame.pipe(upperFunc)

# calling pipeline
print"\nDisplaying column names in uppercase...\n",pipeline
This will produce the following output
DataFrame ...
       Car   Units
0      BMW    100
1    Lexus    150
2     Audi    110
3  Mustang     80
4  Bentley    110
5   Jaguar     90

Displaying column names in uppercase...
       CAR   UNITS
0      BMW    100
1    Lexus    150
2     Audi    110
3  Mustang     80
4  Bentley    110
5   Jaguar     90
Redux - Core Concepts

Let us assume our application’s state is described by a plain object called initialState which is as follows −
const initialState = {
   isLoading: false,
   items: [],
   hasError: false
};

Every piece of code in your application cannot change this state. To change the state, you need to dispatch an action.
An action is a plain object that describes the intention to cause change with a type property. It must have a type property which tells what type of action is being performed. The command for action is as follows −
return {
   type: 'ITEMS_REQUEST', //action type
   isLoading: true //payload information
}

Actions and states are held together by a function called Reducer. An action is dispatched with an intention to cause change. This change is performed by the reducer. Reducer is the only way to change states in Redux, making it more predictable, centralised and debuggable. A reducer function that handles the ‘ITEMS_REQUEST’ action is as follows −
const reducer = (state = initialState, action) => { //es6 arrow function
   switch (action.type) {
      case 'ITEMS_REQUEST':
         return Object.assign({}, state, {
            isLoading: action.isLoading
         })
      default:
         return state;
   }
}
Redux has a single store which holds the application state. If you want to split your code on the basis of data handling logic, you should start splitting your reducers instead of stores in Redux.
We will discuss how we can split reducers and combine it with store later in this tutorial.
Redux components are as follows −
 

    56 Lectures 
     12.5 hours 

 Eduonix Learning Solutions

    63 Lectures 
     9.5 hours 

 TELCOMA Global

    129 Lectures 
     19.5 hours 

 Ghulam Abbas

    31 Lectures 
     3 hours 

 Saumitra Vishal

    55 Lectures 
     4 hours 

 Saumitra Vishal
 Print
 Add Notes
 Bookmark this page
Python | math.factorial() function

11 Mar, 2019
In Python, math module contains a number of mathematical operations, which can be performed with ease using the module. math.factorial() function returns the factorial of desired number.
Syntax: math.factorial(x)

Parameter:
x: This is a numeric expression.

Returns:  factorial of desired number.
Code #1:
# Python code to demonstrate the working of factorial()    # importing "math" for mathematical operations import math     x = 5    # returning the factorialprint ("The factorial of 5 is : ", end ="") print (math.factorial(x))
The factorial of 5 is : 120

Code #2:
# Python code to demonstrate the working of factorial()  # importing "math" for mathematical operations import math   x = 5y = 15z = 8  # returning the factorialprint ("The factorial of 5 is : ", math.factorial(x))print ("The factorial of 15 is : ", math.factorial(y))print ("The factorial of 8 is : ", math.factorial(z))
Output:
The factorial of 5 is :  120
The factorial of 15 is :  1307674368000
The factorial of 8 is :  40320
 Code #3: Throws ValueError if x is not integer
# Python code to demonstrate the working of factorial()    # importing "math" for mathematical operations import math     # when x is not integerprint ("math.factorial(13.7) : ", math.factorial(13.7))
Output:
ValueError: factorial() only accepts integral values
Python math-library-functions
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
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
Python | os.path.join() method
Python | Remove duplicate tuples from list of tuples

30 Jul, 2019
Given a list of tuples, Write a Python program to remove all the duplicated tuples from the given list.
Examples:
Input : [(1, 2), (5, 7), (3, 6), (1, 2)]
Output : [(1, 2), (5, 7), (3, 6)]

Input : [('a', 'z'), ('a', 'x'), ('z', 'x'), ('a', 'x'), ('z', 'x')]
Output : [('a', 'z'), ('a', 'x'), ('z', 'x')]

Method #1 : List comprehension
This is a naive approach to use list comprehension. Here, we use two for loops and set data structure to cancel out all the duplicates.
# Python3 program to remove duplicate # tuples from list of tuples  def removeDuplicates(lst):          return [t for t in (set(tuple(i) for i in lst))]          # Driver codelst = [(1, 2), (5, 7), (3, 6), (1, 2)]print(removeDuplicates(lst))
[(1, 2), (5, 7), (3, 6)]

 Method #2 : List comprehension (Efficient approach)
This method is efficient as compared to the above method, here we use a single for loop within list comprehension and then convert it to set to remove duplicates and then again convert it to list.
# Python3 program to remove duplicate # tuples from list of tuples  def removeDuplicates(lst):          return list(set([i for i in lst]))          # Driver codelst = [(1, 2), (5, 7), (3, 6), (1, 2)]print(removeDuplicates(lst))
[(1, 2), (5, 7), (3, 6)]

 Method #3 : Python enumerate() method
# Python3 program to remove duplicate # tuples from list of tuples  def removeDuplicates(lst):          return [[a, b] for i, [a, b] in enumerate(lst)     if not any(c == b for _, c in lst[:i])]          # Driver codelst = [(1, 2), (5, 7), (3, 6), (1, 2)]print(removeDuplicates(lst))
[[1, 2], [5, 7], [3, 6]]

ManasChhabra2
Python list-programs
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Java Examples - Use for & foreach loops

How to use  for and foreach loops to display elements of an array.
This example displays an integer array using for loop & foreach loops.
public class Main {
   public static void main(String[] args) {
      int[] intary = { 1,2,3,4};
      forDisplay(intary);
      foreachDisplay(intary);
   }
   public static void forDisplay(int[] a) {  
      System.out.println("Display an array using for loop");
      for (int i = 0; i < a.length; i++) {
         System.out.print(a[i] + " ");
      }
      System.out.println();
   }
   public static void foreachDisplay(int[] data) {
      System.out.println("Display an array using for each loop");
      for (int a  : data) {
         System.out.print(a+ " ");
      }
   }
}
The above code sample will produce the following result.
Display an array using for loop
1 2 3 4 
Display an array using for each loop
1 2 3 4 

The following is an another sample example of Foreach
import java.util.*;  

public class HelloWorld {  
   public static void main(String args[]) {  
      ArrayList<String> list = new ArrayList<String>();  
      list.add("Tutorials");  
      list.add("Point");  
      list.add("India PVT Limited");
      for(String s:list) { 
         System.out.println(s);  
      }
   }   
}  
The above code sample will produce the following result.
Tutorials
Point
India PVT Limited

 Print
 Add Notes
 Bookmark this page
How to get the screen size in Tkinter?

Tkinter initially creates a window or frame object where all the widgets, frame are displayed.
Tkinter components adjust the window size and width according to user-defined geometry.
In order to get the screen size, we can use winfo_screenwidth() which returns the screen width and winfo_screenheight() for the height of the screen in pixels.
In this example, we will print the screen size as the output,
#Import the required libraries
from tkinter import *

#Create an instance of tkinter frame
win= Tk()

#Set the geometry of frame
win.geometry("650x250")

#Get the current screen width and height
screen_width = win.winfo_screenwidth()
screen_height = win.winfo_screenheight()

#Print the screen size
print("Screen width:", screen_width)
print("Screen height:", screen_height)

win.mainloop()
Running the code will display a window and print the screen size.
Screen width: 1366
Screen height: 768
spaCy - Convert Command

As name implies, this command will convert files into spaCy’s JavaScript Object Notation (JSON) format especially for the use with the train command and other experiment management functions.
The Convert command is as follows −
python -m spacy convert [input_file] [output_dir] [--file-type] [--converter][--n-sents] [--morphology] [--lang]

The table below explains its arguments −
Following are the output file types, which can be generated with this command −
json − It is regular JSON and default output file type.
json − It is regular JSON and default output file type.
jsonl − It is Newline-delimited JSON.
jsonl − It is Newline-delimited JSON.
msg − It is Binary MessagePack format.
msg − It is Binary MessagePack format.
Following table shows the converter options −
Auto
It will automatically pick converter based on file extension and file content.
conll, conllu, conllubio
These are the universal dependencies .conllu or .conll format.
Ner
It is NER with IOB/IOB2 tags. In this, one token per line with columns is separated by whitespace. The first column is the token and the final column is the IOB tag. The sentences are separated by blank lines and documents are separated by the line -DOCSTART- -X- O O. Supports CoNLL 2003 NER format.
Iob
It is NER with IOB/IOB2 tags. In this, one sentence per line with tokens separated by whitespace and annotation separated by |, either word|B-ENT or word|POS|B-ENT.
Jsonl
It is NER data formatted as JSONL with one dict per line and a "text" and "spans" key.
 Print
 Add Notes
 Bookmark this page
Python program to insert an element into sorted list

04 Dec, 2021
Given a sorted list and an element, Write a Python program to insert the element into the given list in sorted position.
Examples:
Input : list = [1, 2, 4], n = 3
Output : list = [1, 2, 3, 4]

Input : list = ['a', 'b', 'c', 'd'], n = 'e'
Output : list = ['a', 'b', 'c', 'd', 'e']

Approach #1 :This approach is the brute force method. Since the list is already sorted, we begin with a loop and check if the list element is greater than the given element. If yes, the given element need to be inserted at this position.
# Python3 program to insert# an element into sorted list  # Function to insert element    def insert(list, n):      index = len(list)    # Searching for the position    for i in range(len(list)):      if list[i] > n:        index = i        break      # Inserting n in the list    if index == len(list):      list = list[:index] + [n]    else:      list = list[:index] + [n] + list[index:]    return list  # Driver functionlist = [1, 2, 4]n = 3  print(insert(list, n))
[1, 2, 3, 4]

 Approach #2 :Python comes with a bisect module whose purpose is to find a position in list where an element needs to be inserted to keep the list sorted. Thus we use this module to solve the given problem.
# Python3 program to insert # an element into sorted listimport bisect   def insert(list, n):    bisect.insort(list, n)     return list  # Driver functionlist = [1, 2, 4]n = 3  print(insert(list, n))
[1, 2, 3, 4]

Python list-programs
python-list
Python
Python Programs
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 ?
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python EasyGUI – Choice Box

05 Sep, 2020
Choice Box : It is used to display a window having a multiple options i.e items in EasyGUI, it can be used where there is a need to select any one item among a group of items, it consist of title, message to be displayed, group of items and a pair of “Ok”, “Cancel” button to confirm the selection of the item. Below is how the choice box looks like
In order to do this we will use choicebox method
Syntax : choicebox(message, title, choices)
Argument : It takes 3 arguments, first string i.e message/information to be displayed, second string i.e title of the window and third is list of strings i.e items
Return : It returns return the display text of the selected item else None
Example :In this we will create a choice box with multiple items, when any item is confirmed it will show the specific message on the screen according to the item, below is the implementation
# importing easygui modulefrom easygui import *  # message to be displayedtext = "Selected any one item"  # window titletitle = "Window Title GfG"  # item choiceschoices = ["Geek", "Super Geeek", "Super Geek 2", "Super Geek God"]  # creating a button boxoutput = choicebox(text, title, choices)  # title for the message boxtitle = "Message Box"  # message message = "You selected : " + str(output)  # creating a message box msg = msgbox(message, title)
Output :
Another Example :In this we will create a choice box without adding any items, when any item is confirmed it will show the specific message on the screen according to the item, below is the implementation
# importing easygui modulefrom easygui import *  # message to be displayedtext = "Selected any one item"  # window titletitle = "Window Title GfG"  # creating a button boxoutput = choicebox(text, title)  # title for the message boxtitle = "Message Box"  # message message = "You selected : " + str(output)  # creating a message box msg = msgbox(message, title)
Output :
Python-EasyGUI
Python-gui
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
How to Calculate the Area of a Triangle using Python?

Calculating the area of a triangle is a formula that you can easily implement in python. If you have the base and height of the triangle, you can use the following code to get the area of the triangle,
def get_area(base, height):
   return 0.5 * base * height
print(get_area(10, 15))
This will give the output:
75
If you have the sides of the triangle, you can use herons formula to get the area. For example,
def get_area(a, b, c):
   s = (a+b+c)/2
   return (s*(s-a)*(s-b)*(s-c)) ** 0.5
print(get_area(10, 15, 10))
This will give the output:
49.607837082461074
How to parse a string to an int in C++?

You can use a string stream to parse an int in c++ to an int. You need to do some error checking in this method.
#include<iostream>
#include<sstream>
using namespace std;

int str_to_int(const string &str) {
   stringstream ss(str);
   int num;
   ss >> num;
   return num;
}

int main() {
   string s = "12345";
   int x = str_to_int(s);
   cout << x;
}
This will give the output −
12345
In the new C++11, there are functions for that: stoi(string to int), stol(string to long), stoll(string to long long), stoul(string to unsigned long), etc.
You can use these functions as follows −
#include<iostream>
using namespace std;

int main() {
   string s = "12345";
   int x = stoi(s);
   cout << x;
}
This will give the output −
12345
Kotlin Operators

Operators are used to perform operations on variables and values.
The value is called an operand, while the operation (to be performed between the two operands) is defined by an operator:
In the example below, the numbers 100 and 50 are operands, and the
+ sign is an operator:
var x = 100 + 50
Although the + operator is often used to add together two values, like in the example above, it can also be used to add together a variable and a value, or a variable and a variable:
var sum1 = 100 + 50       // 150 (100 + 50)
var sum2 = sum1 + 250     // 400 (150 + 250)var sum3 = sum2 + sum2    // 800 (400 + 400)
Kotlin divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Arithmetic operators are used to perform common mathematical operations.
Assignment operators are used to assign values to variables.
In the example below, we use the assignment operator (=) 
to assign the value 10 to a variable called x:
var x = 10
The addition assignment operator (+=) adds a value to a variable:
var x = 10x += 5
A list of all assignment operators:
Comparison operators are used to compare two values, and returns a Boolean 
value: either true or false.
You will learn much more about Booleans in the Boolean chapter and 
Conditions.
Logical operators are used to determine the logic between variables or 
values:
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
YACC program to recognize string with grammar { anbn | n≥0 } - GeeksforGeeks

08 May, 2019
Problem: Write YACC program to recognize string with grammar { anbn | n≥0 }.
Explanation:Yacc (for “yet another compiler compiler.”) is the standard parser generator for the Unix operating system. An open source program, yacc generates code for the parser in the C programming language. The acronym is usually rendered in lowercase but is occasionally seen as YACC or Yacc.
Examples:
Input: ab
Output: valid string

Input: aab
Output: invalid string

Input: aabb
Output: valid string

Input: abb
Output: invalid string

Input: aaabbb
Output: valid string 
Lexical Analyzer Source Code :
%{   /* Definition section */  #include "y.tab.h" %}  /* Rule Section */ %%[aA] {return A;}[bB] {return B;}\n {return NL;}.  {return yytext[0];}%%  int yywrap()  {   return 1;  } 
Parser Source Code :
%{   /* Definition section */   #include<stdio.h>   #include<stdlib.h>%}  %token A B NL  /* Rule Section */%%stmt: S NL  { printf("valid string\n");              exit(0); };S: A S B |;%%  int yyerror(char *msg) {  printf("invalid string\n");  exit(0); }  //driver code main() {  printf("enter the string\n");  yyparse(); }
Output:
Lex program
Compiler Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction of Compiler Design
Ambiguous Grammar
Difference between Compiler and Interpreter
Code Optimization in Compiler Design
Types of Parsers in Compiler Design
Intermediate Code Generation in Compiler Design
Syntax Directed Translation in Compiler Design
SLR, CLR and LALR Parsers | Set 3
Shift Reduce Parser in Compiler
Directed Acyclic graph in Compiler Design (with examples)
Python Program to check if strings are rotations of each other or not

13 Jun, 2022
Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false) Algorithm: areRotations(str1, str2)
    1. Create a temp string and store concatenation of str1 to
       str1 in temp.
                          temp = str1.str1
    2. If str2 is a substring of temp then str1 and str2 are 
       rotations of each other.

    Example:                 
                     str1 = "ABACD"
                     str2 = "CDABA"

     temp = str1.str1 = "ABACDABACD"
     Since str2 is a substring of temp, str1 and str2 are 
     rotations of each other.
Python
# Python program to check if strings are rotations of# each other or not # Function checks if passed strings (str1 and str2)# are rotations of each otherdef areRotations(string1, string2):    size1 = len(string1)    size2 = len(string2)    temp = ''     # Check if sizes of two strings are same    if size1 != size2:        return 0     # Create a temp string with value str1.str1    temp = string1 + string1     # Now check if str2 is a substring of temp    # string.count returns the number of occurrences of    # the second string in temp    if (temp.count(string2)> 0):        return 1    else:        return 0 # Driver program to test the above functionstring1 = "AACD"string2 = "ACDA" if areRotations(string1, string2):    print "Strings are rotations of each other"else:    print "Strings are not rotations of each other" # This code is contributed by Bhavya Jain
Output:
Strings are rotations of each other
Time Complexity : O(n)
Auxiliary Space: O(n)
Library Functions Used: strstr: strstr finds a sub-string within a string. Prototype: char * strstr(const char *s1, const char *s2); See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strstr.htm for more details strcat: strncat concatenate two strings Prototype: char *strcat(char *dest, const char *src); See http://www.lix.polytechnique.fr/Labo/Leo.Liberti/public/computing/prog/c/C/MAN/strcat.htm for more details Time Complexity: Time complexity of this problem depends on the implementation of strstr function. If implementation of strstr is done using KMP matcher then complexity of the above program is (-)(n1 + n2) where n1 and n2 are lengths of strings. KMP matcher takes (-)(n) time to find a substring in a string of length n where length of substring is assumed to be smaller than the string. Please refer complete article on A Program to check if strings are rotations of each other or not for more details!
simmytarika5
hasani
rotation
Python
Python Programs
Strings
Strings
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers