code-rag-bench/online-tutorials huggingface dataset:
C# | Math.Tanh() Method - GeeksforGeeks

13 Dec, 2021
Math.Tanh() is the inbuilt Math class method which returns the hyperbolic tan of a given double value argument. The result will be NaN if the given argument is NaN.Syntax:
public static double Tanh(double num)
Parameter: 
num: It is the number whose hyperbolic tan is to be returned and type of this parameter is System.Double.
Return Value: The method returns the hyperbolic tan of num. of type System.Double. If num is equal to NegativeInfinity, this method returns -1. If num is equal to PositiveInfinity, this method returns 1. If num is equal to NaN, this method returns NaN.Examples : 
Input  : num = 60.0
Output : 1.0
Below programs illustrate the Math.Tanh() method:Program 1: 
Csharp
// C# program to illustrate the// Math.Tanh()using System; class GFG {     // Main Method    public static void Main(String[] args)    {         double num1 = 60.0, num2 = 0.0, num3 = 1.0;         // It returns the hyperbolic tan of        // specified  angle in radian        double tanhvalue = Math.Tanh(num1);        Console.WriteLine("The tanh of num1 = " + tanhvalue);         tanhvalue = Math.Tanh(num2);        Console.WriteLine("The tanh of num2 = " + tanhvalue);         tanhvalue = Math.Tanh(num3);        Console.WriteLine("The tanh of num3 = " + tanhvalue);    }}
The tanh of num1 = 1
The tanh of num2 = 0
The tanh of num3 = 0.761594155955765
 
Program 2:  
Csharp
// C# program to illustrate the// Math.Tanh() Methodusing System; class GFG {        // Main Method    public static void Main(String[] args)    {         double num1 = (30 * (Math.PI)) / 180, num2 = 11.0, num3 = 45.0;         // It returns the hyperbolic tan of        // angle in radian        double tanhvalue = Math.Tanh(num1);        Console.WriteLine("The tanh of num1 = " + tanhvalue);         tanhvalue = Math.Tanh(num2);        Console.WriteLine("The tanh of num2 = " + tanhvalue);         tanhvalue = Math.Tanh(num3);        Console.WriteLine("The tanh of num3 = " + tanhvalue);    }}
The tanh of num1 = 0.480472778156452
The tanh of num2 = 0.999999999442106
The tanh of num3 = 1
 
ruhelaa48
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
C# | Method Overriding
C# | Abstract Classes
Difference between Ref and Out keywords in C#
Extension Method in C#
C# | Replace() Method
C# | Class and Object
C# | Constructors
Introduction to .NET Framework
How to check the version of CodeIgniter framework ? - GeeksforGeeks

22 Oct, 2021
CodeIgniter is a powerful PHP framework used to create and design projects. The functionality and method calls are dependent on the CodeIgniter framework. The methods get deprecated based on the version of PHP and some of the functionality is specific to the browser. Therefore, it is important to check the version of CodeIgniter framework, which is possible using the following two methods : 
Using system/core/CodeIgniter.php: The CodeIgniter framework provides a well structured framework to visualize the values for constants and sessions stored. It contains a directory within it named system folder which contains core database files like cache, driver, query builder etc. Within this folder is the core folder which contains the base class of your application. The version of CodeIgniter framework can be accessed using this file which has the version stored in the constant named CI_VERSION. The below screenshot indicates this: 
Example: The below screenshot indicates that the version in use is 3.1.11. 
Using php echo command: CI_VERSION is build in constant in CodeIgniter framework, which contains value of version of the framework that is currently being used. This displays the CodeIgniter framework version in which the project is being run on. 
Example:
PHP
<?php    echo CI_VERSION;?>
Output:
3.1.11
PHP-Questions
Picked
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
DateTime.ToUniversalTime() Method in C#

The DateTime.ToUniversalTime() method in C# is used to convert the value of the current DateTime object to Coordinated Universal Time (UTC).
Following is the syntax −
public DateTime ToUniversalTime ();
Let us now see an example to implement the DateTime.ToUniversalTime() method −
using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 12, 11, 7, 11, 25);
      Console.WriteLine("Date = {0}", d);
      DateTime res = d.ToUniversalTime();
      Console.WriteLine("String representation = {0}", res);
   }
}
This will produce the following output −
Date = 11/11/2019 7:11:25 AM
String representation = 11/11/2019 7:11:25 AM
Let us now see another example to implement the DateTime.ToUniversalTime() method −
using System;
public class Demo {
   public static void Main() {
      DateTime localDate, universalDate;
      String str = "11/11/2019 4:10:55";
      localDate = DateTime.Parse(str);
      universalDate = localDate.ToUniversalTime();
      Console.WriteLine("Local time = {0} ", localDate);
      Console.WriteLine("Universal time = {0} ", universalDate);
   }
}
This will produce the following output −
Local time = 11/11/2019 4:10:55 AM
Universal time = 11/11/2019 4:10:55 AM
What is an Expression and What are the types of Expressions?

02 Aug, 2019
Expression: An expression is a combination of operators, constants and variables. An expression may consist of one or more operands, and zero or more operators to produce a value.
Example:
a+b
c
s-1/7*f
.
.
etc

Types of Expressions:
Expressions may be of the following types:
Constant expressions: Constant Expressions consists of only constant values. A constant value is one that doesn’t change.Examples:5, 10 + 5 / 6.0, 'x’
5, 10 + 5 / 6.0, 'x’
Integral expressions: Integral Expressions are those which produce integer results after implementing all the automatic and explicit type conversions.Examples:x, x * y, x + int( 5.0)where x and y are integer variables.
x, x * y, x + int( 5.0)
where x and y are integer variables.
Floating expressions: Float Expressions are which produce floating point results after implementing all the automatic and explicit type conversions.Examples:x + y, 10.75where x and y are floating point variables.
x + y, 10.75
where x and y are floating point variables.
Relational expressions: Relational Expressions yield results of type bool which takes a value true or false. When arithmetic expressions are used on either side of a relational operator, they will be evaluated first and then the results compared. Relational expressions are also known as Boolean expressions.Examples:x <= y, x + y > 2
x <= y, x + y > 2
Logical expressions: Logical Expressions combine two or more relational expressions and produces bool type results.Examples: x > y && x == 10, x == 10 || y == 5 
 x > y && x == 10, x == 10 || y == 5 
Pointer expressions: Pointer Expressions produce address values.Examples:&x, ptr, ptr++where x is a variable and ptr is a pointer.
&x, ptr, ptr++
where x is a variable and ptr is a pointer.
Bitwise expressions: Bitwise Expressions are used to manipulate data at bit level. They are basically used for testing or shifting bits.Examples:x << 3shifts three bit position to lefty >> 1shifts one bit position to right.Shift operators are often used for multiplication and division by powers of two.
x << 3
shifts three bit position to left
y >> 1
shifts one bit position to right.
Shift operators are often used for multiplication and division by powers of two.
Note: An expression may also use combinations of the above expressions. Such expressions are known as compound expressions.
expression-evaluation
Mathematical
School Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Sieve of Eratosthenes
Program to find GCD or HCF of two numbers
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
Java - pow() Method

The method returns the value of the first argument raised to the power of the second argument.
double pow(double base, double exponent)

Here is the detail of parameters −
base − Any primitive data type.
base − Any primitive data type.
exponenet − Any primitive data type.
exponenet − Any primitive data type.
This method returns the value of the first argument raised to the power of the second argument.
This method returns the value of the first argument raised to the power of the second argument.
public class Test { 

   public static void main(String args[]) {
      double x = 11.635;
      double y = 2.76;

      System.out.printf("The value of e is %.4f%n", Math.E);
      System.out.printf("pow(%.3f, %.3f) is %.3f%n", x, y, Math.pow(x, y));
   }
}
This will produce the following result −
The value of e is 2.7183
pow(11.635, 2.760) is 874.008
Matplotlib.pyplot.ylabel() in Python

12 Apr, 2020
Matplotlib is a very powerful plotting library useful for those working with Python and NumPy. And for making statistical interference, it becomes very necessary to visualize our data and Matplotlib is the tool that can be very helpful for this purpose.
This function sets the label for the y-axis of the plot.
Syntax: matplotlib.pyplot.ylabel(ylabel, fontdict=None, labelpad=None)
Parameters:ylabel: The name of the labelfontdict: Adds the font styles to the labellabelpad: This helps us to set the spacing between label and the axis
Example #1:
import matplotlib.pyplot as plt  # setting x valuesx =['Geeks', 'for', 'geeks', 'tutorials']  # Setting y values y =[1, 2, 3, 4]  # Adding label on the y-axisplt.ylabel('Numbers label')  # plotting the graphplt.plot(x, y)
Output:
Example #2:
import matplotlib.pyplot as plt  x =['Geeks', 'for', 'geeks', 'tutorials']y =[1, 2, 3, 4]  # Adding space between label and# axis by setting labelpadplt.ylabel('Numbers label', labelpad = 50)  plt.plot(x, y)
Output:
Example #3:
import matplotlib.pyplot as plt  x =['Geeks', 'for', 'geeks', 'tutorials']y =[1, 2, 3, 4]  # Setting font dictionary font = {'family': 'Verdana',        'color':  'green',        'size': 20,        }  # Adding the font styles to the labelplt.ylabel('Numbers label', fontdict = font)  plt.plot(x, y)
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Column Mean in tuple list - GeeksforGeeks

15 Jan, 2022
Sometimes, while working with records, we can have a problem in which we need to average all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using sum() + list comprehension + zip() This task can be performed using combination of above functions. In this, we cumulate the like index elements, i.e columns using zip(), and then iterate through them using list comprehension and perform summation using sum(). We divide the each result with No of rows for average computation.
Python3
# Python3 code to demonstrate working of# Column Mean in tuple list# using list comprehension + sum() + zip()   # initialize listtest_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)]   # printing original listprint("The original list : " + str(test_list))   # Column Mean in tuple list# using list comprehension + sum() + zip()res = [sum(ele) / len(test_list) for ele in zip(*test_list)]   # printing resultprint("The Cumulative column mean is : " + str(res))
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column mean is : [2.6666666666666665, 5.0, 5.666666666666667]
Method #2 : Using zip() + map() + sum() This method is similar to the above method. In this, the task performed by list comprehension is performed by map(), which extends the summation of columns to zipped elements. We divide the each result with No of rows for average computation.
Python3
# Python3 code to demonstrate working of# Column Mean in tuple list# using zip() + map() + sum()   def avg(list):    return sum(list)/len(list)       # initialize listtest_list = [(1, 2, 3), (6, 7, 6), (1, 6, 8)]   # printing original listprint("The original list : " + str(test_list))   # Column Mean in tuple list# using zip() + map() + sum()res = list(map(avg, zip(*test_list)))   # printing resultprint("The Cumulative column mean is : " + str(res))
The original list : [(1, 2, 3), (6, 7, 6), (1, 6, 8)]
The Cumulative column mean is : [2.6666666666666665, 5.0, 5.666666666666667]
surindertarika1234
ruhelaa48
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
Program to find sum of the sum of all contiguous sublists in Python

Suppose we have a list of numbers called nums, now consider every contiguous subarray. Sum each of these subarray and return the sum of all these values. Finally, mod the result by 10 ** 9 + 7.
So, if the input is like nums = [3, 4, 6], then the output will be 43, as We have the following subarrays − [3] [4] [6] [3, 4] [4, 6] [3, 4, 6] The sum of all of these is 43.
To solve this, we will follow these steps −
N:= size of nums
ans:= 0
for i in range 0 to size of nums, don:= nums[i]ans := ans +(i+1) *(N-i) * n
n:= nums[i]
ans := ans +(i+1) *(N-i) * n
return (ans mod 1000000007)
Let us see the following implementation to get better understanding −
 Live Demo
class Solution:
   def solve(self, nums):
      N=len(nums)
      ans=0
      for i in range(len(nums)):
         n=nums[i]
         ans += (i+1) * (N-i) * n
      return ans%1000000007
ob = Solution()
print(ob.solve([3, 4, 6]))
[3, 4, 6]
43
Moving all special char to the end of the String using Java Regular Expression RegEx)

The following regular expression matches all the special characters i.e. all characters except English alphabet spaces and digits.
"[^a-zA-Z0-9\\s+]"
To move all the special characters to the end of the given line, match all the special characters using this regex concatenate them to an empty string and concatenate remaining characters to another string finally, concatenate these two strings.
public class RemovingSpecialCharacters {
   public static void main(String args[]) {
      String input = "sample # text * with & special@ characters";
      String regex = "[^a-zA-Z0-9\\s+]";
      String specialChars = "";
      String inputData = "";
      for(int i=0; i< input.length(); i++) {
         char ch = input.charAt(i);
         if(String.valueOf(ch).matches(regex)) {
            specialChars = specialChars + ch;
         } else {
            inputData = inputData + ch;
         }
      }
      System.out.println("Result: "+inputData+specialChars);
   }
}
Result: sample text with special characters#*&@
Following is the Java program which moves the special characters of a string to its end using the methods of Regex package.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String args[]) {
      String input = "sample # text * with & special@ characters";
      String regex = "[^a-zA-Z0-9\\s+]";
      String specialChars = "";
      System.out.println("Input string: \n"+input);
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      //Creating an empty string buffer
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         specialChars = specialChars+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("Result: \n"+ sb.toString()+specialChars );
   }
}
Input string:
sample # text * with & special@ characters
Result:
sample text with special characters#*&@
Angular 2 - Metadata

Metadata is used to decorate a class so that it can configure the expected behavior of the class. Following are the different parts for metadata.
Annotations − These are decorators at the class level. This is an array and an example having both the @Component and @Routes decorator.
Following is a sample code, which is present in the app.component.ts file.
@Component ({ 
   selector: 'my-app', 
   templateUrl: 'app/app.component.html' 
}) 
The component decorator is used to declare the class in the app.component.ts file as a component.
Design:paramtypes − These are only used for the constructors and applied only to Typescript.
Design:paramtypes − These are only used for the constructors and applied only to Typescript.
propMetadata − This is the metadata which is applied to the properties of the class.
propMetadata − This is the metadata which is applied to the properties of the class.
Following is an example code.
export class AppComponent {
   @Environment(‘test’)
   appTitle: string = 'Welcome';
}
Here, the @Environment is the metadata applied to the property appTitle and the value given is ‘test’.
Parameters − This is set by the decorators at the constructor level.
Following is an example code.
export class AppComponent {
   constructor(@Environment(‘test’ private appTitle:string) { }
}
In the above example, metadata is applied to the parameters of the constructor.

    16 Lectures 
     1.5 hours 

 Anadi Sharma

    28 Lectures 
     2.5 hours 

 Anadi Sharma

    11 Lectures 
     7.5 hours 

 SHIVPRASAD KOIRALA

    16 Lectures 
     2.5 hours 

 Frahaan Hussain

    69 Lectures 
     5 hours 

 Senol Atac

    53 Lectures 
     3.5 hours 

 Senol Atac
 Print
 Add Notes
 Bookmark this page
How to get a list of installed Android applications in Kotlin?

This example demonstrates how to get a list of installed Android applications in Kotlin.
Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="4dp"
   tools:context=".MainActivity">
   <ListView
      android:id="@+id/listView"
      android:layout_width="match_parent"
      android:layout_height="match_parent" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.content.pm.ApplicationInfo
import android.os.Bundle
import android.util.Log
import android.widget.ArrayAdapter
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
   lateinit var listView: ListView
   var arrayAdapter: ArrayAdapter<*>? = null
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      title = "KotlinApp"
      listView = findViewById(R.id.listView)
      installedApps()
   }
   private fun installedApps() {
      val list = packageManager.getInstalledPackages(0)
      for (i in list.indices) {
         val packageInfo = list[i]
         if (packageInfo!!.applicationInfo.flags and ApplicationInfo.FLAG_SYSTEM == 0) {
            val appName = packageInfo.applicationInfo.loadLabel(packageManager).toString()
            Log.e("App List$i", appName)
            arrayAdapter = ArrayAdapter(this,
            R.layout.support_simple_spinner_dropdown_item, list as List)
            listView.adapter = arrayAdapter
         }
      }
   }
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.myapplication">
   <application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:roundIcon="@mipmap/ic_launcher_round"
      android:supportsRtl="true"
      android:theme="@style/AppTheme">
      <activity android:name=".MainActivity">
         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
execute_script driver method - Selenium Python - GeeksforGeeks

15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python.Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around execute_script driver method in Selenium. execute_script method synchronously Executes JavaScript in the current window/frame. This is a big feature of selenium, because javascript can do everything with a website from hitting APIs to playing with live code.
Syntax –
execute_script(script, *args)
Args –
script: The JavaScript to execute.
*args: Any applicable arguments for your JavaScript.
Example –Now one can use execute_script method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.execute_script("alert("alert via selenium")")

To demonstrate, execute_script method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object.
Program –
# import webdriverfrom selenium import webdriver  # create webdriver objectdriver = webdriver.Firefox()  # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/")  # write scriptscript = "alert('Alert via selenium')"  # generate a alert via javascriptdriver.execute_script(script)
Output –Browser generates alert as verified below –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
C# | Gets an ICollection containing the values in the Hashtable - GeeksforGeeks

01 Feb, 2019
Hashtable.Values Property is used to get an ICollection containing the values in the Hashtable.
Syntax:
public virtual System.Collections.ICollection Values { get; }
Return Value: This property returns an ICollection containing the values in the Hashtable.
Note:
The order of values in the ICollection is unspecified.
Retrieving the value of this property is an O(1) operation.
Below programs illustrate the use of above-discussed property:
Example 1:
// C# code to get an ICollection containing// the values in the Hashtable.using System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Hashtable        Hashtable myTable = new Hashtable();          // Adding elements in Hashtable        myTable.Add("g", "geeks");        myTable.Add("c", "c++");        myTable.Add("d", "data structures");        myTable.Add("q", "quiz");          // Get a collection of the values        ICollection c = myTable.Values;          // Displaying the contents        foreach(string str in c)            Console.WriteLine(str + myTable[str]);    }}
data structures
c++
quiz
geeks

Example 2:
// C# code to get an ICollection containing// the values in the Hashtable.using System;using System.Collections;  class GFG {      // Driver code    public static void Main()    {          // Creating a Hashtable        Hashtable myTable = new Hashtable();          // Adding elements in Hashtable        myTable.Add("India", "Country");        myTable.Add("Chandigarh", "City");        myTable.Add("Mars", "Planet");        myTable.Add("China", "Country");          // Get a collection of the values        ICollection c = myTable.Values;          // Displaying the contents        foreach(string str in c)            Console.WriteLine(str + myTable[str]);    }}
City
Country
Country
Planet

Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.hashtable.values?view=netframework-4.7.2
CSharp-Collections-Hashtable
CSharp-Collections-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Extension Method in C#
Top 50 C# Interview Questions & Answers
HashSet in C# with Examples
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Lambda Expressions in C#
Difference between Hashtable and Dictionary in C#
Convert String to Character Array in C#
Compute the Sum of Rows of a Matrix or Array in R Programming - rowSums Function - GeeksforGeeks

03 Jun, 2020
rowSums() function in R Language is used to compute the sum of rows of a matrix or an array.
Syntax: rowSums(x, na.rm = FALSE, dims = 1)
Parameters:x: array or matrixdims: Integer: Dimensions are regarded as ‘rows’ to sum over. It is over dimensions dims+1, ....
Example 1:
# R program to illustrate# rowSums() function  # Initializing a matrix x <- matrix(rep(2:10), 3, 3)  # Printing Matrixprint(x)  # Calling the rowSums() functionrowSums(x)
Output:
     [, 1] [, 2] [, 3]
[1, ]    2    5    8
[2, ]    3    6    9
[3, ]    4    7   10
[1] 15 18 21

Example 2:
# R program to illustrate# rowSums function  # Initializing a 3D arrayx <- array(1:8, c(2, 2, 2))  # Printing the arrayprint(x)  # Calling the rowSums() functionrowSums(x, dims = 1)
Output:
,, 1

     [, 1] [, 2]
[1, ]    1    3
[2, ]    2    4,, 2

     [, 1] [, 2]
[1, ]    5    7
[2, ]    6    8

[1] 16 20

R Matrix-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming
C program to remove extra spaces using string concepts.

Remove all the extra spaces from an entered string at runtime with the help of while loop by checking the spaces at each index of a character.
Consider an example given below −
It removes all the spaces from a given string. The given string is Tutorials Point C Programming. The result after removing spaces is TutorialsPointCProgramming.
An array of characters is called a string.
Given below is the declaration of a string −
char stringname [size];
For example, char string[50]; string of length 50 characters.
Using single character constant.
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants.
char string[10] = “Hello”:;
There is a control string “%s” used for accessing the string till it encounters ‘\0’.
The logic we used to remove extra spaces between strings is as follows −
len = strlen(string);
for(i=0; i<len; i++){
   if(string[0]==' '){
      for(i=0; i<(len-1); i++)
      string[i] = string[i+1];
      string[i] = '\0';
      len--;
      i = -1;
      continue;
   }
   if(string[i]==' ' && string[i+1]==' '){
      for(j=i; j<(len-1); j++){
         string[j] = string[j+1];
      }
      string[j] = '\0';
      len--;
      i--;
   }
}
Following is the C program to remove all the extra spaces in a sentence by using the string concepts −
#include<stdio.h>
int main() {
   char string[200];
   int i, j, len;
   printf("Enter a statement: ");
   gets(string);
   len = strlen(string);
   for(i=0; i<len; i++) {
      if(string[0]==' ') {
         for(i=0; i<(len-1); i++)
         string[i] = string[i+1];
         string[i] = '\0';
         len--;
         i = -1;
         continue;
      }
      if(string[i]==' ' && string[i+1]==' ') {
         for(j=i; j<(len-1); j++) {
            string[j] = string[j+1];
         }
         string[j] = '\0';
         len--;
         i--;
      }
   }
   printf("\nNew String after removing extra spaces is = %s", string);
   getch();
   return 0;
}
When the above program is executed, it produces the following output −
Enter a statement: Welcome to The world of C programming
New String after removing extra spaces is = Welcome to The world of C programming
Python | How to dynamically change text of Checkbutton - GeeksforGeeks

02 Apr, 2019
Tkinter is a GUI (Graphical User interface) module which is used to create various types of applications. It comes along with the Python and consists of various types of widgets which can be used to make GUI more attractive and user-friendly. Checkbutton is one of the widgets which is used to select multiple options.
Checkbutton can be created as follows:
chkbtn = ttk.Checkbutton(parent, value = options, ...)
Code #1:
# This will import tkinter and ttkfrom tkinter import * from tkinter import ttk  root = Tk()  # This will set the geometry to 200x100root.geometry('200x100')  text1 = StringVar()text2 = StringVar()  # These text are used to set initial# values of Checkbutton to offtext1.set('OFF')text2.set('OFF')  chkbtn1 = ttk.Checkbutton(root, textvariable = text1, variable = text1,                          offvalue = 'GFG Not Selected',                          onvalue = 'GFG Selected')  chkbtn1.pack(side = TOP, pady = 10)chkbtn2 = ttk.Checkbutton(root, textvariable = text2, variable = text2,                          offvalue = 'GFG Average',                          onvalue = 'GFG Good')chkbtn2.pack(side = TOP, pady = 10)  root.mainloop()
Output #1: When you run application you see the initial states of Checkbutton as shown in output.
Output #2: As soon as you select the Checkbutton you’ll see that text has been changed as in output.
Output #3: When you deselect the Checkbutton you’ll again observe following changes.
Code #2: Commands can be integrate with the Checkbutton which can be execute when checkbutton is selected or deselected depending upon conditions.
# Importing tkinter, ttk and# _show method to display# pop-up message windowfrom tkinter import * from tkinter import ttkfrom tkinter.messagebox import _show  root = Tk()root.geometry('200x100')  text1 = StringVar()text1.set('OFF')  # This function is used to display# the pop-up messagedef show(event):    string = event.get()    _show('Message', 'You selected ' + string)  chkbtn1 = ttk.Checkbutton(root, textvariable = text1, variable = text1,                          offvalue = 'GFG Good',                          onvalue = 'GFG Great',                          command = lambda : show(text1))chkbtn1.pack(side = TOP, pady = 10)  root.mainloop()
Output:Note: In above code offvalue and onvalue are used to set the values of Checkbutton of non-selected state and selected state respectively.
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Selecting rows in pandas DataFrame based on conditions
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Python | Get unique values from a list
Create a directory in Python
Python | Pandas dataframe.groupby()
Behave - Scenario Outlines

A Scenario Outline is used if we have a group of similar criteria and the results are to be passed in a Scenario. A Scenario Outline is accompanied with an Examples table. A Scenario Outline can have multiple Examples tables.
The tests get executed once for every row found (after the header row) within the Examples table. The values to be tested are represented by their names enclosed in brackets<>. These names should match with the Examples table header.
It helps to reduce the lines of code (eliminates repeating steps) and orders our tests.
Feature File
The feature file for scenario outline is as follows −
Feature − User information
Scenario Outline: Check login functionality
   Given user enters "<name>" and "<password>"
   Then user should be logged in
   Examples: Credentials
      | name   | password |
      | user1  | pwd1     |
      | user2  | pwd2     |

Please Note: We have kept the name and password parameters enclosed in "<>". These parameters are column headers provided below the Examples section. In the step implementation, we shall pass the parameters enclosed in "{}".
Also, these parameters need to be passed as arguments to the implementation method.
Corresponding Step Implementation File
The corresponding step implementation file is as follows −
from behave import *
@given('user enters "{name}" and "{password}"')
def step_implpy(context, name, password):
      print("Username for login: {}".format(name))
         print("Password for login: {}".format(password))
@then('user should be logged in')
def step_implpy(context):
      pass
Output
The output is obtained after running the feature file and the command used is behave --no-capture -f plain.
The output shows Username for login: user1, Password for login: pwd1 and Username for login: user2, Password for login: pwd2 printed. Here, the two data sets were passed from the Examples.
 Print
 Add Notes
 Bookmark this page
NumPy Array Slicing

Slicing in python means taking elements from one given index to another given 
index.
We pass slice instead of index like this: [start:end].
We can also define the step, like this: [start:end:step].
If we don't pass start its considered 0
If we don't pass end its considered length of array in that dimension
If we don't pass step its considered 1
Slice elements from index 1 to index 5 from the following array:
Note: The result includes the start index, but excludes the end index.
Slice elements from index 4 to the end of the array:
Slice elements from the beginning to index 4 (not included):
Use the minus operator to refer to an index from the end:
Slice from the index 3 from the end to index 1 from the end:
Use the step value to determine the step of the slicing:
Return every other element from index 1 to index 5:
Return every other element from the entire array:
From the second element, slice elements from index 1 to index 4 (not included):
Note: Remember that second element has index 1.
From both elements, return index 2:
From both elements, slice index 1 to index 4 (not included), this will return a 2-D array:
Insert the correct slicing syntax to print the following selection of the array:
Everything from (including) the second item to (not including) the fifth item.
arr = np.array([10, 15, 20, 25, 30, 35, 40])

print(arr)

Start the Exercise
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.
Print concentric rectangular pattern in a 2d matrix in C++

In this problem, we have to print a rectangular pattern in a 2D matrix in such a way that they are concentric to each other.
Let’s take an example to understand this problem better,
For n=4 is :
   4 4 4 4 4 4 4
   4 3 3 3 3 3 4
   4 3 2 2 2 3 4
   4 3 2 1 2 3 4
   4 3 2 2 2 3 4
   4 3 3 3 3 3 4
   4 4 4 4 4 4 4
Here, we have to print the pattern as above taking n, integer value and print concentric rectangles as −
n  n   n   n  n
n n-1 n-1 n-1 n
n n-1 n-2 n-1 n
n n-1 n-1 n-1 n
n  n   n   n  n
Now, in this problem, as we can see there are (2n-1) columns and rows in the 2D matrix in total. This 2D matrix is printed in two parts. The upper one will be from 0 to (2n-1)/2 and the lower half will be from ((2n-1)/2+1) to 2n-2.
Now, each row will go on decreasing value by 1 until the number reaches the number of rows i.e. 1 to i (no. of rows). Then it increases the number back to n.
Using this logic lets create a program to solve the problem,
 Live Demo
#include <bits/stdc++.h>
using namespace std;
void print2Dsequence(int n){
   int s = 2 * n - 1;
   for (int i = 0; i < (s / 2) + 1; i++) {
      int m = n;
      for (int j = 0; j < i; j++) {
         cout << m << " ";
         m--;
      }
      for (int k = 0; k < s - 2 * i; k++) {
         cout << n - i << " ";
      }
      m = n - i + 1;
      for (int l = 0; l < i; l++) {
         cout << m << " ";
         m++;
      }
      cout << endl;
   }
   for (int i = s / 2 - 1; i >= 0; i--) {
      int m = n;
      for (int j = 0; j < i; j++) {
         cout << m << " ";
         m--;
      }
      for (int k = 0; k < s - 2 * i; k++) {
         cout << n - i << " ";
      }
      m = n - i + 1;
      for (int l = 0; l < i; l++) {
         cout << m << " ";
         m++;
      }
      cout << endl;
   }
}
int main(){
   int n = 4;
   cout<<"The sequence of concurrent rectangle of 4 is : \n";
   print2Dsequence(n);
   return 0;
}
The sequence of the concurrent rectangle of 4 is −
4 4 4 4 4 4 4
4 3 3 3 3 3 4
4 3 2 2 2 3 4
4 3 2 1 2 3 4
4 3 2 2 2 3 4
4 3 3 3 3 3 4
4 4 4 4 4 4 4
How to Querying Two Tables For Duplicate Values in SQL?

16 Nov, 2021
In this article, we will see how to write SQL queries to get duplicate values from two tables.
We can perform the given task using two methods:
Using INNER JOIN.Using WHERE clause
Using INNER JOIN.
Using WHERE clause
Now, for the demonstration follow the below steps:
Step 1: Create a database
we can use the following command to create a database called geeks.
Query:
CREATE DATABASE geeks;
Step 2: Use database
Use the below SQL statement to switch the database context to geeks:
Query:
USE geeks;
Step 3: Table definition
We have two tables named ‘demo_table1’ and ‘demo_table2’ in our geek’s database.
Query(demo_table1):
CREATE TABLE demo_table1(
ID int,
NAME VARCHAR(20),
AGE INT,
CITY VARCHAR(20) );
Query(demo_table2):
CREATE TABLE demo_table2(
ID int,
NAME VARCHAR(20),
AGE int);
Step 4: Insert data into a table
Query(demo_table1):
INSERT INTO demo_table1 VALUES
(11,'Romy',23,'Delhi'),
(23,'Rahul',23,'Delhi'),
(31,'Nikhil',24,'Punjab'),
(46,'Ranvir',23,'Punjab'),
(52,'Samiksha',23,'Banglore'),
(61,'Ashtha',24,'Banglore'),
(77,'Tannu',30,'Patna'),
(89,'Girish',30,'Patna');
Query(demo_table2):
INSERT INTO demo_table2 VALUES
(31,'Fanny',25 ),
(77,'Prem', 30),
(15,'Preeti',21),
(46,'Samita',32),
(09,'Rajan',45);
Step 5: View the content
Execute the below query to see the content of the table
Query(demo_table1):
SELECT * FROM demo_table1;
Output:
Query(demo_table2):
SELECT * FROM demo_table2;
Output:
STEP 6: SQL query to get duplicates from two tables
Method 1:
INNER JOIN: It is a keyword used for querying two tables to get the records having matching values in both the table.
Syntax:
SELECT Column_name
FROM table1 INNER JOIN
table2 ON condition;
For demonstration, we will write SQL query that will return duplicate ID values from both the tables
Query:
SELECT demo_table1.ID
FROM demo_table1
INNER JOIN demo_table2
ON demo_table1.ID=demo_table2.ID;
If two tables have the same column name, the table name should be used before the name of column name like table_name.column_name to differentiate the column of both the tables.
Output:
Method 2: By using where clause to compare column values
Syntax:
SELECT column_name from table_name WHERE condition;
Query:
SELECT demo_table1.ID
FROM demo_table1, demo_table2
WHERE demo_table1.ID=demo_table2.ID;
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PyQtGraph – Enable Mouse on Plot Window

01 Jun, 2021
In this article we will see how we can enable mouse on the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics and the Control Panel. When mouse is enable user can use the mouse to interact with the plot like changing size and moving the graph. 
In order to do this we use enableMouse method with the plot window objectSyntax : window.enableMouse(True)Argument : It takes bool as argumentReturn : It returns None  
Below is the implementation  
Python3
# importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np # define the datatitle = "GeeksforGeeks PyQtGraph" # y values to plot by line 1y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16]x = range(0, 10) # create plot window objectplt = pg.plot() # showing x and y gridsplt.showGrid(x = True, y = True) # adding legendplt.addLegend() # set properties of the label for y axisplt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axisplt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal rangeplt.setXRange(0, 10) # setting vertical rangeplt.setYRange(0, 20) # setting window titleplt.setWindowTitle(title) # ploting line in green colorline1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # ploting line2 with blue colorline2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # main methodif __name__ == '__main__':         # importing system    import sys         # Start Qt event loop unless running in interactive mode or using    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):        QtGui.QApplication.instance().exec_()
Output :  
 
surinderdawra388
Python-gui
Python-PyQtGraph
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
Python | datetime.timedelta() function
SQL Query to Find the Average Value in a Column

24 Mar, 2022
In this article, we are going to see how to find the average value in a column in SQL.  A column in the SQL table is the vertical catalog structure. In this article, we will be using the Microsoft SQL Server as our database.
For the purpose of example, we will be creating a sample table and performing the same operations on it.
We have the following car table in our database :
CREATE TABLE car (
companyid integer ,
companyname varchar(20) ,
totalmodels integer )
The above query creates a car table for us.
To insert values into the table we need to use the insert statement. Use the below statement to add data to the car table:
INSERT INTO car values(1,'maruti  suzuki',10);
INSERT INTO car values(2,'tata',12);
INSERT INTO car values(3,'volkswagen',8);
The above query will add the data to the car table.
Note: We have to insert values according to the table created. For example, we created a car table with companyid as integer, companyname as varchar, and totalmodels as an integer. So, we need to insert an integer, a character, and an integer else we may get an error.
To verify the contents of the table use the below statement:
SELECT * FROM car;
This will show us our created table as shown below:
For this, we need to use avg() function. We have to pass the column name as a parameter. The avg() function has the following syntax:
SELECT AVG( column_name ) FROM table_name;
The avg() function can be used with the SELECT query for retrieving data from a table.
The below query can be used to find the average of the totalmodels column of our cars table:
SELECT AVG(totalmodels) FROM car;
Output :
Let’s verify the output. The average of 10, 12, and 18 is 10.  Hence, we have successfully found out the average of all values n a column of a table.
surinderdawra388
SQL-Query
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
How to Import JSON Data into SQL Server?
SQL Query to Compare Two Dates